text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
IRC log of xproc on 2008-01-10
Timestamps are in UTC.
15:58:51 [RRSAgent]
RRSAgent has joined #xproc
15:58:51 [RRSAgent]
logging to
15:58:53 [Norm]
Zakim, this is xproc
15:58:53 [Zakim]
ok, Norm; that matches XML_PMWG()11:00AM
15:59:24 [Norm]
Meeting: XML Processing Model WG
15:59:24 [Norm]
Date: 10 January 2008
15:59:24 [Norm]
Agenda:
15:59:24 [Norm]
Meeting: 97
15:59:24 [Norm]
Chair: Norm
15:59:25 [Norm]
Scribe: Norm
15:59:27 [Norm]
ScribeNick: Norm
15:59:58 [ht]
zakim, please call ht-781
15:59:58 [Zakim]
ok, ht; the call is being made
15:59:59 [Zakim]
-Norm
16:00:01 [Zakim]
+Norm
16:00:03 [Zakim]
+Ht
16:00:06 [Norm]
Zakim, who's on the phone?
16:00:13 [Zakim]
On the phone I see Norm, Ht (muted)
16:00:23 [Zakim]
+[ArborText]
16:00:34 [Norm]
Zakim, who's on the phone?
16:00:34 [Zakim]
On the phone I see Norm, Ht, PGrosso
16:01:12 [avernet]
avernet has joined #xproc
16:01:45 [richard]
richard has joined #xproc
16:02:14 [Zakim]
+??P40
16:02:16 [avernet]
zakim, ? is avernet
16:02:16 [Zakim]
+avernet; got it
16:02:29 [Norm]
Regrets: Murray
16:02:46 [Norm]
Zakim, who's on the phone?
16:02:46 [Zakim]
On the phone I see Norm, Ht, PGrosso, avernet
16:02:48 [Zakim]
+alexmilowski
16:02:56 [Zakim]
+??P43
16:03:02 [richard]
zakim, ? is me
16:03:02 [Zakim]
+richard; got it
16:03:02 [alexmilowski]
alexmilowski has joined #xproc
16:04:09 [Norm]
Zakim, who's on the phone?
16:04:25 [Zakim]
On the phone I see Norm, Ht, PGrosso, avernet, alexmilowski, richard
16:04:27 [Zakim]
-avernet
16:05:07 [Zakim]
+??P0
16:05:08 [avernet]
zakim, ? is avernet
16:05:09 [Zakim]
+avernet; got it
16:05:22 [Norm]
Present: Norm, Henry, Paul, Alessandro, Alex, Richard
16:05:37 [Norm]
Topic: Accept this agenda?
16:05:37 [Norm]
->
16:05:45 [Norm]
Accepted
16:05:58 [Norm]
Topic: Accept minutes from the previous meeting?
16:05:58 [Norm]
->
16:06:01 [Norm]
Accepted
16:06:07 [Norm]
Topic: Next meeting: telcon 17 January 2008?
16:06:14 [AndrewF]
AndrewF has joined #xproc
16:06:25 [Norm]
Present: Norm, Henry, Paul, Alessandro, Alex, Richard, Andrew
16:06:36 [Norm]
Topic: Face-to-face meeting in 2008?
16:07:03 [Zakim]
+??P3
16:07:07 [Norm]
Norm: Anyone think we want to try to do that before the Tech Plenary? (Oct in Mandelieu)
16:07:08 [AndrewF]
zakim, ? is Andrew
16:07:10 [Zakim]
+Andrew; got it
16:08:02 [Norm]
Henry: I can imagine that we are sufficiently finished with XProc in a few months that it will be time to turn our attention to our other task.
16:08:15 [Norm]
...Sitting around a table would be the best way to start.
16:08:42 [Norm]
Norm wonders about Balisage...
16:09:11 [Norm]
Norm: Let's wait and see
16:09:25 [Norm]
Topic: Last call comments
16:09:25 [Norm]
->
16:09:39 [Norm]
Comment 21: XProc localization
16:10:44 [Norm]
Norm outlines his message about making p:error take its description from an input port
16:11:01 [Norm]
Henry: This resonates with something I encountered when trying to simplify the early example pipelines.
16:11:12 [Norm]
...Sometimes you'd like an alternative between an input port and an option.
16:11:45 [Norm]
...For example, I'd like to be able to specify the XSLT stylesheet by way of an option instead of on an input port.
16:12:08 [Norm]
...It's just laziness, but the idea of having an option and a port in a trading relationship seems very natural
16:12:34 [Norm]
Henry: The alternative is that folks won't provide descriptions for errors.
16:13:10 [Norm]
Henry: Do we want to consider adding this feature?
16:14:02 [Norm]
Richard: Can't you do it with a select and an expression?
16:14:11 [Norm]
Norm: No, because it gets turned into a string and the markup is thrown away.
16:14:35 [Norm]
Norm: I guess my reaction is, gosh that's a nice feature but aren't we done adding features?
16:14:42 [Norm]
Henry: It's not a feature it's a design pattern.
16:15:01 [Norm]
Richard: It seems to me that it's a bit excessive for what it does.
16:15:59 [Norm]
Support does not seem to be rising for the coocurrence constraint idea.
16:17:01 [Norm]
Norm: Do we want to make the description of p:error an input port?
16:18:06 [Norm]
Norm: I observe that it does require the user to make up some random document element for the message.
16:18:36 [Norm]
Richard: What about structured content?
16:18:53 [Norm]
Norm: No, way too much feature for now. We could remove the restrction to strings, but that didn't get support alst time it came up.
16:19:01 [Norm]
Zakim, who's on the phone?
16:19:01 [Zakim]
On the phone I see Norm, Ht, PGrosso, alexmilowski, richard, avernet, Andrew
16:19:11 [Norm]
Norm: Straw poll: Input or option?
16:19:43 [Norm]
Input wins with unanimity.
16:19:59 [Norm]
ACTION: Norm to change the spec to make error descriptions come from an input port on p:error
16:20:12 [Norm]
Topic: Split the spec into two or three parts?
16:21:36 [Norm]
Some discussion of why we might dot his
16:21:39 [Norm]
s/dot his/do this/
16:21:51 [Norm]
Richard: I'm inclined to keep them together.
16:22:10 [Norm]
Richard: I think it's simpler for readers to ahve it all in one document.
16:23:50 [Norm]
Paul: The biggest advantage as far as I'm concerned is that you could advance different parts to PER, for example, independently.
16:24:38 [Norm]
Paul: For example, you can tell folks we haven't fiddled the language, we've just changed the steps.
16:24:58 [Norm]
Henry made apoint earlier about the fact that breaking it into pieces doesn't necessarily make it into separate RECs
16:25:09 [Norm]
Paul: I don't think it makes sense to do unless we make different RECs.
16:25:41 [Norm]
Norm: The editor doesn't feel strongly one way or the other, for what it's worth.
16:25:52 [Norm]
Henry: I think Paul's argument has value, but I don't feel that strongly either.
16:26:31 [Norm]
Some discussion of adding steps in the future
16:26:41 [Norm]
Henry: At worst, we can always change our minds later.
16:26:52 [Norm]
...At V1.1 time, for example.
16:27:43 [Norm]
The chair doesn't hear consensus for splitting the document at this time.
16:28:10 [Norm]
Topic: Replace ignored namespaces with p:appinfo (or some such)
16:29:10 [MoZ]
MoZ has joined #xproc
16:29:30 [Norm]
Norm summarizes how we got where we are
16:31:01 [Zakim]
+??P5
16:31:25 [Norm]
Richard: One advantage to inventing your own namespace is that it designates the owner of the ifno.
16:31:28 [Norm]
s/ifno/info/
16:32:25 [Norm]
Norm: We could mandate, suggest, or leave that problem to implementors
16:32:28 [Norm]
Alex: Why?
16:32:39 [Norm]
Henry: Because it's just not clear and is contradictory in the spec.
16:33:31 [Norm]
Henry: The core of my problem is that we invite people to put an element between two steps but we say it musn't change the flow. That's just bizarre.
16:34:41 [Norm]
Some discussion of the extent to which deleting them is appropriate.
16:36:47 [Norm]
Norm: I guess the position I've come to is that ignored namespaces introduce some complexity without much benefit over having a single element for this purpose.
16:37:02 [Norm]
Alex: What about making them top-level?
16:37:11 [Norm]
Henry: Yes, excpet that the spec tries to do that and it gets confusing.
16:38:38 [Norm]
Henry: Instead of putting it in subpipline, couldn't we put it in the prolog?
16:40:51 [Norm]
Richard: Does having a p:appinfo solve the placement problem?
16:40:55 [Norm]
Some discussion, basically yes.
16:41:22 [Norm]
Alex: I'm partial to the ignored namespace thing, but I don't mind having an appinfo, as long as we don't call it "appinfo".
16:42:07 [Norm]
Straw poll: keep ignored namespaces,or abandon them in favor of some element to be named later.
16:42:24 [Norm]
Zakim, who's on the phone?
16:42:24 [Zakim]
On the phone I see Norm, Ht, PGrosso, alexmilowski, richard, avernet, Andrew, MoZ
16:43:35 [Norm]
Results: 6 for new element, 1 for ignored namespaces, and 1 abstention,.
16:43:39 [Norm]
s/n,./n./
16:43:52 [Norm]
Name the new element...
16:44:05 [Norm]
pipedata
16:44:11 [Norm]
userdata
16:44:16 [MoZ]
pipeinfo
16:44:25 [Norm]
pragma
16:47:23 [Norm]
Results: pipedata: 3, userdata: 2, pipeinfo: 4, pragma: 3
16:48:01 [Norm]
The winner is p:pipeinfo.
16:48:23 [Norm]
Topic: Allow sequences on source and result of p:pipeline
16:49:10 [Norm]
Norm: I'm inclined to say not.
16:49:35 [Norm]
Alex: I'm inclined to allow them so that you don't have to jump into a new syntax just to provide two input documents.
16:51:04 [Norm]
Richard: Because this is the simple case, I was expecting it to be used on the command line and that's possibly going to make the output syntax different.
16:51:12 [MoZ]
+1 with Richard on output
16:51:32 [Norm]
...I was planning to implement sequences as directories, that means I'll always get a directory even when there's only a single file.
16:51:50 [Norm]
...I can work around it, but it seems a bit yucky.
16:52:41 [Norm]
Some discussion of the various possibilities
16:52:54 [Norm]
Zakim, who's on the phone?
16:52:54 [Zakim]
On the phone I see Norm, Ht, PGrosso, alexmilowski, richard, avernet, Andrew, MoZ
16:53:22 [Norm]
Alex: If I put an XSLT inside a pipeline, I shouldn't have to fiddle the syntax depending on whether or not a sequence is produced.
16:55:12 [Norm]
Straw poll: sequence or no sequence?
16:55:43 [ht]
I note that saxon 8 just concatenates multiple unnamed result-documents on stdout
16:57:42 [Norm]
Results: sequence: 2, no sequence: 4, abstain: 2
16:58:14 [Norm]
Henry: What about sequence on input, no sequence on output?
16:58:27 [Norm]
Alex: I'm not going to lie down in the road over sequences.
16:59:13 [Norm]
Alessandro: I think we shouldn't let constraints on the command line system influence how we design our language.
16:59:33 [Norm]
Richard: I'd agree, except that we're only discussing the abbreviated form. And that does seem to me to have a more direct connection to useability on the command line.
16:59:36 [Norm]
...It's there for simple cases.
17:00:00 [Norm]
Norm: Is there anyone who can't live with no sequences on input or output
17:00:25 [Norm]
None heard.
17:00:31 [Norm]
Topic: Any other business?
17:00:32 [Norm]
None.
17:00:48 [Norm]
Henry: I'd like to encourage the wG to identify any issues between here and last call.
17:02:45 [Norm]
Some discussion of circular imports in pending mail.
17:04:20 [Norm]
Adjourned.
17:04:25 [Zakim]
-PGrosso
17:04:26 [Zakim]
-Ht
17:04:26 [Zakim]
-avernet
17:04:28 [Zakim]
-Andrew
17:04:29 [Zakim]
-Norm
17:04:29 [Zakim]
-MoZ
17:04:30 [Zakim]
-richard
17:04:30 [Zakim]
-alexmilowski
17:04:34 [Zakim]
XML_PMWG()11:00AM has ended
17:04:36 [Zakim]
Attendees were Norm, Ht, PGrosso, avernet, alexmilowski, richard, Andrew, MoZ
17:04:44 [Norm]
RRSAgent, set logs world visible
17:04:44 [RRSAgent]
I'm logging. I don't understand 'set logs world visible', Norm. Try /msg RRSAgent help
17:04:49 [Norm]
RRSAgent, set logs world-visible
17:04:53 [Norm]
RRSAgent, draft minutes
17:04:53 [RRSAgent]
I have made the request to generate
Norm
17:05:17 [PGrosso]
PGrosso has left #xproc
19:00:08 [Zakim]
Zakim has left #xproc | http://www.w3.org/2008/01/10-xproc-irc | CC-MAIN-2016-44 | refinedweb | 2,140 | 69.92 |
Share Data Across Accounts with Data Exchange
This post was written by Vikram Agrawal and Aswin Anand, who are both lead engineers at Qubole.
Qubole has the concept of users and accounts. While customers sign in as a single user, they can also belong to one or more accounts. This account segregation provides some nice logical separation for compute clusters and metadata. By default, a cluster started by Qubole is shared across all the users in the account. Similarly, the metastore that describes the databases, tables, and underlying table structure is shared across all the users in the account and is accessible by all the clusters in the account.
We’ve heard requests from our customers who want to share their data across Qubole accounts. In some cases, customers are okay with making a full copy of the data available across accounts. In these cases the movement of data can be complex, timely, and expensive: it’s not easy to copy petabytes of data. In other cases, customers want to maintain ownership of the data and simply delegate read access to the data.
Data Exchange on AWS
We’re excited to announce the availability of Data Exchange on AWS for easily sharing your data across Qubole accounts! Data Exchange can be used for some of the following use cases:
- Publishing a specific data set to a subscriber so they can run self-service analytics. This is common among advertising technology companies where a publisher will make the full results of an advertising campaign available to a customer. The customer can then do analyses such as audience correlation and lookalike modeling using Qubole’s suite of analytics offerings, including Hive, Presto, Spark, Pig, and Hadoop MapReduce.
- One-off data sharing across accounts within the same company or group. Our customers will sometimes open multiple accounts for administration purposes across departments. This is helpful for accounting and cost allocation reasons (i.e. they can easily identify how much compute resources each department is using) as well as logical data isolation. Data Exchange makes this easy while still providing allowances for one-off sharing of specific tables or databases across departments.
The basic elements of Data Exchange are Spaces. A Space is a logical container for storing Hive tables that are meant to be shared. For the rest of this blog post, we’ll refer to a publisher as the account that is sharing data and a subscriber as the account that consumes that data.
Data Exchange never moves or copies the underlying data. Rather, a copy of the metadata entry will be shared with the subscriber account. This keeps the ownership of the data within the publisher’s account. And, the data can be configured as read-only for the subscriber of the data.
Walkthrough For Publisher
Getting started is easy. First, you’ll need to create a Space. You can do this within the Explore section of our web interface and choosing Data Exchange within the dropdown list.
As the publisher, you’ll create a new space within My Spaces by hitting the + button. You’ll put in a unique name for the Space (these names are in a global namespace for all Qubole accounts) and an S3 location for storing some metadata that Qubole creates related to Data Exchange.
Next, you’ll export a Hive table to your Space. Within Explore, select Qubole Hive from the dropdown list. From here, select a database and then a table within that database. You’ll see the properties for that table. On the upper-right corner of this screen, you’ll see a gear icon for settings. From this list, select Export to Space.
Now, choose the Space that you recently created and hit the Export button.
AWS console steps for Publisher
Next, you’ll move over to the AWS console to configure some cross-account access for your S3 data. The subscriber needs read access to metadata saved within the space, and the data location of the shared hive table. As the publisher, you’ll need to set the following policy in your AWS account. Here, we’ve named the policy name
cross-account-access-policy.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1444052180000", "Effect": "Allow", "Action": "s3:GetObject", "Resource": [ "arn:aws:s3:::data-exchange-blog-post-demo/path-to-space-s3-location/*" "arn:aws:s3:::bucket-1/path-to-hive-data/* " ] }, { "Sid": "Stmt144405218001", "Effect": "Allow", "Action": [ "s3:GetBucketLocation", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::data-exchange-blog-post-demo*" "arn:aws:s3:::bucket-1*" ] } ] }
Once the policy is in place, you’ll need to create a cross-account role that the subscriber can assume. We’ve named the example role name below
role-for-subscriber.
On the role type, you’ll select the second option, “Allows IAM users from a 3rd party AWS account to access this account”.
Next, you’ll add in the 12-digit AWS account number for the subscriber and a descriptive external ID for easy identification.
Finally, you need to attach the policy we created earlier,
cross-account-access-policy to the role we just created.
Now, you’re ready to share the relevant details with the subscriber. You’ll share the role_arn, which for this example is
arn:aws:iam:::role/role-for-subscriber. The 12-digit AWS account number is for the publisher’s account. You’ll also share the external ID, which we named subscriber1.
Walkthrough For Subscriber
As a subscriber (a different Qubole account from the publisher account), you’ll need to start in the AWS IAM console. You need to add an IAM policy so your account can subscribe to the publisher’s space using the role they created for you.
{ "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Action": "sts:AssumeRole", "Resource": "arn:aws:iam:::role/role-for-subscriber” } }
Next, you’ll go to the Explore in Qubole, select Data Exchange. In Other Spaces, click the + button to add a Space. Enter the info provided to you by the publisher.
Once this Space is added, it becomes visible under the Other Spaces section. Selecting a spaces gives the list of Hive tables which can be imported by the subscriber. To import a table, click the dropdown on the right pane in the same row as the Hive table name and click on “Import”.
As soon as the table is imported, it becomes visible in the Qubole Hive metastore. If the imported table is partitioned, an
alter table recover partitions query should be run from the Analyze screen before the table can be used further. Otherwise, the table can be queried upon directly.
And now, you’re done subscribing to a table – congratulations!
Data Exchange is generally available now for all Qubole customers. You can read more about it in our documentation. Try it out, and we’d love to hear your feedback! | https://www.qubole.com/blog/share-data-across-accounts-with-data-exchange-3/ | CC-MAIN-2018-43 | refinedweb | 1,139 | 55.44 |
.
- How to define a portlet namespace and context paths using JSTL and JSP 29 Apr 2014
Tip - Learn how to define portlet namespaces and context paths using JSTL and the JSP expression language.
- Annotation versus XML configuration: Which JPA option to choose? 04 Oct 2013
Tip - A common debate in the JPA community is whether to configure applications using an XML or annotations based approach. Here are some reasons why you might want to choose XML instead.
- Effective portlet development means respecting the servlet API 20 May 2013
Tip - When moving to portlet development from web development, software engineers must remember that servlet and JSP development rules still apply.
-.
- Include vs. Forward of the Servlet RequestDispatcher 02 Oct 2011
Tip - The key difference between the two is the fact that the forward method will close the output stream after it has been invoked, whereas the include method leaves the output stream open. | http://www.theserverside.com/resources/Java-server-pages?bucketCode=ETA | CC-MAIN-2014-49 | refinedweb | 152 | 54.26 |
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
how to override the write method (in the Edit form) ?
Hi everyone, How can i override the write method in the edit form??
You've to do this:
def write(self, cr, uid, ids, vals, context=None): #code res = super(class_name, self).write(cr, uid, ids, vals, context=context) #res stores the result of the write function #code return res
im doing lik this : def write(self, cr, user, ids, vals, context=None): res1=super(pos_methode1, self).write(cr, user , ids, {'firstname': vals['firstname'] ,'lastname': vals['lastname']}, context=context) return res1 this goes right only when i change both of the 2 field values ,but if change only when an error occured :"Key error :..."
what do you mean with 2 fields? Please post your entire code related to this please. Thanks
class pos_methode def write(self, cr, user, ids, vals, context=None): res1=super(pos_methode1, self).write(cr, user , ids, {'firstname': vals['firstname'] ,'lastname': vals['lastname']}, context=context) return res1 it goes right only when i change all of the 2 fileds value,but if update only one i get an error
What silvi said it's true. if you say vals['lastname'] it's not going to work if you are not sending ['lastname'] so you use vals.get('lastname') beside vals['lastname']
When you try to change one field only, you ll get an error. The reason is you are trying to fetch value from vals dict which is actually not there. Say, you have changed first name only and in write you are updating lastname name as well which is actually not there in vals dict.
so what can i do to have the possiblity of updating both values or even! | https://www.odoo.com/forum/help-1/question/how-to-override-the-write-method-in-the-edit-form-49630 | CC-MAIN-2016-50 | refinedweb | 316 | 70.43 |
We are like the fascicles of tin soldier collections and the free enrollment at gyms … back in September! And with something that seems a little harsh but that surely after reading a few lines will be easier. Today we initiate a series of posts in which we’ll discuss some functional abstractions, that are very related to the world of mathematics, with the aim of being gradually introduced into the world of purely functional Scala libraries, such as as Scalaz or Cats. To do this, we will rely on some features and techniques that have already been discussed, such as type classes.
Today, we’ll start with monoids.
Monoids, monoids everywhere…
Monoid? Weird word. Let’s see what Wikipedia has to say about monoids:
“Algebraic structure with a single associative binary operation and an identity element. Monoids are studied in semigroup theory as they are semigroups with identity.”
Hmmm… yes, right. What the hell? Let’s face it gradually.
- Binary operation: ok, I get this one. It’s an operation with two operands. In order to follow the same convention, we are going to call this operation in a generic way with the symbol |+|.
However, the binary operation must comply with two rules:
- It must comply with the associative property, ie: a |+| (b + c) = (a + b) |+| c
- And besides, it must have a neutral element.: a |+| neutralElement = a
Hmmmm, that makes sense. For instance, the addition of integers follows the rules of monoids:
- Associative property: 1 + (2 + 3) = (1 + 2) + 3
- The neutral element is zero: 1 + 0 = 1
Same reasoning applies to the multiplication of integers (whose neutral element is 1), and the concatenation of strings as well (being the empty string “”, the neutral element). Great! I’m starting to get it.
Monoids in Scalaz
In order to work with monoids, in this post we will be using the Scalaz library. Scalaz offers us a wide range of options, abstractions and functionalities. Today we will only give you a glimpse of Scalaz in order to write an example. We promise to talk at great length about this library in the future 🙂
The first thing to do is to import Scalaz in our project. To do so, we have to include this library in the dependencies of our project:
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.1.3"
and now we write the following imports:
import scalaz._, Scalaz._
If we get a sneak peek at the library, we can find the Monoid Monoid class, or the class Semigroup. They define the functionality we will make use of.
The Monoid class defines the zero method,, which serves us to indicate which is the neutral element. Furthermore, in the MonoidLaw trait, the fundamental rule that a neutral element must comply with is defined.
But, where is the information regarding the associative property?. Well, it is in the Semigroup class. It seems that monoids are an specialization of semigroups. Semigroups are responsible for the associative rule, while monoids add the rule of the neutral element. In fact, if we go to the Semigroup class, we can find the append method, which represents our binary operation |+|, and a bit further down we can see how the associative property is defined.
The next thing we must know is that Scalaz is based on a structure of type classes. This is why we will have to implement implicit objects, defining the inherent behaviour of our structures with respect to the monadic properties.
After this brief but (I hope) sufficient explanation, we will see how to apply all this knowledge to a simple example.
Creating our first monoid
Now finally, we will create our own monoid with Scalaz. Let’s start by creating new data types. We’ll create two types of atoms: oxygen and hydrogen.
trait Atom case object Oxygen extends Atom case object Hydrogen extends Atom
And finally, the molecule type. This type will have a certain number of atoms (which may be of different types), and a molecular stability.
case class Molecule(atoms: Map[Atom, Int], stability: Double)
We want to work with our molecule type as if it were a monoid. For that purpose, and by using the Scalaz type classes, we’ll define an implicit object that defines the monadic behaviour of the molecule:
implicit object MoleculeIsMonoid extends Monoid[Molecule] { def zero: Molecule = Molecule(Map(), 1) def append(f1: Molecule, f2: => Molecule): Molecule = f1.fusion(f2) }
We have decided that the neutral molecule is the one that has no atoms, and whose stability is 1, the maximum stability possible.
In addition, we have decided that the addition of molecules is delegated to a function called fusion. Let’s see how it’s defined:
case class Molecule(atoms: Map[Atom, Int], stability: Double) { def fusion(other: Molecule): Molecule = Molecule( atoms = atoms |+| other.atoms, stability = stability * other.stability ) }
As we can see, the fusion of two molecules is the union of the atoms that compose them as if they were monoids. It turns out that Scalaz provides us with the functionality to address the combination of maps as monoids. In addition, we will combine the stabilities as if they were two probabilities, that is, multiplying them both.
The append method can also be represented by the symbol | + |, just as we had initially defined it.
And that’s all! We can now merge molecules using monoids and the operations that Scalaz provides us with for such abstractions:
val m1 = Molecule(Map(Oxygen -> 1, Hydrogen -> 2), 0.2) val m2 = Molecule(Map(Oxygen -> 1), 0.3) m1 |+| m2 //Molecule(Map(Oxygen -> 2, Hydrogen -> 2), 0.06) List(m1, m2, m2, m1).foldLeft(Molecule(Map(), 1))(_ |+| _) //Molecule(Map(Oxygen -> 4, Hydrogen -> 4), 0.0036) Some(m1) |+| Some(m2) //Some(Molecule(Map(Oxygen -> 2, Hydrogen -> 2), 0.06))
Conclusion
By the time you get to this point, I hope you’ll have lost the fear of bizarre words. As we have seen, algebraic abstractions are just a way of naming items that comply with some properties. Then, we can benefit from this abstraction to treat different operations in the same way. Today, we’ve seen monoids. Later on, other concepts you might have heard about will be discussed, such as the famous monads. Now you know, show off your knowledge about monoids to your friends and family 🙂
One thought on “Abstract alge..what?: Monoids”
[…] I’m afraid we don’t. Would we like to? Very likely. In previous posts we spoke about monoids and monads, but now it’s functor’s time. Functors are everywhere and we can prove it. […]
Me gustaMe gusta | https://scalerablog.wordpress.com/2015/09/14/abstract-alge-what-monoids/ | CC-MAIN-2017-39 | refinedweb | 1,098 | 64.91 |
Compact operator on a Hilbert space more hot questions question feed default about us tour help blog chat data legal privacy policy work here advertising info developer jobs directory mobile contact CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; Create an user for Java and grant it access. this is just init // it will not create a connection MysqlConnect mysqlConnect = new MysqlConnect(); Somewhere else in your code ... Even I had the same issue at the start. his comment is here
Words that Contain Digits The Order of the Identity of a Group Why can't we produce gravitational waves in the lab? Should you recuse yourself from the hiring committee if you have had a past romantic relationship with an applicant? See Licence. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
A "quantum" identity: in search of a proof -Part II How can a person be born from six fathers? Determine the JDBC URL. To solve the one or the other, follow the following advices: Verify and test them with ping.
Closing in finally is just to ensure that it get closed as well in case of an exception. Class [com.mysql.jdbc.Driver] not found4class not found exception Class.forName(“com.mysql.jdbc.Driver”) in webservice1Class not found com.mysql.jdbc.Driver1com.mysql.jdbc.driver class not found exception0class not found exception com.mysql.jdbc.driver1class not found com.mysql.jdbc.Driver jdbc when tying to connect to a In Unix and clones : should be used. Mysql Jdbc Driver Class Remember the port number whenever you've changed it.
About this website Support free content Questions and discussion Tutorial & code license Get source code 7. Java Mysql Driver a firewall or proxy. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.
This is by default 3306. Mysql Jdbc Driver Maven TikZ-Spring Symbol First-person narrative: Does it make more sense to focus on internal thoughts than external gestures? Why do batteries in consumer electronics get used unevenly Is it appropriate to ask an employee for a favor? Exercise: create example database In this exercise you create a new database, a new user and an example table.
Please do not support bad practices. –Luiggi Mendoza Dec 3 '14 at 14:38 | show 8 more comments up vote 17 down vote Initialize database constants Create constant properties database username, Java Mysql Connection Example Links and Literature MySQL homepage Download link for MySQL 7.1. Mysql Jdbc Url Note that you don't need to load the driver everytime before connecting.
Browse other questions tagged java mysql jdbc or ask your own question. this content import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class MysqlConnect { // init database constants private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver"; private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name"; private If it's installed at the same machine where you run the Java code, then you can just use localhost. But I still am not able to connect to the database using the above lines of code and is throwing the exeption com.mysql.jdbc.Driver as an error. How To Connect Mysql Database In Java Using Eclipse
Initialize the database class. // !_ note _! It can also be an IP address like 127.0.0.1. See also among others stackoverflow.com/q/9428573. weblink Something in between Java and DB is blocking connections, e.g.
Some oceans are so remote such that the closest person to you is in the space station Spread operator magically turns functions into 'not functions' Can "plunge" be used for a Jdbc Connection Java Code Here's the code: Product.java ProductDataBean pdb = new ProductDataBean(); Connection connect = pdb.getConnection(); // ClassNotFoundException on this line) ProductDataBean.java package cart; import java.io.*; import java.sql.*; import java.util.*; public class ProductDataBean implements Free use of the software examples is granted under the terms of the EPL License.
more hot questions question feed default about us tour help blog chat data legal privacy policy work here advertising info developer jobs directory mobile contact us feedback Technology Life / Arts The method below takes an argument, queries the DB based on the argument and returns the query result private String db_server = BaseMethods.getSystemData("db_server"); private String db_user = BaseMethods.getSystemData("db_user"); private String db_password This coming from someone who pretends in his profile to have 7+ years Java/J2EE experience is just sad. –BalusC Jan 20 '14 at 22:15 1 @Pankaj you can use connection No Suitable Driver Found For Jdbc:mysql DONE .... } catch (SQLException e) { e.printStackTrace(); } finally { mysqlConnect.disconnect(); } This is all :) If anything to improve edit it!
Not the answer you're looking for? Compact operator on a Hilbert space Boolean switch with a third state World world world world How many times will you have to golf a quine? We offer both public and inhouse training. check over here Introduction to MySQL 3.
MysqlDataSource implements javax.sql.DataSource which is the newer mechanism. –Sean Owen May 21 '10 at 9:00 @SeanOwen +1 for Good explanation. Now that I did, everything is working fine. Why does tabularx fail with siunitx? MySQL JDBC driver To connect to MySQL from Java, you have to use the JDBC driver from MySQL.
You of course want World Domination, so let's use UTF-8 as well. CREATE TABLE comments ( id INT NOT NULL AUTO_INCREMENT, MYUSER VARCHAR(30) NOT NULL, EMAIL VARCHAR(30), WEBPAGE VARCHAR(100) NOT NULL, DATUM DATE NOT NULL, SUMMARY VARCHAR(40) NOT NULL, COMMENTS VARCHAR(400) NOT NULL, If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. This also applies to Statement, PreparedStatement and ResultSet.
Parent insists I lied and getting punished for it XP PCs in company network C++ why does this static cast work? | http://themotechnetwork.com/mysql-jdbc/com-mysql-jdbc-driver-getconnection.html | CC-MAIN-2017-30 | refinedweb | 1,055 | 56.76 |
Hope you’re ready for another challenge! Let’s get started with Day 3. Today’s challenge is modified from user @jayeshcp on CodeWars. Write a ...
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
For further actions, you may consider blocking this person and/or reporting abuse
JavaScript:
Demo on CodePen.
Nice solution, mine was similar in using regex match, but not as short. This one will error on a string without any vowels because
matchwill return a
nullwhich doesn't have a length.
That's a good point. This could be avoided by checking if the result of the match is null and using an empty string instead. Something like this:
I also used template literals before the
matchso numeric values or null would be process too... and now the code is even uglier than before :P
Typo
${s}
Good catch! I corrected it. Thank you for letting me know!
I think this is the best solution if you're ok with regex.
Ruby
Long Solution (my first solution)
Short Solution (my refactored solution)
It would be interesting to know if
str.count("aeiouAEIOU")was faster, or if reordering the letters to try to get the most likely match first was better – e.g.
str.count("eiaouEIAOU")
[...'aeiou'].includes
Fixed, thanks!
Hi, i loved this solution. Took me a bit to get my head around the use of reduce here and it's awesome. Thanks. I learned something nice today.
Cool., I didn't know we can use spread on a string. 👍🏻
Thinking the string as a Set with O(1) for look up operations: solution is O(n), where n = len(str)
JS lambda way
My python solution!
Here is my try at it in JavaScript:
Oh I've been waiting for this one all morning! Decided I wanted to go all out on this on!
Come check it out while I work my way through this challenge! I'm live now and about to get started!
twitch.tv/coreyja
Here is my Rust solution all TDD'ed out!
I'm still live streaming as I type this out, but once I wrap up I'll post a link to the video here!
Ahhh! :panic:
Turns out OBS didn't want to behave for me today, and split my stream into 2 and dies before I finished, but we got almost all of it recorded! Learnings for next stream!
Links to the video that recorded for the longest here
Livestream - Dev.to Challenge Vowel Count in Rust
Corey Alexander ・ Jun 30 ・ 1 min read
Why not so simple as this (JS)...
JS one that's probably pretty speedy
Note that:
and vowels go pretty much eaiou in terms of how common they are in english.
TI-Basic Calculator, where the string is in
Ans:
And yes you can omit ending parens, which helps saves some bytes (:
Python regex example
This is my solution in Swift (with an extension 😊) :
JavaScript, using reduce:
Will have to double check the syntax (on Mobile) but I think this will work
Ruby Language
with specs
output
In go!
Go playground example
Uses
fallthroughmostly because I wanted to,
count++would be smaller, but all cases behave the same (also its more easily maintainable).
You also have to traverse the tree to get to the next letter. But I see what you mean. Only counting equality checks, hard-coding behaves like a linear search. My bad.
I think you might still be missing Brian's point that a hash set has O(1) lookup time, which is faster than the tree set's O(log n).
(On paper. Real-world implementations vary. e.g. Ruby's hashes just do linear search at this size.)
My solution is a bit longer because I don't know regex, but it gets the job done.
CodePen
Nim
Link to playground - play.rust-lang.org/?version=stable...
A solution in Elixir
GO
Ruby:
Haxe
iterators library looked useful but you can't
foldan iterator, only an iterable, disappoint.
ledgible I hope
Could also
Python
//TS
my solution with TDD:
test:
and func
In F#
Here's my solution:
PHP:
Dart
SQL (Postgres)
Go:
Powershell
I do try to keep it as an actual function and give pretty/usable output.
This is very easy in Perl, as the transliteration operator returns the number of matches:
One can also use the Saturn (or Goatse) "secret" operator with a regex match:
The global match returns all the matches in list context, the assignment to () enforces list context, and enforcing scalar context on it by a scalar assignment returns the number of elements.
Java:
Here is my simple solution with PHP:
A little late to the party, but this is my JavaScript solution:
ReasonML
Sketch: sketch.sh/s/jjxviGaqjQ2P0ZI0SFC2Sg/
function findVowelLetters(s){
var v = ["a","e","o","i","u"];
var vow = "";
var slowerCase = s.toLowerCase();
for(var f of v){
for(var i =0; i<s.length ; i++){
if(slowerCase[i] === f){
vow += f;
}
}
}
return vow;
}
BASH
Shell/awk oneliner:
Not sure if I follow. O(n log n) is worst than O(n). Insertions in a binary tree are expensive to keep it balanced.
If you use a set or hashmap assuming zero collisions, the look up is O(1). Then the bottke neck is in the string iteration. Right?
Clojure:
PHP
C++
Python
Given the list :
We can define a function:
Or simply in a one-liner:
R with some Regex fun:
Python
Rubeh
Haskell
Java
Why there's no
y? 🤔
Here comes Another 🚀
Python
Haskell:
Groovy has a nice built-in Pattern matcher
;)
Using Regex in C#
Ruby
We don't care about the vowels being ordered for this problem, so you'd be paying extra time (vs. a hash-based set, or just hard-coded equality checks) for a property you're not using.
// Java
public static int countVowels(String input) {
return input.length()-input.replaceAll("(?i)[aeiou]", "").length();
}
Python :
def count_vowels(word):
word=word.lower()
data={x:word.count(x) for x in "aeiou"}
return data
var vowelCount = Regex.Matches(str, @"[AEIOUaeiou]").Count;
Console.WriteLine(vowelCount); | https://practicaldev-herokuapp-com.global.ssl.fastly.net/thepracticaldev/daily-challenge-3-vowel-counter-34ni/comments | CC-MAIN-2021-49 | refinedweb | 1,038 | 72.46 |
mofcomp
The Managed Object Format (MOF) compiler parses a file containing MOF statements and adds the classes and class instances defined in the file to the WMI repository. MOF files are usually automatically compiled during the installation of the systems with which they are provided, but you can also compile MOF files by using this tool.
For more information about locating and using mofcomp.exe, see Using WMI Management Tools. For information about removing classes and instances from the WMI repository, see the pragma deleteclass preprocessor command.
The following code example shows how to run the MOF compiler on a file.
mofcomp [-autorecover] [-check] [-N:<namespacepath>] [-class:createonly | -class:forceupdate | -class:safeupdate | -class:updateonly ] [-instance:updateonly | -instance:createonly] [-B:<filename>] [-WMI] [-P:<Password>] [-U:<UserName>] [-A:<Authority>] [-MOF:<path>] [-MFL:<path>] [-AMENDMENT:<Locale>] [-ER:<ResourceName>] [-L:<ResourceLocale>] <MOFfile>
Switches
-autorecover
Adds the named MOF file to the list of files compiled during repository recovery. The list of autorecover MOF files is stored in the registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\
The MOF files listed in this registry entry must reside on the local computer because MOF files that use the autorecover command cannot recover MOF files located on a remote computer.
Note
To ensure that all your WMI class definitions for managed objects are restored to the WMI repository if WMI has a failure and restarts, use the #pragma autorecover preprocessor instruction in your Managed Object Format (MOF) file.
-check
Requests that the compiler perform a syntax check only and print appropriate error messages. No other switch can be used with this switch. When this switch is used, no connection to Windows Management Instrumentation (WMI) is established and no modifications to the WMI repository are made.
-N:<namespacepath>
- Requests that the compiler load the MOF file into the namespace specified as *namespacepath*. The compiled MOF is loaded into the default Mofcomp namespace, root\\default, unless this switch is used. You can also insert the preprocessor command **\#pragma namespace ("***namespace path***")** in the MOF file to achieve the same effect. If both the **-N:** switch and the \#pragma namespace command are used, \#**pragma namespace** **autorecover** takes priority. In this case, the only way to compile the MOF into another namespace is to edit the MOF file and change the \#**pragma namespace** command. A remote computer can be specified using \\\\machinename\\root\\default.
-class:createonly
Requests that the compiler not make any changes to existing classes. When this switch is used, the compile operation terminates if a class specified in the MOF file already exists.
-class:forceupdate
Forces updates of classes when conflicting child classes exist. For example, suppose a class qualifier is defined in a child class and the base class tries to add the same qualifier. In -class:forceupdate mode, the MOF compiler resolves this conflict by deleting the conflicting qualifier in the child class. If the child class has instances, the forced update fails.
-class:safeupdate
Allows updates of classes even if there are child classes, as long as the change does not cause conflicts with child classes. For example, this flag allows adding a new property to the base class that was not previously mentioned in child classes. If the child classes have instances, the update fails.
-class:updateonly
Requests that the compiler not create any new classes. When this switch is used, the compile operation terminates if a class specified in the MOF file does not exist.
-instance:updateonly
Requests that the compiler not create any new instances. When this switch is used, the compile operation terminates if an instance specified in the MOF file does not exist.
-instance:createonly
Requests that the compiler not make any changes to existing instances. When this switch is used, the compile operation terminates if an instance specified in the MOF file already exists.
-B:<filename>
Requests that the compiler create a binary version of the MOF file with the name filename without making any modifications to the WMI repository.
If you use the -B:<filename> option to create a binary MOF file, only default qualifier flavors are stored in the WMI repository.
Binary MOF format is the intermediate format for combining a WDM-driver with the MOF as a resource. The binary MOF represents classes and instances just as a text MOF file does and is compressed before it is stored on disk.
-WMI
Requests that the compiler perform a WMI syntax check. The -B: switch must be used with this switch. The -WMI switch is only used for building binary MOF files for use by WDM device drivers. This switch invokes a separate binary MOF file checker, which runs after the binary MOF file is created.
-P:<Password>
Specifies Password as the password for the computer user to enter when logging on.
-U:<UserName>
Specifies UserName as the name of the user logging on.
-A:<Authority>
Specifies Authority as the authority (domain name) to use when logging on to WMI.
-MOF:<path>
Name of the language neutral output. Used with the -AMENDMENT switch to specify the name of the language-neutral MOF file that will be generated.
-MFL:<path>
Name of the language specific output. Used with the -AMENDMENT switch to specify the name of the language-specific MOF file that will be generated.
-AMENDMENT:<Locale>
Splits the MOF file into language-neutral and -specific versions. The MOF compiler creates a language-neutral form of the MOF file that has all amended qualifiers removed. A localized version of the MOF file is also created with an MFL file name extension. The Locale parameter specifies the name of the child namespace that contains the localized class definitions. The format of the Locale parameter is MS_xxx where xxx is the hexadecimal value of the Windows LCID. For example, the locale for American English is MS_409.
-ER <ResourceName>
Extracts binary MOF from a named resource. This switch gets the binary MOF from the class in the WMI repository while the -B switch creates the binary MOF format from a MOF file.
-L:<ResourceLocale>
Optional. Extracts the localized MOF descriptions from the binary MOF when used with -ER switch.
<MOFfile>
Name of the file to parse.
Return Values
As its first operation, the MOF compiler performs a syntax check on the MOF file. If the compiler finds any errors, it prints an error message and the process terminates.
The MOF compiler can return the following values:
0
MOF compile operation was successful.
1
The MOF compiler could not connect with the WMI server. This is either because of a semantic error such as an incompatibility with the existing WMI repository or an actual error such as the failure of the WMI server to start.
2
One or more command-line switches were not valid.
3
A MOF syntax error occurred.
If the MOF file is parsed correctly, but an attempt is made to perform an operation that is forbidden by a command-line switch, the compiler returns an error code generated by WMI instead of any of the return codes listed in the list preceding. For example, a WMI error code is returned when the -instance:updateonly switch is specified and the MOF file attempts to create an instance.
If the #pragma autorecover preprocessor statement is not in the file, then the following warning is returned:
WARNING: FileYourMof.Mof does not contain #PRAGMA AUTORECOVER. If the WMI repository is rebuilt in the future, the contents of this MOF file will not be included in the new WMI repository. To include this MOF file when the WMI Repository is automatically reconstructed, place the #PRAGMA AUTORECOVER statement on the first line of the MOF file.
Remarks
The MOF Compiler is available in the %Windir%\System32\wbem directory. You must specify the MOF file as the parameter of the MOF Compiler. You can also specify an Autorecover switch if you want the MOF file to be automatically recompiled if the CIM Repository ever has to be automatically recovered. For more information, type Mofcomp /? at the command prompt.
A MOF file that uses the Unicode character set contains a signature as the first two bytes of the file. This signature is either U+FFFE or U+FEFF, depending on the byte ordering of the file.
When no errors occur in the parsing process, the MOF compiler connects to the WMI server running on the local computer unless the -check switch is specified. Classes and instances defined in the MOF file are added to the WMI repository.
When an error occurs in updating the WMI repository, the compiler makes no attempt to return the repository to its state before the compiler began processing.
Windows 8: When installing a provider, mofcomp treats the [Key] and [Static] qualifiers as true if they are present, regardless of their actual values. Other qualifiers are treated as false if they are present but not explicitly set to true. | https://docs.microsoft.com/en-us/windows/desktop/WmiSdk/mofcomp | CC-MAIN-2018-51 | refinedweb | 1,476 | 54.12 |
So the point of the program is to input a file and have the program generate the number of lines, characters, and words. As of right not I can generate the lines and the words. However, I cannot generate them both at the same time like when I need to because each method has its own loop. For this reason, which ever action I have second (in this case the loop to generate the number of lines) does not work. I was wondering how I could fix this and I'm also seeking advice on how to find the number of characters in the document.
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** 7 This program applies line numbers to a file. 8 */ public class LineNumberer { public static void main(String[] args) throws FileNotFoundException { // Prompt for the input and output file names Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); // Construct the Scanner and PrintWriter objects for reading and writing //C:\Users\Ben\Documents\NetBeansProjects\Ben\src\LineNumberer\test.txt File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); int wordNumber = 1; while (in.hasNext()) { String word = in.next(); System.out.println(word); wordNumber++; } System.out.println("There are " + wordNumber + "Words"); int lineNumber = 1; while (in.hasNextLine()) { String line = in.nextLine(); lineNumber++; } System.out.println("There are " + lineNumber + "Lines"); } } | http://www.javaprogrammingforums.com/loops-control-statements/7283-counting-words-file-loop.html | CC-MAIN-2014-10 | refinedweb | 235 | 52.56 |
Saving Scraped Data To CSV With Scrapy Feed Exporters
You've built a spider that will scrape data from a website, now you want to save it somewhere. One of the easiest ways to save scrape data is to save it to CSV file.
In this guide, we will go through how:
- What Are Scrapy Feed Exporters?
- Saving CSV Files Via The Command Line
- Saving CSV Files With Feeds Setting
- Saving Data To Multiple CSV CSV files from Scrapy.
Saving CSV Files Via The Command Line
The first and simplest way to create a CSV file of the data you have scraped, is to simply define a output path when starting your spider in the command line.
To save to a CSV file add the flag
-o to the
scrapy crawl command along with the file path you want to save the file to.
You can set a relative path like below:
scrapy crawl bookspider -o bookspider_data.csv
Or you can also set a absolute path like this:
scrapy crawl bookspider -o
You have two options when using this command, use are small
-o or use a capital
-O.
Telling Scrapy to save the data to a CSV via the command line is okay, but can be a little messy. The other option is setting it in your code, which Scrapy makes very easy.
Saving CSV Files With Feeds Setting
Often the cleanest option is to tell Scrapy to save the data to a CSV via the FEEDS setting.
We can configure it in our
settings.py file by passing it a dictionary with the path/name of the file and the file format:
# settings.py
FEEDS = {
'data.csv': {'format': 'csv'}
}
You can also configure this in each individual spider by setting a
custom_setting in your spider.
# bookspider.py
import scrapy
from proxy_waterfall.items import BookItem
class BookSpider(scrapy.Spider):
name = 'bookspider'
start_urls = [""]
custom_settings = {
'FEEDS': { 'data.csv': { 'format': 'csv',}}
}.csv': {'format': 'csv', CSV for the data in the data folder, followed by the subfolder with the spiders name, and a file name that includes the spider name and date it was scraped.
# settings.py
FEEDS = {
'data/%(name)s/%(name)s_%(time)s.csv': {
'format': 'csv',
}
}
The generated path would look something like this.
"data/bookspider/bookspider_2022-05-18T07-47-03.csv".csv': {
'format': 'csv',
'encoding': 'utf8',
'store_empty': False,
'item_classes': [MyItemClass1, 'myproject.items.MyItemClass2'],
'fields': None,
'indent': 4,
'item_export_kwargs': {
'export_empty_fields': True,
},
}
}
Saving Data To Multiple CSV File Batches
Depending on your job, you may want to store the scraped data in numerous file batches instead of in one large CSV CSV.csv': {
'format': 'csv',
'batch_item_count': 10,
}
}
The resulting batch files, with 10 rows in each.
"data/bookspider/bookspider_batch_1.csv"
"data/bookspider/bookspider_batch_2.csv"
"data/bookspider/bookspider_batch_3.csv"
"data/bookspider/bookspider_batch_4.csv"
"data/bookspider/bookspider_batch_5.csv"
"data/bookspider/bookspider_batch_6.csv"
More Scrapy Tutorials
We've covered everything you need to know about saving data to CSV files with Scrapy. If you would like to save your CSV files to AWS S3 then check out our Saving CSV/JSON Files to Amazon AWS S3 Bucket guide here
If you would like to learn more about saving data, then be sure to check out these guides:
- Saving Data to JSON
-. | https://scrapeops.io/python-scrapy-playbook/scrapy-save-csv-files/ | CC-MAIN-2022-40 | refinedweb | 536 | 61.67 |
In this tutorial, we are going to learn about Python Random Number. In our previous tutorial, we learned about Python math module.
Table of Contents
Python Random Number
To work with python random number, we need to import Python’s random module at first. Python random module provides pseudo-randomness.
Python random module uses Mersenne Twister as the core random generator. So, this module is completely unsuitable for cryptographic purposes for being deterministic. However, we can use Python’s random module for most of the cases because Python’s random module contains many well known random distributions.
Python Random Integer
In this section, we will be discussing about generation integer numbers randomly. We can use
randint(a,b) function to get a random integer from range
a to
b. Again, we can get number from a sequence by using
randrange(start, stop, step) function. Let’s see an example to get python random integer.
import random as rand a = 10 b = 100 print('\na =', a, 'and b =', b) print('printing number [', a, ', ', b, ') :', rand.randint(a,b)) start = 1 stop = 12 step = 2 print('\nsequence = [1, 3, 5, 7, 9, 11]') print('printing one number from the sequence :', rand.randrange(start, stop, step))
For each run, the output will change. However, here given a sample output.
Python Random Float
There are several functions that returns real number or float randomly. For example,
random() function returns a real number from 0 to 1 (exclusive).
Again,
uniform(a, b) functions return a real number from a to b. Moreover there are some random distributions also available in Python random module. We can also get real number from those distribution.
We can get random numbers from exponential distribution by using expovariate(lambd) function.
import random as rand print('Random number from 0 to 1 :', rand.random()) print('Uniform Distribution [1,5] :', rand.uniform(1, 5)) print('Gaussian Distribution mu=0, sigma=1 :', rand.gauss(0, 1)) print('Exponential Distribution lambda = 1/10 :', rand.expovariate(1/10))
The values in output will vary for each execution. You will get output like this.
Random number from 0 to 1 : 0.5311529501408693 Uniform Distribution [1,5] : 3.8716411264052546 Gaussian Distribution mu=0, sigma=1 : 0.8779046620056893 Exponential Distribution lambda = 1/10 : 1.4637113187536595
Python Random seed
Python random number generation is based on the previous number, so using system time is a great way to ensure that every time our program runs, it generates different numbers.
We can use python random seed() function to set the initial value. Note that if our seed value doesn’t change in each execution, we will get same sequence of numbers. Below is a sample program to prove this theory about seed value.
import random random.seed(10) print('1st random number = ', random.random()) print('2nd random number = ', random.random()) print('1st random int = ', random.randint(1, 100)) print('2nd random int = ', random.randint(1, 100)) # resetting the seed to 10 i.e. first value random.seed(10) print('3rd random number = ', random.random()) print('4th random number = ', random.random()) print('3rd random int = ', random.randint(1, 100)) print('4th random int = ', random.randint(1, 100))
Below image shows the output produced by the python random seed example program. We will get the same sequence of random numbers for each run.
Python Random List – choice(), shuffle(), sample()
There are some functions to use randomness in a sequence. For example, using
choice() function you can get a random element from a sequence.
Again, using
shuffle() function you can shuffle the elements in a sequence.
Also, using
sample() function you can get x number of elements from a sequence randomly. So, let’s see the following code for random list example.
import random as rand # initialize sequences string = "inconvenience" l = [1, 2, 3, 4, 10, 15] # get a single element randomly print('Single character randomly chosen :', rand.choice(string)) print('one randomly chosen number :', rand.choice(l)) # get multiple element print('Randomly chosen 4 character from string :', rand.sample(string, 4)) print('Randomly chosen 4 length list :', rand.sample(l, 4)) # shuffle the list rand.shuffle(l) print('list is shuffled :', l) # print the list
You may get output like the following.
Single character randomly chosen : i one randomly chosen number : 10 Randomly chosen 4 character from string : ['e', 'c', 'n', 'n'] Randomly chosen 4 length list : [2, 10, 3, 15] list is shuffled : [2, 4, 15, 3, 10, 1]
So, that’s all for python random number. To know more, see their official documentation.
where can i find some real time projects to work in python. I am new to python and unable to find a project in companies as they require prior working project experience. If i could work in some projects that i find online, it will be of help to me. | https://www.journaldev.com/16134/python-random-number | CC-MAIN-2021-10 | refinedweb | 803 | 60.11 |
Summary: Guest bloggers Microsoft PFEs Adam Haynes and Shubert Somer continue their .NET Framework Essentials post by talking about assemblies.
Microsoft Scripting Guy, Ed Wilson, is here. Today is part 4 of a 5-part series written by guest blogger Adam Haynes with help from his friend Shubert Somer. You will want to go back and read part 1, part 2, and part 3 (if you have not already done so) before you read today’s blog.
Here’s Adam …
Shubert warned me about this “simple” blog post on .NET Framework Essentials. I am paraphrasing here, but it’s like getting too close to a black hole. Black holes are cool as is mixing .NET Framework and Windows PowerShell, but if you get close enough to have a peek over the edge, it’s too late and you’re getting sucked in. We tried to keep it simple, and so far, we have talked about: type/class, object, method, constructor, property, and members. While this is not an all-encompassing list of .NET terminology, we actually glossed over a rather important topic.
Remember when I said that in order for the script in the previous post to work you needed to have the Active Directory module available/installed? There is a very specific reason for this. The script did use several cmdlets that are part of the Active Directory module (installed with RSAT), but the part we glossed over was the System.DirectoryServices.ActiveDirectory assembly. Loading the Active Directory module into the Windows PowerShell console, loads the assembly for us.
I don’t want you to have to click back and forth between posts, so we are going to continue this post with a new sample to introduce this new concept and reiterate the previous learning. This script gives us access to Windows Forms objects. I know what you’re thinking. We spent all this time talking about how cool Windows PowerShell is and now I want you to go back to a GUI!? Well, not exactly, and here is why: while I love PowerShell, some users of the scripts I produce and assist with are a little gun shy when it comes to the blinking cursor in the deep blue box.
This little snippet pops open the dialog box we are all used to in the GUI when opening a file for input. It can be a nice thing to have if you are asking for files from the user, and they are not comfortable in the Shell (or if you are lazy like me).
>
Most of this should be familiar to you, but line 1 looks oddly familiar—odd in that I have no idea what reflection.assembly means, and familiar because it looks like a static method. Why is it important or necessary, you ask? Because this is what the script returns when we don’t use it.
It seems that Windows PowerShell doesn’t know about the OpenFileDialog constructor, for some reason. I thought PowerShell was all knowing and all seeing? I want to turn it back over to Shubert, because that one line of the script will consume most of this post. That one line will also allow you to reach into .NET Framework and access whatever Microsoft technology you are working with.
Shubert: There is a lot going on with that one line, so naturally I want to give some background to put it in to context. The way we deliver modular code, that is, code that has a chunk of functionality that can be reused, is to package stuff into DLLs (DLL stands for Dynamic Link Library, which is code that can be loaded into memory and executed on-demand). Back in the pre-.NET days, I liked to compare Windows programs to a bucket of marbles, with each marble representing a DLL. Installing a program was like emptying the bucket into your basement, and uninstalling was like telling one of your kids to go down in the basement and pick up all the green marbles. Keeping track of all the marbles was something known as DLL Hell.
Enter .NET … instead of a bucket of marbles, .NET Framework is more like having a bag of marbles with a little “contents” label. Installing a .NET program is more like putting the bag of marbles in a bag of marbles shelf in your basement, where you keep everything in alphabetical order. Mostly.
“Gee, that doesn’t sound much better,” you may think, but actually it is. It’s easier to find the bag of marbles you are looking for, and the label tells you which marbles are inside and what they do. The bags of marbles are like .NET assemblies, and the label on the bag is what reflection is for .NET Framework.
Like all things in .NET, reflection is actually just another set of .NET objects, and so they have their own sets of properties and methods. Because they are mostly utility-like things, many of these are static. The .NET technical term for reflection is a namespace, and it is very important to understand the difference between a namespace, an assembly, and a class.
Namespaces are just labels that are used to allow classes from different assemblies to have the same name and not interfere with each other. Much like classes form a container, or boundary, for their members (so many different classes can have an “Open()” method, for example), namespaces form a container for classes with the same name. Native .NET namespaces start with “System” (this is the root of the .NET namespace universe). The convention for application-specific namespaces is to start them with {CompanyName}.{ProductName}. So, for example, you may see Microsoft.Office.{some more stuff} for Office-related classes.
An assembly is a packaged chunk of functionality (the .NET equivalent of a DLL). Almost universally an assembly will consist of exactly one file (either a DLL or an EXE). To make things confusing, the naming convention for assemblies is very similar to the naming convention for namespaces. Be warned: they are not the same thing! An assembly may contain classes from many namespaces, and a namespace may cover many assemblies. Although not strictly correct, you can think of the assembly as the physical file containing the executable code and a namespace as a category to organize all the code that relates to a particular area.
So now, this line might start to make sense. Reflection is the namespace that tells Windows PowerShell exactly which assembly class to use (the full namespace is “System.Reflection”, but the left-most parts of the namespace can be dropped as long as it does not lead to any ambiguity—if it does, then Windows PowerShell should complain with some kind of “unable to resolve object path” message). The assembly class has a bunch of static methods for handling assemblies. We are using the method that will load the desired assembly (some file on disk) into memory so that it can be accessed by Windows PowerShell.. If you are looking in MSDN for how to load the assembly that you need to access that cool class you found, check for the assembly name—it may be different (sometimes much different) from the class namespace!
MSDN Reference:
Adam: Well, I have to say that after listening to that in person, I was less smart than before we talked. After reading that a few times, I think it has sunk in. In the example from part 1 of the series, we didn’t need any if this because the Import-Module cmdlet did this work for us. The developers that wrote the module knew they needed the DirectoryServices namespace, so the Active Directory module has this type of code in it, and we don’t have to deal with it as administrators.
Now that we know why line 1 is so important, you might ask why we talked about it at the end? Well, if we started with that, do you know many admins that would have read this far? J I know that when Shubert tried to start out teaching me that one, I was reaching for the fake phone call to bail. We are almost done. In the final post, we will take this new-found knowledge and apply it line by line to the script we introduced in this post.
~Adam
Thank you, Adam and Shubert. any particular reason why you've used [reflection.assembly]::loadwithpartialname("system.windows.forms") instead of Add-Type -AssemblyName System.Windows.Forms?
Note: Readers who use PowerShell ISE to run your code won't see the error, because PowerShell ISE is loading the System.Windows.Forms assembly by default. You might add a note that powershell.exe and powershell_ise.exe don't provide the same assemblies by default.
@jeff yao – PowerShell has been object oriented since its inception. It is a scripting language not a development language so no we don’t create classes, we simply use existing classes to automate tasks. To work as an administrator, I don’t need any special development tools to gain access to the .Net framework. The lines are definitely blurred, but everything in PowerShell is an object. If there is anything specific I can clarify, please let me know.
@Aleksandar Nikolić – Great point on loading the assembly. The goal of the series is to expose administrators to .Net. It was a good segue into reflection and I simply overlooked loadwithpartialname. Shubert worked up a change, so we will try to get the post updated soon.
I have to echo Aleksandar's concern here, as an "expert" here, should not the blogger know LoadWithPartitialName is long considered as depreciated?
To be honest, this series of blog brings me more confusion than value, esp. when I read in the previous blog (part 2) that said "Powershell is object oriented", so when does PS become an OO language? can it create a new class itself? or maybe I know too little (quite possible of course)
@jeff yao
Tell us what in POwerShell is NOT an object. Everything in PowerShell is inherited from System, Microsoft or any other base class we choose to define. Even a lowly 'int' is an object.
Where is there any indication that htere are no objects.
@jeff yao
I almost forgot. Yes – we can create classes (types) in PowerShell. NOw it is up to you to figure out how we do this.
This was a very helpful post. Thank you.
After reading it’s more confusing specially not sample to explan each terms you use, like assembly, namespace, convention that should be used. I’m a beginner and i don’t understand how your explanation can help me to find for exemple what mean this part
of code $expression = new-object Microsoft.SystemsManagementServer.DesiredConfigurationManagement.Expressions.Expression -ArgumentList $arg.
I try in google this to seahc about Microsoft.SystemsManagementServer.DesiredConfigurationManagement.Expressions.Expression coz i need to understand what is this object, what is contructor and propety and methods but i found nothing exept some samples :(. Waht
is it an assembly ? for me it’s an object so mean there is a Class definition somewhere, but where found those information. Hope you Understand what i mean.
Sorry if i may be in a wring forum but it’s 2 days i seach on internet to understand sample i found to make automatic thing for SCCM2012 and the only documentation in MSDN is too poor or not exist.
I can load assembly using above method for this:
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
$openFile = New-Object System.Windows.Forms.OpenFileDialog
$openFile | Get-Member
But I can’t load for SharePoint:
[reflection.assembly]::loadwithpartialname("Microsoft.SharePoint.Publishing") | Out-Null
$obj = New-Object Microsoft.SharePoint.Publishing.Design
$obj | Get-Member
Is there a reason why I am not able to load SharePoint assembly. Always getting below error even using Add-Type:
New-Object : Cannot find type [Microsoft.SharePoint.Publishing.Design]: verify that the assembly containing this type is loaded. | https://blogs.technet.microsoft.com/heyscriptingguy/2013/01/21/using-net-framework-assemblies-in-windows-powershell/ | CC-MAIN-2017-17 | refinedweb | 2,006 | 64.41 |
A Flutter plugin providing signature pad for drawing smooth signatures. Library is written in pure Dart/Flutter environment to provide support for all platforms..
Easy to use library with variety of draw and export settings.
Signature pad drawing is based on Cubic Bézier curves.
Usage
import 'package:hand_signature/signature.dart';
With HandSignatureControl and HandSignaturePainterView is possible to tweak some drawing aspects like stroke width, smoothing ratio or velocity weight.
final control = HandSignatureControl( threshold: 3.0, smoothRatio: 0.65, velocityRange: 2.0, ); final widget = HandSignaturePainterView( control: control, color: Colors.blueGrey, width: 1.0, maxWidth: 10.0, type: SignatureDrawType.shape, );
HandSignatureControl sets up 'math' to control input touches and handles control points of signature curve.
- threshold: (LP) controls minimal distance between two points - higher distance creates smoother curve, but less precise. Higher distance also creates bigger input draw lag.
- smoothRatio: (0 - 1) controls how smooth curve will be - higher ratio creates smoother curve, but less precise. In most of cases are best results with values between 0.5 - 0.75.
- velocityRange: (LP per millisecond) controls curve size based on distance and duration between two points. Thin line - fast move, thick line - slow move. With higher velocityRange user must swing faster to draw thinner line.
- reverseVelocity: swaps stroke width. Thin line - slow move, thick line - fast move. Simply swaps min/max size based on velocity.
HandSignaturePainterView sets up visual style of signature curve.
- control: processes input, handles math and stores raw data.
- color: just color of line.
- width: minimal width of line. Width at maximum swing speed (clamped by velocityRange).
- maxWidth: maximum width of line. Width at slowest swing speed.
- type: draw type of curve. Default and main draw type is shape - not so nice as arc, but has better performance. And line is simple path with uniform stroke width.
Export
Properties, like canvas size, stroke min/max width and color can be modified during export.
There are more ways and more formats how to export signature, most used ones are svg and png formats.
final control = HandSignatureControl(); final svg = control.toSvg(); final png = control.toImage();
Of course draw type is also supported during export. SignatureDrawType shape generates reasonably small file and is read well by all programs. On the other side arc generates really big file and some programs can have hard times handling so much objects.
Export to image supports ImageByteFormat and provides png or raw rgba data.\
Parsing
Exported svg is possible to display in classic flutter_svg widget.
Or use build in HandSignatureView for greater control.
final widget = HandSignatureView.svg( data: svgString, strokeWidth: (width) => width * 0.35, padding: EdgeInsets.all(16.0), placeholder: Container( color: Colors.red, child: Center( child: Text('not signed yet'), ), ), );
Signature is automatically centered and fills given area.
Currently stroke width can be controlled only for line and arc exports.
HandSignatureView handles most of svg files, but is optimized for drawing signatures created with this library and don't provide all features like flutter_svg.
Contribution
Any contribution is highly welcomed.
Library is in good condition, but still in early development.
Mainly to improve smoothing and line weight to better match real signature.
Remove dependency to flutter_svg and make library dependent only on path_drawing or path_parsing.
Performance can be always better..
Also currently there are no tests or documentation. | https://pub.dev/documentation/hand_signature/latest/ | CC-MAIN-2021-31 | refinedweb | 542 | 53.78 |
This article describes a timer component that allows timing to be done to an accuracy of microseconds.
One of the tasks in software development that is often overlooked is performance testing. Most of the time, code is designed to run fast and then tested to make sure that it really is. Whilst there are many ways to test performance and identify slow bits of code, it is quite often difficult to precisely locate or time, specific sections of the code. Using normal time functions, including timer tick functions is only accurate to milliseconds at best. Also, you don't want to have to copy library classes or lots of code around in order to simply time a piece of code. Because of this, I decided to write a general purpose timer that would:
In order to have a timer that has a resolution in the order of microseconds, there are 2 possibilities that I am aware of:
RDTSC
QueryPerformanceCounter
Although the first option is the most accurate and fastest, I decided to use the second option because that is much more portable. QueryPerformanceCounter is supported on all Windows platforms, including Pocket PC devices.
The second requirement was for the timer to be very easy to use. It was fairly obvious to me that the timer should be a strongly named class so that it could be put in the GAC. This would make it very easy to include in an assembly. I also felt that it would be even easier to use if it was a component. That way, if timing was being done on a form (Windows or Web), the component could be dragged from the toolbox onto the page.
The component is very simple to use and has 2 main methods:
Reset()
Trace()
The code relies on the two API calls:
QueryPerformanceFrequency
These are defined in KERNEL.DLL on Windows platforms, and CoreDll.dll on the Pocket PC, and are called using P/Invoke as follows:
#if NET_CF
[System.Runtime.InteropServices.DllImport("CoreDll.dll")]
#else
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
#endif
private static extern int QueryPerformanceFrequency(ref Int64 lpFrequency);
#if NET_CF
[System.Runtime.InteropServices.DllImport("CoreDll.dll")]
#else
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
#endif
private static extern int QueryPerformanceCounter(ref Int64 lpPerformanceCount);
NET_CF should be defined in the build settings if the library is going to be used on the Pocket PC.
NET_CF
The component contains a property called Time_us which is read-only and returns the elapsed time as follows:
Time_us
public double Timer_us
{
get
{
QueryPerformanceCounter(ref m_LastCount);
Int64 Count = m_LastCount;
Count -= m_TimerStartCount;
return (double)Count / (double)m_TimerFreq * 1000000.0;
}
}
The Reset and Trace methods are implemented as follows:
Reset
Trace
public void Reset()
{
QueryPerformanceFrequency(ref m_TimerFreq);
QueryPerformanceCounter(ref m_TimerStartCount);
}
public void Trace(string msg)
{
double t1 = Timer_us;
Int64 c1 = m_LastCount;
StringBuilder s1 = new StringBuilder();
if (t1 < 1000)
s1.AppendFormat("{0} Time = {1} us", msg, t1.ToString("F2"));
else if (t1 < 1000000)
s1.AppendFormat("{0} Time = {1} ms", msg, (t1/1000).ToString("F2"));
else
s1.AppendFormat("{0} Time = {1} s", msg, (t1/1000000).ToString("F2"));
System.Diagnostics.Trace.WriteLine(s1);
//...trace compensation needed here!
}
The Trace.WriteLine statement takes a considerable time to execute (milliseconds). As the code is at the moment, this would seriously affect the displayed times. In order to try and compensate for this, I decided to get the time after the Trace statement has executed and subtract this from the start time. This means that if you call Trace continuously, you will get times that are different by about 1 or 2 us instead of times that are different by milliseconds. Although this means the displayed time is not a true indication of the elapsed time, I felt that this behavior was more useful. Unfortunately, I could not reliably compensate for the QueryPerformanceCounter call, so continuous calls to Trace resulted in increasing times of about 1.4us on my PC. Most of this time is because of the P/Invoke overhead. The code for this is shown below:
Trace.WriteLine
double t2 = Timer_us;
Int64 c2 = m_LastCount;
m_TimerStartCount += (c2-c1); //Take account of the trace statement
The final part of the implementation is the deployment of the component. I wrote a batch file (as part of the build process) to copy the assembly to the Visual Studio directory and install it in the global assembly cache. This way, it can easily be added to the References and Component Toolbox. (In the Add References dialog, look for "Nethercott.Timing". And in the Add/Remove Items dialog in the Toolbox, look for "StopWatch".) Obviously, the component only has to be added once to the toolbox (e.g., under the Components tab) in order to be used on multiple solutions.
The component is very easy to use. There are two ways that it can be included. The easiest way is to drag the component from the toolbox onto a Windows or Web Form. The Reset() and Trace() methods can then be called as required in the code behind page. The other way to use the component is to include the component manually. This means adding a reference to the class, constructing the StopWatch object, and then calling the Reset() and Trace() methods as required. Although not absolutely necessary, it's probably a good idea to call Dispose() when the object is no longer required.
StopWatch
Dispose()
There are several other CodeProject articles on timing, and timer classes. Here are some of them:
This is a very detailed article that shows how you can include performance measures as part of your unit tests. It also shows how to limit the misleading effect of JIT compilation, garbage collection, and task switching, to make the results more reliable.
This is using QueryPerformanceCounter and RDTSC to calculate the processor speed.
General purpose timing classes (using QueryPerformanceCounter).
General purpose timer class for C++.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
void TimeStuff()
{
// Instantiate a timer
StopWatch timer = new Stopwatch();
// Start the timer
timer.Reset();
// Do some stuff
DoStuff();
// Print the timing to the trace log.
timer.Trace("Stuff done.");
}
void Reset()
void Start()
double Timer_us
TimeSpan Current
Current
void Trace()
void Trace(string msg)
TimeSpan Trace()
TimeSpan Trace(string msg)
string ToString()
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/7764/Easy-to-use-Performance-Testing-Component?msg=881037 | CC-MAIN-2015-18 | refinedweb | 1,073 | 54.52 |
- PopUp
- DNS Server
- Accessing multiple NTFS filestreams using the framework
-
- Software Engineering...
- New .NET related new portal
-
- viewing emails on exchange
- help: how to config to use dotnet's quickstart?
-
- ssl
- Confirm understanding - web service exceptions
- Need help- Dataview row index issue
- Intercept Data Sent to Print and Insert into Database
- Windows services and GetObject
- WSHNetwork.AddWindowsPrinterConnection in VB.NET
- JIT Debugging - Access is denied
- Debugging MS SQL Server procedured within Visual Studios .NET
- Socket.BeginReceive()
- Convert WMF to greyscale without losing resolution?
- Position Cursor
- disconnecting from the internet
- Calendar Control non hyperlink dates
- OWC 10 Chart control question......
- how to search with the MSDN web-based client?
- Component Class
- How to work with commandbuilder and transactions ?????
- IDE Bug
- Reformat Number on Databinding
- Crystal Report Viewer Issue
- Windows Installer - "A portion of the folder path '' is invalid"
- How to make Object type comparision ??
- Version Management
- Debugger is not properly installed
- Tumbnails in .NEt
- Specifying a network share with FSO
- How to open a html file in internet explorer
- Removing from GAC
- Struct marshaling Problem
- Dart PowerFTP File Transfer Error
- c# passing objects as method parameters??
- aspnet_wp.exe says no permission!
- How to fetch CPU Usage from DOT Net
- How to test for Multiple Users ?
- shaped form
- Server Application Unavailable Error
- menu graphics
- DTS programming
- Getting XML via HTTP secured with ACL
- DataGrid
- System.Configuration.ConfigurationException
- Embedding a manifest file
- Type class in config file ???
- Crystal Report Datetime formatting problem
- String Builder - not appended
- PLease help Application Configuration file access error ???
- difference between vb and vb.net
- Refering a COM component in VS.NET
- dataset error
- FYI: System.Security.SecurityException: Failure decoding embedded permission set object.
- howto : frameset ???
- How to write a batch to compile .net projects?
- dataset manipulation
- Cannot register VS .NET
- How to do a Task Manager 'Switch To'?
- Retrieving browser information with ASP.NET
- Windows 2000 Crash after installing Visual Stuido .NET 2003
- Application Unavailable
- Windows Service - run only Once a day
- multi-panel form and validators
- Is this custom-control buildable?
- Storing Code Snipets
- .net cannot contact localhost..HELP!
- Cannot remove a .NET assembly from GAC
- Error in Event Viewer after installing Desktop SQL Server
- dumpbin.exe
- I need dncdev00.hxs
- Dll
- 3 Simple Questions
- Number of Specific Files in A Directory
- Enumeration Format Strings. Difference between g and f?
- Best way to use XML and HTML to maintain Data.
- Validating Newlines and Carriage Returns via Schema
- [DocBook] binary imagedata
- XSLT - How can I find out the name of an Element
- Namespaces and Custome DTD's
- Create XML schema with xerces-c
- HTML to XML transform
- How widely used is Docbook?
- Tri-XML 2005 -- Annual Conference, July 28-29, 2005 -- McKimmon Center
- question regarding "graphML"
- How to know the length of text in SVG (in advance) ??
- Announcing sTToXML XML Data Conversion Service
- analysing an XML document and validating with a schema ...
- Resources For A Beginner
- Core XML attributes
- Docbook titlepage with 2 images
- (patch for Bash) GTK+2 + Bash
- XML Forum
- Parsing node names
- XSLT generates values, but not tags
- Text search using parameter
- XML/XSD/XSL Display Problem
- PHP generating XML
- creating a link in XSLT
- using XPathAPI with xalan extension functions
- can't get the xpath working
- Number hierarchically across heterogeneous elements
- using libxml
- a CSS problem (annotating a novel, horizontal flush alignment)
- WSDL configuration
- Cannot set background color (XML+CSS)
- Problem with xml:variable in xsl:for-each
- saving WordML as XML data only/boilerplate text
- Using param value in xpath
- remove XHTML from XML source file
-?
- Open Source Software Directory
- XML editor using only indentation for nesting?
- Saxon and XQuery : how not to repeat the XML source file name in the query ?
- XSL / XPATH: how to test if text contains apostrophe
- getting name and value of tag in an XML.
- SVG: attributes relativ to other elements / special anchors ??
- Problems with UTF-8 characters and XSLT
- Define RDMBS structure via XSD ?
- Sort xml and write to xml
- Custom XML tags in BackBase
- Empty element match
- XPath error with xsltproc/libxslt
- TEI book ann.
- XML FAQ 4.2
- strictly, <p> inside <div> ok?
- XSL sorting problem
- Line breaks in text mode for XSLT
- libxml2 overhead?
- Write to XML file client side
- xml encoding
- XSL select emplty nodes
- Representing BNF grammer using XML
- XSL matches in RSA/eclipse, not with Xalan 2.5.1
- Problem: <img></img>
- Fragment parsing
- XML parser
- output RSS with ASP
- Schema building help
- Append XML using ASP
- XSL ability to select node by links?
- Bullets not rendering properly
- Reomoval of name space attribute
- Parsing large XML files FAST
- Tri-XML 2005 (Conference notice; July 28-30th)
- rss feed repository or directory
- XSL Umformung
- xsl:for-each with [not(@Name=preceding::*/@Name)] not working
- xmlns:xsd generation problem
- how to validate a non empty element with only attributes
- Need to do a "book style" Table of Contents
- XML schema - Make xsd include another xsd
- XSLT Scripting Question
- XML Schema Google Web Service
- validate element with attribute soapenv:encodingStyle="..."
- Split file that contains multiple XML
- manual management tooling
- Create tag names via XSL
- syntax of 'nested' tags
- open HTML tags problem
- Generating HTML image map from a SVG file
- Reporting line number of parse exception?
- web apps using php to generate xml
- Simple C++ HTTP+XML server
- Looking for an XML (database-based) Query Reporting Tool/advice
- XML & XSLT gallery confused
- XPath Expression
- HTML Decode and CDATA Problems
- html String from Xml in Xlst
- What am I doing wrong in this XPath expression?
- JDOM and SVG fonts
- RXP parser
- standoff XML markup tools?
- Book: Document Object Model (Developers Guide) - Joe Marini on ebay
- XML transform inconsistency with different processors
- Question about createTextNode in xml files
- Offline XHTML validator ?
- galax and jbuilder integration
- Easy Schema Question About Naming Convention
- XSLT Simple Question
- xml schemas - work around the min=1 max=1 in the 'all' group
- Validating XML against XSD
- MSXML4 - parsing XML Leaves with multiple parameters
- Defaulting empty attributes to nbsp
- XPATH evaluation with libxml
- Search Function with XML Results
- Simple (?) question
- XSL-FO Question
- Google rankings when going from html to xml
- Building minimal latex from scratch?
- Absolute Path in Document() in a xsl
- XSLT for Dummies available
- XSLT question: how to use params as strings
- XQuery status
- How to model data in XML?
- Using xsl to generate html with embedded content
- parsing xsd using xerces
- Can you query from a non-root node using XPathAPI?
- defining schema for recursive element
- Render XML structure using XSLT
- validate element with attribute xsi:type="xsd:string"
- test existence of a similar node with same key name
- Content model ANY
- xs:element with two types (xs:string and xs:int)
- Open XML in excel problem
- Using XSLT to convert adhoc element name to attribute name
- HTMLSerializer with xalan
- Transforming XML containing Asian characters?
- Elements within elements
- Translate Euro Sign(€) in 'EUR'
- XQuery ( XML Query )
- XSLT/XPath help
- Reusing XML Processing Code in non-XML Applications
- XML Transformation
- Survey definition formats
- Exchangeable top-elements in XML Schema?
- XPath expression
- MathML to SVG
- June meeting of the Philadelphia XML User Group
- Validation of XUpdate
- relationshipbetween ebXML and BPEL
- Another new question
- parent::*/preceding-sib*ling::tagname VS parent::preceding-sib*ling::tagname
- Problems with <xsl:param name Help!
- Populate XML & change attribute
- String parsing in XSL & XPath
- pathelement with javac
- Showcase of useful pipelines from Markup Technology
- accented characters
- Query with subelements inside words
- RDBMS table definition to WordXML Word table
- need test expression for all "unhandled" text
- Translate schema -> schema
- RSS 2.0 feed namespace problem
- defining dynamic sized tables in XML schema...
- my select statement only works on first listed of repeatable element
- XSLT: need help with xsl:for-each
- Php into XML
- uuid field
- Combining characters separated by markup
- Can I keep metadata for each item of RSS feed ?
- XSLT: looking help with XPath-expression
- How to build a Multilingual XML file ?
- xsl:function does abort just after the call of the function
- XSLT: select n-th element (how to use position?)
- web page build on XML/XSL
- where on the web are the characters for UTF-8 listed in dec or hex value?
- What does this do: <xsl:apply-templates
- XML FAQ
- Using XML in multilingual website pages
- Tool that generates xsl:template tags from xsd?
- XML - why???
- Strings of an xml element using XSL and XPath
- XSL Question tp xsl:for-each and xsl:variable
- XSLT: concat and quotes
- Which XML open-source parsers is the fastest
- handling commonality in similar XSD schemas
- Compare 2 XML using XSLT
- XPath Relational Query
- XML - schema and data
- Xml2PDF version 2.3 with support for WordML is released
- >> Simple question about escaping content in XSL
- XSLT: how to match attribute having a specific value?
- xsd+data = xml
- simple XPATH question
- Flattening out an XML document
- strengths and weaknesses/limitations of Relax NG
- Wysiwyg XSTL editor
- Query on text and element nodes
- XML Key Validation
- Modify two parts of a page independently
- Test SOAP client
- Users of XMetaL 2.x and 3.x
- Global variable not working in my XSL
- Bluetooth xml service/device descriptor
- Help with asp - xml
- Use styles AND collapsable tree display?
- docbook customization stylesheet
- new line in node's content
- Help on xslt - grouping
- Sort XML
- Can you add additional elements to XHTML 1.0 page?
- XSLT for filtering XML based on attribute value?
- Reading output xml in the same XSLT, which perform the transformation
- XSD Restricting Anytype behaviour
- displaying xml with indents
- XSLT Select Text; Add href
- XSL Page Output
- XSLT Dynamic Table Column Headers and Rows
- setting currentScale, currentTranslate.x, currentTranslate.y
- Why isn't fixed considered a restriction?
- xpath query query
- A better xPath statement
- thesis topics in xml
- xsd (XML Schema) to c++ code generator
- select only the first node from a for-each loop that contains a specific element
- Reject an attribute that has only spaces in schema
- edit SimpleTable XML in a spreadsheet-type GUI without extra formatting
- NEW TO COCOON
- TEI Questions
- HTML Form Action and XML Syntax Problem
- XSL: SUM BY GROUP
- Correct use of externalRef sought
- "XSL FO" first row in a table after a page break
- path to node as a string
- simple xslt problem/question
- XML tools for merging tables | https://bytes.com/sitemap/f-312-p-212.html | CC-MAIN-2019-43 | refinedweb | 1,698 | 50.97 |
> cygwin-1.3.17-1-src.rar > aout64.h
/* `a.out' object-file definitions, including extensions to 64-bit fields __A_OUT_64_H__ #define __A_OUT_64_H__ /* This is the layout on disk of the 32-bit or 64-bit exec header. */ #ifndef external_exec struct external_exec { bfd_byte e_info[4]; /* magic number and stuff */ bfd_byte e_text[BYTES_IN_WORD]; /* length of text section in bytes */ bfd_byte e_data[BYTES_IN_WORD]; /* length of data section in bytes */ bfd_byte e_bss[BYTES_IN_WORD]; /* length of bss area in bytes */ bfd_byte e_syms[BYTES_IN_WORD]; /* length of symbol table in bytes */ bfd_byte e_entry[BYTES_IN_WORD]; /* start address */ bfd_byte e_trsize[BYTES_IN_WORD]; /* length of text relocation info */ bfd_byte e_drsize[BYTES_IN_WORD]; /* length of data relocation info */ }; #define EXEC_BYTES_SIZE (4 + BYTES_IN_WORD * 7) /* Magic numbers for a.out files */ #if ARCH_SIZE==64 #define OMAGIC 0x1001 /* Code indicating object file */ #define ZMAGIC 0x1002 /* Code indicating demand-paged executable. */ #define NMAGIC 0x1003 /* Code indicating pure executable. */ /* There is no 64-bit QMAGIC as far as I know. */ #define N_BADMAG(x) (N_MAGIC(x) != OMAGIC \ && N_MAGIC(x) != NMAGIC \ && N_MAGIC(x) != ZMAGIC) #else #define OMAGIC 0407 /* ...object file or impure executable. */ #define NMAGIC 0410 /* Code indicating pure executable. */ #define ZMAGIC 0413 /* Code indicating demand-paged executable. */ #define BMAGIC 0415 /* Used by a b.out object. */ /* This indicates a demand-paged executable with the header in the text. It is used by 386BSD (and variants) and Linux, at least. */ #ifndef QMAGIC #define QMAGIC 0314 #endif # ifndef N_BADMAG # define N_BADMAG(x) (N_MAGIC(x) != OMAGIC \ && N_MAGIC(x) != NMAGIC \ && N_MAGIC(x) != ZMAGIC \ && N_MAGIC(x) != QMAGIC) # endif /* N_BADMAG */ #endif #endif #ifdef QMAGIC #define N_IS_QMAGIC(x) (N_MAGIC (x) == QMAGIC) #else #define N_IS_QMAGIC(x) (0) #endif /* The difference between TARGET_PAGE_SIZE and N_SEGSIZE is that TARGET_PAGE_SIZE is the finest granularity at which you can page something, thus it controls the padding (if any) before the text segment of a ZMAGIC file. N_SEGSIZE is the resolution at which things can be marked as read-only versus read/write, so it controls the padding between the text segment and the data segment (in memory; on disk the padding between them is TARGET_PAGE_SIZE). TARGET_PAGE_SIZE and N_SEGSIZE are the same for most machines, but different for sun3. */ /* By default, segment size is constant. But some machines override this to be a function of the a.out header (e.g. machine type). */ #ifndef N_SEGSIZE #define N_SEGSIZE(x) SEGMENT_SIZE #endif /* Virtual memory address of the text section. This is getting very complicated. A good reason to discard a.out format for something that specifies these fields explicitly. But til then... * OMAGIC and NMAGIC files: (object files: text for "relocatable addr 0" right after the header) start at 0, offset is EXEC_BYTES_SIZE, size as stated. * The text address, offset, and size of ZMAGIC files depend on the entry point of the file: * entry point below TEXT_START_ADDR: (hack for SunOS shared libraries) start at 0, offset is 0, size as stated. * If N_HEADER_IN_TEXT(x) is true (which defaults to being the case when the entry point is EXEC_BYTES_SIZE or further into a page): no padding is needed; text can start after exec header. Sun considers the text segment of such files to include the exec header; for BFD's purposes, we don't, which makes more work for us. start at TEXT_START_ADDR + EXEC_BYTES_SIZE, offset is EXEC_BYTES_SIZE, size as stated minus EXEC_BYTES_SIZE. * If N_HEADER_IN_TEXT(x) is false (which defaults to being the case when the entry point is less than EXEC_BYTES_SIZE into a page (e.g. page aligned)): (padding is needed so that text can start at a page boundary) start at TEXT_START_ADDR, offset TARGET_PAGE_SIZE, size as stated. Specific configurations may want to hardwire N_HEADER_IN_TEXT, for efficiency or to allow people to play games with the entry point. In that case, you would #define N_HEADER_IN_TEXT(x) as 1 for sunos, and as 0 for most other hosts (Sony News, Vax Ultrix, etc). (Do this in the appropriate bfd target file.) (The default is a heuristic that will break if people try changing the entry point, perhaps with the ld -e flag.) * QMAGIC is always like a ZMAGIC for which N_HEADER_IN_TEXT is true, and for which the starting address is TARGET_PAGE_SIZE (or should this be SEGMENT_SIZE?) (TEXT_START_ADDR only applies to ZMAGIC, not to QMAGIC). */ /* This macro is only relevant for ZMAGIC files; QMAGIC always has the header in the text. */ #ifndef N_HEADER_IN_TEXT #define N_HEADER_IN_TEXT(x) \ (((x).a_entry & (TARGET_PAGE_SIZE-1)) >= EXEC_BYTES_SIZE) #endif /* Sun shared libraries, not linux. This macro is only relevant for ZMAGIC files. */ #ifndef N_SHARED_LIB #if defined (TEXT_START_ADDR) && TEXT_START_ADDR == 0 #define N_SHARED_LIB(x) (0) #else #define N_SHARED_LIB(x) ((x).a_entry < TEXT_START_ADDR) #endif #endif /* Returning 0 not TEXT_START_ADDR for OMAGIC and NMAGIC is based on the assumption that we are dealing with a .o file, not an executable. This is necessary for OMAGIC (but means we don't work right on the output from ld -N); more questionable for NMAGIC. */ #ifndef N_TXTADDR #define N_TXTADDR(x) \ (/* The address of a QMAGIC file is always one page in, */ \ /* with the header in the text. */ \ N_IS_QMAGIC (x) \ ? (bfd_vma) TARGET_PAGE_SIZE + EXEC_BYTES_SIZE \ : (N_MAGIC (x) != ZMAGIC \ ? (bfd_vma) 0 /* object file or NMAGIC */ \ : (N_SHARED_LIB (x) \ ? (bfd_vma) 0 \ : (N_HEADER_IN_TEXT (x) \ ? (bfd_vma) TEXT_START_ADDR + EXEC_BYTES_SIZE \ : (bfd_vma) TEXT_START_ADDR)))) #endif /* If N_HEADER_IN_TEXT is not true for ZMAGIC, there is some padding to make the text segment start at a certain boundary. For most systems, this boundary is TARGET_PAGE_SIZE. But for Linux, in the time-honored tradition of crazy ZMAGIC hacks, it is 1024 which is not what TARGET_PAGE_SIZE needs to be for QMAGIC. */ #ifndef ZMAGIC_DISK_BLOCK_SIZE #define ZMAGIC_DISK_BLOCK_SIZE TARGET_PAGE_SIZE #endif #define N_DISK_BLOCK_SIZE(x) \ (N_MAGIC(x) == ZMAGIC ? ZMAGIC_DISK_BLOCK_SIZE : TARGET_PAGE_SIZE) /* Offset in an a.out of the start of the text section. */ #ifndef N_TXTOFF #define N_TXTOFF(x) \ (/* For {O,N,Q}MAGIC, no padding. */ \ N_MAGIC (x) != ZMAGIC \ ? EXEC_BYTES_SIZE \ : (N_SHARED_LIB (x) \ ? 0 \ : (N_HEADER_IN_TEXT (x) \ ? EXEC_BYTES_SIZE /* no padding */ \ : ZMAGIC_DISK_BLOCK_SIZE /* a page of padding */))) #endif /* Size of the text section. It's always as stated, except that we offset it to `undo' the adjustment to N_TXTADDR and N_TXTOFF for ZMAGIC files that nominally include the exec header as part of the first page of text. (BFD doesn't consider the exec header to be part of the text segment.) */ #ifndef N_TXTSIZE #define N_TXTSIZE(x) \ (/* For QMAGIC, we don't consider the header part of the text section. */\ N_IS_QMAGIC (x) \ ? (x).a_text - EXEC_BYTES_SIZE \ : ((N_MAGIC (x) != ZMAGIC || N_SHARED_LIB (x)) \ ? (x).a_text \ : (N_HEADER_IN_TEXT (x) \ ? (x).a_text - EXEC_BYTES_SIZE /* no padding */ \ : (x).a_text /* a page of padding */ ))) #endif /* The address of the data segment in virtual memory. It is the text segment address, plus text segment size, rounded up to a N_SEGSIZE boundary for pure or pageable files. */ #ifndef N_DATADDR #define N_DATADDR(x) \ (N_MAGIC (x) == OMAGIC \ ? (N_TXTADDR (x) + N_TXTSIZE (x)) \ : (N_SEGSIZE (x) + ((N_TXTADDR (x) + N_TXTSIZE (x) - 1) \ & ~ (bfd_vma) (N_SEGSIZE (x) - 1)))) #endif /* The address of the BSS segment -- immediately after the data segment. */ #define N_BSSADDR(x) (N_DATADDR (x) + (x).a_data) /* Offsets of the various portions of the file after the text segment. */ /* For {Q,Z}MAGIC, there is padding to make the data segment start on a page boundary. Most of the time the a_text field (and thus N_TXTSIZE) already contains this padding. It is possible that for BSDI and/or 386BSD it sometimes doesn't contain the padding, and perhaps we should be adding it here. But this seems kind of questionable and probably should be BSDI/386BSD-specific if we do do it. For NMAGIC (at least for hp300 BSD, probably others), there is padding in memory only, not on disk, so we must *not* ever pad here for NMAGIC. */ #ifndef N_DATOFF #define N_DATOFF(x) ( N_TXTOFF (x) + N_TXTSIZE (x) ) #endif #ifndef N_TRELOFF #define N_TRELOFF(x) ( N_DATOFF (x) + (x).a_data ) #endif #ifndef N_DRELOFF #define N_DRELOFF(x) ( N_TRELOFF (x) + (x).a_trsize ) #endif #ifndef N_SYMOFF #define N_SYMOFF(x) ( N_DRELOFF (x) + (x).a_drsize ) #endif #ifndef N_STROFF #define N_STROFF(x) ( N_SYMOFF (x) + (x).a_syms ) #endif /* Symbols */ #ifndef external_nlist struct external_nlist { bfd_byte e_strx[BYTES_IN_WORD]; /* index into string table of name */ bfd_byte e_type[1]; /* type of symbol */ bfd_byte e_other[1]; /* misc info (usually empty) */ bfd_byte e_desc[2]; /* description field */ bfd_byte e_value[BYTES_IN_WORD]; /* value of symbol */ }; #define EXTERNAL_NLIST_SIZE (BYTES_IN_WORD+4+BYTES_IN_WORD) #endif struct internal_nlist { unsigned long n_strx; /* index into string table of name */ unsigned char n_type; /* type of symbol */ unsigned char n_other; /* misc info (usually empty) */ unsigned short n_desc; /* description field */ bfd_vma n_value; /* value of symbol */ }; /* The n_type field is the symbol type, containing: */ #define N_UNDF 0 /* Undefined symbol */ #define N_ABS 2 /* Absolute symbol -- defined at particular addr */ #define N_TEXT 4 /* Text sym -- defined at offset in text seg */ #define N_DATA 6 /* Data sym -- defined at offset in data seg */ #define N_BSS 8 /* BSS sym -- defined at offset in zero'd seg */ #define N_COMM 0x12 /* Common symbol (visible after shared lib dynlink) */ #define N_FN 0x1f /* File name of .o file */ #define N_FN_SEQ 0x0C /* N_FN from Sequent compilers (sigh) */ /* Note: N_EXT can only be usefully OR-ed with N_UNDF, N_ABS, N_TEXT, N_DATA, or N_BSS. When the low-order bit of other types is set, (e.g. N_WARNING versus N_FN), they are two different types. */ #define N_EXT 1 /* External symbol (as opposed to local-to-this-file) */ #define N_TYPE 0x1e #define N_STAB 0xe0 /* If any of these bits are on, it's a debug symbol */ #define N_INDR 0x0a /* The following symbols refer to set elements. All the N_SET[ATDB] symbols with the same name form one set. Space is allocated for the set in the text section, and each set elements value is stored into one word of the space. The first word of the space is the length of the set (number of elements). The address of the set is made into an N_SETV symbol whose name is the same as the name of the set. This symbol acts like a N_DATA global symbol in that it can satisfy undefined external references. */ /* These appear as input to LD, in a .o file. */ #define N_SETA 0x14 /* Absolute set element symbol */ #define N_SETT 0x16 /* Text set element symbol */ #define N_SETD 0x18 /* Data set element symbol */ #define N_SETB 0x1A /* Bss set element symbol */ /* This is output from LD. */ #define N_SETV 0x1C /* Pointer to set vector in data area. */ /* Warning symbol. The text gives a warning message, the next symbol in the table will be undefined. When the symbol is referenced, the message is printed. */ #define N_WARNING 0x1e /* Weak symbols. These are a GNU extension to the a.out format. The semantics are those of ELF weak symbols. Weak symbols are always externally visible. The N_WEAK? values are squeezed into the available slots. The value of a N_WEAKU symbol is 0. The values of the other types are the definitions. */ #define N_WEAKU 0x0d /* Weak undefined symbol. */ #define N_WEAKA 0x0e /* Weak absolute symbol. */ #define N_WEAKT 0x0f /* Weak text symbol. */ #define N_WEAKD 0x10 /* Weak data symbol. */ #define N_WEAKB 0x11 /* Weak bss symbol. */ /* Relocations There are two types of relocation flavours for a.out systems, standard and extended. The standard form is used on systems where the instruction has room for all the bits of an offset to the operand, whilst the extended form is used when an address operand has to be split over n instructions. Eg, on the 68k, each move instruction can reference the target with a displacement of 16 or 32 bits. On the sparc, move instructions use an offset of 14 bits, so the offset is stored in the reloc field, and the data in the section is ignored. */ /* This structure describes a single relocation to be performed. The text-relocation section of the file is a vector of these structures, all of which apply to the text section. Likewise, the data-relocation section applies to the data section. */ struct reloc_std_external { bfd_byte r_address[BYTES_IN_WORD]; /* offset of of data to relocate */ bfd_byte r_index[3]; /* symbol table index of symbol */ bfd_byte r_type[1]; /* relocation type */ }; #define RELOC_STD_BITS_PCREL_BIG ((unsigned int) 0x80) #define RELOC_STD_BITS_PCREL_LITTLE ((unsigned int) 0x01) #define RELOC_STD_BITS_LENGTH_BIG ((unsigned int) 0x60) #define RELOC_STD_BITS_LENGTH_SH_BIG 5 #define RELOC_STD_BITS_LENGTH_LITTLE ((unsigned int) 0x06) #define RELOC_STD_BITS_LENGTH_SH_LITTLE 1 #define RELOC_STD_BITS_EXTERN_BIG ((unsigned int) 0x10) #define RELOC_STD_BITS_EXTERN_LITTLE ((unsigned int) 0x08) #define RELOC_STD_BITS_BASEREL_BIG ((unsigned int) 0x08) #define RELOC_STD_BITS_BASEREL_LITTLE ((unsigned int) 0x10) #define RELOC_STD_BITS_JMPTABLE_BIG ((unsigned int) 0x04) #define RELOC_STD_BITS_JMPTABLE_LITTLE ((unsigned int) 0x20) #define RELOC_STD_BITS_RELATIVE_BIG ((unsigned int) 0x02) #define RELOC_STD_BITS_RELATIVE_LITTLE ((unsigned int) 0x40) #define RELOC_STD_SIZE (BYTES_IN_WORD + 3 + 1) /* Bytes per relocation entry */ struct reloc_std_internal { bfd_vma r_address; /* Address (within segment) to be relocated. */ /* The meaning of r_symbolnum depends on r_extern. */ unsigned int r_symbolnum:24; /* Nonzero means value is a pc-relative offset and it should be relocated for changes in its own address as well as for changes in the symbol or section specified. */ unsigned int r_pcrel:1; /* Length (as exponent of 2) of the field to be relocated. Thus, a value of 2 indicates 1<<2 bytes. */ unsigned int r_length:2; /* 1 => relocate with value of symbol. r_symbolnum is the index of the symbol in files the symbol table. 0 => relocate with the address of a segment. r_symbolnum is N_TEXT, N_DATA, N_BSS or N_ABS (the N_EXT bit may be set also, but signifies nothing). */ unsigned int r_extern:1; /* The next three bits are for SunOS shared libraries, and seem to be undocumented. */ unsigned int r_baserel:1; /* Linkage table relative */ unsigned int r_jmptable:1; /* pc-relative to jump table */ unsigned int r_relative:1; /* "relative relocation" */ /* unused */ unsigned int r_pad:1; /* Padding -- set to zero */ }; /* EXTENDED RELOCS */ struct reloc_ext_external { bfd_byte r_address[BYTES_IN_WORD]; /* offset of of data to relocate */ bfd_byte r_index[3]; /* symbol table index of symbol */ bfd_byte r_type[1]; /* relocation type */ bfd_byte r_addend[BYTES_IN_WORD]; /* datum addend */ }; #ifndef RELOC_EXT_BITS_EXTERN_BIG #define RELOC_EXT_BITS_EXTERN_BIG ((unsigned int) 0x80) #endif #ifndef RELOC_EXT_BITS_EXTERN_LITTLE #define RELOC_EXT_BITS_EXTERN_LITTLE ((unsigned int) 0x01) #endif #ifndef RELOC_EXT_BITS_TYPE_BIG #define RELOC_EXT_BITS_TYPE_BIG ((unsigned int) 0x1F) #endif #ifndef RELOC_EXT_BITS_TYPE_SH_BIG #define RELOC_EXT_BITS_TYPE_SH_BIG 0 #endif #ifndef RELOC_EXT_BITS_TYPE_LITTLE #define RELOC_EXT_BITS_TYPE_LITTLE ((unsigned int) 0xF8) #endif #ifndef RELOC_EXT_BITS_TYPE_SH_LITTLE #define RELOC_EXT_BITS_TYPE_SH_LITTLE 3 #endif /* Bytes per relocation entry */ #define RELOC_EXT_SIZE (BYTES_IN_WORD + 3 + 1 + BYTES_IN_WORD) enum reloc_type { /* simple relocations */ RELOC_8, /* data[0:7] = addend + sv */ RELOC_16, /* data[0:15] = addend + sv */ RELOC_32, /* data[0:31] = addend + sv */ /* pc-rel displacement */ RELOC_DISP8, /* data[0:7] = addend - pc + sv */ RELOC_DISP16, /* data[0:15] = addend - pc + sv */ RELOC_DISP32, /* data[0:31] = addend - pc + sv */ /* Special */ RELOC_WDISP30, /* data[0:29] = (addend + sv - pc)>>2 */ RELOC_WDISP22, /* data[0:21] = (addend + sv - pc)>>2 */ RELOC_HI22, /* data[0:21] = (addend + sv)>>10 */ RELOC_22, /* data[0:21] = (addend + sv) */ RELOC_13, /* data[0:12] = (addend + sv) */ RELOC_LO10, /* data[0:9] = (addend + sv) */ RELOC_SFA_BASE, RELOC_SFA_OFF13, /* P.I.C. (base-relative) */ RELOC_BASE10, /* Not sure - maybe we can do this the */ RELOC_BASE13, /* right way now */ RELOC_BASE22, /* for some sort of pc-rel P.I.C. (?) */ RELOC_PC10, RELOC_PC22, /* P.I.C. jump table */ RELOC_JMP_TBL, /* reputedly for shared libraries somehow */ RELOC_SEGOFF16, RELOC_GLOB_DAT, RELOC_JMP_SLOT, RELOC_RELATIVE, RELOC_11, RELOC_WDISP2_14, RELOC_WDISP19, RELOC_HHI22, /* data[0:21] = (addend + sv) >> 42 */ RELOC_HLO10, /* data[0:9] = (addend + sv) >> 32 */ /* 29K relocation types */ RELOC_JUMPTARG, RELOC_CONST, RELOC_CONSTH, /* All the new ones I can think of, for sparc v9 */ RELOC_64, /* data[0:63] = addend + sv */ RELOC_DISP64, /* data[0:63] = addend - pc + sv */ RELOC_WDISP21, /* data[0:20] = (addend + sv - pc)>>2 */ RELOC_DISP21, /* data[0:20] = addend - pc + sv */ RELOC_DISP14, /* data[0:13] = addend - pc + sv */ /* Q . What are the other ones, Since this is a clean slate, can we throw away the ones we dont understand ? Should we sort the values ? What about using a microcode format like the 68k ? */ NO_RELOC }; struct reloc_internal { bfd_vma r_address; /* offset of of data to relocate */ long r_index; /* symbol table index of symbol */ enum reloc_type r_type; /* relocation type */ bfd_vma r_addend; /* datum addend */ }; /* Q. Should the length of the string table be 4 bytes or 8 bytes ? Q. What about archive indexes ? */ #endif /* __A_OUT_64_H__ */ | http://read.pudn.com/downloads17/sourcecode/others/62363/cygwin-1.3.17-1-src/cygwin-1.3.17-1/include/aout/aout64.h__.htm | crawl-002 | refinedweb | 2,554 | 53.92 |
Shaders – The Basics
Last time we discussed the building blocks of CG life, the vertex and the pixel. This time we shall dive into something without which computer graphics would be stuck running on the CPU, slowing down your operating system, forever. I’m talking of course about the humble shader. More specifically, we’ll talk about the two most basic shaders: the vertex and fragment ones.
What are shaders?
You presumably know how simple C or C++ programs run on the CPU. Well, shaders are programs too, the difference being that they run on the GPU (Graphics Processing Unit). This frees up the CPU from the task of drawing hundreds, maybe thousands of polygons each frame, thus giving it the time to listen for pressed keys, running AI scripts, doing physics calculations (although with CUDA you can move all that stuff on the GPU too).
Shaders come in all shapes and sizes, so to speak. There are a few types, illustrated in the following image:
As you can see, here, we are focusing on the beginning and end of the programmable pipeline, the vertex and fragment shaders. Vertex and fragment shaders are the most important ones because without them we can’t draw anything. In the pre-shaders days this functionality was fixed. Shaders allow us to customize how and when the pixels get coloerd. Tessellation and Geometry shaders are optionals and they can be skipped during the rendering process. Vertex fetch, Rasterization and Framebuffer operations can’t be directly programed. Before we move on, let’s talk about some basic interactions between shaders with the CPU or other shaders.
Between shaders, you can pass information through in/out variables. This operation has to follow certain rules for it to be successful:
- The name and type of the in variable from the destination shader must be the same as its corresponding out variable from the sender shader
- An out variable can be sent only to the next existing shader in the pipeline (for ex., you can’t send a variable directly from the vertex to the fragment shader if you have a tessellation shader between them)
From the CPU, shaders receive information through buffers, each value corresponding to one or multiple vertices (accessed only by the vertex bufer) and through uniform variables which, can be accessed by any shader directly.
Our shaders will be written in the GLSL, which is similar to C++, however there are other possibilities (HLSL, fx, etc.)
Reading and Loading Shaders
Before they can be used, you need to read the files where the shaders are kept, compile them and integrate them into your program. To do this, we need to create a C++ class which will deal with these operations and can be easily created and used within the main file without taking up a lot of lines.
First, create a folder called Core in your project. In this folder we are going to create our classes that are required for building our scene. The first class is Shader_Loader. To create a class you need a header file (Shader_Loader.h) and a code file (Shader_Loader.cpp).
This is the .h file:
#pragma once #include "../Dependencies/glew/glew.h" #include "../Dependencies/freeglut/freeglut.h" #include <iostream> namespace Core { class Shader_Loader { private: std::string ReadShader(char *filename); GLuint CreateShader(GLenum shaderType, std::string source, char* shaderName); public: Shader_Loader(void); ~Shader_Loader(void); GLuint CreateProgram(char* VertexShaderFilename, char* FragmentShaderFilename); }; }
As you can see, the header file is used for defining the class structure and what it contains (methods, variables, constructors, etc.). It’s necessary to include the GLEW and FreeGLUT libraries, because we need the variable types GLuint and GLchar, not to mention important functions like glLinkProgram and glAttachShader. The GLuint variables will hold the shader and program handles (basically empty objects to hold these entities) which will be used for integration. OpenGL confusingly uses the name “program” – a program is a container that holds the shaders added to it (vertex, fragment, tessellation, geometry).
Shader_Loader is the class constructor (a function which is called when the class is instanced) and ~Shader_Loader is the destructor. ReadShader reads and returns the contents of a file. CreateShader method creates and compiles a shader (vertex or fragment). CreateProgram method uses ReadShader to extract the shader contents and to create both shaders and load them into the program which is returned to be used in rendering loop.
Next up, here is the .cpp file:
#include "Shader_Loader.h" #include<iostream> #include<fstream> #include<vector> using namespace Core; Shader_Loader::Shader_Loader(void){} Shader_Loader::~Shader_Loader(void){} std::string Shader_Loader::ReadShader(char *filename) { std::string shaderCode; std::ifstream file(filename, std::ios::in); if(!file.good()) { std::cout<<"Can't read file "<<filename<<std::endl; std::terminate(); } file.seekg(0, std::ios::end); shaderCode.resize((unsigned int)file.tellg()); file.seekg(0, std::ios::beg); file.read(&shaderCode[0], shaderCode.size()); file.close(); return shaderCode; } GLuint Shader_Loader::CreateShader(GLenum shaderType, std::string source, char* shaderName) { int compile_result = 0; GLuint shader = glCreateShader(shaderType); const char *shader_code_ptr = source.c_str(); const int shader_code_size = source.size(); glShaderSource(shader, 1, &shader_code_ptr, &shader_code_size); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_result); //check for errors if (compile_result == GL_FALSE) { int info_log_length = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_log_length); std::vector<char> shader_log(info_log_length); glGetShaderInfoLog(shader, info_log_length, NULL, &shader_log[0]); std::cout << "ERROR compiling shader: " << shaderName << std::endl << &shader_log[0] << std::endl; return 0; } return shader; } GLuint Shader_Loader::CreateProgram(char* vertexShaderFilename, char* fragmentShaderFilename) { //read the shader files and save the code std::string vertex_shader_code = ReadShader(vertexShaderFilename); std::string fragment_shader_code = ReadShader(fragmentShaderFilename); GLuint vertex_shader = CreateShader(GL_VERTEX_SHADER, vertex_shader_code, "vertex shader"); GLuint fragment_shader = CreateShader(GL_FRAGMENT_SHADER, fragment_shader_code, "fragment shader"); int link_result = 0; //create the program handle, attatch the shaders and link it GLuint program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &link_result); //check for link errors if (link_result == GL_FALSE) { int info_log_length = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_log_length); std::vector<char> program_log(info_log_length); glGetProgramInfoLog(program, info_log_length, NULL, &program_log[0]); std::cout << "Shader Loader : LINK ERROR" << std::endl << &program_log[0] << std::endl; return 0; } return program; }
Of course we must import the header file and a couple of C++ libraries. For the time being, we can leave the constructor and destructor alone. As for ReadShader, it’s basically just reading a file.
CreateShader encapsulates all relevant operations required to create a shader. The following functions are called:
- glCreateShader(shader_type) – it creates an empty shader object (handle) of the wanted type
- glShaderSource(shader, count, shader_code, length) – it loads the shader object with the code; count is usually set to 1, because you normally have one character array, shader_code is the array of code and length is normally set to NULL (thus, it will read code from the array until it reaches NULL) , however here I set the actual length.
- glCompileShader(shader) – compiles the code
- glGetShaderiv(shader, GLenum ,GLint ) – Check for errors and output them to the console
You do this operation chain for any shaders you have, to create their objects.
Then in CreateProgram, you create the program through glCreateProgram() and attach the shaders to it with glAttatchShader(). Finally, you finish it off by linking the program with glLinkProgram(). We also need to check if the shader was linked properly using glGetProgramiv() and output possible errors to the console. Checking and catching shader and linking program errors is extremely important, helping you saving time and many headaches.
To use this program (these shaders) the following method needs to be added to the render loop when we begin to draw.
glUseProgram(program);
Vertex and Fragment Shaders
The first and most important of all shaders, they have the critical job of processing every vertex and returning its position on-screen through a series of transformations (we’ll get to them in a later tutorial). Along with the vertices, the vertex shader also receives arrays of data associated with each vertex (offset, normal, texture coordinate, etc.) in buffers. We won’t go into how this is done, because for the time being we don’t need it.
The only predefined variable you need to remember at this point when it comes to the vertex shader is gl_Position, in which the final on-screen position of the current vertex is saved (after the chain of transformations).
The fragment shader’s primary responsibility is determining the color of each fragment. The only output from this shader is the color vector, without which all objects would be colored completely black.
I haven’t given examples of these shaders because the main focus of this tutorial was to provide you with the necessary tools to add shaders to your program and to explain what they are. Starting with the next tutorial, you will learn how to actually write shaders and to draw a simple triangle.
So far, the project folder structure should look like this: | http://in2gpu.com/2014/10/29/shaders-basics/ | CC-MAIN-2019-13 | refinedweb | 1,464 | 50.46 |
In this week's KDE Commit-Digest:.
Also in this Digest, Seb Ruiz writes about the reception of Amarok 2 and current and future developments. Read the rest of the Digest here.
5 lines of Javascript! That is AMAZING!
Just imagine: web developers creating fully-functional software/"webware" with little or no learning curve. I've yet to see anyone else achieve this. Well done KDE devs!
"Write <amazing thing> in <very few> lines of code!!" claims are always pointless. They always boil down to something like:
#include <web_browser.h>
int main()
{
Browser b;
b.run();
return 0;
}
OMG! I just wrote a web browser in 2 lines of code!!!
in this case, however, it's not just a proof of concept that's useless but something that allows people do something both useful and commonly desired: embed media (audio, video..) into a widget with extreme ease. it's not at all, therefore, like your web browser example which is, indeed, typically what these sorts of things are. this is an actually useful step that lowers the bar to creating actually useful things. :)
As a developer - consultant myself, I would love such feature. But I am still waiting.... please hurry up -:)worldclass for models clothes shopping hong kong fashion garments tops.
Currently I'm using Dolphin and Gwenview and lots of folders for most of my image management in KDE, but after a visit to a friend I noticed Digikam is much more powerful and easy to use. Last time I tried (some years ago) it was unreliable and crash prone and I somehow never got around to test it again. Back home I instantly tried it and it is almost exactly what I need. However I have trouble with photos which are managed by PicStor, a commercial photo management program I need for my work and use via wine. PicStor creates a ridiculously large tif index file in each folder which makes Digikam take a very long time to scan this folder and use up a lot of memory. I had to raise the values in limits.conf to prevent it from getting killed. And Digikam ignores all photos which are tagged or edited in PicStor. PicStor adds .0000 to the files and .0001 etc. for each edited version. I inserted the 0000 on the config page but Digikam only shows the original photo. In Dolphin and Gwenview I can see all photos and their versions.
How can I make Digikam to show all subsequent photos too? And how can I prevent it from reading the index file?
This is one of the best examples of use case which should by submitted to Digikam's bugzilla.
Maybe Digikam developers do not know anything about this issue. So let them now on bugzilla.
regards
I haven't yet received my bugs.kde.org login details. It is possible and sadly very probable my providers filter again might have dropped it. This wouldn't be the first time.
Why is there no unified kde login? Except the svn maybe...
On the Digikam note i found a workaround to keep the memory consumption reasonable: I simply let a script traverse all folders and set the index files to 000. I have added to the script to start PicStor to restore them to 600. But I have not yet found a way to tell Digikam to accept non raw photos which have extensions other than jpg or 0000. This is rather confusing as Dolphin and Gwenview display and do accept them. Maybe pebkac but more i suspect the factory 4.2 rpms may be the reason. I'll try to build rc2 0.10 myself to see if works better.
Just can't wait for KDE4.3!
Edit: I'll read the Digest _before_ asking questions next time *blushing*
From the post
... and also some for usability reasons (such as the tabular playlist design - remember, we're the experts!).
Oh please don't try to convince that everybody are fools and just don't get it. There are 2 features that Amarok users mostly hate in 2.x series:
1. Large central area with context information.
2. New play list.
I remember history of both these new "features". Initial motivation of placing context info at the center was that Amarok developers believe that this context related stuff is really a central thing that distinguishes Amarok from other player. But all users ask is to place playlist next to the collection browser so that it was easier to drag items to playlist.
The mock up for new playlist was introduced long time before any real usability expert worked on Amarok 2. And current playlist is almost exact copy of that mockup. A lot of usability experts say that it is more natural for people to understand information if it is in the table. All usability experts say that that it is easier for human eyes to accept information by lines. There is no real usability reason to have current playlist. Not even saying about having some "context" space between collection and play list.
In free software world developers make all decisions because they really write code. That's fair. And that's the only reason for current Amarok 2.x UI. There are no real usability reasons for this.
I am ok with statement that "We write Amarok so we decide how it looks". Why can't you just say this. But I really don't like when 10 people say to few hundreds of people that "we are the experts and we know better". To say this you need to be a real expert. If someone don't write any code for Amarok it doesn't means he is not an expert. Or he doesn't know what he is talking about. I am senior software developer. But I don't want to start writing code for Amarok only for purpose so my voice as well as voice of large number of other people was heard.
How many times amarok users must say something so that amarok developers at last started to listen???
perhaps it was more ment like a joke...
Besides, like the guy said, the ones who do like the new playlist are the ones who don't complain. Plus, you can get the old view if you want, so I don't really see the problem.
In free software world developers make all decisions because they really write code.
In free software world developers make all decisions because they really write code.
There is an interesting article in the current (03/2009 P.24) Communications of the ACM that asks the big question: Is Software Engineering [really] Engineering?
Whether or not it is really engineering, developers need to realize that software development is a lot more than writing the code. Writing the actual code should be only a small part of software development. If it is engineering, then analyzing the problem and designing the solution are the important parts of the project. Writing the code is only implementing the solution.
To make my point clear: design is what is important. You need to develop a good design before you write the code.
This mantra of FOSS has come to mean that those that write the code do the system analysis and project design. Why should it be that way? Does knowing a programing language automatically make someone good at analysis and design? I don't think so.
To make my point clear: design is what is important. You need to develop a good design before you write the code.
You should really read up on agile software development. It's really big in the general softwre development world now, and is basically based on the observation that big up-front designs seldom are any good. We've been doing Big Up-Front Designs for a few decades now, and if there is anything software projects are generally know for, it's failing. They're very often delivered late, above budget and non-working.
Agile development tries to correct this by producing functioning code early, and improving and extending the code base over several iterations, all in close cooperation with the user/customer. Notice how this sounds like the "release early, release often" mantra of open source.
One cornerstone of agile methods is to constantly asking the user "does this work? is this what you want?". Whether or not the amarok project is doing that, I have no idea... ;)
@KSU257,
Of course that design is what is important, and developers are not designers by itself. But users are not designers either. Especially advanced FLOSS users which are the vocal minority in FLOSS world. Pro users have a bad tendency of adding (or suggesting this) more and more widgets, buttons and checboxes without thinking about overall design ;)
So in this perspective developers are the ones which have more to say about their application. They know what they want to achieve. AFAIR Amarok developers during 2.0 development clearly stated what is their vision, and 2.0 is really good implementation of this vision.
Not agreeing to this vision is completely different topic.
Also lack of usability experts willing to work with both developers and end users is completely different topic.
"Also lack of usability experts willing to work with both developers and end users is completely different topic."
Just FYI: We have _two_ notable usability people working closely with us: Dan Leinir Turthra Jensen, and Celeste Lyn Paul. The names might ring a bell.
We take usability very seriously, better believe that. We've made mistakes in the past, and we don't plan to repeat them. And we are continuously working very hard on improving in this area; it's a "priority thing" for us.
Mark, when writing last sentence I was thinking generally about FLOSS world. I could write it more clearly...
I'm really glad that usability people are working with amarok devs :)
as an amarok 1.4 user, i still feel that dragging from collection to playlist is unnecessary more complex and unintuitive in v2.
would be interesting to see percentage of users who would choose to put playlist besides collection if that was possible ;)
I feel that too. Thought that maybe it was just a "bad habit" from using amarok 1.4 and have been giving it a chance but it stills feel kind of weird.
Part of it is simply how the distance makes it more weird in my mind. We are doing something on the far left to affect what's on the far right, with that big whole in the middle. Where should I focus my attention.
But then there is the dragging itself too. Sure if you just want to append you got alternatives. But what if you want to put songs from your collection in a particular place in your playlist. How do you do that without dragging it all the way from one side to the other?
(yes, 0.4, not 1.4)
... I can say that I really DO like Amarok 2 more than 1.x. The UI is simpler, clearer and more focused on one thing: the context. What's the point in having a giant playlist occuping a width of ~1200px? When you're listening to music, probably you have amarok minimized and you're doing another task. When Amarok is maximezed and focussing your attention, what's the point in staring at a giant playlist? Are you messing up the playlist every moment? Or perhaps you just create it once (when starting your listening session) and maybe modify something here and there from time to time?
I mean, the context view is not perfect (layouting could be enhanced/fixed for example.. yes arrows that control the "activities", I'm pointing my finger at you!) but it without ANY doubt the way to go.
Amarok 1.4 is dead. Hurray for Amarok 1.4
Thank you for this thoughtful and constructive comment. As for the context view - you are right with your criticism - and we have been working hard to improve it for the upcoming Amarok 2.1.
Please check out this informative blog for an overview of Amarok 2.1 features.
Ok, I'm not saying that a good design isn't important (it IS important) but as others already said.. do you know agile dvelopment? Release early, release often has proven to be quite successful in the FLOSS world (do you know that software called "Linux"?). Moreover freesoftware has always and always will have a clear hacker attitude. To do boring software development there are old school companies which pay their employees to do just that: lot of boring development overhead.
I know about eXtreme Programing and I think that it is a good idea. "Agile Software Development" appears to be similar. XP requires that you "Release early, release often"
However, these good ideas are not an excuse for writing code without designing it first (hacking) and the poor design that is the usual result. XP and ASD do not mean that we should discard the traditional engineering cycle (analyze, design, implement), rather they require that the cycle is done many times on a small part of the project rather than the inefficient old school method of doing it once for the whole project.
Is the KDE project actually meeting the goals stated in the ASD manifesto?
Working software?
Customer collaboration?
If not, perhaps we need to refine our development methods.
I'm using a regularly compiled SVN snapshot of KDE and extragear, and for about two months now, My playlists in Amarok are quite broken : showing me lots of weird new playlists that seem to point to some m3u files in my music dirs, not allowing to save new playlists, I even cannot create dirs anymore.
Is that something normal considering the development state of Amarok or is that something should be reported?
if it shows up as a new user (or after removing config files and database - back them up first!) you should report it as an bug... | https://dot.kde.org/2009/03/07/kde-commit-digest-15th-february-2009 | CC-MAIN-2017-22 | refinedweb | 2,354 | 74.79 |
Details
- Type:
Bug
- Status: Resolved
- Priority:
Major
- Resolution: Won't Fix
- Affects Version/s: 1.8.3
- Fix Version/s: None
- Component/s: Bean / Property Utils
- Labels:None
Description
We have migrated the library from version 1.6.0 to 1.8.0 and the copyProperties() method fails when copying a java.util.Date attribute with a null value.
Here is a simple testcase :
public class Test { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public static void main(String[] args) throws Exception { Test dest = new Test(); Test source = new Test(); BeanUtils.copyProperties(dest, source); } }
As a workaround, we can do this :
ConvertUtils.register(new DateConverter(null), Date.class);
When can also use PropertyUtils.copyProperties() because in this case no conversion is required but the impact is unknown on our big application.
The problem is that there seems to be a regression between version 1.6.0 and 1.8.0.
Attachments
Issue Links
- blocks
BEANUTILS-255 Date and Calendar Converter implementations
- Closed
- is duplicated by
BEANUTILS-454 copyProperties() throws conversion exception for null Date
- Closed | https://issues.apache.org/jira/browse/BEANUTILS-387 | CC-MAIN-2018-09 | refinedweb | 184 | 51.75 |
Configuring user sets
Applies To: Forefront Threat Management Gateway (TMG)
Forefront TMG provides a number of predefined user sets that cannot be modified, but you can by creating new user sets for use in firewall policy rules.
Creating a user set
In the Forefront TMG Management console, in the tree, click the Firewall Policy node.
On the Toolbox tab, click Network Objects.
On the toolbar beneath Users, click New.
When the New User Set Wizard starts, follows the on-screen instructions.
Modifying a user set
In the Forefront TMG Management console tree, click Firewall Policy.
On the Toolbox tab, click Network Objects.
Click to expand Users, and double-click the user set.
In the user set property pages, modify the required settings.
Note the following:
For Windows user sets you can specify any user or group. For RADIUS, SecurID and LDAP user sets you can specify either all users in the namespace or a specific user. If you specify all users in a namespace, the rule will be applied for any user who successfully authenticates to the RADIUS, SecurID, or LDAP server.
For outbound client requests, only Windows and RADIUS authentication is supported. SecurID and LDAP server are only supported for incoming requests handled by Web publishing rules.
When RADIUS or SecurID authentication is used, Forefront TMG compares the credentials passed by the user with the string specified on the Users tab of a rule's properties. For example, if you apply a rule to a user set that includes only Domain\User and the user types credentials as User@Domain, the rule is not applied. | https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc441551%28v%3Dtechnet.10%29 | CC-MAIN-2019-35 | refinedweb | 266 | 54.93 |
Is there a way to do a remote "ls" much like "scp" does a remote copy in a standard linux shell?
7 Answers
You could always do this:
ssh user@host ls -l /some/directory
That will SSH to the host, run ls, dump the output back to you and immediately disconnect.
- 8
- how would you alias this to, say, "rls" ? Oct 18, 2014 at 16:24
- 2
- The only problem with this is that file not found returns an error code,when my reason for doing it is precisely why I want to call ls. Nov 28, 2017 at 18:54
To list all files in a directory:
rsync host.name.com:directory/path/'*'
For something like find directory/path -ls
rsync -r host.name.com:directory/path
- 1If rsync is not installed on the host, then you get something like
bash: rsync: command not found. I guess this implies it's using SSH in the background? Sep 25, 2015 at 10:23
For all coming via google to this question because they are looking for a way to list remote files but can not access the remote server via ssh (common case for backup servers) you could use 'sftp'.
Example:
sftp username@hostname.xyz ls cd somedir exit
Start an interactive session in a specific remote directory:
sftp [user@]host[:dir]
Yes. SSH and do an
ls:
ssh host ls /path
You could easily script this to be more flexible, or use the host:path syntax
scp uses.
The above answers do not contemplate when you need to add a password. To include password and username in a single command, install
sshpass.
For mac:
$ brew install hudochenkov/sshpass/sshpass
For linux:
sudo apt-get install sshpass -y
Then:
$ sshpass -p your_password ssh user@hostname ls /path/to/dir/
You can also save output:
$ sshpass -p your_password ssh user@hostname ls /path/to/dir/ > log.txt
In python3:
import subprocess cluster_login_email = 'user@hostname' cluster_login_password = 'your_password' path_to_files = '/path/to/dir/' response = subprocess.run([ 'sshpass', '-p', cluster_login_password, 'ssh', cluster_login_email, 'ls', path_to_files], capture_output=True) response = response.stdout.decode("utf-8").split('\n')
I find my most frequent use of this is to get the ls result, a simple list of files without all the permissions and dates and such, and keep it in a local file.
{ ssh me@host.com "cd /dir/of/interest; ls -1f *.txt;" } > /home/me/listoffiles.txt
You can run anything you want within the quotes. All output ends up in your local text file. Or if you want to run a big nasty script on the server and capture all of its output, even errors:
{ ssh me@host.com <script.remote.sh } > /home/me/output.log 2>/home/me/output.err
- 1
- @glglgl+ in the 1st code line also (it's the quoting, and only the quoting, that controls what gets sent to remote system for execution) Sep 13, 2020 at 8:09
As mentioned, if you can SSH into the host, you can do whatever you like.
You can use either
ssh user@host or
ssh alias (defined in
~/.ssh/config)
Examples
Edit: Fixed some examples by single quoting the entire command to be sent. Thanks @dave_thompson_085 for pointing to the problem.
$ ssh user@host 'ls /dir/file'
You mentioned that you don't want to receive the errors from
ls if the file does not exist.
One option is to just discard the error messages
$ ssh user@host 'ls /dir/file 2>/dev/null'
This will preserve the return as well. So
$? will be 0 only if the ls command found /dir/file. This is nice because it works for files, folders, symlinks or anything that can be listed by ls.
Another option is to check if the file exists before listing.
$ ssh user@host '[ -f /dir/file ] && ls /dir/file'
You could also test and list a folder, but the syntax changes
$ ssh user@host '[ -d /dir/sub ] && ls /dir/sub'
You could chain and test for ANY as well
$ ssh user@host '[ -f /dir/file ] || [ -d /dir/file ] && ls /dir/file'
You could also just check if the item exists and nothing else
$ ssh user@host '[ -f /dir/file ] || [ -d /dir/file ]' $ echo $? # exit code will be 0 ONLY if the file exists 0
You may want to include a test for symlinks with
[ -L /my/target ] as well.
You could run conditional codes remotelly
$ ssh user@host '[ -f /dir/file ] && echo "File EXISTS!" || echo "File NOT FOUND!"' File EXISTS!
Or locally if you move the commands outside the command string
$ ssh user@host '[ -f /dir/file ]' && echo "File EXISTS!" || echo "File NOT FOUND!" File EXISTS!
The way quoting and expansion works can be tricky though. If you use double quotes outside the main command (instead of single quotes as above), variables will be expanded BEFORE connecting ssh, unless you escape the
$. It is normally easier to use single quotes to avoid that, but your mileage may vary. Some times you need stuff to expand locally AND remotelly, which can be tricky.
- Your 2nd example is wrong; the
lsruns locally, or tries to. Similarly in your 5th example the
echo's run locally (which is okay for echo) and in your 6th example
{ }does not change that. Lastly, for shells with history expansion, normally interactive bash and zsh,
echo "FILE EXISTS!"doesn't work (anywhere, not just with
ssh). Sep 13, 2020 at 8:08 | https://serverfault.com/questions/242176/is-there-a-way-to-do-a-remote-ls-much-like-scp-does-a-remote-copy | CC-MAIN-2022-33 | refinedweb | 902 | 70.53 |
Hi ,
I have the below API Response which contains a Key : Attachment Path.
I am trying to verify using Groovy Script Test Step if the file exists on that Path or not. The thing is when i try to open the path manually , i get a Windows Security popup (asking me to enter username and password) and only then can i enter the path and verify the image exists or not on that location.
I found a workaround where Iff i Map this Attachment Location path in widows (maps as Z drive), i am able to use groovy to check for the existence of the image. But the problem with that is , each time my PC restarts , the Mapped drive is gone and i have to remap it for this test step to run.
Can some one help me if there is a way to validate the existence of the image on this server
{"Bulletin" : {"BulletinID" : "******-***-4e62-a84e-85cce1b49540","UniqueKey" : "TS88-****","CreatedByID" : "8989","Title" : "Bulletin_edit","ModuleLookupID" : "35453452","DateClosed" : null,"IsActive" : true,"DateCreated" : "2019-06-17T03:10:50.857","ModifiedByID" : "4354333345","DateLastModified" : "2019-06-19T06:55:38.08","LastModifiedBy" : "abc","COMSmodules" : "sdadasdadas"},"Section" : "Bulletin","FileTitle" : "title","FileName" : "filename.jpg","AttachmentPath" : "\\\\blahblah.com\\abc00$\\QA\\Attachments\\Bulletins\\filename.jpg","AttachmentID" : "54546"}
Groovy Script :
import groovy.json.JsonSlurperdef response = context.expand( '${GET Request#Response}' )def jsonSlurper = new JsonSlurper()def jsonObject = jsonSlurper.parseText(response)
def path = jsonObject.AttachmentPath.toString() //Get the attachment Path from the API Responselog.info pathpath = path.replaceAll("]","")Split = path.split(/[\\]/)
size = Split.lengthFileName = Split[size-1]log.info "File name is : " +FileName
Filename = "Z:\\\\"+FileName \\Mapped drive file namelog.info "Mapped Path : " +Filename
File file = new File(Filename)log.info "Check if the File exists on the Mapped Path : " +file.exists()
assert file.exists().toString()=="true","File does not exist on the Server: Z:\"
Solved!
Go to Solution.
Hi @ashutosh
i can't help with the ReadyAPI!/SoapUI/Groovy option - but i was wondering about whether you'd accept a workaround?
Your User Account Control is enabled and this is what's hindering the file Open windows dialogue being generated. Could you not disable the UAC? (depends if you have local admin rights or if Policy is forcing it enabled)
If you can't disable the UAC and the issue is that you lose the drive mapping after restarting your machine - could you not create a login script to automatically map the drive on startup? i.e. create a .bat file (using net use command to map the drive) and stick the .bat file in one of the many startup folders/registry settings.
it's real simple - the following link tells you how to do it - link
Just an option....
ta,
richie
View solution in original post
Hi all,
@richie thanks for looking into this!
@ashutosh does the workaround work for you?
Let me mark Richie's workaround as a solution for now.
@ashutosh, you can always get back to this thread if you would like to investigate this further.
Have a great day! | https://community.smartbear.com/t5/API-Functional-Security-Testing/Connect-to-Network-Path-with-Windows-security-using-Groovy/td-p/186228 | CC-MAIN-2020-50 | refinedweb | 504 | 58.69 |
On Voting Bots
In response to a post describing why, in the author’s view, paid content promotion services are bad for the Steem platform, I was asked to share my thoughts on the matter. That post made some sweeping allegations against the owners and operators of such services, including that we have “remained silent” and refuse to answer questions posed by the community about these services and how they benefit the platform.
These allegations are blatantly untrue as myself and many of the other owners and operators of content promotion services are always available and open to discussion about these topics which are of key importance. I am not only open to, but also genuinely excited for, the opportunity to discuss the topic of paid content promotion services and what role they play in the future of the Steem platform.
The key is that those discussions take place in an open-minded, civilized, and respectful manner. I refuse to participate in any discussions characterized by personal attacks and disrespect for those with differing opinions as is unfortunately so often the case with online communications.
With that out of the way, I would like to start by discussing the two primary ways in which paid content promotion services benefit the Steem platform:
- Providing real utility, and therefore value, to the STEEM token; and
- Providing passive investors with attractive returns on their investment in Steem Power
Utility for the STEEM Token
Currently, the market value of the STEEM token is almost completely driven by speculation - as is the case with all cryptocurrencies right now. That is not sustainable however, so for Steem to succeed over the long term it needs to have real value, derived from real utility.
The STEEM token has a few different things that give it utility and therefore value, however the primary utility of the token is that it allows one to promote content on Steem-based websites. @ned says it better than I could starting at around the 5:25 mark in this video:
The transcription of the relevant segment is as follows (emphasis mine):
The 5th thing, and probably the most important aspect of the value cycles in all of this, is the idea that STEEM and SMTs really are the world’s advertising network. These are tokens that get laid across applications and they have these functional properties underneath everything that cause interfaces to basically sort order posts in terms of their value, and once you have posts sorted in their order of value, then any blogger curator content creator video creator or straight up advertiser can look at that sort order of value and say well you know if i just buy some more SMTs or STEEM i can promote my post higher up in that sort order and thereby get more attention which may help me sell more of my products, so that’s a good thing for me, there’s a return on investment.
So there’s a very natural, very sustainable, flow of value that’s caused by these tokens where value is coming in to buy or rent STEEM to promote content that causes sales in other places. That’s a value flow that’s very analogous to what we see with traditional advertising businesses like Facebook, Reddit, and Twitter. So all that is happening behind the scenes where there’s no company and that’s what’s so new about all of this and what makes it so possibly pervasive across the internet.
Paid content promotion services, currently in the form of voting bots, provide this utility for the STEEM token. Publishers can buy STEEM (and hopefully soon SMTs) and promote their content in order to sell more products, get more brand recognition, increase their followers, etc.
This is just like like advertising on traditional media sites, like @ned has said, but instead of this value going to the company that owns the site, on Steem it goes to Steem Power holders and helps increase the price of the STEEM token.
Some people have questioned whether or not this type of promotion actually provides these stated benefits for content publishers. Obviously that depends on the content that is being promoted, but @spiritualmax ran an experiment that clearly showed that using these services “increases your profit, your follower growth rate, and the SP value of your account.” Generally advertising works, which is why it is so prevalent, and there is no reason to believe it would not work on Steem-based sites as well.
Returns for Steem Power Investors
All of this content promotion is provided by holders of Steem Power. The returns are currently very attractive and therefore provide a very good incentive to invest in, and hold Steem Power, which I think we can all agree is a good thing for the platform.
I know of well over $100,000 that has been recently invested in Steem Power specifically for this opportunity and I expect that is just the tip of the iceberg for what is possible as the Steem platform grows and the word spreads.
I know one of the main issues people have with this is that it’s a small number of “whales” that are earning the vast majority of these returns. That is a distribution problem with Steem which pretty much everyone is aware of. It really has nothing to do with voting bots at all.
It’s just the way that Steem works that these accounts control the vast majority of the reward pool. It’s naive to think that they will give it all away and not seek to earn a return on their investment. If there were no voting bots they could still just as easily take the same portion of pool they are taking now, if not more! At least by selling their vote they are allowing everyone the opportunity to benefit through what is effectively free advertising.
The Problems
I want to be clear that I am not trying to say that everything is all sunshine and roses and that people are complaining for no reason. There are absolutely a number of issues with the Steem platform and with content promotion specifically.
My point is simply that paid content promotion services such as voting bots are not the cause of these problems, and getting rid of them (were that even possible) will not really change anything. Additionally I do believe that they add value to the platform and token as I described above so getting rid of them, in my opinion, would be like throwing the baby out with the bathwater.
I would love to discuss each of the problems in detail, but then this post would turn into a book and I would never get it finished! Perhaps I will try to address some of them in future posts if I can find the time and in those posts I can show how getting rid of paid content promotion services doesn’t solve the problem and also offer some potential alternative solutions.
For now though, I urge anyone who thinks getting rid of voting bots will solve whatever problem they see to really take some time and think through (a) how they plan to actually get rid of voting bots; and (b) whether anything would really be solved if they were successful.
Witnesses who run content promotion services
Last, but not least, I want to address the people who do not feel that witnesses or other respected community members should be running paid content promotion services and actively campaign against those that do. Let’s consider what would actually happen if those campaigns were successful…
There is clearly a large demand for these services both by content publishers and Steem Power holders, so if a campaign was successful to either force witnesses to stop running these services, or have them lose their position / respect in the community, then others who are not witnesses, or otherwise respected community members, would pick up the slack and run these services themselves.
Witnesses, especially those at the top, are typically very active in the Steem community, are trustworthy, and are truly doing what they can to make the Steem platform the best it can be. Some people might disagree with me, and there always may be a couple of exceptions, but I talk with many of the top witnesses on a regular basis and I wholeheartedly believe this to be true.
So the question you should ask yourself is: who do you want to be running the content promotion services on Steem? Who can we trust to run them in a proper and responsible manner? The top witnesses with the traits I described above, or random people whose intentions are unknown and who may not ever engage with the community or care about its long term success?
I know my answer, and I work every day to do what I can to ensure that the paid content promotion services on the platform are run responsibly and in a way that will hopefully benefit the platform as a whole.
In Conclusion
There are three main points that I hope my readers take away from this post:
- Paid content promotion services create real utility and value for the STEEM token
- The problems that exist are not caused by paid content promotion services, nor would they be solved if paid content promotion services did not exist
- It’s highly preferable to have these services run by top witnesses and other well known and respected members of the Steem community who will run them responsibly and have the best interests of the platform at heart.
Lastly, you - the reader - may disagree with the things that have been written here, and that’s okay - in fact it’s great to have different opinions and people who see things from different perspectives. The important thing, like I said at the beginning of the post, is to present your differences of opinion in a respectful and constructive manner.
I expect this post may stir up a good number of lengthy discussions in the comments, which, again, is great. I will do my best to try to read, upvote, and respond to each one that adds value to the discussion. It might take me a while to get to them all though, so please be patient with me!
For those of you who made it this far, thank you for your time and I look forward to continuing to discuss these topics as the Steem platform grows and evolves!
Banner artwork by @nateaguila
Matt, first of all I want to say publicly that your first point about you wanting to engage with others in a honest discussion about the bots or any other topic is completely true... I have seen you interact on many occasions with me and others that you may disagree with, but you have always been approachable and helpful in trying to get across your point of view. So I think the point that people make about "bot owners" not engaging clearly can't be talking about you, since you are readily available and happy to engage. It is why I support you as a witness because I clearly think that you have the community at heart and care about the little guys too.
On your second point about the advertising, I completely understand the concept. And I would be thrilled to accept that point if people were using the bot services to advertise a product. But from what I've witnessed, I haven't seen anything approaching "advertising". I think most people that use the bots do so with the desire to 1) make a profit 2) have a scheme where if it gets high enough they will get some less informed people to upvote (or follow) or 3) want to increase their reputation so they can earn instant "respect".
Don't get me wrong, I'm not saying all bots need to go simply because they aren't really "advertising" yet, what I am saying is that people can see with their own eyes the truth. And when that advertising argument is used it diminishes the credibility of the argument.
In my opinion, we might one day have advertising so its good to have the architecture in place. And I completely agree some of the bots provide value for steemit, most of the bots provide value to the SP holders (which is good for short term demand for steem as you say), and some of the bots even provide value to the users.
Where I think the good bot owners such as yourself could improve the message is through continuing to increase your transparency... And I know you are the leader in this area as you are the creator of steembottracker which attempts to provide transparency (and does some really amazing things btw). So this comment isn't really so much directed at you, as it is to other legit bot owners. I think the bot owners have made a big effort to do so in the past few months too btw... Gone are the 6 days posts for instance. But there is still a wide range of abuse by the bot owners that give you all a bad name... Things like taking payments and not delivering the votes, changing the rules from one day to the next with no notice, some bidding on their own auctions to give a losing vote value. These are things that if they could be cleaned up will help you all a bit more with the image.
But I will agree with you that the bots are not the cause of the problems that people have with the platform. My opinion is that the bots provide that utility you discussed for the owners of the SP, ie you can monetize their votes so they can be passive owners of steem. Let's face it, that is really what the bots do (including minnow booster and smartsteem too)
So whether the paid upvotes are "advertising" or simply a way for people to make a profit, they by themselves are definitely not the problem. And frankly I use bid bots myself to make a profit, so I don't see anything wrong with that either. I think the problem people have is much deeper, and the bots bear the brunt of the anger as they are easy targets because of 1) some bad apples that take advantage of users 2) lack of transparency (but getting much better) and 3) there is a lack of consistency in enforcement of what is considered "good".
In my opinion, the true thing that people get frustrated about deep down is the point you made here. It is dead on.
And by the way, I think this problem will get fixed too... One way or the other. People don't like to think that the prices going down are a good thing, but in reality it is how the free market adjusts for imbalances. I have faith that things will get better in the future. And I have a lot of respect for many people I have met through this platform. And that definitely includes you! Thank you for what you do for all of us and for taking the time to talk about these issues that we face in an open and honest way!
I don't agree with the bidder's profit motive of bid bots, there's clearly no value added in that transaction to the platform, and while I understand that it's something that helps a minnow earn, it does no good for the platform. I anticipate arguments about this attracting new folks to the platform, but I don't think that is the right approach and is largely short term thinking for a social media platform.
As for advertising, I would feel a hell of a lot better if the native promotion worked better and made bid bots obsolete. That leads to a healthier platform in my opinion, because now the rewards pool can focus on content independently of advertising. I already know there are some good ideas for that so I'm curious to see how the discussion evolves.
I hear your point @eonwarped, and as far as user of the bots not adding value of to the platform I would also mostly agree with you. But it is what it is. They way it currently sits, the owners of the system have delegated so much of their voting power to encourage the use of bidbots, minnowbooster, and smartsteem that it essentially necessitates that people earn a profit or their wouldn't be any more vote selling. There are no natural buyers yet of the "advertising", and until that develops we will have the owners do what they can do to get their return on their SP. They aren't going to let is stay unused, I can promise you that.
Yeah I know how that goes. It's just that it's a shame that everyone thinks that that are entitled to such gross returns on their SP to begin with. It's the old fight between doing more for the platform vs maximizing what you can for yourself. In my ideal world even when advertising develops the $$ won't go to SP holders anyway. We'll see...
This is the best possible outcome for the platform.
Currently, SBD is sent to @null for "promotion." In exchange for this sacrifice, you are rewarded with a higher ranking on a separate tab which nobody in their right mind would visit.
In my opinion this was the most terrible idea ever to exist, and I'd like to have a conversation with whoever came up with it. Not to shout or demean or attack in any way... to listen. I want to understand the reasoning behind that decision, because in my view, it alone is to blame for the current situation.
(That's right! I don't blame bot owners for doing what they're doing. They're doing what the platform allows them to do. The bidbot problem is systemic. It's a problem with our consensus code, full stop.)
Let's replace the current in-built promotion mechanism with one that actually assigns higher trending ranking to promoted posts, in proportion (let's say 10x) to the amount of STEEM (not SBD) that was burned. That's the first step and it would help the platform in several ways:
Hi @yabapmatt
Thanks for taking the time to write this piece.
I concede to being vocally against bid-bots, how they are managed by some, and am guilty too of casting general assumptions that the owners would rather not discuss their implications for STEEM and Steemit.
This post has proved some of the above not to be the case.
I'll save the long-winded response for another post on Bots at some point, but would like to ask the following:
What would Steemit look like if we all delegated our stake to bid-bots?
and in response to:
Do you not think that (minus bot owner take), delegating to a bot is essentially self-voting?
Cheers.
I 100% agree with your very last point Asher...
I agree with you that delegating to the bot and then receiving 90% is the same as self voting... There is practically no difference as it is just monetizing your vote value. The 10% is what the lazy man gives away so he doesn't have to open his account and then self vote. (plus may a fraction of that to not look so bad)
That's why I think this issue is a lot more complex, because the owners of the system are doing one thing, and then the community are frowning on the exact same thing done at the lower levels. Its also why people get mad when someone flags another (think haejin), because you can always find a shittier post that got a big upvote and then got to keep it. We see it every day.
I think the solution will happen when the whales are begging at some point for the "community" to develop. Usually that will occur when they want the price to stop going down. At this point there is not that kinda pain. Its fat city for many of the owners.
But it will change and they will come knocking at your door and they will say "Asher, what can we do for you so that we build a strong community?"... "Can we delegate you 100k steem power and have you build out a network where the people are happy and feel like engaging daily?" "Where is fulltimegeek, can he help us lead people to be good community participants?"
You watch, it is coming... Maybe not this week or the next... But when the price gets low enough that will be what happens. The demand for community builders like you will grow very large (and also that applies to Matt with his services too)
Oh yeah, I feel like this needs to be a component of every discussion. Delegating to a bid bot is absolutely just self voting with the stake from the point of view of the delegator, but even more efficient. (Well except for shameless self upvoters that make sure they vote their own comments throughout the day to not"waste stake".)
I suppose a little goes to the bidder and the bidders gets some promotional value (questionable and even then, unpredictable), so it's better than the delegator actually self voting, but not by much.
One might ask, so what should they be doing with their stake anyway? Delegations to places that increase the value of the platform, obviously. Long term thinking and their own steem will explode in value. Making their bid bot generated SP look like dirt in comparison.
Hey, okay, otherwise we can build a better platform and let these bid bots rule over a drying pond. Shrug.
As I responded to Asher above,
So is it any wonder why people get confused? When the guys that own the system do one thing (whales), its kinda hard to complain about lesser people doing the same thing (every other fish).
Its kinda funny... when I use minnowbooster I see many of my friends in the vote totals because they sold their vote away to minnowbooster. But they will frown on someone who upvotes their own post. I don't blame them though, they are encourage to do such things on a regular basis (sell their votes that is)
Yeah I totally struggled with this disparity. Some people take the position that it's okay until your vote gets to a certain point, but I feel to be fully consistent you have to reject the behavior altogether. And the people that take such positions are really at a disadvantage vs the ones that don't. Oh well....
I've been waiting on this post for a while. I knew you had it coming. And I couldn't agree more with what you've said. For example, I run a promotion service (upvote bot) myself and can say that because of this service I have put an extra $10,000 of my own hard-earned money into Steem that I wouldn't have done otherwise. I also know that many of my delegators have powered up their Steem (locking it in and increasing the value) just so that they could delegate more to my service.
Content promotion is a key component of all media sites and I think it should be embraced here as well because it adds value to our platform and token like you've mentioned. I know that the biggest concern most people have is about the rewards pool and the way in which the Trending page is ordered. But to my understanding, the rewards pool doesn't really grow. It's long-term utility is dependent on the value of Steem's value rising. So get rid of upvote bots (SP holders and investors) and that value will drop... therefore damaging the value of the coin and causing more harm to the rewards pool. Please correct me if I'm wrong on that.
As for the trending page, I feel it's pretty simple to tell who has paid for promotion and who hasn't. And I also think that once HiveMind (communities) is added this will take care of most of the complaints. Our sub-steemits (if you will) will have much better categorized content for you to view. So it wont' be as likely that you'll see things that don't interest you.
Anyways, just my thoughts. But I really appreciate you taking the time to write this article. I've been waiting to hear your thoughts for a while. 👍
Thanks @brandonfrye! I've been working on this post for a while and went through quite a few drafts and different directions. It's really hard to clearly explain your thoughts on things!
You're definitely right about the reward pool - the amount of STEEM in it does fluctuate a bit but it's fairly constant. The value all comes from the market price of STEEM, which is currently driven mostly by speculation, but ultimately will be driven by the token's utility.
And the trending page, I think that should just be gotten rid of entirely (which I've posted about before). I actually had an entire page written about that in a previous draft of this post but I felt the post was already long enough and I didn't want to get off on too many tangents.
You're probably right. I've spoken with a lot of Steemians who say they rarely visit the Trending page except to see what the recent flag wars are about lol. I would be perfectly fine with it going away or at least showing new users to Steemit something else when they first log on.
This is an interesting comment, because without the trending page, I would argue that bid bots are irrelevant (from a promotional point of view). (Or are you thinking about leaving HOT in there?) So if you do make a post about it, I would be happy to read it.
I will be addressing the main part of this well-written post shortly(ish). I have plenty to say :P
Here's the post i made a little while back about getting rid of the trending page: It's really just the global trending page i'm saying to get rid of, and just keep the content-specific ones.
Overall I think there needs to be a balance between advertisements and interesting content. The global trending page clearly does not strike a good balance. Also Steem currently poses a weird situation where advertisements and interesting content overlap that you don't see in most traditional media.
Ah okay I see. I don't actually have a problem with the concept of a global trending. But more filters and search functions are much needed.
In terms of traditional media, it's funny because botting and shady engagement services try to optimize the metric that would grant access to exposure, but it seems to be difficult enough that it isn't causing major problems (or there are systems in place to look for it perhaps). So the actual platform provided promotion service is used, and clearly marked as such.
On steemit we only have the the former kind (okay fine promoted was the attempt at the latter and... Yeah we all know that's a joke), and it clearly just looks shady, even if that isn't the intent. Like you say, it all blends together. And only a platform change will help with that.
Bid bots are a promotion hack that have the intended promotion effect, but there are so many downsides (to be written... Bleh). I think someone needs to drive the way to a healthier ecosystem.
(And I don't think communities will solve all the problems)
So here's my take from someone relatively new to STEEM and sees the massive opportunity that the promotion 'bots' have...
Like you mentioned in your bio, they are content promotion services / software in my opinion too. The 'bot' brand almost hides what they CAN be used for...Promoting (hopefully) great content!
I do my best to create the best content on the blockchain I can . That being said, getting on the radars of others isn't that easy here. So waiting for a 'whale' to upvote or engage with you can take some time.
Time I'm willing to invest in for sure...
I'm here for the long run and have a multi-year plan for developing my brand on this platform.
'Bots' are helping me on my journey!
As a content creator on this platform I look at every time I invest in a bot, I'm not doing it for any return other than...Getting my stuff out there to more people. And it's working, slowly but surely.
Is it a perfect solution? Nope. And I'm sure things will improve overtime. But as a content creator who WANTS to promote his stuff on the blockchain...I enjoy the services you and other provide.
Well said, @jongolson. Creating your best content is all you can really do and I know that you do that very well. Glad we got connected early on!
One of the complaints we've seen is that bots are "mindless" and are upvoting crap posts. Of course this is subjective... but there really are spammers, plagiarizers, and down-right con artists using our promotion services. Luckily there are people like @themarkymark who have spent countless (and thankless) hours combatting this and creating the ultimate Steemit blacklist.
And with the latest @postpromoter code created by @yabapmatt I believe @buildawhale's blacklist (run by @themarkymark) is added in by default. I know that I've personally added his blacklist to my service and many others have done the same. And this goes back to what Matt said about those running these services being trustworthy. We've all got to do our part to be responsible and ultimately the community will judge for themselves.
You guys all have a tough job and thankless one too. And I get the arguments from all sides, there is a ton of garbage out there...But like you said man, in your comments above...Content promotion is key for all media sites. You have to take the good with the bad. That's social media LOL The more money coming into STEEM though, I think is great.
I had the same experience myself when I first started, and I've heard from many other people like us whom these services have really helped. I appreciate your support and I wish you the best of luck on your Steem journey!
Oh for sure. They are a huge help. By no means I guarantee though. And I think if people have the right mindset when using them, and follow it up with the engagement, etc...It's a great game plan for success long term here.
This post brought up a lot of interesting aspects of promotion/advertising in relation to the value of the Steem token that I hadn't thought of before. For that I thank you @yabapmatt. I, too, have been awaiting this post from you and the angle you took on it is informative and intriguing. I have used bots occasionally- dabbled with them early on, but didn't get a positive ROI or any noticeable benefits for my account on Steemit. This, coupled with the general "frowned upon nature" of using voting bots on the platform led me to try to grow my account organically. But I really appreciate where you're coming from here. I agree with you that most of the top witnesses do have a high degree of awareness on the platform and want it to succeed. Again, I hadn't thought of advertising services as boosting the token in quite that way. That's of course a huge boon to many of us powering up SP.
Of course, like so many, my main offense in the voting bot category is just the way it makes Steemit appear to an outside group of people due to the overall poor material on the trending page (so much better stuff out here making less than $2!). I understand it would be incredibly difficult, if not impossible to truly control the quality unless someone was fully dedicated to the task as a full-time job! I am glad to hear you say "do away with trending". Like many others I don't read it, but find/follow/peruse content "through the grapevine" so to say.
Personally, I've found it more sustainable/lucrative for my account to delegate SP to a private bot service that then gives me a daily upvote. It's nothing to get me anywhere close to "trending", but it provides me a steady positive ROI. As I said above, my experience was different than spiritualmax's in that I didn't find using the bots really helped my account grow. I'll be interested to see how SMTs, Oracles, Communities, etc all shift this current conversation significantly. It seems that with the SMTs and Oracles on top of the blockchain, Steemit.com and its issues will fade as the Communities come into focus. Again, thanks for writing this piece and sharing your thoughts as a witness, bot owner and all around person who cares about the future of Steem.
Thank you, @mountainjewel!
This is exactly right. As far as I understand it steemit.com was supposed to just be a proof of concept site to show what can be done and other third-party sites would come along and carry the bulk of the usage. It seems that the Steemit team is still focusing on trying to empower third-party sites to overtake steemit.com and then they can choose the best UI/UX for their audience which I think is great.
That's the whole point of SMTs and Communities and I, like most people here, are really really looking forward to that!
That is an interesting point Matt... It would make a lot of sense if you are right. Maybe they really don't care about steemit being anything other than a proof of concept site. If that is really the plan then it would explain many things!
While I'm against using bidbots myself, this is an interesting post that reminds us in a very clear way that attracting capital is one of steemit's primary aims (and it's always been clear about this from the outset. )
I basically have the same opinion (or I think it's more of an objective fact) that bid-bots are basically the mechanism whereby advertising takes place, although I'd never really thought about the idea that the revenue generated is more widely distributed than to just the owners of the big corporate sites, which is something I'll have to take away and think through.
I think it's just that all of us who prefer not to use bid bots just value the human validation more than self-valuation/ validation, but then again perhaps we're just naive in that we haven't adjusted this brave new age of micro-capitalism.
When I say 'think through' above I mean what I need to think through is why I'm perfectly happy to spend £1/ day on targeted Facebook ads, and earn £100s a month through advertising from WordPress, when I find the idea of self advertising on here through bid-bots as somehow demonstrating a lack of integrity.
Perhaps it's because it's my professional services I sell through those other platforms and more of of my personal interest stuff I share through here, which I think still has value, and I think that's true of many of us 'community curation types' who are haranguing your comments stream... we're not here to sell services.
As you and everyone else says, perhaps it's soon to be that the advertising services and the community aspect separate out so all of this will be moot, I can't see the bots going anywhere. Until then, it grates seeing good content undervalues and mediocre content bid-botted up, which is maybe something of a long term problem because surely for steemit to have utility as an advertising platform, people have to actually be using it? And clearly many people are being put off by not being able to get any kind of return (and maybe because of a sense of injustice caused by relative deprivation), so something does need to be done about making a distribution more equal, but I'm rambling and point taken about that not being a bot issue.
Bit tired to go into any more depth and am still thinking these issues through, just wanted to put something out there though.
It's still a very new space of course, full of contradiction and innovation so none of us can be certain what's going to happen moving forwards.
Useful article.
It's great to see an intelligent counterargument from a voting bot provider as typically they are silent on this issue, and vastly outnumbered by the amount of people crying out to ban voting bots.
This is a multi-variable discussion but typically I see most people latching onto one piece of the argument and then completely ignoring all other aspects along with their potential benefits.
Like you say the issue is around inequality of reward distribution on Steemit, which is definitely broken. I was very turned off at first when joining the platform (before investing $1k of my own money) because you start with 15SP, which isn't even enough to earn curation rewards. Then as you earn SP, the delegated amount drops away.
So you spend a lot of time literally earning nothing in terms of net SP, and the rate at which you earn SP at first is incredibly slow which is very demotivating. I think more needs to be done to help people get off the ground when they join Steemit and this should be accomodated with increased controls to prevent people having multiple accounts.
If you get an intelligent and balanced critique of this post from someone, will you share it to continue the discussion? It would be great to get some feedback from the devs on this but I haven't seen anything to date.
Great article @yabapmatt. You've certainly contributed a lot to the community and I would say you are engaged.
Bots are advertising and I avoid advertising. I want to see what I want to see not what the highest bidder puts in front of me. I've not been on steem much lately as a consequence. A lot of advertised content has been of no value to me.
Having said that I think you have valid points. It's a complex issue. And indeed the fact that the money is so skewed to the whales is deflating. But this happens everywhere in life. Not just steem.
It also means that if I want my post to be seen then I have to engage in the bot buying. But this is the same outside of steem.
Ultimately the bots are a response not a cause. And what is a paradigm shift in blockchain is that the governance of how people operate is led by the protocol. So new protocols (blockchains etc) will be created until a balance has been found.
👍🏾🙏🏿
Well that's why you can create your own feed and choose who you want to follow. I love my steem feed!
I’m not educated enough about this topic to make a proper comment. I do see both sides of the coin. I agree that many blame what’s broken on here with the obvious enemy. There are so many other problems that many just don’t want to dig further to find root causes. Or simply not care to acknowledge.
No more of my spammy comment. You have plenty of lengthy ones to keep you busy. I wanted to reply to this comment because I saw your feed remark.
I hope I don’t spam that feed of yours! 😀
Hi @yabapmatt and thank you for the vote. It is deeply appreciated.
Yes, but my feed was mostly all resteems. Wherever I looked I seemed to be getting articles that were paid upvoted. The effort to find content got bigger than the time I had.
I work 12 hour shifts on a psych ward 3 - 4 times a week. I already know im going to take a percentage of my check to delegate to @jerrybanfield, and @postpromoter because its a great investment. Its a mother fucking excellent fucking investment. Are kidding me. Daily returns just for holding and delegating the influence of steem. This kills a traditional savings account. Thats a major incentive.
Plus I do music. Music is 80% PROMOTION!
I have spent a lot of money promoting my music on platforms like youtube, and IG and all it gained me was a little bit of followers, but promoting with a bot gives me back a return on my on my investment, more followers, and increase the value of steem in general because i had to buy steem to even promote. Thats a win, win, win. I would have spent the same $300, $500, $1000 anywhere else to get my music in front of peoples eyes, why is it a problem here?
Yes there is a lot of hoarse crap on the trending page, buts thats everywhere. People are promoting on facebook, people are promoting on youtube, people are promoting on twitter, people are promoting on instagram, people are promoting, on billboards and guess what?
Sometimes what they're promoting in my opinion is a piece a shit, but these platforms are still taking the money happily anyway.
Everywhere in the modern world are dull people who have the money to show you their new unremarkable work.
You got a 25 have always thought that you are a good person as I see you are transparent, opened up yuor code that helped people create bots which is also one thing that a lot of people dredge up against you, blaming you on the bid bot epidemic and creating the Steembottracker.
The way that I see it when someone uses the bid bots just for the sake of profit then they are just deluding themselves. Shitty post + boost will make people do the opposite and not engage with you and may even down vote you.
Quality post + boosted at the right time can net you additional eyeballs in your post. followers, which can boost engagement and of course some SP.
I look up to Max and when I joined the Empire saw how to properly use bots and have gotten stronger and faster in terms of my growth.
It also provides liquidity and utilization which is very important. The more the token circulates and create need the better it is.
Then investors see potential and bring in their money into the platform.
One thing that irks a lot of people is they say it kills engagement. I would say I am still pretty engaged and build and support communities.
Although I have to say renting delegations has been so expensive nowadays.
I know that I won't be making mad money in curation but i do it to be able to support people so maybe that is one thing that I don't like about bid bot delegations since it is harder for little fishes like me to rent.
The longer I'm here, the more I'm starting to think that the paid voting bots are a form of arbitrage that arises from an imbalance in the incentive system.
I have long advocated for each author to be able to set their own author/curation reward ratio on a per-post basis. It just doesn't make sense that an inexperienced author and an experienced top-performer would give out the same percentage to their curators. With adjustable curation ratios, newer authors could compete by giving some of their rewards to their voters.
Because that capability does not exist, maybe paid voting bots have arrived to arbitrage the gap.
I think they are sometimes used that way but generally regardless of the incentive system it's important to have a way to promote/advertise your content here. Simply setting a high curation percentage wouldn't get you the visibility of buying promotion.
Well, I can't speak for anyone else, but I don't often look at the trending page, so I'm not sure how much visibility they're providing. OTOH, I guess that's true with more traditional advertising too. You place an ad, but you have no guaranty that it will ever actually get someone's attention.
I also rarely look at the trending page (except sometimes just to see what all the fuss is about). But it is what everyone who is new to steemit.com sees first, and it gives a very bad impression. It's as if the first thing you see when you go to Facebook is a list of the highest paid advertisements!
My suggestion was to get rid of the global trending page and instead ask new users to choose a few interests and then show them trending posts from the categories they choose. That way there will be a better mix of promoted and non-promoted posts and they will at least be more relevant to the reader.
I would actually love that. I remember seeing somebody create a UI mockup (think it was similar to Pinterest if I'm not mistaken) and it showed new users making those selections. Not only is that more personal to the end user but also allows Steemit to provide up better content for said user.
That is a good idea. I am fairly new user and it took quite a while to get my feed showing mainly stuff I am interested in. Picking some initial areas of interest would definitely make the new user experience better. I suspect alot of new users see the trending page and maybe start to question whatever positive impression of Steemit bought them there in the first place
I use postpromoter and feel it makes me post better content. I only use it when I have something I think is worth while. It also helps build up my steem-power so I can use it to reward other's good content.
This is exactly how it's meant to be used!
Well done! Sadly, you are one of the few taking this approach!
I don't agree. If you post crap it should be rejected.
ahh but, that requires a decision making process, and who are the bot owners to judge quality of content?
That's were it get dicey.
Bots are not problem and they are legit business on Steem and they are improving Steem value. According to data, there is less than 2% of votes coming from bots. Good thing is that lately bot owner have started to fight against spam and they are only ones who can do that by creating blacklists for spammers...
I only can say Thank YOU @yabapmatt for this post!
there are so many Steemit users who see the voting bots only negative.
I can say as a still Plankton user, the bots are such a great tool for all of us to promote our posts to get more audience.
The bots are a part of the Steemit system and can be used so.
Since I start using bots my steempower grow, my followers get more and more, the audience of my posts increased very positive.
I only can say Thank You, especially to your fantastic tool Steembottracker.
Thank you @yabapmatt !
Best regards
Tom
Resteemed, much more negatve thinkers should read that!
what are your thoughts on allowing ads on steemit. As you would know that all popular ad platforms like google, facebook etc are banning crypto ads, it would make sense for a blockchain company to allow them on its site. This will also provide tangible value to steem tokens.
Well that's what this is really - you post content and you can pay to promote it. Those are ads. You're probably talking about Steemit Inc selling advertising directly on the site which I don't expect they will ever do nor do I think it makes sense for them to do that. Steem is a decentralized system and this is sort of a decentralized way of having advertising.
Also one thing I don't think enough people realize is that the advertising on Steem is practically free right now. You get most, if not all, of the money you spent back when your post pays out. Really every ICO or other crypto project that is trying to get users should be buying STEEM to advertise to this audience. It just shows how early and unknown Steem is that that isn't happening yet.
I understand your point, my only problem with the current system is its adding way more inflation.
Lets say we don't have bots, then only few posts will get upvoted, which in turn will mean lesser number of steem will be distributed hence lower inflation. Due to current system, lot more steem tokens are getting added into circulation which is hurting steem price. We need a way to burn steem token somehow.
Burning is accomplished by sending coins to @null.
That's not correct. The inflation rate of STEEM is on a fixed schedule and will continue on that schedule regardless of how many upvotes are cast.
Thats something i did not know. I will have to study more to understand economics of steem then. Thanks for your reply.
Personally I don't mind them at all. Having the ability to promote your posts is part and parcel of any platform today - and it continues to drive value in the platform. Ultimately there will be an ecosystem for promoted content, and there will be an ecosystem for found content. Personally I'd like to be in the latter...but I don't hate the former.
23.05.18 I send you 5.35 for promote my post. But I didn't get upvote on my post and didn't get my sbd back. Please chack it
@hphabib you have been sent a refund. Please accept my sincere apologies for the issue.
In my honest opinion I think more people should be buying steem and there should be a little less bid bot buying. I've been seeing a lot of negative ROI's lately especially during peak times. I think a higher steem price would be beneficial to the platform.
we need post promotion and i am thankful most of it is being handled by responsible parties that are trying to be fair with their services.
i support the work you guys do and i often use your services to enhance my own account.
Paid votes have to be bad if we expect the best content to rise to the top and hit the trending boards.
You weren't here much before the bots existed. Even if we magically got rid fo the bots it doesn't mean vote selling stops. It just moves into Discord and DMs where newbies CANNOT get access. It becomes black market vote selling and swapping... This is so much better than what it was.
Have you checked sweetsssssssj or kpine's wallet recently? :)
The black market was not, and could not never be as efficient as tracking the bots and eeking out every last bit of VP - I don't feel we are in a 'so much better' place in this regard.
It used to be the same 15-20 people were in trending for 2k posts every time. It's different now. it went from teh chosen dozen to anyone with money to spend.
I know that people want the best content to rise up rather than the people with the most money to spend. I'm not against that if there's a good way to do it, which I think comes from altering downvoting so it doesn't cost people money to do.
The crusade again bid bots is often a crusade against platform investors that want a profitable return as opposed to interested in reading 20 articles about Canadian Deer Testicles every day to find the best one.
You should drop by the tag #comedyopenmic / @comedyopenmic @aggroed, getting a strange tinglie suspicious you might enjoy the show
I and many others have money to spend, but what would this place look like if we all chose to buy or sell our votes?
Delegate to @curie, delegate to @comedyopenmic, or whatever communities content you are interested in seeing and take a curation rewards share?
It's not as profitable for sure, but it would certainly make @ned feel more comfortable in a Bloomberg interview = positive press = more people = we all become steadily wealthy.
Yes, making it "investor friendly" in the present means it's very anti-user right now. There are very few such investors who are willing to invest in Steemit in its present form, and it's up in the air what happened to Upbit a few days ago. There would be untold numbers of investors willing to invest heavily in a platform with 1 million+ and growing real users which is why this place should be catering to people right now, not investors. Unfortunately all changes are coming from the top-down via STINC and not bottom-up, as most witnesses don't care what the masses have to say about ways to improve the platform for ordinary people. Short-sightedness is in abundance when it comes to how this place is run.
You know I delegate 80k Sp to useful communities right? I have 10k SP into msp-curation which is a manual curation project?
I wasn't aware of the scale, that's brilliant - thank you!
And although a reply to you, it was for everyone to see. I don't know what SP you are at in total, but this sounds like a large % is going out to support communities.
I rent 4k SP, give 7k out for nothing. Can we have more of us please?
You well illuminate the essential difference between the extant profiteering through vote buying and stake-weighting, and delegations that increase the distribution of Steem and thus encourage the healthy profit motive of capital gains.
Thanks!
Have you tried deer testicles sauteed in bear lard with some fresh rosemary and basil?
I bet that's tasty.
@yabapmatt sir,Now @postpromoter is unfavourite bot for all. Some reasons. Upvote time minimum 20 min and low voting weight.I think it's better 1 weeks ago's condition.I hope sir @yabapmatt sir see this.
If it weren’t for the voting bots, I’d probably be abandoning steemit due to how hard it is to gain attention and engagement otherwise. I hate and am discouraged when I put good content out and no one sees it but me.
@yabapmatt do you have any idea why rewards are changing within the time? I've used bots several times and I've noticed that within each day estimated reward seem to pretty much always drop. Example:
Noone downvoted this post and yet my predicted rewards in SBD went down from 78sbd do 71sbd. Which is insane.
I thought that rewards may drop once price of steem and SBD is also dropping. But right now both STEEM and SBD increased their value but my rewards seem to be lower than just a day ago.
I would appreciate if you could share your thoughts. It seem that whenever value of steem and sbd is changing, it affect our rewards negatively.
Yours
Piotr
The value of the rewards shown on steemit.com and other frontends depends on the market price of the STEEM token. It uses a 3.5 day average of the price. So the reason you saw a lower reward value is because the 3.5 day average price of STEEM was lower when you looked a day later than when you looked originally. Similarly if the market price of STEEM increases the payout value you see will increase.
Thank you for your kind reply.
i'm very sorry for such a late reply. have been away for several days but Im back now :)
just wanted to thank you for your previous comment
To listen to the audio version of this article click on the play image.
Brought to you by @tts. If you find it useful please consider upvote this reply.
Minnows don't have a chance to get noticed even if they produce quality content. The upvote services makes it possible for those who are new to the platform to get noticed. Upvote services are the great equalizer.
I am a living example. I've been here for only two months but my rep is already 59. On top of that, I'm seeing a return on my investment. I invested a little of my own money and used that to promote my posts.
I just wish there'd be more services like minnowbooster that guarantee a profit. The bid bots are good for getting your post to the trending page but there's still a chance that you'd lose money.
Advertising generally costs money, so I don't think there should be any qualms about losing out on a send to a promotion tool.
When you advertise, you expect a return. You can't expect a return from the limited audience from steemit unless you're targeting white males interested in crypto and gaming. So, at least for now, the minnowbooster model works the best for me.
But you don't expect a 10-20% return within 7 days. The return comes when people who notice you keep coming back to upvote.
Great piece, @yabapmatt.
I think what is being overlooked is the obvious to me of what the root cause of this "need" of using bid bots is to begin with. The answer to that question, in my view, is the lack of viability to begin with on steemit and inability of good quality to rise to the top organically. If someone new really could come on steemit, post a decent quality piece and see it go viral on steemit to make decent money, then growth would become organic. In my view firming up this core foundation is where the focus should be on and not SMTs that seem to me to be more of a distraction and may become a problematic build on a weak foundation. Now maybe I'm over simplifying it for some, but the core foundation of any business is the always the customers and that is where steemit seems to be failing thus far.
Thank you for your opinions on vote bots. I am new on the platform and have found that the returns I get from delegating to bots makes it worth being here.
I have followed and read the blogs of some of the people who are against bidbots an have been looking for reassurance as to why they can be a good thing for Steemit.
Many of the people who complain about bidbots are trying to make a living by posting on steemit. I suppose that some few people can do that. The majority of users, however, will have to keep their day jobs and come to steemit for fun. The moralizing and shaming make it not very fun.
I have an idea to implement up/down arrow like on reddit and steemit power will be used on tipping. For now there is common idea and social agreement on this platform to upvote own content, which I have also do because will loose money, if not done so. Even posting button has upvote by default checked. Liking own conten on another social network is embarassing. Patology here is like = money = good content. New voting system will rely on unlimited likes / dislikes and content will be scored that way. Tipping own content will become considered like selfupvoting on other platforms. I will get rid also of curation. It does not simply work well. Even if you are first, ones with better power comes before you anyway. Additionaly curation causes fake smiles and even not reading post just upvoting promissing one in exchange of potential profit.
@yabapmatt I've been learning a lot from your post. I'm new to steemit since January 2018. I have one account and enjoy writing encouraging post and I'm getting a lot of up votes and comments lately. I like using the bots but at the same time some of them don't pay. I don't understand how @grumpycat can come and take money from my posts? I believe I'm following all the rules. Not a clue what I'm doing wrong? I upvote most of the people who comment on my post because they will get a little bit for commenting. I don't even know if I receive anything for that? Anyways thats not why I upvote. I'm a little confused on the whole issue. you have my witness vote and I use your bot. Can you give me a little direction pls
@yabapmatt Hey man, I'm interested in having you set up a voting bot for me. What is the best way to get in touch with you?
@metama You can contact me on steem.chat or the PALnet Discord
How can I find you on steemil.chat?
Posted using Partiko Android
a think wat we all want it the same a good platfrom. and open openness how its working in the back. this post is a good start. personal
am I against bots bots or say it in a different way am against bad post bad
boost up. so good white listing or sample testing of users can help. a few days a go a read on somebody doing this..this is good. the clip from Ned was very true just the sad truth of the open wallet system her we can all see it. and on Facebook we think is not there as a normal user.
Todo es por donde se mire el cristal.
Algunos pueden satanizar el uso de los bots. Pero otros los podemos usar de manera honrada para avanzar en steemit.
Podemos hacer artículos de calidad igual o mejor de los que no usan los bots para obtener ganancias más rápidos porque muchos de nosotros vivimos en países donde la situación económica es fuerte y no podemos darnos el lujo de simplemente esperar a obtener las ganancias a largo plazo.
Aunque respeto la opinión de cada uno si los usa o no,es importante que veamos más allá de la situación.
Podemos combinar calidad y negocio en steemit.
Well said, agree with you 💯
Good stuff man! i've been watching your youtube videos and i'm hoping that it'll help me through the beginning of my steemit life! ^-^
well presented information , ty
I will also add that every voting bot should have a support where people can reach out to them for complaints on missing votes. Some of these bots don't deliver votes and don't refund or you have run after them for days. You have been helpful on this topic and I hope enforce this.
One @sneaky-ninja bot has not refund my 2 SBD for like 3 days now even after commenting on his post and there is nothing more I can do pray that he refunds. The voting bot system is Centralized right now because if somehow a bot miss your post, instead of holding it responsible, you may never be refunded like it is your fault.
I think (if it is possible) the voting bots should halt their operations for 1 or 2 days and let's see what happens to the trending page.
It would be interesting to notice the accounts coming up, the highest payout, and quality of the content on the trending page. I also use bid bots and just curious to see the difference on stemit with bots and without bots.
This will also give answers to the people who curse bid bots.
What do you think?@yabapmatt
I loved the video but the gun shots in the video made me laugh :D
That was extremely educational @yabapmatt. I'm learning so much everytime I log onto Steemit. Your post is overwhelming, because I'm still learning more about the blockchain and what it means to me personally. The bigger picture is mentally stimulating and I'm finding that I need to understand SMT's. The thing I love the most about voting bots is the return on investment, but also the efficacy of use. I've been on Facebook since 2011 and have never used their advertising services professionally. Steemit on the other has made a lay person such as myself perform as an investor and entrepreneur which is very valuable if you're living in a Third World country where financial education is worth more than gold..
I think the main reason upvote bots are so widespread is because steemit lacks a good way to promote your posts. I know there is a "Promoted" page but no one ever uses it.
You got a 16.51%!
Well done
you are said very well
thanks for sharing
You got a 21.00% upvote from @brandonfrye courtesy of @brandonfryeroi!
this is noteworthy
@yabamatt Well said. Thank you
English version
A partir de ahora para ser miembro y recibir votos y resteem:
delegar 100 SP (si tienes Power Dawn programado no te deja delegar, quítalo y lo vuelves a programar después)
o también puede ser :
donar 3 STEEM para poder arrendar algo menos de 100 SP por 4 semanas, en esta modalidad la membresía dura eso, 4 semanas.
Necesitamos más stemians. Si conoceis a alguien que quiera entrar en la comunidad, que lo diga y lo incluimos. Lo importante es que publique con frecuencia y con cierta calidad.
Se pueden leer las bases aquí en español
saludos
@rafestrape
¿Abrimos un Discord Chanel?
This is a very general discussion and here are my own opinions. You see about using voting bots, so many people out there just don’t get the concept cause if they do, everyone will generally accept voting bots as the most essential things on the platform
The concept of promotion on steemit should be better understood , any business, projects , ideas , contents that actually wants more exposure even outside steemit is being promoted so I don’t see why promotion on steemit should be a taboo
Paid promotion to me hasn’t caused any problems and I don’t think removing them will actually change anything.
I believe this is a decentralized system, everyone is trusted cause nothing is actually hidden but whoever runs voting bots. I believe voting bots is the number one thing for steem power investors and why should this be taken away.
Thanks for this deep discussion
Great points. But steem also gives the promise of a space without advertising. Where content is what is most important.
But you are right ,advertising brings money into the blockchain and that makes steem valuable.
Does it? Where does it ever say that it is supposed to be a space without advertising? As Ned said in the video it is "the world's advertising network". In my opinion the value of STEEM is all about advertising. The difference between Steem and traditional sites is where the value derived from that advertising goes. On traditional sites it goes to the companies that own the site, and on Steem it goes to the holders of the tokens and the content publishers on the platform.
Steem didn't make the promise in that way. It was that I saw a place that was about the people not the corporation. "Promising".
It is as good to see the intelligent countergroup from a voting provider, as they are silent about this
This is a multi-variant discussion, but in general, I see most people cut into pieces in a reasonable way. Ignore everything completely.
When you join the platform where the opinion is distributed on the Steemit, the issue of discrimination in the matter of discrimination, which is clearly broken, in the first place I used to tremble very much, then as you earn SP, the amount allocated to the drop
So you spend a lot of time on a large part of Net SP, and the rate at which you initially earned the SP is incredibly slow, which is very daemoniting. More needs to be done and it should be acquired with additional control to prevent people from multiple accounts.
If you get an intelligent and rich criticism of this post from someone, will you share it to continue the discussion? Some feedback would be great but I did not see anything in date.
It makes a lot of sense to run promotion services. For one it gives new account holders a chance to promote their works that would normally not be seen on account of their low steempower. There are many advantages to promoting. It increases reply score, steempower and also profits for the users.
Definitely content promotion is not bad yet all. I myself use these services to promote my posts. With the help of bid-bots I increased my reputation score from 25 to 52 in just two months after joining steemit. Otherwise, I would have been struggling to find a place on this platform.
I have invested my hard earned money on buying Steem and SBD so that I may earn some profit here. Everyone is here to get a share in daily reward pool. No one can deny that he/she is here just to earn some money for him/herself.
Content promotion is not bad as I have already mentioned but bot owners should also see that many a times average or below average posts become trending on this platform just because of vote buying. People follow herd mentality. They don't see a post is worth their vote or not. They just see that a post is in the trending section and they rush to vote it. Also, some bid-bots are cheating people. Sometimes they don't upvote after sending bid. They don't even reply. Do we have any mechanism to address this problem ? I think the answer is no. Also, people are sending too much SBD or Steem to bid-bots in comparison of their vote value which becomes a matter of loss for every participants in that voting session. Should bid-bots not refund the excessive amount to the senders? Who are the real winners on this platform? I think the bid-bots because they earn for their vote and also receive huge curation rewards for upvoting. This becomes a win-win situation for them, though the ROI of them is most of the times negative for the senders.
In my view bot owners should address these issues as early as possible. They can implement mechanism that after a certain amount a post would not be upvoted. They can refund the excessive amount. They can impose the maximum limit on sending bid in single instances. They can blacklist the abusers (some bots are doing this) and distribute the curation reward to the community. There are many ways. Problem is not the unavailability of solutions but the problem is the lack of will.
Kickass new banner Matt!
As for this topic, I think the better thing to do would be to:
How would you do this? Well, the trending being about rewards is wrong... I dont know if it is possible, but a more advanced algorithm to detect:
what we should have is a downvote option. which is not as severe as a flag but lets the creator know like, "hey, you know that post of you drinking soup and Switzerland, yea the one you spent 700 STU on is trash and you're not going to get a full return on your promotion because we all down voted it. please do better.
Votebots for the most part result in a loss for the consumer, a profit for the owners. Due to the payout structure, where half is in SBD and some weird percentage way below half is awarded in SP one never receives the value they invested back. This gives the bot owners and those who delegate the SP a means of bypassing this skewed payout by getting it all up front in SBD, then they collect gravy on the curation payout a week later.
If people want to help those who have get richer while they get poorer they better damn well make sure they have a great product. And not sure how much the visibility is really there. Who even looks at Trending and Hot?
I am not rabid against the bots as some are, but I do believe they have made search a mess and make the rich richer and the poor poorer. I wish there were more honesty from not only bot owners but you and your bot tracker site when it comes to leading your clients into believing they will make a profit when they will not. I have to wonder if this is the reason why SBD, which is supposed to be pegged at 1.00 is worth so much more.
My friend who uses the bots crunched the numbers and according to the math being pitched a bot order would have to pay out at 200% roughly for the person to break even on paying for these services.
Seems like a scam to me. But all is fair in business I guess. I know I personally will not vote for a witness that is running one of these bots. It is hard enough to get newer people to stay. They come, believe they must use these bots and it will make their already pitiful payouts shrink as they hand over more than they make from your votes. I believe this is poor vision for long term sustainability so in good conscious can't lend my vote to those profiting from this.
Thanks for opening this discussion.
You said true
i agree with you
thanks for sharing
I think voting bots & paid voting services have arisen out of the vacuum the poorly implemented Promoted feature has left. But the inbuilt promotion system is a great concept as it eliminates middlemen and profiteering, instead spreading the benefit to everyone through the burn mechanism. Simple fix #1 that would give competition to vote services is just to break it out of a segregated tab & mix it into regular content pages.
I’m going to copy over a comment I made in another discussion about a month ago for another promotion system to compete with bidbots.
My dream for advertisement is this...
Steemit partners with a service such as Anonymous Ads. Their simple embed code gets whitelisted so it works on Steemit. Anonymous Ads of course begins accepting & paying out in Steem in addition to their current Bitcoin.
Every Steemian can now create banner ad slots in their posts. Rather than bid bots & the trending page, it becomes a valuable alternative to purchase ad space direct from other Steemians to promote your own blog, posts, & projects.
We get a working advertising system vs. the current broken promotion system. Ad revenue creates a de facto unlimited payout timeframe allowing good content to be “evergreen.”
The system should be largely self policing too. If a blogger goes overboard with ad slots they’ll risk being unfollowed or outright flagged if folks are truly miffed!
Anonymous Ads already has the ad inventory creation & management tools. It would probably be extremely simple to allow their code and create a user driven advertising market overnight.
And of course the system also easily allows outside advertisers to tap into Steemit, and Steemit creators to advertise on outside sites as well from a single account/dashboard.
The ad service takes a percentage of course, and it could be increased or divided to allow some back to Steemit Inc. or for burning purposes.
An alternative “partner service” with a better bid system but no crypto roots is Project Wonderful.
The overall idea behind both these aims is to give control to users, eliminate middlemen, and give the bots competition and see if their business model still thrives.
this seems to be a 180 turn from "one account one vote" ... which i'm not mad for, i feel the freedom to choose outweighs the idea of any group or subgroup on what defines "bad" and what defines "good", it has a mute button, it could use a block button. I'm well aware it's a blockchain but a simple out-of-sight out-of-mind on the Steemit UI could already do wonders, a single flag that allows people to hide posts by default could also help, if the main chunk adopts common sense. There's a reason why adblock exists for a while now : to give people the choice wether they want to see it or not, but wether you see it or not, its still there
... quite confused by all the things i hear lately , regulation has never been a good idea on planet krypton so far and i doubt it will be, i think the community works pretty fine for something without real enforcement where everyone can see everything for all time, so i'll stick to it, just a little out of sight would be a lot out of mind for people who get annoyed easily, or people who don't know how to use the search , or theres probably dozens of reasons , better (and easy to use for dummies) filters on the U.I. :)
also a lot of fud going around and yes, i think its the takes of the powerusers to find ways to sell the steem chain to wallstreet class money, but without going public, definitely without giving up sovereignty and going public, that would be a bad thing. To find alternative uses, ANY alternative use that could entice a few millions this way, would always be a good thing lol
there should be some serious brainstorming at whale level on that. It would benefit everyone, not just the already rich if the price can go up because wallstreet money comes in and THEN , preferebly before that, awareness campaign on NOT to dump sh*tloads at once in the sea, so to speak or its back to start
fyi - total bids for "pushup" are not appearing on the steembottracker site - fyi
Thanks for the article! It feels like I learned months worth of info about STEEM and SMT in just one article! 2 thumbs up!
I appreciate this explanation and you presenting your argument as to why running voting bots is beneficial for the platform and why banning them would be throwing the baby out with the bathwater, to use the same analogy. One thing that I didn't see much discussion about is about whether or not distributing your power in that manner is ethical, which anecdotally speaking, it seems that most of us agree is not (and by "us" I mean the people in my orbit). But that's only one issue.
I think that while having the bid bots may have some effect of raising the value of STEEM as an investment (and therefore its value as a token)--which I admit, is an argument I had not considered until I saw it laid out so eloquently--it simultaneously has the indirect effect of cheapening the value of the project and by extension, the token. A consistent experience that I see from just about every newbie (which I shared) is that they almost gave up at some point in the first week because they saw hundreds of dollars next to what is essentially spam littering the front page, while earning dustvotes that turned to nothing on their own. You have to provide the caveat to newbies that they basically need to ignore the front pages of this site, which is obviously a huge problem for the usability of this site, since we don't really have a solid search and navigation system for fresh content.
There are also all sorts of other issues related to artificially raising the value of content that did not surface on its own merit. You mention advertising, but how often is that front page spam content really "advertising" (except by the loosest definition of the term, i.e. "self promotion")? You say that our arguments are naive, but these arguments seem pretty naive to me too. There are already official mechanisms on this site that allow you to pay to promote your content, which are basically rendered useless and ineffective because of these home-grown voting bots, so the proverbial "baby" in the bathwater that you speak of could easily be resolved by other means. You may be one of the "good guys," but there are plenty of bad actors who are running bots or taking advantage of them, and I don't see this blacklisting and self-policing that you speak of, and if it exists, then it's certainly not doing the job adequately.
I hope that I didn't offend you in expressing my personal opinion. I truly appreciate reading these counter-arguments, and it gives me a lot to think about.
Sir, I will suggest to insist on bots having a support or always checking the replies on daily bases. It's been over 9 days since @sneaky-ninja missed to vote on my post and I have not broken any of his rules yet, no refund of my 2SBD even after several comments on his latest post. Many others too are complaining.
If the whole idea is to have a decentralized system, how are these acts by bots different different from those of the centralized governments we have? A bot missed to vote on your post, you loose your money like it is your fault.
I have just given you my witness vote and I pray you take necessary actions.
what APR are people earning on steem?
When just curating?
When delegating to voting bots?
The voting bot owners themselves?
Greetings, I dont understand the Vote Value for @promobot
@badnews The vote value shown on the bot tracker site is in USD by default. If you would like it to match what is shown on steemit.com and other front ends please change the currency setting to show "POST REWARDS".
Hi @yabapmatt this is more of a technical support question on Steem Bot Tracker; I can't seem to see the Details or any other options appear when I click the Actions button on any of the bid bot listing. Maybe I'm the only one experiencing this since a couple of days ago? In any case, a head's up on this issue if it's not just me, and hope it gets resolved. Thanks.
@webgrrrl what browser / device are you using? The site is made for desktop and definitely doesn't work well on mobile devices, but let me know if it's something else.
Sir @yabapmatt
I sent 6 SBD to postpromoter for an upvote, but it did not upvote, can you refund it sir, I cant afford to losse it this way. I am very little minnow sir, please help me out and also I request you dont upvote at this point and it has no meaning now, so kindly refund my 6 sbd, i will be grateful to you.
I am very sorry about that! Your payment has been refunded. Please let me know if there is anything else you need.
I am really touched by your kindness sir when I saw 2 sbd extra in refund. My heart felt respect to you sir. I have never seen such a kind person in my life in any social media. I am grateful to you and obliged.
Hello,@yabapmatt today I have sent 5.100 sbd to @postpromoter But I didn't get the upvote from the bot!
If there are any technical problems?
I therefore pray and hope that you should kindly return my sbd.
Chat Conversation End
I am very sorry about that - your payment has been refunded!
thanks you for your service
Dear @yabapmatt , sorry to inform you so earlier, im supposed to wait 24 hours but my post has not been promoted by postpromoter, i checked several time, postpromoter received my payment, Here is my post link:
You have been sent a refund for the missed vote. Please accept my sincere apologies for the issue.
Hello,@yabapmatt today Few minutes ago I have send 5.350 sbd to @postpromoter and but
I won't get upvote from the bot!Also my bid was not added to the next round. Please check it if there any technical problem.
For this post:
I therefore pray and hope that you should kindly return my sbd.By the way postpromoter is so much correct then any other bot. But today i face problem.
I hope you will solve it as soon possible.
You have been sent a refund for the missed vote. Please accept my sincere apologies for the issue.
Thanks for this lovely behavior.
Something wrong with your bot? Didn't receive upvote for 50 SBD
You have been sent a refund for the missed vote. Please accept my sincere apologies for the issue.
No issues bro.
Just a suggestion, kindly put your discord(if you have) link in the profile somewhere. Steemit community is more active on discord than anywhere else.
I sent 5 SBD to promote my Post but it wasn't Upvoted.
I guess there was some Missed Votes as it seems there were Many Missed Votes.
Can you please check it out @yabapmatt.
You have been sent a refund for the missed vote. Please accept my sincere apologies for the issue.
It's all right @yabapmatt .
Thanks for the Refund.
Hello sir, sorry for the comment but I have not received my upvote. I have sent to @postpromoter 5.36 sbd for this post but I have not received upvote yet please check my post.
@anilkumar125469 you have been sent a refund. I sincerely apologize for the issue!
Hi @yabapmatt,
Is it possible to get on your list of "Other bots" on "Steem Bot Tracker"?
Please see our into post to our service:
@upvotebank has been added to the list of other bots on the site.
Thanks!!!! :-)
i didn't got my vote back and it's about 18 hours! will you please check sir? :)
@sfturzo you have been sent a refund. I sincerely apologize for the issue!
mention not! thanks btw ^_^
Hello @yabapmatt, The robot didn't vote for my post. How to solve this problem. Thanks;)
@rosy440 You have been sent a refund. I sincerely apologize for the issue!
Thank you!
Who owns boomerang?
@deliberator Please contact me on steem.chat or Discord.
What channel on discord?
Is this your scam bot? I am hearing many complaints like mine, half value upvote compared to bid, is it your bot?
You can reach me on the PALnet discord here: I do not run the boomerang bot and do not have any affiliation with it.
Hello, @yabapmatt . why not response about_7<<
Missed Upvote 2:
sir, you know i am plankton in steemit.But at any notice i can't find my answer.Please refund my SBD.I am waiting for you.
Chat Conversation End!
@shabbirahmad you have been sent a refund. Please accept my sincere apology for the issue.
@yabapmatt sir, Thank you so much. I got that. :-) God bless you.
Hii Respected @yabapmatt, today I am very depressed when I buy vote from one of the bot named @boomerang working under your steembottracker. I send him 9.821 SBD and astonishing to see that he just giving me 4.81 Vote. this is not fair with me, I hardly earned with day and night working and this bot looting me by scamming. he stopped the max bid suggested timer for dodging us. It is my humble request to you plz check the matter with your personal interest and Refund or balance my loss and also take action against him because he is scamming with innocence. Thanks in advance.
@rabeel I have contacted the owner of boomerang and asked that he resolve all of the complaints or i would be forced to remove the bot from the site. In general though I would suggest that you only use bots that set a minimum ROI value since those limit the number of bids that can come in in each round to guarantee a set level of return.
Thanks, @yabapmatt, when i send then i checked the ROI, but @boomerang dodging us by manipulating the system steembottracker of (max suggested bid) just scamming.
anyway thanks for replying and encouraging.
Thanks @yabapmatt, my problem solved. really appreciated_8<<
Missed Upvote 2:
sir, you know i am plankton in steemit.But at any notice i can't find my answer.Please refund my SBD.I am waiting for you.
Chat Conversation End!
Hello sir ,
23.05.2018 I send you 5.25 for promot . But i did't get upvote on my post and you did't back my sbd. Please return my sbd.
@wasif33 You have been sent a refund. Please accept my sincere apology for the issue.
Hello Matt, I know this post is 'old' and my comment is not related. But I sent 5 SBD for a post 5 hours ago and have not received an upvote from @postpromoter. Wondering if you can look into it when you have a chance?
@glennolua it looks like you transferred 5 SBD to the postpromoter savings account. That's why it did not pick up your bid. I have just sent you a refund.
Hey Matt, thanks for the reply. I woke up at 4am PST (California) for work and made the exchange from my phone. Probably not the best time to work with wallets and transferring crypto as I was sleepy...
Lesson learned, thanks again! -
This post is from yesterday and boomerang is still broken.
Pasting it here to being it to your attention.
@boomerang
I lost money on your voting bot because its not updating on steembottracker.com
It showed only 4 bids while you were actually oversold:
Wallet snapshot
Your bot is losing people money because of it. Mine is a small acct and it takes lot of effort for me to recover from losses.
CC: @yabapmatt If this is an issue in the site, can you please check it out
I think upvote bots are not good in the long term in spite of the benefits for those that use them in the short term. They retard the growth and full potential of what Steem.
Maybe an option to filter out posts with paid votes would be good for people. If don't come to Steem for ads, I come here for outstanding content. With bid bots in place, sometimes the best content is difficult to find.
Hello, @yabapmatt . why not response about this!!
Hello, @postpromoter and @yabapmatt. 2 days ago I send you 5.400:
@uncommonriad You have been sent a refund. Please accept my sincere apology for the issue.
Yes, I got it. I am very happy. Thank you so much @yabapmatt
Hi @yabapmatt sir
I have a missing bid
Can you please check, I haven't received refund yet.
Here is the link to post
@uxair You have been sent a refund. Please accept my sincere apologies for the issue.
Thank you -
You have been sent a refund.:
hi @yabapmatt is there any channel I can reach you? email or discord maybe?
@grimjaw I am available on steem.chat or the PALnet discord. Same username as on steem!:
Every time we post our blogs to twitter etc we are advertising the platform and the token. That's what I got from Neds video. SMT's may expand knowledge of the steem token and hopefully demand. | https://steemit.com/steem/@yabapmatt/on-voting-bots | CC-MAIN-2018-39 | refinedweb | 15,510 | 70.63 |
Type: Posts; User: N@R!MAN
I have Problems with deleting node in trees!my first problem is I don't understand the algorithm of deleting a node with two child!:confused: I write some kind of code that delete a node with two...
I used o.flush() after writing process and mu problem is solved now!!! it was not read function problem!
tnx
of Course!
after I read information from file :
if(stu.getNum() != 0 )
{
cout << "Name : " << stu.getName() << endl;
}
Here is My Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
I'm Learning Exception Handling And now I Have a problem with Exception Specifications!
Right? But look at my code :
// Test.cpp : Defines the entry point for the console application.
//
tnx, I get it!:thumb:
hey guys
I wrote a simple Complex Class and overload input/output and +/- Operators in it!But there is something that doesn't work correctly!I can print an object of that class but I can't print sum... | http://forums.codeguru.com/search.php?s=ce7e5d3b55e4f3a639b626874caf17e1&searchid=6781597 | CC-MAIN-2015-18 | refinedweb | 172 | 79.16 |
A stream buffer is the vegetated land adjacent to a streambank.
Stream buffers are strips of trees and other vegetation that improve water quality by filtering pollutants from stormwater runoff such as oil, fertilizers, pesticides; reduce flooding and erosion by stabilizing stream banks; moderate stream temperature and sunlight, keeping fish and other aquatic life healthy; provide nesting and foraging habitat for many species of birds and animals.
Yeah, OK - not those stream buffers. I’d like to talk a bit about the beloved, intuitive, C++ standard library kind, the ones everybody loves (to hate) and understands (not).
When I was a wee C++ apprentice (pre-C++98), I was taught that when designing your API don’t take a file-name or assume a standard input/output stream. Instead, take a
std::istream& or
std::ostream& (or
std::iostream) and thus support any such (derived) stream.
Recently, while working on integrating two libraries, I came across an interesting challenge.
One library,
Encoder, the encoding library, expected an
std::ostream& to write data too (it thus naturally supported file serialization given a
std::ofstream):
Encoder::encode(std::ostream& os);
The other library, call it the device library, provided a C-style write function such as
int device_write_callback(const char* buf, int sz).
I needed to get the encoding library to encode my data and write the encoded data into the device using this API. The easiest solution is of course:
Encoder encoder; // fill encoder with data... std::ostringstream ostr; encoder.encode(ostr); auto buf_str = ostr.str(); // makes another COPY! device_write_callback(buf_str.c_str(), buf_str.size());
This works, but has a major drawback: the encoder will first encode all the data into an internal in-memory buffer. Only after this is allocated and done, will the entire thing be written to the device. If our encoded data is very large, this can consume copious amounts of memory.
To make matters worse,
ostr.str() returns an additional copy of that giant buffer!
What we’d like is to create a
std::ostream that instead of writing to a memory buffer, directly calls the device-writer function.
One option is to use Boost.Iostreams. If you already have Boost in your project that is a valid way to go, but if you don’t, or don’t want the extra power and complexity that it brings, it turns out we can get the same benefit by rolling our own little
streambuf.
Custom Stream Buffers
The standard provides two ready made stream buffers
std::basic_filebuf and
std::basic_stringbuf which are the basis of
std::basic_fstream and
std:: basic_stringstream respectively.
We will create our own class derived from
std::streambuf and pass that to a generic
std::ostream.
A thorough review of iostreams and stream-buffers is way beyond the scope of this post (or my knowledge for that matter). So here’s how to create a simple little
streambuf to avoid the extraneous memory allocations (at least on your side) and just call the callback with whatever data is ready to be written:
template <typename Callback> struct callback_ostreambuf : public std::streambuf { using callback_t = Callback; callback_ostreambuf(Callback cb, void* user_data = nullptr): callback_(cb), user_data_(user_data) {} protected: std::streamsize xsputn(const char_type* s, std::streamsize n) override { return callback_(s, n, user_data_); // returns the number of characters successfully written. }; int_type overflow(int_type ch) override { return callback_(&ch, 1, user_data_); // returns the number of characters successfully written. } private: Callback callback_; void* user_data_; };
Basically, we derive our class from
std::streambuf and override the two virtual functions
xsputn() and
overflow(). The default (base) implementations of the rest of the streambuf methods will eventually reach these two functions: one writes a single character and the other several (in fact, the default implementation of
std::streambuf::xsputn() calls
std::streambuf::overflow()
n-times).
A few things to note:
- The class is templated on a
Callbacktype. Although we know the desired signature of the write callback (since we have to call it in the methods and they must return the number of characters successfully written), we use a template type parameter as the callback type so we can also pass capturing lambdas as our callbacks.
- In the code above, I made the write function be a callback that also accepts a
void* user_dataargument. This is useful with C-style APIs but not always necessary (and not really relevant for the discussion here).
We can also add a little helper
make function:
template <typename Callback> auto make_callback_ostreambuf(Callback cb, void* user_data = nullptr) { return callback_ostreambuf<Callback>(cb, user_data); }
We can now use our class like this:
auto cbsbuf = make_callback_ostreambuf([](const void* buf, std::streamsize sz, void* user_data) { std::cout.write(reinterpret_cast<const char*>(buf), sz); return sz; // return the numbers of characters written. }); std::ostream ostr(&cbsbuf); ostr << "TEST " << 42; // Write string and integer
Although somewhat contrived, this will print
TEST 42 to the console. In fact in such a lambda we can call any other device writing API regardless of the actual signature of that API.
Sweet 17 and beyond
The code above should work with C++11 and C++14 (up to some minor fixes). In fact, without the lambdas it’ll should also work with pre-C++11 compilers (the iostream library is pre-C++98!).
However, there are a few issues with the code above that make it less modern and type safe than it could be.
For starters,
make_callback_ostreambuf() is an ugly API wart. The only reason we need it is so that we don’t need to write
callback_ostreambuf<decltype(callback_fun)> my_streambuf(callback_fun); where we must specify the type to the template class (i.e.
<decltype(callback_fun)>).
C++17 will bring us class template deduction so with a C++17 conforming compiler we will be able to declare
callback_ostreambuf my_streambuf(callback_fun); and the callback type will be deduced automatically just like with
make_callback_ostreambuf().
A more subtle annoyance is that there is actually no static type enforcement on the callback type. It is called
Callable but it is only assumed that:
- it is a callable;
- it has the correct arity (number of args);
- it has the correct return type;
- all the args have the correct types.
Duck typing galore!
Any deviation from these will be rewarded with a compilation error or various wanrnings. However, to make matters worse, these errors and warnings will be shown at the point of duck-type usage, i.e. inside the method implementations of our class and not at the point of call at the class ctor.
Ironically, had we made our class non-template and decided to support only function-pointer callbacks, the compiler would have warned us of a type mismatch at the ctor call.
Using SFINAE it is, in fact, possible to decompose the
Callable type into various types of callables (e.g. function pointers, class member
operator(), etc.) and
static_assert correct conversions. While demonstrating some very clever template meta programming (TMP) techniques is appealing, the resulting code would be several times larger and many more times more obscure than our current 20 line class.
There is however a glimmer of hope. Part of the raison-d’être of C++ concepts, which may be available as soon as C++20, is to allow more powerful and expressive static type checking and allow the compiler to warn at the point of usage. Concepts would allow us to precisely describe the callback type for proper type checking. I quiver in anticipation.
TL;DR
To create a custom
streambuf:
- Derive your class from
std::streambuf;
- Override the two virtual functions
xsputn()and
overflow().
(You can even get away with overriding only
overflow()and the default
xsputn()will call it
ntimes).
(see what I did? put the TL;DR at the end… mwahahaha)
🦆
Custom Stream Buffer View
So we have a buffer with our encoded data. Maybe we saved it, maybe we sent it over the network. At some point we’d like to decode from such a buffer. We have a large contiguous memory buffer and we’d like to read from it. Our decoding library, again, sports a
std::istream interface for decoding. How can we provide it with such a stream?
As before, the obvious option is to create a
std::istringstream initialized with our buffer. However, inspecting the docs for
std::istringstream shows that both the ctor and the
std::istringstream::str(<string>) methods create copies of the data, something we’d like to avoid for very large buffers.
What we want is an “
istring_viewstream” that will stream a view of our buffer just like C++17
std::string_view is to
std::string.
Fortunately, that’s pretty short work:
template <typename Byte = char> class istreambuf_view : public std::streambuf { public: using byte = Byte; static_assert(1 == sizeof(byte), "sizeof buffer element type 1."); istreambuf_view(const byte* data, size_t len) : // ptr + size begin_(data), end_(data + len), current_(data) {} istreambuf_view(const byte* beg, const byte* end) : // begin + end begin_(beg), end_(end), current_(beg) {} protected: int_type underflow() override { return (current_ == end_ ? traits_type::eof() : traits_type::to_int_type(*current_)); } int_type uflow() override { return (current_ == end_ ? traits_type::eof() : traits_type::to_int_type(*current_++)); } int_type pbackfail(int_type ch) override { if (current_ == begin_ || (ch != traits_type::eof() && ch != current_[-1])) return traits_type::eof(); return traits_type::to_int_type(*--current_); } std::streamsize showmanyc() override { return end_ - current_; } const byte* const begin_; const byte* const end_; const byte* current_; };
Again, we derive our class
istreambuf_view from
std::streambuf and this time override a different set of virtual functions. All this class really does is manage 3 pointers.
The usage is quite straight forward:
auto buffer = "TEST 42"s; auto view_buf = istreambuf_view<>(buffer.data(), buffer.size()); std::istream istr(&view_buf); std::string str; int v = 0; istr >> str >> v; // Read string and then integer assert("TEST" == str && 42 == v);
A few things to note:
- The class is templated on a
Bytetype. Any 1-byte type should work and this is
static_asserted.
- The default character type is
char. Using that we get the aptly named “diamond operator”
<>.
- For convenience I added two constructors, one for pointer+size and the other for a begin+end.
Sweet 17
In this case too, C++17 will come to our aid and slightly simplify our code. With either class template deduction or user-defined deduction guides we will be able to drop the diamond operator in the default case and remain with the cleaner
auto view_buf = istreambuf_view(buffer.data(), buffer.size());
A natural extension to this class would be to also accept a
std::string_view or GSL’s various span flavors.
💎
Update
In the Feb. 2017 ISO C++ mailing, Peter Sommerlad proposes:
P0408R1 - Efficient Access to basic stringbuf’s Buffer.
From the paper:
Streams have been the oldest part of the C++ standard library and their specification doesn’t take into account many things introduced since C++11. One of the oversights is that there is no non-copying access to the internal buffer of a
basic_stringbufwhich makes at least the obtaining of the output results from an
ostringstreaminefficient, because a copy is always made… This paper proposes to adjust the API of
basic_stringbufand the corresponding stream class templates to allow accessing the underlying string more efficiently.
If accepted this would allow direct access, a-la
string_view, to a
streambuf’s underlying buffer and avoid the additional copy created by calling
str()as mentioned in the Custom Stream Buffers section above.
Alternatively, Peter Sommerlad points me to another proposal of his: P0448R0 - A strstream replacement using
span<charT>as buffer which proposes “a class template
basic_spanbufand the corresponding stream class templates to enable the use of streams on externally provided memory buffers. No ownership or re-allocation support is given. For those features we have string-based streams.”
If accepted this would allow creating a
streambufobject
basic_spanbufas a direct view over our external buffer in the Custom Stream Buffer View example.
Good luck Peter!
💎
Summary
Iostreams are much maligned, but they go back a long way and for better or worse they shall remain with us for a while yet. Many idioms build upon them and occasionally one needs to dip a toe into these frigid waters. This post is not intended as a comprehensive tutorial but mostly as a public pasteboard where I can come and remember how to do these things in a few years instead of rummaging and collecting this info again elsewhere. I hope you find it useful too.
Acknowledgments:
- I’d like to thank Simon Brand, Jonathan Müller, Anthony Williams and Lynden Shields for the great discussion about SFINAE on lambdas on the lovely C++ Slack channel.
- Miro Knejp taught me the term diamond operator and cool uses for user-defined template constructor deduction guides.
- This SO answer and this post for pointing me in the right directions.
If you found this post helpful, or you have more thoughts on this subject, please leave a message in the comments, Twitter or Reddit. You can also follow me on Twitter. | http://videocortex.io/2017/custom-stream-buffers/ | CC-MAIN-2020-16 | refinedweb | 2,150 | 51.89 |
CodeCogs is an Open-Source library, with technical references and numerical components written in C/C++.
It is an interactive library, with working examples, online calculator and interactive graphs, covering Mathematics, Statistics, Science, Engineering and Finance.
This Website needs Javascript
Many features on the website will NOT work correctly if you do not have javscript or if you have it disabled.
Please change the setting within your browser. If you browser does not support Javscript, then we recommend that you update to a new version. The following are all free:
FireFox, Internet Explorer 7, Safari
#include <codecogs/stats/moments/correlation.h>
#include <iostream>
int main()
{
int x[4] = {3 , 7 , 5 , 6 };
int y[4] = {4 , 3 , 7 , 1 };
double corr = Stats::Moments::correlation<int>(4, x , y);
std::cout << "The correlation of x and y is: " << corr << std::endl;
return 0;
}
The correlation of x and y is: -0.278132 | http://www.codecogs.com/pages/home.php | crawl-002 | refinedweb | 151 | 51.78 |
1
O.k i searched the site but didn't find anything related to my problem.
all ive done is made a simple calculator using the "else if" command.
I'll post my coding and compiler errors below.
#include <stdio.h> main() { int valid =0; char operator; float number1,number2,sum; printf("calculator\n"); printf("number\t operator\t number"); scanf("%f\t %c\t %f\t", &number1, &operator, &number2); if(operator == '+') sum = number1 '+' number2; else if(operator =='-') sum = number1 '-' number2; else if(operator =='/') sum = number1 '/' number2; else if(operator == '*') sum = number1 '*' number2; else valid = 1; if(valid != 1) printf("%f %c %f = %f", number1, operator, number2, sum); else printf("invalid command unlucky"); }
compile errors are as follows :
Error E2379 keelan.c 15: Statement missing ; in function main
Error E2379 keelan.c 17: Statement missing ; in function main
Error E2379 keelan.c 19: Statement missing ; in function main
Error E2379 keelan.c 21: Statement missing ; in function main
Warning W8070 keelan.c 30: Function should return a value in function main
*** 4 errors in Compile ***
now to my knowledge the: else for, for or while command don't use ; as a close.
as you can see I'm new to programming so don't be to harsh please.
thanks. | https://www.daniweb.com/programming/software-development/threads/138939/need-help-with-a-calculator-also-diffrent-reason | CC-MAIN-2016-50 | refinedweb | 209 | 54.93 |
Azure Event Hub libraries for Java
Overview
Collect and manage millions of events per second from connected IoT devices and applications with Azure Event Hubs.
To get started with Azure Event Hubs, see Receive events from Azure Event Hubs using Java.
Client library
Send events to an Azure Event Hub and consume and process events from an Event Hub using the Event Hubs client library.
Add a dependency to your Maven
pom.xml file to use the client library in your project.
Example
Send an event to an event hub.
final ConnectionStringBuilder connStr = new ConnectionStringBuilder() .setNamespaceName(namespaceName) .setEventHubName(eventHubName) .setSasKeyName(sasKeyName) .setSasKey(sasKey); final EventHubClient ehClient = EventHubClient.createSync(connStr.toString()); final byte[] payloadBytes = "Test AMQP message".getBytes("UTF-8"); final EventData sendEvent = new EventData(payloadBytes); ehClient.sendSync(sendEvent);
Samples
Explore Event Hub data-plane API using samples
Write to Event Hub via JMS and read from Apache Storm
Read and write from EventHubs using a hybrid .NET/Java topology
Explore more sample Java code for Azure Event Hubs you can use in your apps.
Feedback | https://docs.microsoft.com/en-us/java/api/overview/azure/eventhub?view=azure-java-stable | CC-MAIN-2019-35 | refinedweb | 175 | 57.98 |
Ive been working on a solution to my homework problem for a couple hours and I believe I have found the answer but I keep getting)
#include<iostream> #include<cmath> #include<iomanip> #include "Mortgage.h" using namespace std; void process() ; void maxLoan() ; void debt() ; double calc_payment(double Loan, double rate, int term); void printTable(double payment, double Loan, main() { int choice ; char resp[10]; printf("\n\t\tWelcome to CSC262 Mortgage Calculator System!!\n") ; while(true) { main_menu() ; while(true) { printf("\n\t\tYour choice is: ") ; cin >> choice ; if ( choice < 1 || choice > 3 ) { printf("\n%d is an invalid choice!") ; printf("\nPlease enter your choice 1, 2 or 3 :") ; } else break ; } switch (choice) { case 1: process() ; break ; case 2 : maxLoan() ; break ; case 3: debt() ; break ; case 0 : printf("\n\nThank you for using CSC262 mortgage calculator System!\n\n") ; return 0; break ; } printf("\n\tWant to to continue? (Y/N)") ; cin >> resp; if ( resp[0] == 'Y' || resp[0] == 'y') continue ; else break ; } printf("\n\nThank you for using CSC262 mortgage calculator System!\n\n") ; return 0; } void process() { // process option 1 : determine Monthly mortgage payment int term ; double Loan , rate ; double total_interest = 0.0 ; char resp[10] ; double payment; cout << "\n\tPlease enter the Loan amount in $ :" ; cin >> Loan ; cout << "\n\tPlease enter the interest rate (e.g 4.5 for 4.5%) :" ; cin >> rate ; cout << "\n\tPlease enter the terms in # of months :" ; cin >> term ; Mortgage mtg(Loan, rate, term); double calc_payment(double Loan, double rate, int term); { payment = Loan * ((rate*pow((1+rate),(term)))/(pow((1+rate),(term))-1)); } void printTable(double payment, double Loan, =, Loan , rate ; double total_interest = 0.0 ; double payment = 0.0 ; double interest = 0.0 ; int n = 0 ; cout << "\nPlease enter the debt amount in Dollars : " ; cin >> Loan; cout << "\nPlease enter the interest rate : " ; cin >> rate; // put your code here ; // main logic for determine the # of payment in order to pay-off double remain = Loan ; while ( remain > 0 ){ interest = remain * rate/1200 ; total_interest += interest ; n++ ; remain -= payment - interest ; } }
I know some of the logic that makes the calculator work might be messed up but I am just trying to figure out how to fix the error, any help is greatly appreciated. | https://www.daniweb.com/programming/software-development/threads/346822/error-problem | CC-MAIN-2018-30 | refinedweb | 366 | 55.78 |
Next: Client-Side IMAP Splitting, Previous: Connecting to an IMAP Server, Up: Using IMAP [Contents][Index] should connect to the server. Possible values are:
undecided
This is the default, and this first tries the
ssl setting, and
then tries the
network setting. to be
what you need.
plain
Non-encrypted and unsafe straight socket connection. STARTTLS will not be used even if it is available.,
cram-md5 or
xoauth2. (The latter method
requires using the oauth2.el library.)
nnimap-expunge
When to expunge deleted messages. If
never, deleted articles
are marked with the IMAP
\\Delete flag but not automatically
expunged. If
immediately, deleted articles are immediately expunged
(this requires the server to support the UID EXPUNGE command). If
on-exit, deleted articles are flagged, and all flagged articles are
expunged when the group is closed.
For backwards compatibility, this variable may also be set to t
or nil. If the server supports UID EXPUNGE, both t and nil are
equivalent to
immediately. If the server does not support UID
EXPUNGE nil is equivalent to
never, while t will immediately
expunge ALL articles that are currently flagged as deleted
(i.e., potentially not only the article that was just deleted)..
nnimap-use-namespaces
If non-
nil, omit the IMAP namespace prefix in nnimap group
names. If your IMAP mailboxes are called something like ‘INBOX’
and ‘INBOX.Lists.emacs’, but you’d like the nnimap group names to
be ‘INBOX’ and ‘Lists.emacs’, you should enable this option.
nnimap-keepalive-intervals
By default, nnimap will send occasional ‘NOOP’ (keepalive)
commands to the server, to keep the connection alive. This option
governs how often that happens. It is a cons of two integers,
representing seconds: first how often to run the keepalive check, and
the second how many seconds of user inactivity are required to
actually send the command. The default,
(900 . 300), means run
the check every fifteen minutes and, if the user has been inactive for
five minutes, send the keepalive command. Set to
nil to
disable keepalive commands altogether.
Next: Client-Side IMAP Splitting, Previous: Connecting to an IMAP Server, Up: Using IMAP [Contents][Index] | http://www.gnu.org/software/emacs/manual/html_node/gnus/Customizing-the-IMAP-Connection.html | CC-MAIN-2022-33 | refinedweb | 355 | 58.28 |
I need to determine what operations are safe to do with users who are using LiveID for authentication. My backend relies on IDs to grant access to users, and that ID has to be consistent across migrations of my project.
Can someone tell me if the unique ID returned for a user from the ACS is consistent between
* Labs ACS and Prod ACS
* Different relying parties in different subscriptions (in prod)
* Different RPs in the same subscription
* If I delete and rebuild the RP to the same realm, same account
The user ID that you receive from ACS for Windows Live ID will be specific to that user at your service namespace. If you use a different service namespace, you'll get a different value for the same user. So to answer your questions:
* Labs ACS and Prod ACS [Different IDs]
* Different relying parties in different subscriptions (in prod) [Different IDs]
* Different RPs in the same subscription [Same ID if the service namespace is the same, different for 2 namespaces in the same subscription]
* If I delete and rebuild the RP to the same realm, same account [Same ID]
Thanks Oren
Since the Azure ServiceBus/ACS FAQ mentions the need to purchase multiple namespaces if
(1) More than one connection Pack is needed (for example two packs of 100)
(2) According to support, if I exceed the maximum number of Service Identities (default is 200max, ??? is system max)
How can I consider using LiveID for my production application if I have to re-verify the user for each ACS namespace that is dictated by the ACS architecture?
Is this considered a bug, are there workarounds planned?
I'm still in the design phase, and am still sorting out the feasibility of different approaches. One requirement of multiple namespaces depends on the restrictions put in place on the ACS service.
If I outgrow the ACS, which is likely given the current limits, I must come up with a solution or an alternate method of authentication.
I haven't yet figured out how to associate users to namespaces yet... since I have yet to hear back from the ACS support team to determine how rigid the limitations are.
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.
Would you like to participate? | http://social.msdn.microsoft.com/Forums/en-US/windowsazuresecurity/thread/82c2006a-69f6-43d7-a03e-946cd586e3e6 | CC-MAIN-2013-20 | refinedweb | 406 | 52.83 |
Learning Kotlin: the Difference Between the Notnull Delegate and Lateinit
Learning Kotlin: the Difference Between the Notnull Delegate and Lateinit
Want to learn more about using the notnull and lateint delegates in Kotlin? Check out this post where we take a look at the advantages and disadvantages of both.
Join the DZone community and get the full member experience.Join For Free
Atomist automates your software deliver experience. It's how modern teams deliver modern software.
A lot of introductions to Kotlin start with how null is opt-in because that makes it safer — we even looked at this way back in post 8. The problem, however, is that sometimes we do not know what we want the value to be when we initialize that there is no good default value. Let's look at a house with just a ground floor at 0, a multistory office building that could have 10 floors, and an underground bunker that could have -30 floors.
class Building() { var numberOfFloors : Int fun getBuildingInfo(erfNumber : String){ //
Fom our previous delegates, we have the
notnull delegate. We can use the
notnull delegate to allow the property to not be set initially. And, then:
import kotlin.properties.Delegates class Building() { var numberOfFloors : Int by Delegates.notNull() fun getBuildingInfo(erfNumber : String){ //, this is not exactly a null exception but close enough that it makes no difference.
Lateinit
Another option is
lateinit, which we can add before the
var keyword. But, we cannot use it with
Int or other primitive types, so we need to change that as well to a class. This is a really nice and simple solution.
data class Floors(val aboveGround: Int, val belowGround: Int) class Building() { lateinit var numberOfFloors : Floors fun getBuildingInfo(erfNumber : String){ // these simple examples, both methods achieve the same goal, but they both have their own limitations and advantages:init,you gain access to the
.isInitializedmethod, which you can use to check if it was initialized.
Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, }} | https://dzone.com/articles/learning-kotlin-the-difference-between-the-notnull | CC-MAIN-2019-04 | refinedweb | 344 | 62.27 |
Strongly Typed Events - EventsStrongly Typed Events - Events
Add events that are modeled after .Net with a
sender and
argument to your project. If you use typescript, you can leverage the support for generics and get strongly typed code.
Need a different type of event? Check out the others.
Subscription made easySubscription made easy
An example says more than a 1000 words. Imagine if you have events like this on your class:
let clock = new Clock("Smu", 1000); //log the name of the clock and the tick argument to the console - this is an event clock.onClockTick.subscribe((c, n) => console.log(`${c.name} ticked ${n} times.`) );
Events made easyEvents made easy
So let's look at the implementation from a TypeScript perspective. (Do you program NodeJs without typescript? Check this)
import { EventDispatcher } from "ste-events"; class Clock { private _onClockTick = new EventDispatcher(); private _ticks: number = 0; constructor(public name: string, timeout: number) { setInterval(() => { this._ticks += 1; this._onClockTick.dispatch(this, this._ticks); }, timeout); } public get onClockTick() { return this._onClockTick.asEvent(); } }
Check the documentation or the examples for more information.
Need more info? Check the repo.
MaintenanceMaintenance
This project is maintained by Kees C. Bakker. | https://www.npmjs.com/package/ste-events | CC-MAIN-2021-21 | refinedweb | 193 | 69.99 |
Write a Java program to input days from user and find total years, weeks and days. How to convert days to years weeks and days in Java programming.
Following up our previous mathematical conversion programs in Java. In this post, I will explain how to find number of years, weeks and days in given number of days.
Example
Input
Input
Enter days: 1025
Output
1025 days = 2 year/s, 42 week/s and 1 day/s
Required knowledge
Arithmetic operators, Data types, Basic Input/Output
Days conversion formula
Days to years (ignoring leap year) and weeks conversion formula is expressed as:
1 year = 365 days 1 week = 7 days
Using above formula we can construct our Java expression to convert days to years, weeks and days.
years = days / 365; weeks = (days - (years * 365)) / 7; days = days - ((years * 365) + (weeks * 7));
Logic to convert days to years weeks and days
Step by step descriptive logic to convert days to years, weeks and days.
- Input number of days from user, store it in some variable say days.
- First we will find years in given days. Divide number of days with 365 to get total years i.e.
years = days / 365;.
- Next, we will find remaining weeks. To find remaining weeks, divide remaining days after calculated years by 7, say
weeks = (days - (years * 365)) / 7;. You can also use a simple approach i.e.
weeks = (days % 365) / 7;.
- Finally, to find remaining days after years and weeks. Apply formula to calculate remaining days i.e.
days = days - ((years * 365) + (weeks * 7));. You can also use a simpler approach i.e.
days = (days % 365) % 7;.
Program to convert days to years weeks and days
/** * Java program to convert days to years weeks and days. */ import java.util.Scanner; public class DaysConverter { public static void main(String[] args) { Scanner in = new Scanner(System.in); /* Input number of days from user */ System.out.print("Enter days: "); int days = in.nextInt(); /* Year, weeks and days conversion */ int years = (days / 365); int weeks = (days % 365) / 7; days = (days % 365) % 7; /* Print total years, weeks and remaining days in given days */ System.out.println("Year/s = " + years); System.out.println("Week/s = " + weeks); System.out.println("Day/s = " + days); } }
Output
Enter days: 373 Year/s = 1 Week/s = 1 Day/s = 1
Happy coding 😉
<pre><code> ----Your Source Code---- </code></pre> | https://codeforwin.org/2018/07/java-program-to-convert-days-to-years-weeks-and-days.html | CC-MAIN-2019-04 | refinedweb | 392 | 74.9 |
This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
trouble with try-catch...
Posted by Steve on May 28, 2000 at 11:59 PM
I entered a simple program because it uses a try and catch statement and I have no experience with the two. Here's the codeas seen in the book. It throws two errors and I cannot find the answer. Give a holler if you see anything wrong with the code.
Thanks, Steve:
public class Fruit { public static void main(String[] args) { int numOranges = 5; int numApples = 10; int numFruit = 0; numFruit = numOranges + numApples;
System.out.println("A totally fruity program."); System.out.println("Total fruit is " + numFruit); System.out.println("(press ENTER to exit)"); try { System.in.read(); } catch (IOException e) { return; } }}
The errors are:
17: Exception java.io.IOException must be caught, or it must be declared in the throws clause of this method. System.in.read(); ^
19: Class IOException not found. catch (IOException e) ^ | http://www.artima.com/legacy/answers/May2000/messages/69.html | CC-MAIN-2017-43 | refinedweb | 181 | 68.97 |
Previous: Function Basics, Up: Functions
9.6.2 Function Bodies
A function that has a definition in the current translation unit will
have a non-
NULL
DECL_INITIAL. However, back ends should not make
use of the particular value given by
DECL_INITIAL.
The
DECL_SAVED_TREE macro will give the complete body of the
function.
9.6.2.1
- In C++, statements normally constitute “full expressions”; temporaries created during a statement are destroyed when the statement is complete. However, G++ sometimes represents expressions by statements; these statements will not_EXPR
- Used to represent an inline assembly statement. For an inline assembly statement like:
asm ("mov x, y");.will hold of the
ASM_EXPR.
BREAK_STMT
- Used to represent a
breakstatement. There are no additional fields.
CASE_LABEL_EXPR
- Use to represent aand
CASE_HIGHare defined, the statement is a range of case labels. Such statements originate with the extension that allows users to write things of the form:
case 2 ... 5:
The first value will be,
- Used to represent a
continuestatement. There are no additional fields.
CTOR_STMT
- Used to mark the beginning (if
CTOR_BEGIN_Pholds) or end (if
CTOR_END_Pholds of the main body of a constructor. See also
SUBOBJECTfor more information on how to use these nodes.
DECL_STMT
- Used to represent a local declaration. The
- Used to represent a
doloop. The body of the loop is given by
DO_BODYwhile the termination condition for the loop is given by
DO_COND. The condition for a
do-statement is always an expression.
EMPTY_CLASS_EXPR
- Used to represent a temporary object of a class with no data whose address is never taken. (All such objects are interchangeable.) The
TREE_TYPErepresents the type of the object.
EXPR_STMT
- Used to represent an expression statement. Use
EXPR_STMT_EXPRto obtain the expression.
FOR_STMT
- Used to represent a_EXPR
- Used to represent a
gotostatement. The
GOTO_DESTINATIONwill usually be a
LABEL_DECL. However, if the “computed goto” extension has been used, the
GOTO_DESTINATIONwill be an arbitrary expression indicating the destination. This expression will always have pointer type.
HANDLER
- Used to represent a C++
- Used to represent an
ifstatement. The
IF_CONDis the expression.
If the condition is a
TREE_LIST, then the
TREE_PURPOSEis a statement (usually a
DECL_STMT). Each time the condition is evaluated, the statement should be executed. Then, the
TREE_VALUEshould be used as the conditional expression itself. This representation is used to handle C++ code like this:
if (int i = 7) ...
where there is a new local variable (or variables) declared within the condition.
The
THEN_CLAUSErepresents the statement given by the
thencondition, while the
ELSE_CLAUSErepresents the statement given by the
elsecondition.
LABEL_EXPR
- Used to represent a label. The
LABEL_DECLdeclared by this statement can be obtained with the
LABEL_EXPR_LABELmacro. The
IDENTIFIER_NODEgiving the name of the label can be obtained from the
LABEL_DECLwith
DECL_NAME.
RETURN_STMT
- Used to represent a
returnstatement. The
RETURN_EXPRis the expression returned; it will be
NULL_TREEif the statement was just
return;
SUBOBJECT
- In a constructor, these nodes are used to mark the point at which a subobject of
- Used to represent a
- Used to represent a_Pholds of the
TRY_BLOCK, then the
TRY_HANDLERSwill not be a
HANDLERnode. Instead, it will be an expression that should be executed if an exception is thrown in the try block. It must rethrow the exception after executing that code. And, if an exception is thrown while the expression is executing,
terminatemust be called.
USING_STMT
- Used to represent a
usingdirective. The namespace is given by
USING_STMT_NAMESPACE, which will be a NAMESPACE_DECL. This node is needed inside template functions, to implement using directives during instantiation.
WHILE_STMT
- Used to represent a
whileloop. The
WHILE_CONDis the termination condition for the loop. See the documentation for an
IF_STMTfor more information on the representation used for the condition.
The
WHILE_BODYis the body of the loop. | http://www.ecoscentric.com/ecospro/doc/html/gnutools/share/doc/gccint/Function-Bodies.html | CC-MAIN-2018-05 | refinedweb | 610 | 51.24 |
From ARM NEON to Intel SSE- the automatic porting solution, tips and tricks
By victoria-zhislina (Intel), published on December 12, 2012.
29 commentsTop
Luo, Chongyang said on Mar 16,2018
Hi victoria,
Really appreciating your efforts on this great thing. But, may I konw how you do the extensive correctness tests for the ARM Neon intrinsic functions? Could you share the test report, or the test code?
victoria-zhislina (Intel) said on May 19,2017
Zihan H, thanks a lot for this fix, I will apply it for sure.
Zihan H. said on May 12,2017
about function vrshrn_n_s32
_NEON2SSE_INLINE int16x4_t vrshrn_n_s32(int32x4_t a, __constrange(1,16) int b) // VRSHRN.I32 d0,q0,#16
{
int16x4_t res64;
__m128i r32;
r32 = vrshrq_n_s32(a,b);
r32 = _mm_shuffle_epi8 (r32, *(__m128i*) mask8_16_even_odd); //narrow, use low 64 bits only. Impossible to use _mm_packs because of negative saturation problems
return64(r32);
}
I think mask8_32_even_odd is correct, not mask8_16_even_odd.
Ilya K. said on Jun 27,2016
> And if possible could you please tell me in very generic terms - what kind of project do you use this header at?
Image processing for smartphones camera. Many of code already ported on SSE4 intrinsics. So I'm just tested this solution on real code, not simple artificial tests.
victoria-zhislina (Intel) said on Jun 24,2016
Hi, Ilya K. I confirm this bug (or a gcc compartibility issue because it works fine with Intel comiler I use) and even more bugs of this kind found by me. I'm preparing the new version having all of them fixed. Meanwhile if more bugs found please feel free to contact me directly by mail = victoria.zhislina at intel.com. And if possible could you please tell me in very generic terms - what kind of project do you use this header at?
Ilya K. said on Jun 22,2016
Found more "lvalue required as unary ‘&’ operand" errors:
{
uint8x16_t q4 = vdupq_n_u8(0);
uint16x8_t q0 = vmovl_u8(vget_low_u8(q4));
}
{
int16x4_t c1 = vcreate_s16(0x0003000200010000L);
}
victoria-zhislina (Intel) said on Jun 7,2016
Ilya K, megathanks for your bugs report - the bugs mentioned to be fixed ASAP (it is strange they haven't been found earlier)
And let me say that you are not right about SSE4.2 - I do use the function from this set: _mm_cmpgt_epi64.
And yes, the reciprocal difference is the feature currently - to be changed if any serious complains appear.
Ilya K. said on Jun 4,2016
Found two errors (tested with GCC 4.7 and 4.9).
GCC output:
main.c: In function ‘main’:
main.c:14:28: error: expected ‘)’ before ‘;’ token
main.c:14:28: error: too few arguments to function ‘_mm_add_epi8’
main.c:20:3: error: lvalue required as unary ‘&’ operand
main.c:20:3: error: lvalue required as unary ‘&’ operand
Clang 3.8 also gives errors on this code.
Fixes:
(1)
#define LOAD_SI128(ptr) \
( ( ((unsigned long)(ptr) & 15) == 0 ) ? _mm_load_si128((__m128i*)(ptr)) : _mm_loadu_si128((__m128i*)(ptr)) )
(2)
#define M1 { return _mm_unpacklo_epi64 (_pM128i(low), _pM128i(high)); }
static inline int8x16_t vcombine_s8(int8x8_t low, int8x8_t high) M1
static inline int16x8_t vcombine_s16(int16x4_t low, int16x4_t high) M1
static inline int32x4_t vcombine_s32(int32x2_t low, int32x2_t high) M1
static inline int64x2_t vcombine_s64(int64x1_t low, int64x1_t high) M1
#undef M1
Also two flaws:
(1) SSE4.1 is enough here, SSE4.2 intrinsics not used.
#if defined(__SSE4_2__)
#define USE_SSE4
#endif
...
#ifdef USE_SSE4
#include <smmintrin.h> //SSE4.1
#include <nmmintrin.h> //SSE4.2
#endif
(2) vrecpeq_f32 not match output from ARM processor, gives more precision. So results from emulation and real run on ARM not exactly match.
Junaid S. said on Apr 27,2016
@ victoria,
The simple fix to this bug I found is to comment line 173 of your code. clang/llvm is strict in implementing some C standards which GCC does not care off. So, I think the error was caused by strictness. Plus I think replacing __ with _ can also do the trick.
victoria-zhislina (Intel) said on Apr 20,2016
Junaid S, thanks for your comment. the library hasn't ben tested with clang/llvm, so if you could test it and do some fixes there it would be great.
Pages
Add a CommentSign in
Have a technical question? Visit our forums. Have site or software product issues? Contact support. | https://software.intel.com/en-us/blogs/2012/12/12/from-arm-neon-to-intel-mmxsse-automatic-porting-solution-tips-and-tricks | CC-MAIN-2018-13 | refinedweb | 706 | 66.54 |
Case against templates
Many pundits have written eloquently about templating engines for PHP, the truth is that many templating systems go against the grain of PHP. Let's illustrate this point by studing a few lines of code from a blog/CMS that uses such a templating system.
$query = "SELECT * FROM posts WHERE topic_id = '$topic_id' ORDER BY post_date DESC"; $res = mysql_query($query);
if (!$res || !mysql_num_rows($res)) return (false); $posts = array(); while ($row = mysql_fetch_array($res)) { $row['post_permalink'] = 'post.php/'.$row['post_id']; $row['post_trackback_ping_url'] = 'trackback.php/'.$row['post_id']; ... ... $posts[] = $row; }
What this code does is fairly obvious, it retrieves a list of posts from the database and loads them into an array. It is equally obvious that doing so will result in the consumption of a lot of memory, particularly if your result set has hundreds or thousands of records. What exactly happens to this array? see the code sample below:
for ($c = 0; $c < count($posts); $c++) { $tpl->assign('POST', $posts[$c]); $tpl->parse('main.posts_list.post'); ... ... }
A few lines of code has been removed for clarity. $tpl is obviously an instance of the template class, and we can see that that code loops through the array and assigns each element of the array to an element of the template. After this assignment the template element is parsed.
We shall not go into the code of the parse() function, suffice to say it is 31 lines long and packed with memory and CPU hungry regular expressions functions. Oh, and btw there is yet another loop inside parse()
Now we have two copies of the data that was originally in the database in memory. The first in the form of a simple array, the second in the form of a several strings; which is the result of the $tpl->parse() method calls. That does not take into consideration the memory required to hold the template itself, and the memory needed to load the templating class.
We still have to print out this string before any output can be seen. Guess what printing the parsed template involves yet another loop. All in all we are looping four times with each query.
Now consider the other approach, simply echoing out each row of the resultset as it's read in:
$%s</a></td>', 'post.php/'.$row['post_id'], 'post.php/'.$row['post_id']); printf('<td><a href="%s">%s</a></td></tr>', 'trackback.php/'.$row['post_id'],'trackback.php/'.$row['post_id']); ... ... }
We loop only once, we keep nothing in memory, the output is produced instantly and we have managed to do it in a just two lines of code. What can be simpler?
Now suppose for a moment that a new member is joining your team and he is still wet behind the year. If you had used the templating approach he would have to learn about mysql queries, array manipulation, regular expressions and the templating engine itself before he is completely familiar with the system.
Now suppose you had written the project the way it's supposed to be written - without templates, the newcomers only needs to know the mysql functions and printf(). So much for the myth that 'web apps with template systems are easier to maintain' | http://www.raditha.com/wiki/Case_against_templates | CC-MAIN-2014-15 | refinedweb | 532 | 61.67 |
Hi there,
I've written a CG shader that's meant as an overlay on top of the existing material, ie: you have your base diffuse/specular/whatever material and then drop my shader material on top. It works great for normal meshes. Problem I have is I need to do this for the terrain as well... At the moment I've written a basic CG version of the terrain shader but I can't seem to copy the lighting of Unity's diffuse surface shader exactly in a CG shader. Could someone point me in the right direction to find a simple diffuse shader written in CG? Or is there an easier way to combine my CG shader with Unity's terrain surface shader? Obviously it would be easier if I could have my shader as a second pass on a replacement terrain shader rather than having to re-write the terrain shader in CG.
Help is much appreciated! :)
Answer by whydoidoit
·
Apr 12, 2013 at 08:44 AM
Here's my CG terrain shader:
Shader "Custom/Terrain" {
Properties {
_Splat0 ("Layer 1 (R)", 2D) = "white" {}
_Splat1 ("Layer 2 (G)", 2D) = "white" {}
_Splat2 ("Layer 3 (B)", 2D) = "white" {}
_Splat3 ("Layer 4 (A)", 2D) = "white" {}
_Control ("Control (RGBA)", 2D) = "white" {}
_MainTex ("Never Used", 2D) = "white" {}
}
SubShader {
"SplatCount" = "4"
"Queue" = "Geometry-100"
"RenderType" = "Opaque"
}
Pass {
ZTest LEqual
Lighting on
ZWrite on
CGPROGRAM
// Upgrade NOTE: excluded shader from DX11 and Xbox360; has structs without semantics (struct v2f members lightDirection)
#pragma exclude_renderers d3d11 xbox360
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D_half _Splat0;
sampler2D_half _Splat1;
sampler2D_half _Splat2;
sampler2D_half _Splat3;
sampler2D_half _Control;
half4 _Splat0_ST;
half4 _Splat1_ST;
half4 _Splat2_ST;
half4 _Splat3_ST;
half4 _Control_ST;
struct a2v
{
half4 vertex : POSITION;
half3 normal : NORMAL;
half4 texcoord : TEXCOORD0;
};
struct v2f
{
fixed4 pos : SV_POSITION;
half2 uv : TEXCOORD0;
half2 uv0 : TEXCOORD1;
half2 uv1 : TEXCOORD2;
half2 uv2 : TEXCOORD3;
half2 uv3 : TEXCOORD4;
fixed4 light : TEXCOORD5;
};
v2f vert (a2v v)
{
v2f o;
o.pos = mul( UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX (v.texcoord, _Control);
o.uv0 = TRANSFORM_TEX (v.texcoord, _Splat0);
o.uv1 = TRANSFORM_TEX (v.texcoord, _Splat1);
o.uv2 = TRANSFORM_TEX (v.texcoord, _Splat2);
o.uv3 = TRANSFORM_TEX (v.texcoord, _Splat3);
fixed3 toLight = normalize(unity_LightPosition[0].xyz);
fixed3 lightColor = saturate(
UNITY_LIGHTMODEL_AMBIENT.rgb
+ (unity_LightColor[0].rgb *
(dot( normalize( mul( (float3x3) UNITY_MATRIX_IT_MV, v.normal)), toLight.xyz ))));
o.light = fixed4(lightColor * 2,1) ;
return o;
}
fixed4 frag(v2f i) : COLOR
{
fixed4 c = tex2D (_Control, i.uv);
fixed3 c1 = tex2D (_Splat0, i.uv0);
fixed3 c2 = tex2D (_Splat1, i.uv1);
fixed3 c3 = tex2D (_Splat2, i.uv2);
fixed3 c4 = tex2D (_Splat3, i.uv3);
return fixed4(((c1.rgb * c.r) + (c2.rgb * c.g) + (c3.rgb * c.b) + (c4.rgb * c.a)), 1) * i.light;
}
ENDCG
}
}
FallBack "Diffuse"
}
The diffuse calculation is for one directional light only and is shown in the line that won't format properly no matter what I do. And the lines before and after.
Unity Terrain - shader for custom post-splat?
0
Answers
uv not being passed through from vertex to surface shader
1
Answer
Terrain custom shader not lit per pixel?
1
Answer
Simple Cg shader not compiling
1
Answer
Too many texture interpolators would be used for ForwardBase pass (again)
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/436767/cg-diffuse-shader.html | CC-MAIN-2022-40 | refinedweb | 529 | 57.77 |
Introduction to Priority Queues in Python
A queue, in general, can be defined as arrangement or storage order of data/ elements using the principle ‘First In First Out’ (FIFO). In python, priority queueing is an extension of the FIFO method, where the data/elements are arranged in a prioritized order. A Priority Queue should obey a few behavioral constraints, such as every data/ element in the system should have a priority assigned to it, data/ element with higher priority are placed before a data/ element with lower priority, and if more than one data/ element is holding same priority then FIFO is followed for its placement. In python, this is achieved using heap sort or list function.
Examples to Implement Priority Queues
Here are some of the examples of priority queues in python which re as follows:
Example #1
This is the example of priority queues using python sorted list.
while que:
queue_item=que.pop()
print(queue_item)
Output:
Explanation: First we have declared an empty list into which elements are inserted using the append() method of List class. The list is then sorted in ascending order. While the loop is used to retrieve elements from the list using the pop() method. This is a manual method of implementing priority queues.
Pros and Cons of this Approach: It is best suitable to quickly identify and delete the smallest or largest element. The main drawback is that inserting a new element into the list is a slow operation. Therefore, sorted lists are suitable only when there are few insertions.
Example #2
This is the example of priority queues using the heapq module. A binary heap is often used to implement priority queues. This Python provides a heapq library. But heapq only provides a min-heap implementation.
Min heap: A complete binary tree where the key at the root must be minimum among all the keys present in Binary heap.
Code:
# Implementing Priority queue using heapq module
# Importing heapq module
import heapq
# declaring empty list
que = [] # adding elements to the list
heapq.heappush(que, (5, 'Medium Priority task'))
heapq.heappush(que, (1, 'High priority task'))
heapq.heappush(que, (10, 'low priority task'))
# dequeuing elements
print("Elements will be dequeued according to their prorities")
while que:
deque_item = heapq.heappop(que)
print(deque_item)
Output:
Explanation: First we’ve imported the heapq module then created an empty list. Using the heappush() method of the heapq module we have inserted the elements into the list. While loop is then used to pop elements out of the list. It can be clearly depicted in the output that the order in which the elements are entered (5 -> 1 -> 10) is different from the dequeuing order (1 -> 5 -> 10).
Example #3
This is the example of priority queues using the queue.PriorityQueue class. Python provides a built-in implementation of the priority queue data structure. Python uses a binary heap to implement priority queues.
Min heap: A complete binary tree where the key at the root must be minimum among all the keys present in Binary heap.
Max heap: A complete binary tree where the key at the root must be maximum among all the keys present in Binary heap.
1. This is the basic example to implement a priority queue using a queue. PriorityQueue class.
Code:
# Implementing priority queue using queue.PriorityQueue class
import queue as PQ
q = PQ.PriorityQueue()
q.put(10)
q.put(1)
q.put(5)
print("Dequeing elements")
while not q.empty():
print (q.get())
Output:
Explanation: The queue module is imported. An object “q” of PriorityQueue() is then created. Elements are inserted into this queue using the put() method. After that while loop is used to retrieve or dequeue the elements using get() method. Queue stores the elements according to their priorities ( 1 -> 5 -> 10 ) not by the order of element creation/insertion(10 -> 1 -> 5) as shown in the above output.
2. Below is the example of a priority queue which can store any object in addition to basic built-in primitive.
Code:
# Implementing priority queue using Queue.PriorityQueue class
import queue as PQ
q = PQ.PriorityQueue()
q.put((10,'Low priority task'))
q.put((1,'High priority task'))
q.put((5,'Medium priority task'))
print("Dequeing elements")
while not q.empty():
print (q.get())
Output:
Here, we have inserted a tuple-> task name along with its priority.
Time Complexity using the queue.PriorityQueue Class
Why Priority Queues are Used?
Priority Queues have many applications. Some all listed below:
- Graph algorithms: The priority queues are used in Graph algorithms like Dijkstra’s Shortest path and Prim’s Minimum spanning trees.
- Data Compression: It is used in Huffman codes which are used to compress data.
- Artificial Intelligence: A* search algorithm finds the shortest path between two vertices of a weighted graph, trying out the most promising routes first. The priority queue is used to keep track of unexplored routes, the one which has a lower bound on the total length is smallest is given the highest priority.
- Operating System: It is also used in the OS for load balancing and Interrupt handling. Priority queues are also used in Process Scheduling where a high priority task is assigned to CPU before a low priority task.
Conclusion
A priority queue is a modified version of basic queues where the priority of tasks is considered rather than their insertion order. There are multiple ways to implement priority queues in python as explained above. Each has slightly different use cases. But PriorityQueue is a good default choice because it has a nice object-oriented interface.
Recommended Articles
This is a guide to Priority Queues in Python. Here we discuss examples of priority queues in python and its detailed explanation along with the uses of priority queues. You may also look at the following articles to learn more- | https://www.educba.com/priority-queues-in-python/?source=leftnav | CC-MAIN-2021-04 | refinedweb | 969 | 57.16 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
[SOLVED] Steps to print a report (RML)?
I am trying to understand how to create a report. In fact, I created a new module with a new model, and I am trying to print just an empty report of this new model. After I manage it, I will fill the report in step by step.
But there is something that I am doing wrong, and I would like that you corrected me. By the moment, these are the steps I think I have to do (check the names I am using, because I think the error is there).
I have to generate a folder called report. Inside it, I have to create a __init__.py file (which includes the python file of the report folder).
- Inside the folder report, I have to create a .py file, for example, print_my_model.py. The code of this file should be the following:
from report import report_sxw
import time
class print_my_model_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context=None):
super(print_my_model_parser, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
})
report_sxw.report_sxw('report.my_module.my_report_name', 'my.model',
'addons/my_module/report/name_of_rml_file.rml',
parser="print_my_model_parser")
- Still inside the report folder, I have to create the RML file with the name specified above, inside the .py (in this case, the name of the RML file must be name_of_the_rml_file.rml). I decided to create a test RML file, with no data, so the code inside is:
<?xml version="1.0"?>
<document filename="preview_report.pdf">
<template title="Preview Report" author="OpenERP S.A.(sales@openerp.com)" allowSplitting="20">
<pageTemplate id="first">
<frame id="first" x1="57.0" y1="57.0" width="481" height="728"/>
</pageTemplate>
</template>
<story>
<para>
</para>
</story>
</document>
- Finally, in the main folder of my module, I have to create a XML file to declarate the reports I want to create (this way, the button Print will be generated automatically in the interface). This XML file must be included in the __openerp__.py file, and its content should be:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<report auto="True" id="whatever_id"
model="my.model" name="my_module.my_report_name"
rml="my_module/report/name_of_the_rml_file.rml"
string="Whatever message to show in the Print button of the interface" />
</data>
</openerp>
This is not working. I would like you to correct me, specially just above, where I declare the available reports, because I think I am doing some mistakes. In the id I can write anything I did not use earlier. In name, I think I have to write the name of my module followed by a dot and whatever name I want, but in the .py, when I pass parameters to report_sxw.report_sxw(), the first one must be exactly this name, with report. just before. Is this right? Do you see anything I am doing wrong?
I always get this error when I click the button Print and then mines (Whatever message to show in the Print button of the interface):
except_osv: (u"'str' object is not callable", (<type 'exceptions.TypeError'>, TypeError("'str' object is not callable",), <traceback object at 0x7f8c3cb2c1b8>))
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
hi, in your file "print_my_model.py", replace super(rplc_print_history, self) by super(print_my_model_parser, self) I think
@Guillaume Seran I am so sorry, you are right but it was a mistake I made, copying and pasting code, and then trying to write easier names to make you understand my question better. I corrected it, but that was not the mistake I was refering to.
you write parser="print_my_model_parser" in my file i don't use quote.
@Guillaume Seran that was the problem!! Thank you so much!!! I do not have enough karma to convert your comment as an answer, so if you write your comment in a new answer, I will check it as the solution. Thank you again!! | https://www.odoo.com/forum/help-1/question/solved-steps-to-print-a-report-rml-67269 | CC-MAIN-2018-26 | refinedweb | 692 | 65.62 |
On 2 Jun 2005, Peter Simons wrote: > Graham Klyne writes: > > > > > > This code is all heavily refactored from the original > > HaXml for improved XML entity handling, namespace, > > xml:lang and xml:base support [...]. > > Is there any chance of reuniting the two HaXml versions into > a single release? Even worse, since I like strong typing and was annoyed by the (a -> [a]) filters and the separation of characters and entities I started some wrappers to HaXml. I use a general tree data structure which is then filled with XML data. The modules allow me to use the type specific functions 'filter', 'concatMap' and all the other standard list functions instead of 'o'. | http://www.haskell.org/pipermail/haskell-cafe/2005-June/010273.html | CC-MAIN-2014-15 | refinedweb | 110 | 58.01 |
First impressions about namespaces in PHP
The only doubt I have is: Are they really better than classical naming conventions?
I make myself the question because as well as in classical naming convention the Classes are fully defined, with namespaces we must take care about aliases, ‘use’ statements and the scope. When I say ‘fully defined’ it means that in a glance to the class name we known exactly the location of the class in the filesystem.. We pay a tax for it. Our class name become bigger. Namespaces come to help us but they add to our code a bit of complexity. I feel really comfortable with classical naming conventions but namespaces are cool. Are they some kind of hype? I don’t think so but I am not 100% convinced. Yet. What do you think?
Posted on August 2, 2010, in php, Technology. Bookmark the permalink. 4 Comments.
I have a framework which I aim to modify to make use of the new namespace support in PHP 5.3.x, but whenever I look into doing this the ugly syntax (yes the backslash!) really puts me off engaging with namespaces in PHP.
I’m afraid you’re not the only one :). But after a few days working on it it’s not so bad. Even, I feel it’s useful. This symbol is so ugly for me that I can easily detect any reference to namespaces within the code in a glance. And that’s cool. isn’t it?. (maybe it’s my way to convince myself because it’s really ugly)
Actually sad if a single character is affecting your decision on using namespaces in your project.
The addition of the namespaces was the kick in the butt I needed to start using python. The guys hacking this language just don’t give a damn. | http://gonzalo123.com/2010/08/02/first-impressions-about-namespaces-in-php/ | CC-MAIN-2013-48 | refinedweb | 308 | 75.3 |
Anyhoo, that's enough background. Let's suppose we want to hydrogenate all instances of C=C and C=O. Just copy and paste the following into the end of plugindefines.txt:
OpTransform hydrogenate # ID used for commandline option * # Asterisk means "no datafile specified" Hydrogenate C=C and C=O double bonds TRANSFORM [C:1]=[C:2] >> [C:1][C:2] TRANSFORM [C:1]=[O:2] >> [C:1][O:2]This gives a new obabel option, --hydrogenate, that will do the job:
C:\Tools\tmp>obabel -L ops ... hydrogenate Hydrogenate C=C and C=O double bonds ... C:\Tools\tmp>obabel -:C=C -osmi --hydrogenate CC C:\Tools\tmp>obabel -:O=CSC=CC=S -osmi --hydrogenate OCSCCC=SNotes:
(1) This works best in the latest SVN as Chris sorted out some longstanding bugs.
(2) I've just enabled this in Python where it works as follows:
import pybel transform = pybel.ob.OBChemTsfm() success = transform.Init("[C:1]=[C:2]", "[C:1][C:2]") assert success mol = pybel.readstring("smi", "C=C") transform.Apply(mol.OBMol) assert mol.write("smi").rstrip() == "CC" | https://baoilleach.blogspot.com/2012/08/ | CC-MAIN-2018-34 | refinedweb | 181 | 51.44 |
Supreme Court Judgments
Subscribe
The Commissioner of
Customs, New Delhi Vs. M/s. Caryaire Equipment India Pvt. Ltd.
[Civil Appeal No.
6404 of 2003]
O R D E R
1. short "the DEPB Scheme"). The assessee has succeeded before the Customs,
Excise and Gold (Control) Appellate Tribunal (for short 'the Tribunal'). The
Revenue in this appeal calls in question the correctness or otherwise of the judgment
and order of the Tribunal. By the impugned judgment and order, the Tribunal has
set aside the order of confiscation of goods and the penalty imposed by the
Commissioner of Customs.
2.
The
facts in nutshell are: the assessee is the manufacturer of aluminium grills
made out of extruded aluminium sections. In its regular business activity, the assessee
had filed a shipping bill dated 18.06.2002, inter alia, claiming the benefit of
the DEPB Scheme for export of the said products as falling under Item Serial No.
7 of Product Group: Engineering-Product Code: 61 at 7% ad valorem. The Customs
Officer, on verification of the shipping bill, has found that the goods in question
are fabricated aluminium products and therefore, denied the export of goods as being
prima facie liable for confiscation under the Customs Act, 1962 (for short "the
Act")
3.
Thereafter,
the assessee, by his letter dated 24.6.2002 had made a request to the Commissioner
of Customs for a personal hearing in lieu of the show cause notice. At the time
of the personal hearing, the assessee had contended that the aluminium grills were
fabricated items, but the end-product is made out of the extruded aluminium. The
Commissioner, while rejecting the contention of the assessee, has passed an order
dated 28.6.2002 for confiscation of goods and imposition of penalty in exercise
of his powers under Section 113 and 114 of the Act read with Rules 11 and 14 of
the Foreign Trade (Regulation) Rules, 1993. However, he had permitted the assessee
to redeem the goods on payment of certain amount of fine.
4.
Aggrieved
by the aforesaid order of the Commissioner of Customs, the assessee had carried
the matter in appeal before the Tribunal. The Tribunal, after appreciating the contention
of the assessee, had set aside the order of the Commissioner vide its order dated
16.10.2002. In its order, the Tribunal holds that aluminium grills are nothing but
the extruded aluminium products. Therefore, the Tribunal is of the opinion that
the Commissioner of Customs was not justified in passing the order in exercise
of his powers under Section 113 and 114 of the Act.
5.
The
Revenue, being aggrieved by the judgment and order passed by the Tribunal, has filed
this appeal under Section 130-E of the Act.
6.
Shri
Harish Chandra, learned senior counsel appearing for the Revenue, contends that
aluminium grill is altogether a separate product and the same cannot be equated
with extruded aluminium product which is mentioned under Entry 7 of the Product
Group Engineering (Code 61). He submits that the benefit of the DEPB Scheme
encompasses within its ambit only to the extruded aluminium products which are
obtained from the process of aluminium extrusion. Shri Abhinav Mukerji, learned
counsel for the Revenue, who is assisting Shri Harish Chandra, would elaborate the
process of aluminium extrusion and contends that it is a product, which is
strictly obtained from the process of extrusion, without any alterations or
modifications, is eligible for the benefit provided under the DEPB Scheme. He, therefore,
submits that the product obtained by fabricating the extruded aluminium is not eligible
for the benefit of the Scheme. In support of their contention, they have produced
a xerox copy of the book titled as "The Complete Technology Book on Aluminium
and Aluminium Products". A reference is also made to certain observations made
by this Court while explaining the meaning of the expression "the product".
7.
Per
contra, Shri Aditya Kumar, learned counsel appearing for the assessee submits
that the expression "extruded aluminium products" used in Entry 7 of Code
61 is sufficiently wide to include products which are made out of the extruded
aluminium by fabricating it. He contends that even the finished end-product which
is in the fabricated form of the extruded aluminium, the same would fall under Entry
7, as extruded aluminium product.
8.
In
order to resolve the controversy posed in this appeal by the parties to the lis,
a reference to Duty Exemption/Remission Scheme requires to be noticed. Chapter
4 of Exim Policy and Handbook of Procedures provides for Duty Exemption/Remission
Scheme. Paragraph 4.37 of the said chapter provides for the DEPB Scheme. The
said paragraph reads as under:"The Policy relating to Duty Entitlement
Passbook Scheme (DEPB) Scheme is given in Chapter 4 of the Policy. The duty
credit under the scheme shall be calculated by taking into account the deemed
import content of the said export product as per SION and the basic custom duty
payable on such deemed imports. The value addition achieved by export of such product
shall also be taken into account while determining the rate of duty credit
under the scheme." Entry 7 of the Product Code 61 in the DEPB schedule
reads as under:"Extruded Aluminium products including pipes and
tubes".
9.
The
facts are not in dispute. The assessee is a manufacturer of aluminium grills made
out of the extruded aluminium. Admittedly, the export of the aforesaid item was
made and shipping bill dated 18.6.2002 was presented before the Customs Officer,
inter alia, claiming the benefit under the aforesaid entry. While denying the said
benefit, the Commissioner of Customs has passed an order of confiscation of the
goods and has also levied a penalty, in exercise of his powers under Section
113 and 114 of the Act read with Rules 11 and 14 of the Foreign Trade (Regulation)
Rules, 1993. However, he had permitted the assessee to exercise its right of
redemption, if it so desires. We do not know whether the assessee had exercised
that right. We are not concerned much on that.
10.
Admittedly,
the assessee had carried the matter in appeal before the Tribunal. The Tribunal
has given relief to the assessee by holding that the aluminium grills are nothing
but extruded aluminium products and, therefore, the assessee is entitled to
take benefit of Item Serial No. 7 of the Product Group: Engineering- Product
Code: 61.
11.
As
we have already noticed, the only issue which requires to be considered and decided
in this Civil Appeal is, whether the aluminium grills can be termed as Extruded
aluminium products, and if it is so, whether the assessee can take the benefit
of the Item 7 of Code 61?
12.
To
appreciate what is extruded aluminium, a reference can be made to the literature
that is produced by learned counsel appearing for the parties.
13.
The
process of "extrusion", as explained in the Textbook McGraw-Hill Encyclopedia
of Science & Technology, reads as under : process of
the cold extrusion of aluminium can also be noticed from the aforesaid book.
The same is as under:"Cold extrusion: 8the. A process requiring less pressure
than backward extrusion is the forward-extrusion process, originally called the
Hooker process. A formed blank (usually a thick-walled cup) is placed in a die
cavity and struck by a punch having a shoulder or enlarged section a short
distance from the end. Upon contact with the blank, the nose or end of the punch
starts to push the center of the blank through the die cavity, in a manner
similar to the action occurring in deep drawing of sheet metal. After the punch
has advanced a short distance, the shoulder comes in contact with the top of
the thick wall of the blank.
The punch shoulder
then extrudes the metal through the annular space between the die and the end
of the punch. Thus, in forward extrusion, the metal moves in the same direction
as the punch, whereas in backward extrusion the metal moves in the opposite
direction."
14.
In
the book "The Complete Technology on Aluminium and Aluminium
Products", a reference is made to the manufactured forms of the aluminium.
A useful reference can be made to the literature on aluminium and its
manufactured form, from the aforesaid book. It shows aluminium and its alloys
may be cast or formed by virtually all known processes. Manufactured forms of aluminium
and aluminium alloys can be broken down into two groups. Standardized products and
Engineered Products. The Standardized products include sheet, plate, foil, rod,
bar, wire, tube, pipe, and structural forms. In the same book, it is said that Engineered
products are those designed for specific applications and include extruded shapes,
forgings, impacts, castings, stampings, power metallurgy (P/M) parts, machined parts,
and metal-matrix composites (MMCs). The standardized products are again described
to include only the extruded aluminium product simplicitor. If anything that is
done to those extruded aluminium products, that would become the engineered
products.
15.
In
the instant case, it is the assessee's stand before the Commissioner of Customs
and also before the Tribunal, that it fabricates extruded aluminium into aluminium
grills. It is not the case of the assessee either before the Commissioner of
Customs or before the Tribunal, that aluminium grills are the same as extruded aluminium
products. It is an admitted position that assessee carries out the fabrication to
derive a product known as aluminium grills made out of extruded aluminium
products. If that fact situation is accepted, then the Tribunal was wholly
incorrect in holding that the aluminium grills are nothing but extruded aluminium
products and therefore, they would fall under Entry 7 of Code 61. The issue
before us can be looked into from another angle also. The Legislature, while enumerating
the goods that would fall under Item 7 of the Product Code 61 of the DEPB
Schedule, immediately after the expression "extruded aluminium products"
has specifically used the expression "included" to include pipes and
tubes. The legislature recognizes pipes and tubes which are engineered out of
the extruded aluminium products, as included under the Item 7. The expression "including
pipes and tubes" following the words "extruded aluminium
products" in Item 7 is restrictive in nature and will give `extruded aluminium
products' a restrictive meaning in order to include the standardized products
such as pipes and tubes within the meaning of the term extruded aluminium
products.
16.
In
South Gujarat Roofing Tiles Manufacturers Assn. & Anr. v. State of Gujarat &
Anr., (1976) 4 SCC 601, this Court has held thus:."
17.
In
Reserve Bank of India & Ors. v. Peerless General Finance & Investment
Co. Ltd. & Ors., (1987) 1 SCC 424, this Court while analysing the different
connotations of the `inclusive definitions' has held: "32. We do not think
it necessary to launch into a discussion of either Dilworth case2 or any of the
other cases cited. All that is necessary for us to say is this: Legislatures
resort to inclusive definitions . Depending on the context, in the process of enlarging, the
definition may even become exhaustive."
18.
In
Godfrey Phillips India Ltd. & Anr. v. State of U.P. & Ors., (2005) 2
SCC 515, this Court has observed thus: "73. Having rejected the second
premise contended for by Mr Salve, the next question is whether the language of
Entry 62 List II would resolve the issue. The juxtaposition of the different
taxes within Entry 62 itself is in our view of particular significance. The
entry speaks of "taxes on luxuries including taxes on entertainments, amusements,
betting and gambling". The word "including" must be given some
meaning. In ordinary parlance it indicates that what follows the word
"including" comprises or is contained in or is a part of the whole of
the word preceding. The nature of the included items would not only partake of the
character of the whole, but may be construed as clarificatory of the whole.74. It
has also been held that the word "includes" may in certain contexts be
a word of limitation (South Gujarat Roofing Tiles Manufacturers Assn. v. State
of Gujarat28). ..."
19.
In
Karnataka Power Transmission Corporation & Anr. v. Ashok Iron Works Private
Limited, (2009) 3 SCC 240, this Court while considering the meaning and connotations
of the word `inclusive' has held thus:"
14. The learned counsel
also submitted that the word "includes" must be read as
"means". In this regard, the learned counsel placed reliance upon two
decisions of this Court, namely; (1) South Gujarat Roofing Tiles Manufacturers
Assn. v. State of Gujarat1 and (2) RBI v. Peerless General Finance and
Investment Co. Ltd.2
15. Lord Watson in
Dilworth v. Stamps Commr.3 made the following classic statement: (AC pp.
105-06)"...."
16. Dilworth3 and few
other decisions came up for consideration in Peerless General Finance and
Investment Co. Ltd. and this Court summarised the legal position that (Peerless
case2, SCC pp. 449-50, para 32) inclusive definition by the legislature is
used:"32. ... ." used. It may be equivalent
to `mean and include' and in the case it may afford an exhaustive explanation of
the meaning which for the purposes of the Act must invariably attached to those
words or expressions. Thus the word include may in certain contexts be a word
of limitation."
21.
In
view of the aforesaid reasons, in our opinion, the goods in question namely,
the aluminium grills cannot fit into Item 7 of the Product Code 61 of the DEPB Schedule
in order to claim benefit of the DEPB Scheme and therefore, we cannot sustain the
order passed by the Tribunal.
22.
In
the result, while allowing the appeal filed by the Revenue, we set aside the impugned
judgment and order passed by the Tribunal and restore the order passed by the
Commissioner of Customs. No costs.
Ordered accordingly.
.....................................J.
(H.L. DATTU)
.....................................J.
(ANIL R. DAVE)
NEW
DELHI,
FEBRUARY
14, 2012
Back | http://www.advocatekhoj.com/library/judgments/index.php?go=2012/february/38.php | CC-MAIN-2018-17 | refinedweb | 2,315 | 50.97 |
Abstract
Contents
- Abstract
- Background
- Proposal
- Key Benefits
- New Ways of Using Classes
- Implementation Details
- Reference Implementation
- Backward compatibility issues
- Rejected Design Options
- History
- References, and a hook to initialize attributes.
The new mechanism should be easier to understand and use than implementing a custom metaclass, and thus should provide a gentler introduction to the full power of initialization of descriptors and keeping the order in which class attributes were defined.
The first two categories can easily be achieved by having simple hooks into the class creation:
- An __init_subclass__ hook that initializes all subclasses of a given class.
- upon class creation, a __set_name__ hook is called on all the attribute (descriptors) defined in the class, and
The third category is the topic of another PEP, PEP 520.
As an example, the first use case looks as follows:
>>> class QuestBase: ... # this is implicitly a @classmethod (see below for motivation) ... def __init_subclass__(cls, swallow, **kwargs): ... cls.swallow = swallow ... super().__init_subclass__(**kwargs) >>> class Quest(QuestBase, swallow="african"): ... pass >>> Quest.swallow 'african'
The base class object __set_name__ initializer for class attributes, especially if they:
import weakref class WeakAttribute: def __get__(self, instance, owner): return instance.__dict__[self.name]() def __set__(self, instance, value): instance.__dict__[self.name] = weakref.ref(value) # this is the new initializer: def __set_name__(self, owner, name): self.name = name
Such a WeakAttribute may, for example, be used in a tree structure where one wants to avoid cyclic references via the parent:
class TreeNode: parent = WeakAttribute() def __init__(self, parent): self.parent = parent
Note that the parent attribute is used like a normal attribute, yet the tree contains no cyclic references and can thus be easily garbage collected when out of use. The parent attribute magically becomes None once the parent ceases existing.
While this example looks very trivial, it should be noted that until now such an attribute cannot be defined without the use of a metaclass. And given that such a metaclass can make life very hard, this kind of attribute does not exist yet.
Initializing descriptors could simply be done in the __init_subclass__ hook. But this would mean that descriptors can only be used in classes that have the proper hook, the generic version like in the example would not work generally. One could also call __set_name__ from within the base implementation of object.__init_subclass__. But given that it is a common mistake to forget to call super(), it would happen too often that suddenly descriptors are not initialized..
New Ways of Using Classes
Subclass registration
Especially when writing a plugin system, one likes to register new subclasses of a plugin baseclass. This can be done as follows:
class PluginBase: subclasses = [] def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.subclasses.append(cls)
In this example, PluginBase.subclasses will contain a plain list of all subclasses in the entire inheritance tree. __init__(self, minimum, maximum): self.minimum = minimum self.maximum = maximum def __get__(self, instance, owner): return instance.__dict__[self.key] def __set__(self, instance, value): if self.minimum < value < self.maximum: instance.__dict__[self.key] = value else: raise ValueError("value not in range") def __set_name__(self, owner, name): self.key = name
Implementation Details
The hooks are called in the following order: type.__new__ calls the __set_name__ hooks on the descriptor after the new class has been initialized. Then it calls __init_subclass__ on the base class, on super(), to be precise. This means that subclass initializers already see the fully initialized descriptors. This way, __init_subclass__ users can fix all descriptors again if this is needed.
Another option would have been to call __set_name__ in the base implementation of object.__init_subclass__. This way it would be possible even to prevent __set_name__ from being called. Most of the times, however, such a prevention would be accidental, as it often happens that a call to super() is forgotten.
As a third option, all the work could have been done in type.__init__. Most metaclasses do their work in __new__, as this is recommended by the documentation. Many metaclasses modify their arguments before they pass them over to super().__new__. For compatibility with those kind of classes, the hooks should be called from __new__.
Another small change should be done: in the current implementation of CPython, type.__init__ explicitly forbids the use of keyword arguments, while type.__new__ allows for its attributes to be shipped as keyword arguments. This is weirdly incoherent, and thus it should be forbidden. While it would be possible to retain the current behavior, it would be better if this was fixed, as it is probably not used at all: the only use case would be that at metaclass calls its super().__new__ with name, bases and dict (yes, dict, not namespace or ns as mostly used with modern metaclasses) as keyword arguments. This should not be done. This little change simplifies the implementation of this PEP significantly, while improving the coherence of Python overall.
As a second change, the new type.__init__ just ignores keyword arguments. Currently, it insists that no keyword arguments are given. This leads to a (wanted) error if one gives keyword arguments to a class declaration if the metaclass does not process them. Metaclass authors that do want to accept keyword arguments must filter them out by overriding __init___.
In the new code, it is not __init__ that complains about keyword arguments, but __init_subclass__, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each __init_subclass__ may take out it's keyword arguments until none are left, which is checked by the default implementation of __init_subclass__.
For readers who prefer reading Python over English, this PEP proposes to replace the current type and object with the following:
class NewType(type): def __new__(cls, *args, **kwargs): if len(args) != 3: return super().__new__(cls, *args) name, bases, ns = args init = ns.get('__init_subclass__') if isinstance(init, types.FunctionType): ns['__init_subclass__'] = classmethod(init) self = super().__new__(cls, name, bases, ns) for k, v in self.__dict__.items(): func = getattr(v, '__set_name__', None) if func is not None: func(self, k) super(self, self).__init_subclass__(**kwargs) return self def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns) class NewObject(object): @classmethod def __init_subclass__(cls): pass
Reference Implementation
The reference implementation for this PEP is attached to issue 27366.
Backward compatibility issues
The exact calling sequence in type.__new__ is slightly changed, raising fears of backwards compatibility. It should be assured by tests that common use cases behave as desired.
The following class definitions (except the one defining the metaclass) continue to fail with a TypeError as superfluous class arguments are passed:
class MyMeta(type): pass class MyClass(metaclass=MyMeta, otherarg=1): pass MyMeta("MyClass", (), otherargs=1) import types types.new_class("MyClass", (), dict(metaclass=MyMeta, otherarg=1)) types.prepare_class("MyClass", (), dict(metaclass=MyMeta, otherarg=1))
A metaclass defining only a __new__ method which is interested in keyword arguments now does not need to define an __init__ method anymore, as the default type.__init__ ignores keyword arguments. This is nicely in line with the recommendation to override __new__ in metaclasses instead of __init__. The following code does not fail anymore:
class MyMeta(type): def __new__(cls, name, bases, namespace, otherarg): return super().__new__(cls, name, bases, namespace) class MyClass(metaclass=MyMeta, otherarg=1): pass
Only defining an __init__ method in a metaclass continues to fail with TypeError if keyword arguments are given:
class MyMeta(type): def __init__(self, name, bases, namespace, otherarg): super().__init__(name, bases, namespace) class MyClass(metaclass=MyMeta, otherarg=1): pass
Defining both __init__ and __new__ continues to work fine.
About the only thing that stops working is passing the arguments of type.__new__ as keyword arguments:
class MyMeta(type): def __new__(cls, name, bases, namespace): return super().__new__(cls, name=name, bases=bases, dict=namespace) class MyClass(metaclass=MyMeta): pass
This will now raise TypeError, but this is weird code, and easy to fix even if someone used this feature.
Rejected Design Options
Calling the hook on the class itself
Adding an __autodecorate__ hook that would be called on the class itself was the proposed idea of PEP 422. Most examples work the same way or even better if the hook is called only on strict subclasses. In general, it is much easier to arrange to explicitly call the hook on the class in which it is defined (to opt-in to such a behavior) than to opt-out (by remember to check for cls is __class in the hook body),.
When it's desired to also call the hook on the base class, two mechanisms are available:
- Introduce an additional mixin class just to hold the __init_subclass__ implementation. The original "base" class can then list the new mixin as its first parent class.
- Implement the desired behaviour as an independent class decorator, and apply that decorator explicitly to the base class, and then implicitly to subclasses via __init_subclass__.
Calling __init_subclass__ explicitly from a class decorator will generally be undesirable, as this will also typically call __subclass_init__ a second time on the parent class, which is unlikely to be desired behaviour.
Other variants of calling the hooks.
For the __set_name__ hook other names have been proposed as well, __set_owner__, __set_ownership__ and __init_descriptor__..
Adding a class attribute with the attribute order
This got its own PEP 520.
History
This used to be a competing proposal to PEP 422 by Nick Coghlan and Daniel Urban. PEP 422 intended to achieve the same goals as this PEP, but with a different way of implementation. In the meantime, PEP 422 has been withdrawn favouring this approach. | http://docs.activestate.com/activepython/2.7/peps/pep-0487.html | CC-MAIN-2018-09 | refinedweb | 1,595 | 55.44 |
Agenda
See also: IRC log
<scribe> Scribe: Rhys
<scribe> Scribenick: Rhys
SW: Reviews the agenda and invites comments
DO: Could add links to the updated versioning draft
SW: I'll do that
NM: Don has joined us as the AC rep from Web 3D. He's also been helping me with identification in virtual worlds
... There is no formal issue for this yet
... In IBM I look at new technologies appearing and point these out. There is a lot going on in the virtual worlds space, including starting businesses and signing up users. Some are talking about standards, but there is limited interoperabilty at the moment
... Any interop is in a very piecewise way
... Interop rather limited. Seems that starting with identification might be a good idea
... Suppose on a billboard, there is a URI, I could use the URI and access the information from the web
... In virtual worlds, could I click on a virtual URI on a virtual billboard and access a virtual view of the information
TBL: So does the URI identify a point in 3 space
NM: This is one of the questions
... I'd like to find out what the community is doing in this area, which is why Don is with us
... I've skimmed the note, but not gone through the detail
... The Web3d does seem to be doing something in this space, and I'd like to understand this
... W3C needs to have a relationship with the Web3D folks, and then we should discuss if we think that things are going in the right direction
DO: A friend of mine does some second life development. He has a way of using Amazon gift tokens within second life. You can transfer these between people, and effectively move money.
NM: Second life doesn't know its a URI though presumably?
DO: Right
NM: What do you want to identify within these virtual worlds? Is it just an item like a showroom, or is it a point in 3 space
DB: There are a lot of issues in what has just been layed out.
... Backdrop is that Web3D is small but persistent. I've been coming to liason meetings since 2000.
TBL: There was a 3D workshop at the first web conference
DB: There are 40 company and 200 personal members. Been around for more than 10 years. Stable working group structure. Similar approach to W3C. Aligned with web architecture
... Industry players often think they can own 3D on the web.
... Familiar with second life. I need to be careful about IP.
... I am familiar with the approaches that such systems use
... Everything will eventually align with the Web, I believe
TBL: There is some open source 3D stuff. How aligned is that with your standards?
DB: There is lots of open source. We require two implementations, and one has to be open source. We have a total of 18 implementations
NM: XJ3D is a set of code. What's its scope?
DB: It implements the specs that we have for 3D on the web, geometry, spatial component, etc.
... We've just been working on globe-building code bases using the technology.
... We don't show a formal preference for open source, as there are company implementations too.
NM: How extensive is the industry support
DB: There is healthy churn in the industry. Efforts come and go. We could position ourselves as a virtual worlds technology.
... We have about 80% of the complete technology stack needed to deploy a complete stack, though that would be a mission change for us
NM: One of the specs, is aimed at the virtual worlds or not?
DB: Actually no, though it could work there
... The summary is that we've always had a URL field in objects that need network resources. We have an anchor, so that a URL can be activated
... It could be a bookmark, etc. We have a convention for these viewports.
NM: Are these HTTP?
DB: Yes. Actually, we had forgotten to update the specs to URI, but we have done that now.
TBL: From this anchor, I follow a link to one of these, I get a view?
DB: Typically we're just accessing some other 3D world view or a texture wrapped on something. Could be imported into the current world?
TBL: Do you have some idea of level of detail as you zoom in?
DB: Yes, based on distance of view from the object. The URIs could reference anything.
TBL: You move to the new point, and then render whatever is there
NM: I have a URI. I click on the object and activate the http URI and there could be a # sign and a viewport.
... What comes back has your media type, and that spec defines the rules for the fragid which you process and then render the result
DB: We have a fixed coordinate system in the base, but others in extensions
TBL: Suppose I have a 3d plugin in my browser, can I bookmark a coordinate?
DB: Right now that would be a browser feature
TBL: That would be a good point for interoperability
DB: Its a good point. There is a potential tension between the various players. We sometimes get pushback if you save bookmarks and maybe e-mail them to someone else, the quesiton arises about what then you do with them
TBL: Surely the place I am at is just a coordinate.
NM: What fraction of the references tend to be symbolic, and what are 3 space coordinates?
DB: More coordinates, but they are not in a common coordinate space
... There is no global reference other than the URI
TBL: So if in my world im building a town, and I place your house at a particular place in my town.
DB: And if you wanted to be in a particular lat/long location, you can do that.
TBL: So if someone comes to my world and goes to your house, I should be able to bookmark your house.
DB: Almost, because there is a limitation right now about moving from one coordinate system in an included item shared with the one in which it is embedded
NM: I think there may be a slightly different use case here
... The web got the cosmic goal early. The Web3D approach seems to have been a collection of point solutions that interoperate
TBL: Second life has a global 3D coordinate system.
DB: There is actually a variety of SURLS.
NM: A SURL is based on a region, and then has an x,y,z. So the island name is the base for the SURL
SW: So the web3d approach is to use URIs to point out elements within the world.
... Anchors provide named view points.
DB: And those anchors can include behaviour.
NM: I think that the mechanisms are there in the Web. You have them too, but the statistics are different. On the Web, not being accessible is unusual. On Web3D, people have used the specs differently.
... The default is local serving rather than making them available. via the web
s/avaialble/available/
DB: There has been an historic lack of consensus, that has meant that a common view of how to use URIs for this has no common definition yet.
... Our model is that anyone can have a 3D scene and point to parts of it
TBL: Anyone with a 3D web browser could go directly from the current web straight into the 3D world. I think we are at the point where there could be value in enablihng that.
... The ideal could be that the virtual worlds links are used just like web links
NM: We should identify a set of things that we should follow up.
... Tell us about the list of links
DB: Our problem was that we often needed multiple alternate links for the same resource, for connectivity, performance, reliability reasons
... Typically you need a set of objects for a view. You'd normally use a relative link first, then other links
... They all point to the same thing, but ordered for performance. They are tried in order
NM: Is there a URI that represents this list?
DB: It's possible that people might do that, but its not inherent. The references are ordered lists of URIS
SW: What do they look like?
DB: They are a list of quoted strings
NM: So in X3D you could have an attribute that includes a string as the list of URIs
SW: So is the syntax attr='"uri1" "uri2" ...'
DB: yes.
SW: There are things in XML that accept lists of URIs
NM: Yes, but in this case these are treated as what is effectively the same thing
TBL: So you have to use this list each time you want to refer to a URI. Also the URI could refer to an entire view, so maybe you don't have to access these that often
... Typically on the web people would have a single URI that references the list.
<Noah> Noodling on questions we might track:
DB: So we also allow relative and absolute URIs and URNs.
<Noah> * Are particular specs such as Web 3D specs using the Web and URIs in a good way?
SW: Architecturally it would be good not to restrict the types of URI
<Noah> * Is there a need for something resembling conneg, in which the same URI could sometimes resolve to a traditional Web resource (product demonstration on the traditional web) vs. 3D representation (product demonstration in virtual world)
TBL: The classic approach would be to use this canonical URI approach. Actually, my laptop does this. It looks in the local filespace first, uses that if its there
... The other approach could be to use a catalog
NM: I just typed into IRC a couple of questions. They are the things with the asterisks
... Are particular specs such as Web 3D specs using the Web and URIs in a good way?
... that's the kind of thing we could look at
<timbl> A catalog is a chunk of metadata which gives for each canonical URI a set of equivalent URIs to try, or a set of rewriting rules for URI patterns.
DB: Web 3d would like to engage in that discussion
NM: Is there a need for something resembling conneg, in which the same URI could sometimes resolve to a traditional Web resource (product demonstration on the traditional web) vs. 3D representation (product demonstration in virtual world)
... If I have a product specification, I may send you a different representation if you are on a cell phone than if you are on a desktop
... Maybe I could give you a 3D representation if I knew you were in a virtual world
... Maybe it just needs a redirection. The question is whether anyone cares about the use case. I don't think anyone is doing this yet
TBL: It should just work shouldn't it?
NM: In Web3D this looks promising, but in other worlds, there doesn't seem to be this capability
... The issue is about virtual worlds in general. So part of this is that the Web3D approach looks like it could work, but for other players this might not be the case
DB: Also, would the same facilities be available via other mechanisms too, like web services catalogues etc.
SW: I'd like to understand things that need to be addressed by the TAG
NM: I thought that TAG has a role to liase with communities beyond the web, I could be wrong
... Is it in scope? If so, what is its priority?
<Noah> Mission statement
.
TBL: I'd like to encourage the Web3D community to develop a technology that could cross link via HTTP and in which there are bookmarkable links by coordinate
... to enable references that can be shared and can be used from anywhere in the Web
... I think it could be really valuable and that it would create interesting markets
... Decentralised worlds and decentralised development to encourage scalability
<Noah> FWIW: I think the use case where the same http link sometimes gives a representation in the form of an HTML product description for desktop, sometimes resolves to one tailored to cell phone, and sometimes gives you a 3D representation (if you've got the necessary client), is very, very important. I think it's a good use of the TAG's time in principle to keep an eye on that, but I'm not strongly saying higher priority than other things we're trying to do.
<dorchard> right, I wanted to ask about URIs for things.
DB: I'd like to talk about this with our partners.
DO: How about URIs for things rather than places. That's the httpRange-14 question in virtual worlds
... Could have a URI for a real thing that could be referenced in a virtual world.
TBL: For lots of things they have this. For example, if the representation is a bunch of polygons
<Noah> I'm not sure I'm looking forward to discussing the question: "Is there anything about the essence of an avatar that cannot be conveyed in a computer message?"
TBL: Sometimes the refrence will be to an instance, sometimes to a 'class'. By class I mean a design for an object, from which instances can be created at specific 3 space coordinate
Discussion ensues about the relationship between instances and models (classes), where they are, how they might be transferred and how ownership might be transferred...
<timbl> The instance of an object needs an IS so we can say things about it like who owns it, whether it s for sale, and so on
<dorchard> I mean can we have a URI for a thing in the real world
<dorchard> then we transfer the "thing" from place to place
NM: Resources have URIs, but representations tend not to.
<dorchard> Or even link to thing in the real world, for transfer, etc.
TBL: I don't think there is a philosophical issue here. It's just like images. It's just that in 3D its a set of polygons
DB: We do worry about the ownership of the model when it is being used in multiple scenes
... We support specific protocols. One problem has been a lack of network capability in ECMAScript. There are other approaches including Ajax for 3D worlds. There are other approaches, but networking is tricky
TBL: What is the relationship with the distributed 3D communities?
DB: complete mixture of overlaps and alternative architectures
... We continue to try and apply the web approach to distributed 3D simulation
TBL: One of the ways this might go is that there are large databases of interesting information that is geographically related.
... There is increasing interest in streaming this kind of data across networks so that multiple people can see views of changes immediately
... We might end up with streams of changes flowing over the Web. This is roughly the same challenge as might be needed to keep views consistent across 3D worlds
<dorchard> I think I heard that the polygons of an object have URI(s) but not the thinng.
<dorchard> Don: common thing is to worry about multi-user representation
<dorchard> Don: not so much a URI for the thing.
DB: We don't have an equivalent of DRM. We will use EXI when it becomes available.
SW: What is the follow up?
NM: I think that there is a lot of interest for me. I think this could be a big deal because its similar to the cell phone situation. The key is that you can call land lines from cell phones
... There is an analog here. I don't think it's urgent yet. I think it will be. There is fragmentation now, which it will be important to fix over time. It's equivalent to a situation where cell phones could not call land lines.
... Not sure we need to open an issue right now.
SW: Reviews agenda progress
TAG thanks Don for participating
Don Brutzman leaves
DO: changed the first good practice to 'server or resource' from server
NM: Should include the notion of the representation
<dorchard> Server, or more specifically the representations served such as forms, should not solicit ...
<dorchard> Server, or more specifically the representations served such as forms, should not solicit ...
<Noah> suggest s/served/it serves/
<dorchard> A server, or more specifically the representations it serves such as forms, should not solicit any passwords in clear text.
<Stuart>
<dorchard> fugged about it, back to A server should not solicit any passwords in clear text.
<dorchard> A server should not solicit any passwords in clear text.
<dorchard> A server should not solicit any passwords in clear text.
DO: The paragraph about warning the end user has been removed. I've added text to describe why a good practice about this is not possible
TBL: I think there is a case for having a 'mode' of javascript that is hampered to prevent unsafer operations
<dorchard> Noah: don't do paragraph break
<dorchard> Noah: don't say "can provide", say "provides"
NM: Let me clarify this. If I don't have network access, for example, why would I ask for a password?
TBL: If you don't have javascript that could make the request, you would have to use a form, for example when the padlock is on
NM: This doesn't cover the situation for other sensitive data. Should this feature that Tim is advocating cover more than just passwords
... Lots of people won't understand the issue. People will simply assume that if the site they are using is reputable that they will be doing something reasonable with a password.
... You could imagine defining more field types in, say HTML, where these could reflect additional uses. This sounds like its beyond what we want to design in this finding
DO: I removed the problematic good practice guide about warning users when sending a password in the clear.
<dorchard>
<dorchard> Timbl: note that it's dangerous to send sensitive information such as passwords in clear text, there's no obvious method by which a web browser can reliably know when the data entered is sensitive.
<dorchard> furthermore, in browsers which enable scripting, it may be impossible to know whether the information is transmitted in clear text.
<dorchard> (and the same for versioning...)
NM: Begs the question about the password type in HTML. We need to explain that
DO: Can we get some words?
NM: Points out that the HTML spec says that type=password can be used for sensitive information such as passwords
DO: I added text for digest authentication from Hal.
NM: There was a part of the finding that encouraged the use of digest, but actually because of this issue of salted hashes, you actually can't do this.
... You can't get the secrets to the correct place to enable use of digests in some use cases. These were the cases that Hal thought were the majority, hence there was no value in using digest.
... I think there may be cases where it can be used, in some kinds of newly written web applications
... Suggest that we add something about issues with digest where passwords are already stored as salted hashes
TBL: I thought that the problem was about accessing the secret key.
... suggest change to 'Because many systems store passwords as salted hashes....'
<dorchard> NM: change "because most passwords are stored.." to "Because many systems store passwords"
DO: Next, in section 3, the good practice changed to should from must. Added an explanation about circumstances under which masking is not required
NM: Could we change the 'It is the TAG's opinion...' because its not our normal phrasing.
<dorchard> NM: s/It is the TAG's opinion that if the form field is a password, password masking must take "/If the form field is a password, password masking should take
<dorchard> nm: s/is displayed/be displayed
<dorchard> nm: s/or the password/or that the password/
<dorchard> One example is that the uswer may request that the password be displayed in the clear in order to check the password as it is being entered.
<dorchard> Another example is that the password is intended to prevent search engine access and so it is not particularly sensitive.
<dorchard> Another example is a password that is intended to prevent search engine access and so it is not particularly sensitive.
<dorchard> Another example is that the password is intended to prevent search engine access and so the password is not particularly sensitive.
Another example is a password intended merely to prevent search engine access, and which consequently is not particularly sensitive
TBL: Do we cover temporal versioning and exensibility, or just the temporal aspect?
NM: I don't want to lose the sense of extensibility
<dorchard>
<dorchard> nm: change because evolution to "because support for evolution"
DO: Any objections up to section 1.1?
<Stuart> suggest for 3. s/...., then a given language version/....then a given language version specification/
Discussion ensues on the text of list item #3 in section 1, and whether it requires clarification.
scribe: should define a set of future version identifiers that will be considered compatible. This set could, of course, be empty.
RL notes that the previous line was his attempt to help a discussion, but was not discussed
Discussing section 1.1
<dorchard> nm: section 1.1, bullet 2: common is unclear, name structure should be something like person name structure
SW: Is there a section elsewhere where the name example is discussed?
... Could you link to it rather than explaining it here?
DO: Yes
<dorchard> NM: #3 change "schemas" to languages.
NM: In point 3, could we use langauage instead of schema
<dorchard> all three of thouse languages employ markup from the same namespace but they are different languages.
<dorchard> tbl: sentences shouldn't start with "And.."
<dorchard> tbl: change to separate bullet, #4.
<dorchard> nm: kill last paragraph.
<dorchard> nm: swap last 2 sentences.
<dorchard> nm: change "those applications" to "the applications using it"
DO: Any other other changes for 1.1?
None raised
Section 1.2
<dorchard> NM: in some languages, each instance contains just a name.
DO: Maybe I need to remove the first bullet ("Just Names")
SW: I might choose a URI as the example.
DO: I did mean the abstract, when I first wrote it. I need to think whether I want to extend the notion of language to deal with this kind of abstraction
NM: Please don't. We started with texts because these are things that can be exchanged across the Web
<dorchard> I need to remove the abstract names from this..
NM: I thought you were building this up from the simplest case, where there is just a name
DO: Ok, I'll craft something
SW: Points out that we are runing out of time.
<dorchard> nm: move non-markup text before markup
NM: Any reason not to put text languages ahead of markup? If we did it would be in the sequence of increasing elaboration.
<dorchard> put link to versioning xml
DO: Have we got to the end of section 1.2?
NM: Not sure about the bullet on binary. We said that we were talking about languages composed of texts
<dorchard> I'd prefer to include gif, jpeg in our versioning strategy
<dorchard> while our formal definition of language restricts itself to text based language, the advice herein may be useful for binary languages such as gif, jpeg.
DO: We could move the GIF and JPEG to a section that mentions non-text languages to which many of the findings in the documnent apply.
... What about binary coded XML
SW: There is some layering going on here.
NM: Dave wants to be able to deal with abstract trees, for example. I think we chose not to do that in Edinburgh
SW: I'm not sure we did say that.
NM: We could change the definition of languages or we could restrict this to text-based languages
<RhysL> TBL: We're not covering APIs
<RhysL> TBL: I would be loath to talk about versioning and APIs
<RhysL> DO: Serialisations are languages, but they have an affect on the API
<dorchard> tbl: can relax definitions to be sequence of characters or bytes
<dorchard> nm: need to be on bits
<RhysL> DO: I could live with Tim's suggestion of defining a text as a sequence of characters or bits
<RhysL> TBL: Let's just leave it for now and work on text for the definition of texts in languages
<dorchard> How about changing text to Text is a sequence of characters or bits
<RhysL> NM: I think we need to re-read the terminology section, to check that there are no additional issues that are caused
<dorchard> tbl: happy down to 2 Versioning Strategies
<Stuart> rrsagent pointer?
<Stuart> rrsagent pointer
<Stuart> logger, pointer
<Stuart> logger, pointer? | http://www.w3.org/2001/tag/2007/11/09-minutes | crawl-001 | refinedweb | 4,167 | 70.53 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Critical
- Resolution: Fixed
- Affects Version/s: Scala 2.10.0-M7, Scala 2.10.0
- Fix Version/s: Scala 2.10.0-M7, Scala 2.10.0
- Component/s: Misc Compiler
- Labels:
- Environment:
Scala 2.10.0-20120906-172417-b7e08723d1
Description
import language.dynamics object I { val x = new X(3) // Doesn't compile. It should be a call to applyDynamic("apply")(9) val y = x(9) class X(i: Int) extends Dynamic { def applyDynamic(name: String)(in: Int): Int = i + in } }
I.scala:7: error: I.X does not take parameters val y = x(9) ^
The above is unexpected because applyDynamic does get called for update. The following compiles fine:
import language.dynamics object I { val x = new X(3) x(9) = 12 class X(i: Int) extends Dynamic { def applyDynamic(name: String)(left: Int, right: Int): Int = i + left + right } }
Activity
Section 6.6 of the spec describes how `x(9)` is translated to `x.apply(9)`, so I don't think the SIP needs to mention anything specifically about "apply" unless there will be an exception that dynamic doesn't kick in for "apply". An updated section 6.6 for this SIP or an explicit note in the SIP would of course make this clearer, but because of the handling of "update", I think it is reasonable to infer the SIP means to handle "apply" like everything else.
I believe Mark is right here.
Yeah, Mark is right. We either explicitly disallow or fix. I already bumped to critical, do we need to bump to blocker?
I think we just need to find somebody who can fix it. Unfortunately, type checker is not area of my expertise but let me look around for folks more knowledgeable than me.
Nada has a lot of experience with dynamic so she is probably the best fit. She said she will have a look at this ticket on Tuesday.
Fixed by Nada here:
This SIP proposal mentions nothing about "apply". I think perhaps we just need to make a decision here, but this may be "not a bug". | https://issues.scala-lang.org/browse/SI-6353 | CC-MAIN-2014-10 | refinedweb | 353 | 67.86 |
Lily is an interpreted language with low memory overhead, static typing, and type inference.
Safety through types
Every variable has to have a starting value. Every expression has a known type. Everything has a type, even if it's not explicitly stated. Lily's type system exists to aid the programmer, not get in the way.
To further this notion, Lily provides Option for values that may be None.
Type inference
Strong static typing goes hand-in-hand with good inference. Lily knows that [1, 2, 3] is a List[Integer].
Lily requires that functions explicitly specify their input and output types. But, aside from that, most explicit typing is optional.
Isolated
The interpreter does not write any global data. This allows multiple interpreters to exist at the same time without worrying about them colliding into each other.
Built-in templating
Lily can be run from a server and used as a templating language. When used as a templating language, code is between <?lily ... ?>, and everything else is text.
Code that is imported is expected to always be in code mode. No more importing something that accidentally sends headers. import is also namespaced, among many other things.
Low memory use
Most interpreted languages have to dynamically allocate a lot of memory just to get started. A few hundred KB, or even 2 MB isn't unheard of.
Allocating memory takes time. One way that Lily cuts down on memory (and startup time) is to not dynamically allocate memory for functions and (some) functions that you aren't going to use.
Lily can do this, because it's statically typed, and knows for sure what will and won't be used. This technique, termed dynaloading, allows Lily to print 'Hello world' in less than 10 KB of memory.
print("Hello from Lily!") class Cat(name: String) { # The body of a class is the constructor. # Properties start with @<name> var @name = name print($"My name is ^(@name).") } # Types can almost always be inferred. This is List[Cat]. var cats = [ Cat("Muffin"), Cat.new("Fuzzy"), "Snowball" |> Cat] # a |> b is the same as b(a) cats.map{|c| c.name} |> print # Option is either Some(A), or None. var maybe_cat: Option[Cat] = None match maybe_cat: { case Some(s): print("Cat.") case None: print("None") } | http://fll.presidentbeef.com/lang/lily | CC-MAIN-2019-13 | refinedweb | 381 | 69.38 |
The Java Specialists' Newsletter
Issue 1022005-01-31
Category:
Language
Java version: Sun JDK 1.5.0_01
GitHub
Subscribe Free
RSS Feed
Welcome to the 102nd edition of The Java(tm) Specialists' Newsletter. I am in Johannesburg this week,
presenting my first Java 5 Delta Course - Letting the Tiger out of the cage. This
course is for professional Java programmers, who have already managed the
nuances of JDK 1.4. Java Tiger has many pitfalls, and the syntax is at
times, well, strange. Today we learned what this means:
public static <T extends Comparable<? super T>> void sort(List<T> list)
A few words about Johannesburg. It is a young city, and bustling with
activity. I arrived much too early this morning since the chauffeur service
overestimated the traffic, and even at 6:30am, my customer's building was a
hive of activity. It is also a dangerous place to be, so the chauffeur is
not a luxury. For example, you should not walk down the road carrying a
notebook, a wallet or even a mobile phone. You could be relieved of your
burdens! On the positive side, the people here are very friendly and
welcoming.
NEW:
Please see our new "Extreme Java" course, combining
concurrency, a little bit of performance and Java 8.
Extreme Java - Concurrency & Performance for Java 8.
When I was a kid, I enjoyed fiddling with computers, so my aunt Elke gave me
a sign that read: "To err is human, to really louse things up requires a
computer."
I believe that Java misses a feature, that would make it a lot safer. It
should be possible to make the contents of arrays immutable. A final handle
does not help at all, since the elements of the array can still be changed.
In Issue 14,
I gave an example of how it was possible to have
("hi there".equals("cheers !")) == true.
This could easily have been made impossible by adding a language feature to
prevent users from modifying the contents of an array.
("hi there".equals("cheers !")) == true
However, this gets much worse with auto-boxing. Integer, Long, Short and
Byte have now got a new function called
Integer valueOf(int). This follows the Flyweight
Pattern, similar to String objects, but only caches Integer objects from
-128 to 127, inclusive. It either returns an Integer object from the cache,
or creates a new object.
Integer valueOf(int)
Nice function this valueOf(int), but I wondered what would happen if that
cache were to get corrupted? The interesting part about this function is
that it is called by all the autoboxing code generated by the compiler.
So if it returned incorrect values, the entire number system of Java
would be corrupted ... for example ...
public class Arithmetic {
public static void main(String[] args) {
CoolClass.makeExcellentCuppaCoffee(); // hmmm - we all need that!
int upto = 1000;
// using Integer
Integer total1 = 0;
for(int i=1; i<=upto; i++) {
total1 += i;
}
System.out.println("total1 = " + total1);
// using int
int total2 = 0;
for(int i=1; i<=upto; i++) {
total2 += i;
}
System.out.println("total2 = " + total2);
System.out.println("Should be " + ((upto+1)*upto)/2);
}
}
The output on my machine is:
Hmmm, the first cuppa in the morning is the best!
total1 = 492372
total2 = 500500
Should be 500500
I have not shown you the fantastic coffee-making method in the CoolClass.
Here goes:
import java.lang.reflect.Field;
public class CoolClass {
static {
try {
Class[] classes = Integer.class.getDeclaredClasses();
for (Class clazz : classes) {
if (clazz.getName().endsWith("IntegerCache")) {
Field cacheField = clazz.getDeclaredField("cache");
cacheField.setAccessible(true);
Integer[] cache = (Integer[]) cacheField.get(null);
for (int i = 0; i < cache.length; i++) {
cache[i] = new Integer(0);
}
}
}
} catch (Throwable e) {
// we silently pretend we didn't want to destroy Java...
}
}
public static void makeExcellentCuppaCoffee() {
// let's pretend this function does something amazing,
// like make a good cup of coffee
System.out.println("Hmmm, the first cuppa in the morning is the best!");
}
}
Of course, this is not Java's fault, but of lax security procedures. First
off, you should always run your programs with a security manager, even if
you do not think you need it. And of course, any libraries that you use
should be checked for malicious code.
It is a pity though that you cannot turn autoboxing off, and that you are
not able to easily find all places that use autoboxing, just to know what
code to verify. Who knows, maybe in future we will have a -Xlint option to
show us where autoboxing is used.
Kind regards
Heinz
Language Articles
Related Java Course | http://www.javaspecialists.eu/archive/Issue102.html | CC-MAIN-2015-18 | refinedweb | 762 | 65.73 |
Blog Map
(July 10, 2008 - I've written a new blog post on a better way to accomplish this.)
This blog is inactive.New blog: EricWhite.com/blogBlog TOCThis post presents a refinement of the OpenXmlDocument class, which is a new class (WordprocessingML) that derives from the OpenXmlDocument class. The WordprocessingML class adds additional functionality that is specific to WordprocessingML documents, including:
· Some constant strings that contain the DocumentRelationshipType, the StylesRelationshipType, and the CommentsRelationshipType.
· An XNamespace object that contain the main XML namespace for WordprocessingML documents.
· Initialized properties that find the main DocumentRelationship object, the StylesRelationship object, and the CommentsRelationship object. The Relationship class is declared in the code found in the link below, and represents a node in the object graph that contains an entire OpenXML document.
· A DefaultStyle method that queries for the default style of the document.
· A Paragraphs method that enumerates all paragraphs in the document. The Paragraphs method returns IEnumerable<Paragraph>. The Paragraph class is a tupple class that contains: the XElement node of the paragraph for further querying if necessary, the style of the paragraph, the text of the paragraph, and a collection of comments for the paragraph. It needs to contain a collection because a paragraph can have more than one comment.
You can see the complete listing here: The WordprocessingML Class
Following is a simple example that shows the use of the WordprocessingML class:
string filename = "Test.docx";
using (WordprocessingML doc = new WordprocessingML(filename)){ foreach (var p in doc.Paragraphs()) { Console.WriteLine("Style: {0} Text: >{1}<", p.StyleName.PadRight(16), p.Text); if (p.Comments != null) foreach (var c in p.Comments) { Console.WriteLine(" Comment:"); Console.WriteLine(" Id: {0}", c.Id); Console.WriteLine(" Author: {0}", c.Author); Console.WriteLine(" Text: >{0}<", c.Text); } }}
When run on a small document, the code produces the following output:
Style: Normal Text: >This is a test.<
Comment: Id: 0 Author: Eric White Text: >Hello worldtestcomment<Style: Heading1 Text: >This is only a test.<Style: Normal Text: >This is another paragraph.<
Comment: Id: 1 Author: Eric White Text: >another<
The last week has seen some interesting discussions and useful how-to posts on Open XML blogs ... Three
This post presents a refinement of the OpenXmlDocument class, which is a new class (WordprocessingML)
Interesting post, haven't used it yet but after reading this will give it a try. Thanks.
Let me know how it goes. BTW, I've updated my approach - see for more info.
-Eric | http://blogs.msdn.com/b/ericwhite/archive/2007/12/13/the-wordprocessingml-class-a-refinement-of-the-approach-of-using-linq-to-xml-to-access-open-xml.aspx | CC-MAIN-2014-41 | refinedweb | 409 | 58.18 |
CodeGuru Forums
>
Visual C++ & C++ Programming
>
C++ (Non Visual C++ Issues)
> question
PDA
Click to See Complete Forum and Search -->
:
question
lindawqu
January 28th, 2002, 02:53 PM
How does MS SQL server interface to C/C++ program? (I want C/C++ program to read/write db of ms sql) thanks
Gonyoda
January 28th, 2002, 02:59 PM
Are you talking about an extended stored procedure? Or reading/writing directly from/to the raw SQL database files?
ESP are relatively easy, but raw access - you're on your own I think.
- John
thew
January 28th, 2002, 03:23 PM
The most versitile method for database I/O is odbc. A newer, slower, and less versitle way though perhaps easier is using the new DAO microsoft yucky paradigm.
To use odbc just install an odbc driver using your control panel "Data Source" program. Then create a datasource. Then in your program instanciate a CDBObject variable.
CDatabase m_dbCust;
Then open the database object using the open method.
m_dbCust.Open( _T( "MYDATASOURCE" ), FALSE,
FALSE, _T( "ODBC;UID=JOES" ),
You can also add a password in their if you want to avoid that naste login dialog popping up..
To execute SQL directly from your CDatabase object use the following command structure..
TRY
{
m_dbCust.ExecuteSQL( strCmd );
}
CATCH(CDBException, e)
{
// The error code is in e->m_nRetCode
}
if you want to read data out of the database or you want to pase through records use a CRecordset ojject in conjuntion with your CDatabase object.
you can create one directly from your class wizard and bind it to the table you like and automajically generate all the field varibles conforming to your table.. Then you can use edit, addnew and update methodes to insert new records.. et al...
don't forget to close your recordsett and close your database object or you could cause a fur ball.
lindawqu
January 28th, 2002, 03:32 PM
thanks.
how can c or c++ program know (recognize) "CDatabase"? Do i need to include a header file (.h)? or do something else?
thew
January 28th, 2002, 03:37 PM
#include <afxdb.h> // CDatabase + CRecordset
We're talking VC++ here right? If you're talking if your talking linux or solaris or something we're going to have to go back to the drawing board.
lindawqu
January 28th, 2002, 03:37 PM
I don't know if 'extended stored procedure' can interface with c/c++. If yes, please tell me where to get something to start with. And for 'directly', how to do it? In Oracle, I use Pro*C and OCI to interface with c/c++. I don't know how to interface with c/c++ by using MSSQL. thanks
Gonyoda
January 28th, 2002, 04:05 PM
Ok, I think you are trying to access a SQL Server database using your C/C++ client program? [Your original email sorta implied the other way around].
If you ARE trying to access the SQL Server database from your C/C++ client program to perform standard SQL commands (like SELECT, UPDATE, etc) you have a variety of options.
You can use DBLib, OLE-DB, ADO, MFC or ODBC.
DBLib is the SQL 6.5 recommended interface to SQL Server. Since versions 7.0 and later, MS recommends you use OLE-DB. DBLib is straight-up C calls to the SQL Server.
OLE-DB is real messy to use directly since you have a lot of COM work to do. The easist OLE-DB wrapper I've used is ADO. Look for objects like Recordset, Command, Connection in the MSDN. If you are using Visual C++, you can import the ADO library [msado15.dll] so you can access the ADO COM objects directly using the _com_ptr type. The ADO object model is pretty clean and easy to use.
You can also use MFC's CDatabase object, but that uses ODBC, which MS doesn't recommend us developers use any more. [OLE-DB provides an interface to ODBC for legacy database drivers] To use ODBC directly there are a ton of ugly C-style API calls.
Good luck,
- John
PS: If I'm mistaken and you DO want your sql server to talk to a C/C++ program, let me know.
lindawqu
January 28th, 2002, 04:39 PM
Sorry for something not clear.
I want to write a pure c or c++ program (not VC++) in which I want to include some statements that can call MS SQL db (query) and read data from db and write to db.
Thanks again for help.
thew
January 28th, 2002, 04:57 PM
>> I want to write a pure c or c++ program (not
>> VC++)
You're out of luck. If you're familiar with OCI or PRO C you know that such solutions require libraries and are platform specific same with all the idea's which we've covered here. You could write write multi platform code but that would mean #define 'ing out all the platform specific code and testing the app on both platform.. double the complexity, tripple the effort.
Use odbc as I suggest or use DBLib. Both are Microsoft specific. ODBC is more versitle if you later decide to replace mssql with oracle which is what microsoft objects about it. The performance is better I've found although it's undecernable for most tasks.
codeguru.com | http://forums.codeguru.com/archive/index.php/t-180539.html | crawl-003 | refinedweb | 891 | 73.58 |
Differential high voltage measurement using a transformer Can time travel make us rich through trading, and is this a problem? Join the community Back I agree Powerful tools you need, all for free. Budget Calendar Creating an event calendar that not only track appointments but also money events. However, the Event Viewer displays other system events too, making it more tedious to find the login records.
more hot questions question feed lang-bsh about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life / Arts Culture / Recreation Uses a regex comparison to determine how to pull the user name out based on the first number of the event ID. Installed the new drivers, and uninstall all. Did the page load quickly?
View this "Best Answer" in the replies below » 21 Replies Ghost Chili OP cduff Jan 29, 2015 at 4:31 UTC I don't have any 4800 or 4801 read more... Event viewer shows errors solved Event viewer harddisk1 /dr1 has bad blocks error solved What causes a computer to suddenly freez without a Bsod or error in event viewer ?
up vote 1 down vote favorite 2 How does one read logon and logoff events from the Windows event log, and retrieve the corresponding information for each user from Active Directory, Note: For Windows Vista, use the Classic View display option in Control Panel to see the Administration Tools. Manage Your Profile | Site Feedback Site Feedback x Tell us about your experience... Event Id 7001 Computer Browser Service Depends Browse other questions tagged powershell login active-directory event-log winlogon or ask your own question.
Your cache administrator is webmaster. Event Id 7001 Windows 10 Text-
I already have 3 other uses for this script template. 0 Mace OP Chamele0n Jan 29, 2015 at 10:32 UTC cduff wrote: We have to define those namespaces Event Id 7001 User Logon Notification For Customer Experience Improvement Program I'm modifying a script that gets me the user logon\off workstation lock\unlock times for a remote computer. Event Viewer Error Problems with Microsoft Windows 10 Windows 8 Event Viewer - - "Corrupt" errors. Get the answer scout_03Sep 21, 2012, 9:15 AM you could also check this for your bigfoot network software also look at this from killer gaming angry12345Sep 22, 2012, 11:44
secpol.msc>advanced audit policy configuration>system audit policies-local group policy object>logon/logoff>audit other logon/logoff events> check "configure the following events" "success" and "failure". We appreciate your feedback. Event Id 7001 Service Control Manager Are people of Nordic Nations "happier, healthier" with "a higher standard of living overall than Americans"? Event Id 7001 Windows 7 TECHNOLOGY IN THIS DISCUSSION PowerShell Active Directory Read these next... © Copyright 2006-2017 Spiceworks Inc.
that right? 10 answers Last reply Sep 25, 2012 More about event viewer showing error 7001 7000 scout_03Sep 20, 2012, 1:20 PM i would do a full virus without network connected this contact form Also you'd be better off performance wise getting your events like this: PowershellGet-WinEvent -FilterHashtable @{LogName='System';[email protected](7001,7002,4800,4801);StartTime=(Get-Date).AddDays(-$Days)} 1 Serrano OP philgman Jan 29, 2015 at 6:52 UTC That is almost Ask ! please help! Event Id 7002 Winlogon
It also reports when services fail to start or hang while starting. Not to hijack this thread I will do a little research on this and post a new topic if I need. While I am not sure what this particular Event ID means, I can share what I did - I went to the Task Scheduler and disabled all tasks related to the have a peek here Add Cancel × Insert code Language Apache AppleScript Awk BASH Batchfile C C++ C# CSS ERB HTML Java JavaScript Lua ObjectiveC PHP Perl Text Powershell Python R Ruby Sass Scala SQL
If event ID 7034 is also logged for this service, then restoring the service default settings to resolve event ID 7034 would also resolve this error. Event Id 10005 matches any event number from 7000 to 7999. To be complete it would match any four character string that starts with 7, so, it'll match 7bob and 7?!*. The same goes User logon/logoff times in AD Best Answer Ghost Chili OP cduff Jan 29, 2015 at 8:08 UTC Powershell$Days = 1 $events = @() $events += Get-WinEvent -FilterHashtable @{ LogName='Security' [email protected](4800,4801) StartTime=(Get-Date).AddDays(-$Days)
Help Desk » Inventory » Monitor » Community » Click Event Viewer (Local), then Windows Logs and System. contents of table bigger than rest of text and also not centered Is there any way to take stable Long exposure photos without using Tripod? Event Id 414 Windows 10 The namespace and the xpath are parameters needed by select-xml. 0 Ghost Chili OP cduff Jan 29, 2015 at 8:46 UTC And we didn't have to use xml.
I think this is what has been hanging me up on a Powershell script for reading .etv files (windows event logs in a file format). I rebooted, and when i did, my clock was messed up on wrong time and this error has showed up on every reboot now.Also noticed that my Peer to Peer Service remote PCs event viewer)? 0 Datil OP M Boyle Oct 26, 2016 at 11:50 UTC Get-WinEvent has a -ComputerName parameter. Even with 5 minutes per server (to check the logs and other parameters), it may take an hour to make sure that everything is ok and no "red lights" are blinking
I ran malewarebytes and found nothing. Related Searches Tech for Learning How to Set Up Gmail on Your iPad How Change Gmail Settings to Delay Sending Emails How to Make Sure That the Purple Results on Google What Should I Do if I Forgot My Instagram Name? | http://juicecoms.com/event-id/event-id-7001-service-control-manager.html | CC-MAIN-2018-26 | refinedweb | 978 | 57 |
, you invent DRAKON!
ДРАКОН, "dragon"
Backronym for ."
Translation: "Friendly Russian algorithmic language that guarantees clarity."
Drakon allows you to transform this:
Into This:
Frankly, it's a little bit like magic.
Why Use Drakon?
I've only just started exploring the possibilities of Drakon - so I have a convert's zeal and a neophyte's experience - but here's the elevator pitch..
It really is amazing when you start to use it. If you have a complex process, a knotty algorithm, or any large scale information that you want to convey to an audience - Drakon is perfect.
Let's take, for example, Dijkstra's algorithm. When expressed in Python, it takes a savant to intuitively understand what the algorithm does - even if it is well commented.
It takes someone with a lot of experience to spot inefficiencies or problems.
Here's the algorithm expressed in Python.
from priodict import priorityDictionary def Dijkstra(G,start,end=None): D = {} # dictionary of final distances P = {} # dictionary of predecessors Q = priorityDictionary() # est.dist. of non-final vert. Q[start] = 0 for v in Q: D[v] = Q[v] if v == end: break for w in G[v]: vwLength = D[v] + G[v][w] if w in D: if vwLength < D[w]: raise ValueError, "Dijkstra: found better path to already-final vertex" elif w not in Q or vwLength < Q[w]: Q[w] = vwLength P[w] = v return (D,P) def shortestPath(G,start,end): D,P = Dijkstra(G,start,end) Path = [] while 1: Path.append(end) if end == start: break end = P[end] Path.reverse() return Path
Now, let's take a look at how that would be constructed in Drakon.
With almost zero knowledge you can quickly and easily see where your mistakes are. Drakon flowcharts can be exported as images, blown up on projectors, or simply emailed around.
Once you're happy with the diagram, you click a button and it spits out JavaScript, Java, C#, C/C++, Python, Tcl, Lua or Erlang.
What Have I Used It For?
My dad wants some help building an app. Like the dutiful son I am, I agreed and asked him to send over what he had so far. This is what I got.
Not exactly the easiest of things to work from, dad!
So, I began transcribing the algorithm by hand into JavaScript. It quickly became a mess of if...else, nested conditions, and general spaghetti code - I think I even threw in a GOTO statement :-)
None of which was made easier by the fact that there were some obvious errors in the original flow chart. "Yes" where "no" was meant, lines which criss-crossed each other, etc.
After an hour or so of using Drakon for the first time, I'd transformed the pen and ink drawing into this:
Perhaps not the finest flowchart known to man, but a lot easier to understand. I was able to make changes, see where the errors were, optimise the flow. My father - who has no knowledge of JavaScript - was able to look at the chart and verify that it was correct.
Most importantly, I clicked a button and it generated the sort of intricately nested JavaScript which would have taken me all day to write by hand.
Finally, there's no save button! Every action is automatically saved without the need for any user interaction. Stepan Mitkin, the Russian developer behind the current open source Drakon project, says:
The "Save" button is obsolete. Pressing "Save" is boring and stressful work. Boring work must be done by the machine.
Writing algorithms is boring, stressful, repetative, error-prone work. Let Drakon do it for you.
Getting Started
Download Drakon for Linux, Mac, Windows.
On Linux, you'll need to install a few dependencies.
sudo apt-get install tk tcl libsqlite3-tcl tcllib libtk-img
To run, open the command line, navigate to where you unzipped the files and run:
tclsh drakon_editor.tcl
or, simply:
./drakon_editor.tcl
Drakon files are SQLite 3.6 databases - so you are not locked in to a proprietary file format.
BONUS!
Several years ago, the Technikmuseum Speyer in Germany purchased Buran Analog BST-02 - one of the craft used for test flights in the Soviet Buran programme. I was in Düsseldorf at the time and got to watch it being sailed down the Rhine. Magical! | https://shkspr.mobi/blog/2013/04/use-drakon-to-generate-code-from-flowcharts/ | CC-MAIN-2017-04 | refinedweb | 721 | 65.83 |
Python Certification Training for Data Scienc ...
- 53k Enrolled Learners
- Weekend/Weekday
- Live Class
Technological advancements have lead to reduced effort. This makes Python programming language as one of the most sought out programming language due to its ease of access and readability. This also means a surge in the number of people experimenting with Python codes. In this blog, we will go through few of the most sought after fundamental python programs. Here is the list of same:
def pal(num): x1 = num[::-1] if x1 == x: print('palindrome') else: print('not a palindrome') print(pal('edureka'))
Factorial of a number is the product of all the positive numbers less than or equal to the number. The factorial of a number n is denoted by n!.
data-src=
Following is the program to find the factorial of a number.
def fact(num): if num == 0: return num else: return num * fact(num - 1) print(fact(5))
data-src=
Following is a program to print a fibonacci series.
a = int(input('enter the first element')) b = int(input('enter the second element')) n = int(input('enter the number of elements ')) print(a,b, end=" ") while n-2: c = a + b a = b b = c print(c, end=" ") n = n-1
It is a special number, If we sum the cube of each of the digits in an armstrong number it will be equal to the number itself.
data-src=
Following is the python program to check whether a number is an armstrong number or not.
num = int(input('enter the nuber')) s = 0 temp = num while temp > 0: c = temp % 10 s += c**3 temp //= 10 if s == num: print('armstrong number') else: print('not an armstrong number')
data-src=
Following is the program to create a calculator in python
def add(a,b): return a+b def sub(a,b): return a-b def prod(a,b): return a * b def div(a,b): return a / b def si(p, r, t): return (p*r*t) / 100 def ci(p, r ,t): return p * pow((1 + r/100), t) def sqr(num): return num**2 def sqrt(num) return num**0.5 print(add(10,15)) #to add two numbers, similarly you can use other functions for other operations.
data-src=
Following is the program for patterns in python.
num = 5 a = (2 * num) - 2 for i in range(0, num): for j in range(0, a ): print(end=" ") for j in range(0, i+1) print('*' , end=" ") print(" ")
data-src=
Following is the program to check if a year is a leap year
year = int(input('enter year')) if year % 400 == 0: print('it is a leap year') elif year % 4 == 0: print('it is a leap year') elif year % 100 == 0: print('not a leap year') else: print('not a leap year')
num = int(input('enter number')) for i range(2, num): if num% i == 0: print('not a prime number") break else: print('prime number') break
We will take the following shapes and try to calculate the area of all these shapes in python.
data-src=
Following is the program to calculate areas in python
import math pi = math.pi def circle(radius): return pi * radius**2 def cube(side): return side**3 def cylinder(radius, height): return 2*pi*radius + 2*pi*height def sphere(radius): return 2*pi*(radius**2) print(circle(10)) #You can use other functions to calculate the areas of other shapes.
data-src=
Following is the program to reverse a list
a = [1,2,3,4,5,6,7,8,9,10] print(a[: : -1]) #this will print the list in reverse.
have any questions? mention them in the comments, we will get back to you. | https://www.edureka.co/blog/python-programs/ | CC-MAIN-2019-51 | refinedweb | 625 | 61.8 |
Pagy Gem
Recently, I came across the gem “Pagy” that helps to handle pagination in Rails applications and thought it would be good to review how to include it. Pagination is so important as your database grows because no one wants to scroll through hundreds or thousands of posts. However, someone might click through a few pages if there are only 10 posts per page. “Pagy” has some benchmarks listed in their docs that show it performing better than other standard pagination gems, so I decided to go with it.
The first step is to add the gem to the gemfile and run bundle install.
gem 'pagy'
Pagy splits pagination into the frontend and backend so in order to set our data up correctly on the backend and show it correctly on the front end we need to do a little configuration. For this application, I have a Post and User model and I want the index of Posts to show only 10 per page. If I know that posts are the only model I want paginated, I write some code in the Post Controller, but if I might use it for multiple models, I write it in the Application Controller as below:
class ApplicationController < ActionController::Base
include Pagy::Backend
end
This gives us access to Pagy on the backend. For the frontend, I need to include it in our Application Helper as below. Again, if I only wanted it for posts, I could write this directly in the Post Helper.
module ApplicationHelper
include Pagy::Frontend
end
Now we have access to Pagy but need to tell the controller and view to actually use it. In the post controller for the index of posts instead of writing @post = Post.all, write this line:
def index
@pagy, @posts = pagy(Post.all, items: 10)
end
This assigns posts to a @pagy variable in addition to the @posts variable. The items parameter specifies how many objects (in this case posts) to display on each page and can be modified very easily. Now we tell our view how to handle the @pagy variable. So in the index view for posts we write:
<%== pagy_nav(@pagy).html_safe%>
This displays the pagination in the default format of Prev, page numbers and Next. There are many customizations available for Pagy including Bootstrap so definitely take advantage of how to customize the view. If I start my server and access “/posts” I now see 10 posts per page with pagination at the bottom and I can easily navigate between pages. It’s that simple! I hope this was helpful and encourage everyone to continue researching new gems to make applications even better! | https://andrewksmoker.medium.com/pagy-gem-a8bc26eb76ff?source=post_internal_links---------7---------------------------- | CC-MAIN-2021-39 | refinedweb | 443 | 68.4 |
Hello was wondering if anyone could help me with this code. I am writing it for exercise 1-13 in the book "The C Programing Language". I am tring to get an array of word lengths. When I compile it i get the warning multi-character character constant. Also the code doesn't work. Any ideas?
thanks
#include <stdio.h> #define IN 1 #define OUT 0 main() { int c, nc, i, state; int ndigit[26]; state = OUT; nc = 0; for(i = 0; i < 26; ++i) ndigit[i] = 0; while ((c = getchar()) !='\t') { if (c == ' ' || c == '|n' || c == '\t'){ state = OUT; ++ndigit[nc-'0']; nc = 0; } else if (state == OUT) { state = IN; ++nc; } else if (state == IN) { ++nc; } for (i = 0; i < 26; ++i) printf("%d", ndigit[i]); } } | https://www.daniweb.com/programming/software-development/threads/429781/the-c-programing-language-exercise-1-13 | CC-MAIN-2018-43 | refinedweb | 127 | 82.14 |
Amazing Charts In Rails
- |
-
-
-
-
-
-
Read later
My Reading List
For generating charts from reports or data in the database, we need a good charting product. Gruff, JFreeChart, XML/SWF charts, FusionCharts are few of the products available for Ruby on Rails. The following table gives a rough comparison of these charting products. Note that not all products have been tried and tested. Most of the analysis below is based on information gathered from the documentation of the products.
In this article, we will explore charting in Rails using FusionCharts and MySQL database. FusionCharts is a flash-based charting component which can generate interactive and animated charts. FusionCharts can be used with any web scripting language, to deliver powerful charts with fairly minimal coding. FusionCharts comes with wrapper modules for use with RoR. Easy to use, variety of chart types, good documentation and great support is the motivation behind using FusionCharts for this article.
This article describes the mechanism of generating charts using FusionCharts in Ruby on Rails through a sample application. To run the sample application discussed in this article, the following would be needed:
• FusionCharts Free/ v3:
FusionCharts Free can be downloaded from , or the commercial version with more options can be downloaded from . In this article, we use the free version to create the charts.
Installation of FusionCharts merely involves copying and pasting the SWF and .rb files from the download package into appropriate application folder. The .rb files are present in Download Package > Code > RoR > Libraries folder.
• Ruby 1.8.6 or above:
Available at
• Rails gem 2.0.2 or above:
With RubyGems loaded, you can install all of Rails and its dependencies through the command line:
gem install rails
Rails can also be downloaded as stand-alone package from here .
• MySQL 4.0 or above:
Can be downloaded from here .
The sample application developed for this article is a basic time tracker application. This is a simple application where an employee fills out time for a week and views the chart based on the input hours. This article will discuss the sample application in two parts. The first part deals with the development of the basic application which includes list, edit, show and destroy for employees and timesheets. If you already have an application in which you have to integrate charts, then you can skip this part and go directly to the next part, which explains the integration of charts with the application. The article expects the reader to have a basic knowledge of Ruby on Rails.
Creating the Basic time tracker application
Using scaffold, the basic functionality of list, show, edit and delete for employees and timesheets can be generated. The commands to generate the basic employee and timesheet controllers are as follows: (run the last two commands from within the TimeTrackerApplication folder created with the first command)
rails –d mysql TimeTrackerApplication ruby script/generate scaffold Employee name:text ruby script/generate scaffold Timesheet log_date:datetime hours_spent:integer employee_id:integer
Next, you would modify the database.yml present in the config folder to point to “timetrackerdb” and the username and password entries corresponding to your database. Then, you would run the following rake commands to create the database,
rake db:create rake db:migrate
In order to establish the foreign key relationship between employees and timesheets table, you would run the following query in your mysql instance:
alter table timesheets add constraint fk_employee_id foreign key fk_employee_id(employee_id) references employees(id) on delete cascade
Of course, there are other ways of creating foreign keys; the discussion of which is beyond the scope of this article. To represent the above foreign key relationship in Ruby on Rails, you will have to create an association between the models.
In Employee Model, after the class declaration statement, write the following statement:
has_many :timesheets
And in Timesheet Model you need to write:
belongs_to :employee
To insert the sample values into the database, you would need to run the sql script db/sampledata.sql. The basic application is now ready. You can add, view, edit or delete employees.
Integrating Charts In The Application
With the basic time tracker application in place, here is what it takes to generate the time tracker charts for an employee:
• Copy the FusionCharts folder available in the download package of FusionCharts Free/Pro
(Download Package > Code > FusionCharts), to the public folder of TimeTrackerApplication.
• Copy the file FusionCharts.js present in the Download Package > Code > FusionCharts folder
to the public/javascripts folder.
• Copy the fusioncharts_helper.rb from the Download Package > Code > RoR > Libraries folder
of the download into the lib folder of TimeTrackerApplication.
That completes the FusionCharts setup.
From the list of employees page, a link to the Time Tracker Chart needs to be created. Thus, for every employee, there will be a link to view his time as a chart. The link to the time tracker chart is created in the app/views/employees/index.html.erb file. Listing 1 shows the details of the link added. Add this link after the other links in the page.
Listing 1
<td><%= link_to 'Time Chart', {:action=>'view_timesheet_chart',:id=>employee.id} %></td>
Figure 1 illustrates the list of employees page from the application. The features seen in Figure 1 have been acheived easily via database setup and ruby scaffold as seen in the previous section. This page can be viewed by accessing the address "". The relevant portion of this screen is shown in Figure 1.
Figure 1
The action invoked on clicking this "Time Chart" link is the view_timesheet_chart action of the employees controller. Listing 2 shows the code for this action. This action renders the chart for the selected employee. The action contacts the Employee model to find the timesheets for this employee in the date range "2008-12-01" to "2008-12-07" and then renders the "view_timelog_chart.html.erb". To keep things simple, the date range has been fixed in the controller. In real world applications, the date range for generating the report/ chart would be selected by the user.
Listing 2
EmployeesController
def view_timesheet_chart start_date= "2008-12-01" end_date="2008-12-07" @employee_id = params[:id] employee_details_with_timesheets = Employee.find_with_timesheets_in_date_range(@employee_id,start_date,end_date) if(!employee_details_with_timesheets.nil?) @employee_details_with_timesheets =employee_details_with_timesheets[0] else @employee_details_with_timesheets =nil; end headers["content-type"]="text/html" end
Using the employee id as parameter, this action contacts the Employee model to find the timesheets for this employee within the specified period. The function to be added in the Employee model is shown in Listing 3 below:
Listing 3
Employee.rb
def self.find_with_timesheets_in_date_range(id, start_date, end_date) conditions="employees.id =? and log_date between ? and ?" employee_details_with_timesheets=self.find(:all, :include=>'timesheets', :conditions=> [conditions,id,start_date,end_date], :order=>'log_date asc') return employee_details_with_timesheets end
The action finally renders "view_time_chart.html.erb". The template "view_timelog_chart.html.erb" uses the layout "employees.html.erb" which is common to all views of employees controller. Hence, the code in the view is short and sweet as seen in Listing 4.
Listing 4
view_timesheet_chart.html.erb (in app/views/employees folder)
<%= javascript_include_tag "FusionCharts"%> <% # The xml is obtained as a string from builder template. str_xml = render "employees/timesheet_data" #Create the chart - Column 3D Chart with data from strXML render_chart '/FusionCharts/Column3D.swf' , '' , str_xml , 'TimeChart' , 650 , 400 , false , false do -%> <% end -%>
From the above code, we understand the following as the steps involved to render the chart in the view page:
- Include the FusionCharts.js file.
- Obtain the xml data from the builder. ( The builder uses the data from the controller action to build the xml)
- Render the chart by calling render_chart function with appropriate parameters
Usually, time is represented in a Gantt chart and this chart is also available in FusionCharts. Here, for the sake of simplicity, the Column chart has been used.
The second step involves the creation of xml. FusionCharts uses XML (eXtensible Markup Language) to create and manipulate charts. The entire FusionCharts chart is controlled by XML parameters i.e., you use XML to define the cosmetic as well as functional properties for the chart. There are a lot of properties that you can define for each chart type. FusionCharts has a specific XML structure for each chart. The chart under discussion is a single-series chart (having only one set of data), representing the day of the week and the number of hours spent by the employee on that day. A sample xml for this chart is shown in Listing 5.
Listing 5
Sample Single-Series Chart XML
<graph xAxisName="Day" showValues="1" caption="Time Tracker Chart" numberSuffix=" hrs." subcaption="For Employee John Wilson" yAxisName="Hours Spent"> <set name="Monday" value="8" color="AFD8F8"/> <set name="Tuesday" value="6" color="F6BD0F"/> <set name="Wednesday" value="5" color="8BBA00"/> <set name="Thursday" value="9" color="A66EDD"/> <set name="Friday" value="9" color="F984A1"/> <set name="Saturday" value="8" color="CCCC00"/> </graph>
To generate an xml similar to the one shown in Listing 5 but with the data present in the database, the builder file is used.
How does the builder build the chart xml? The builder builds the xml for the chart using the @employee_details_with_timesheets variable stored in the action. Listing 6 shows the contents of the builder file.
Listing 6
timesheet_data.builder (in app/views/employees folder)
xml = Builder::XmlMarkup.new(:indent=>0) options = { :caption=>'Time Tracker Chart', :subcaption=>'For Employee '+ @employee_details_with_timesheets.name , :yAxisName=>'Hours Spent', :xAxisName=>'Day', :showValues=>'1', :formatNumberScale=>'0', :numberSuffix=>' hrs.' } xml.graph(options) do for timesheet in @employee_details_with_timesheets.timesheets do log_day = timesheet.log_date.strftime('%a') xml.set(:name=>log_day,:value=>timesheet.hours_spent,:color=>''+get_FC_color) end end
In the builder, you would first create a new XMLMarkup object with the value for "indent" equal to zero and use this object for building the xml.
All the options required for configuring the chart is present in a hash named options, which is passed to the top-most (graph) tag. For details on the options that can be provided to the chart, please refer to the complete FusionCharts documentation. The xml root element is "graph". Within this, there is a "set" element corresponding to each timesheet of the selected employee. Each “set” element has name and value as attributes. The name would contain the day of the week and the value will contain the hours spent on that day by that employee. The builder uses the @employee_details_with_timesheets variable present in the controller action, to obtain these values.
Finally, in the view page, the chart is rendered using the function render_chart which takes the swf chart file name, url, xml, width, height, debugMode, registerWithJS as parameters. This function is available in the fusioncharts_helper module present in the lib folder. This can be made accessible to all the views by including it in the application_helper.rb as shown in Listing 7.
Listing 7
application_helper.rb
require 'fusioncharts_helper' include FusionChartsHelper
The swf files required to show the charts are present in the public/FusionCharts folder. Here the Column3D.swf has been used but any other type of single-series chart could also be generated by just changing the swf filename. The data has been provided using dataXML method but the data could also be provided through a dataURL. Examples of this are present in FusionCharts documentation.
Now, on clicking the "Time Chart" link for an employee in the list of employees page, the time log entries for the week 01/12/2008 to 07/12/2008 are displayed in the form of a chart. The timesheet chart will be similar to Figure 2 shown below.
Figure 2
Summary of steps to generate chart:
After the setup of FusionCharts in the application and including FusionChartsHelper in the application_helper.rb, the following are the steps
- In the controller action, find the data required for the chart from the database.
- Write a builder to build the chart xml from this data.
- In the view for the controller action in step 1, get the xml from the builder by either passing the data to it or letting the builder use the data from the controller action.
- Next, call the function render_chart with appropriate parameters (including the xml obtained from step 3)
In this article, you have learnt how to create a simple chart using FusionCharts in Ruby on Rails through the time tracker application. With a few modifications to the sample application, you could create a chart with the overview of time log for all the employees. Probably, from this chart you could drill-down on a particular employee to get the time details for him. You could use Ajax for retrieving the chart. The possibilities are innumerable. FusionCharts download package itself contains a number of examples which can be explored. The entire sample application discussed in this article is available for download here.
About the Author:
The author is a Consultant with over 6 years of experience in the IT Industry and has interests in a wide range of web technologies involving the J2EE stack, Ruby On Rails & PHP.
Rate this Article
- Editor Review
- Chief Editor Action
Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered.
Get the most out of the InfoQ experience.
Tell us what you think | https://www.infoq.com/articles/sharma-charts-in-rails | CC-MAIN-2017-04 | refinedweb | 2,199 | 55.34 |
Unofficial Lecture 9 Notes
Hi all, apologize for the delay, here’s the lecture 9 notes
Tim
import sys sys.path.append('/Users/tlee010/Desktop/github_repos/fastai/')
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.nlp import * from sklearn.linear_model import LogisticRegression # from torchtext import vocab, data, datasets
from fastai.io import * path = './' FILENAME='mnist.pkl.gz' def load_mnist(filename): return pickle.load(gzip.open(filename, 'rb'), encoding='latin-1') ((x, y), (x_valid, y_valid), _) = load_mnist(path+FILENAME) mean = x.mean() std = x.std() x=(x-mean)/std mean, std, x.mean(), x.std() x_valid = (x_valid-mean)/std x_valid.mean(), x_valid.std()
(-0.0058509219, 0.99243325)
md = ImageClassifierData.from_arrays(path, (x,y), (x_valid, y_valid))
if you are missing the en library
#!python -m spacy download en
Auto Encoder
When you have unlabeled data. How can you create a NN that makes a features for you if you dont have the dependent variable. Lets have our input be the output as well.
Reconstruct the details of this insurance policy.
Less activations than inputs. Will compress features down into fewer features and then expand it back out. Great way for making embeddings and features even when you don’t have labels
Denoising the Auto Encoder
Start with a noisy version and then come out with the clean dataset. The 15% were randomly replaced with another row. The dependent variable would stay the same. Can show a lot of different rows. Gave him features (first layer weights), then took the NN and trained it on the claims data.
2 Models would have been enough to win.
He did no feature engineering
Embeddings
From last week
Iterators & Streaming
Its a object that we call next on. We can pull different pieces, ordered or randomized that can be pulled for mini-batches.
Pytorch is designed to handle this concept too, of predicting a stream of data (or the next item).
fastai is also designed around this concept of iterators.
DataLoader is created with the same concept, but with multiprocessing, which is multi threaded applications ( so you can use your entire processor)
Variable - keeps track of computations being made to a tensor. It’s a wrapper
pytorch - autograd
If we call
back it will calculate the gradient.
def get_weights(*dims): return nn.Parameter(torch.randn(*dims)/dims[0]) class LogReg(nn.Module): def __init__(self): super().__init__() self.l1_w = get_weights(28*28, 10) # Layer 1 weights self.l1_b = get_weights(10) # Layer 1 bias def forward(self, x): x = x.view(x.size(0), -1) x = torch.matmul(x, self.l1_w) + self.l1_b # Linear Layer x = torch.log(torch.exp(x)/(1 + torch.exp(x).sum(dim=0))) # Non-linear (LogSoftmax) Layer return x
def score(x, y): y_pred = to_np(net2.forward(Variable(x)))#.cuda()))) return np.sum(y_pred.argmax(axis=1) == to_np(y))/len(y_pred)
A re-write of
fit
net2 = LogReg()#.cuda() loss=nn.NLLLoss() learning_rate = 1e-3 optimizer=optim.Adam(net2.parameters(), lr=learning_rate)(l) # Before the backward pass, use the optimizer object to zero all of the # gradients for the variables it will update (which are the learnable weights # of the model) optimizer.zero_grad() # Backward pass: compute gradient of the loss with respect to model # parameters l.backward() # print(loss.data) # Calling the step function on an Optimizer makes an update to its # parameters optimizer.step() val_dl = iter(md.val_dl) val_scores = [score(*next(val_dl)) for i in range(len(val_dl))] print(np.mean(val_scores))
0.910429936306
Within a
fit lets rewrite some of the functions (
gradient and
step)
optimizer.zero_grad() optimizer.step()
This code will be replaced with the following:
if w.grad is not None: w.grad.data.zero_() b.grad.data.zero_() # Backward pass: compute gradient of the loss with respect to model parameters l.backward() w.data -= w.grad.data * lr b.data -= b.grad.data * lr
All gradients have to be added together to get that gradient for that parameter.
wis the variable we set before
.gradreferring to the gradient part of the variable
.data.zero_will zero the gradients, note this is the initializing
w.grad.data.zero_()
net2 = LogReg()#.cuda() loss_fn=nn.NLLLoss() lr = 1e-2 w,b = net2.l1_w,net2.l1_b(loss) # Before the backward pass, zero the gradients for all of the parameters if w.grad is not None: w.grad.data.zero_() b.grad.data.zero_() # Backward pass: compute gradient of the loss with respect to model parameters l.backward() w.data -= w.grad.data * lr b.data -= b.grad.data * lr val_dl = iter(md.val_dl) val_scores = [score(*next(val_dl)) for i in range(len(val_dl))] print(np.mean(val_scores))
0.905155254777
Going backwards
Momentum
fastai can speed up the iteration rate and looping.
optimizer.step()- updates
optimizer.zero_grad()-
fit- is the loop that cycles through
nn.Softmax- does the softmax calculation
nn.Linear- does the linear multiplication
A word on learning rate
Sometimes if your learning rate is too large, it gets hard to converge near the later iterations
will pull out the parameters of the model
How many weights vs. the size of the data. Since our dataset is small, and our weights are very large, chances are that we will dramatically overfit.
t = [ 0.numel() for o in net.parameters] t, sum(t)
File "<ipython-input-25-112692b70a57>", line 1 t = [ 0.numel() for o in net2.parameters] ^ SyntaxError: invalid syntax
Regularization
Add new terms to the loss function. If we add L1 and L2 norms of the weights to the loss functions, it incentives the coefficients to be zlose to zero. See the extra term below.
$$ loss =\frac{1}{n} \sum{(wX-y)^2} + \alpha \sum{w^2} $$
How to implement?
- Change the loss function
- Change the training loop to add the derivative adjustment <-- weight decay (not the same as momentum)
net = nn.Sequential( nn.Linear(28*28, 100), nn.ReLU(), nn.Linear(100, 10), nn.LogSoftmax() )
loss=nn.NLLLoss() metrics=[accuracy] opt=optim.SGD(net.parameters(), 1e-1, momentum=0.9). 0.33271 0.28169 0.92725] [ 1. 0.22736 0.24474 0.94715] [ 2. 0.23459 0.26795 0.94118] [ 3. 0.21125 0.27423 0.94805] [ 4. 0.21197 0.32224 0.9384 ]
opt=optim.SGD(net.parameters(), 1e-1, momentum=0.9, weight_decay=0.3). 1.11321 1.13041 0.62271] [ 1. 1.08937 1.06073 0.70482] [ 2. 1.04438 1.35849 0.46795] [ 3. 1.08236 1.12079 0.63515] [ 4. 1.08296 1.20425 0.62988]
On to NLP!
!wget
--2017-11-30 14:16:02-- Resolving ai.stanford.edu... 171.64.68.10 Connecting to ai.stanford.edu|171.64.68.10|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 84125825 (80M) [application/x-gzip] Saving to: âaclImdb_v1.tar.gzâ aclImdb_v1.tar.gz 100%[===================>] 80.23M 10.6MB/s in 10s 2017-11-30 14:16:12 (7.80 MB/s) - âaclImdb_v1.tar.gzâ saved [84125825/84125825]
!gunzip aclImdb_v1.tar.gz
#!tar -xvf aclImdb_v1.tar
PATH='aclImdb/' names = ['neg','pos']
trn,trn_y = texts_from_folders(f'{PATH}train',names) val,val_y = texts_from_folders(f'{PATH}test',names)
def texts_from_folders(src, names): texts,labels = [],[] for idx,name in enumerate(names): path = os.path.join(src, name) for fname in sorted(os.listdir(path)): fpath = os.path.join(path, fname) texts.append(open(fpath).read()) labels.append(idx) return texts,np.array(labels)
??texts_from_folders
trn[0]
"Story of a man who has unnatural feelings for a pig. Starts out with a opening scene that is a terrific example of absurd comedy. A formal orchestra audience is turned into an insane, violent mob by the crazy chantings of it's singers. Unfortunately it stays absurd the WHOLE time with no general narrative eventually making it just too off putting. Even those from the era should be turned off. The cryptic dialogue would make Shakespeare seem easy to a third grader. On a technical level it's better than you might think with some good cinematography by future great Vilmos Zsigmond. Future stars Sally Kirkland and Frederic Forrest can be seen briefly."
First we will throw away the order of words --> Bag of words
Let’s use sklearn to convert corpus to bag of words
veczr = CountVectorizer(tokenizer=tokenize)
Key Concepts
Vocabulary - need to find the unique terms throughout the entire corpus
Term Document Matrix
- columns - vocab or words
- rows - different documents
- cells - count of occurance
Sentiment Approach: bays rule
The probability that a document is from class 1 given that the document is from class 0. We will use a conditional probability as follows below
$$ \frac{P(C_1 | d)}{P(C_0 | d}) = \frac {P(d|C_1)P(C_1)}{P(d)} = \frac {P(d|C_1)P(C_1)}{P(d|C_0)P(C_0)}$$
How do we calculate?
- Gather the documents of one class together
- Create profile made up of the words, and their probabilities
- Note: we add a dataset that assumes every word occurs at least one in the document
- We should have a probability per word, for each class
- For each doucment we can multiple the coefficients and that will give us a P(C_1 | d) and P(C_0 | d)
we will learn the word features from the training set and split. Then use the same framework to split the test set
trn_term_doc = veczr.fit_transform(trn) val_term_doc = veczr.transform(val)
We now have 25000 words, with 75132 docs
trn_term_doc
<25000x75132 sparse matrix of type '<class 'numpy.int64'>' with 3749745 stored elements in Compressed Sparse Row format>
Sparse Matrix
Special format when most of your matrix is filled with zeros. This assumes that most of the matrix is zero, and only keep track of the elements that are non-zero.
The first feature has 93 items
trn_term_doc[0]
<1x75132 sparse matrix of type '<class 'numpy.int64'>' with 93 stored elements in Compressed Sparse Row format>
What are the features (words) ?
vocab = veczr.get_feature_names(); vocab[5000:5005]
['aussie', 'aussies', 'austen', 'austeniana', 'austens']
Lets look at our 93 words
w0 = set([o.lower() for o in trn[0].split(' ')]); #w0
Look up a specific word
veczr.vocabulary_['absurd']
1297
How many times does this word show up in document 1
trn_term_doc[0,1297]
trn_term_doc[0,5000]
Naive Bayes
We define the log-count ratio r for each word f:
$r = \log \frac{\text{ratio of feature f in positive documents}}{\text{ratio of feature f in negative documents}}$
where ratio of feature f in positive documents is the number of times a positive document has a feature divided by the number of positive documents.
p = x[y==1].sum(0)+1 - Number of times it shows in positive corpus
p = x[y==0].sum(0)+1 - Number of times it shows in negative corpus
r = np.log((p/p.sum())/(q/q.sum())) - summing logs is a lot easier to do, otherwise you might run into float errors
b = np.log(len(p)/len(q)) - this is our naive bays
x=trn_term_doc y=trn_y p = x[y==1].sum(0)+1 q = x[y==0].sum(0)+1 r = np.log((p/p.sum())/(q/q.sum())) b = np.log(len(p)/len(q))
Here’s our predictions from Naive Bayes ~ 80% positive
pre_preds = val_term_doc @ r.T + b preds = pre_preds.T>0 (preds==val_y).mean()
0.80740000000000001
Binarized: instead of using the 0.66 for a word, why not just 1 if the word shows up. 83% chance
pre_preds = val_term_doc.sign() @ r.T + b preds = pre_preds.T>0 (preds==val_y).mean()
0.82623999999999997
Logistic Regression
Here is how we can fit logistic regression where the features are the unigrams. So instead of using bayes, we set it up like a supervised problem
m = LogisticRegression(C=1e8, dual=True) m.fit(x, y) preds = m.predict(val_term_doc) (preds==val_y).mean()
0.85648000000000002
Regularized version -> 0.0000001
m = LogisticRegression(C=1e8, dual=True) m.fit(trn_term_doc.sign(), y) preds = m.predict(val_term_doc.sign()) (preds==val_y).mean()
0.85528000000000004
Regularized version -> 0.1
m = LogisticRegression(C=0.1, dual=True) m.fit(x, y) preds = m.predict(val_term_doc) (preds==val_y).mean()
0.88271999999999995
Regularized version -> 0.1 with traing doc terms
m = LogisticRegression(C=0.1, dual=True) m.fit(trn_term_doc.sign(), y) preds = m.predict(val_term_doc.sign()) (preds==val_y).mean()
0.88404000000000005
Trigram with NB features
Instead of using words, we will use small phrases of words, or phrases. In this case we will use 3 word phrases, also referred to as trigrams
veczr = CountVectorizer(ngram_range=(1,3), tokenizer=tokenize, max_features=800000) trn_term_doc = veczr.fit_transform(trn) val_term_doc = veczr.transform(val)
Let regularization do the feature selection, just bound the overall space
trn_term_doc.shape
(25000, 800000)
vocab = veczr.get_feature_names()
vocab[200000:200005]
['by vast', 'by vengeance', 'by vengeance .', 'by vera', 'by vera miles']
y=trn_y x=trn_term_doc.sign() val_x = val_term_doc.sign() p = x[y==1].sum(0)+1 q = x[y==0].sum(0)+1 r = np.log((p/p.sum())/(q/q.sum())) b = np.log(len(p)/len(q)) | https://forums.fast.ai/t/unofficial-lecture-9-notes/8539 | CC-MAIN-2020-05 | refinedweb | 2,147 | 52.66 |
How to print an exception in Python?
For Python 2.6 and later and Python 3.x:
except Exception as e: print(e)
For Python 2.5 and earlier, use:
except Exception,e: print str(e)
The
traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:
import tracebacktry: 1/0except Exception: traceback.print_exc()
Output:
Traceback (most recent call last): File "C:\scripts\divide_by_zero.py", line 4, in <module> 1/0ZeroDivisionError: division by zero
In Python 2.6 or greater it's a bit cleaner:
except Exception as e: print(e)
In older versions it's still quite readable:
except Exception, e: print e | https://codehunter.cc/a/python/how-to-print-an-exception-in-python | CC-MAIN-2022-21 | refinedweb | 117 | 60.21 |
Build Your Own Lucene Codec!
Build Your Own Lucene Codec!
Join the DZone community and get the full member experience.Join For Free
How to Simplify Apache Kafka. Get eBook.
I’ve been having a lot of fun hacking on a Lucene Codec lately. My hope is to create a Lucene storage layer based on FoundationDB – a new distributed and transactional key-value store. It’s a fun opportunity to learn about both FoundationDB and low-level Lucene details.
But before we get into all that fun technical stuff, there’s some work we need to do. Our goal is going to be to get MyFirstCodec to work! Here’s the source code:
public class MyCodec extends FilterCodec { public MyCodec() { super("MyCodec", new Lucene42Codec()); } }
Great! Done. Well not quite. A real codec looks more like this
public final class SimpleTextCodec extends Codec { // pretend there’s private vars here @Override public PostingsFormat postingsFormat() { return postings; } @Override public StoredFieldsFormat storedFieldsFormat() { return storedFields; } @Override public TermVectorsFormat termVectorsFormat() { return vectorsFormat; } @Override public FieldInfosFormat fieldInfosFormat() { return fieldInfosFormat; } @Override public SegmentInfoFormat segmentInfoFormat() { return segmentInfos; } @Override public NormsFormat normsFormat() { return normsFormat; } @Override public LiveDocsFormat liveDocsFormat() { return liveDocs; } @Override public DocValuesFormat docValuesFormat() { return dvFormat; } }
This example is a bit more explicit. This is Mike McCandless’s SimpleText codec that is a great codec to browse for browsing for educational purposes. In this codec, each part of the class is being customized.
Typically you only want to implement a subset of the components of the codec. Lucene provides a convenient base class called “FilterCodec”. You can customize whatever pieces you’d like to, delegating the rest to another codec. For example, If we were, however, to implement a custom storage implemenation for only term vectors, we can override like so:
public class MyCodec extends FilterCodec { final private TermVectorsFormat myTermVectorsFormat; public MyCodec() { super("MyCodec", new Lucene42Codec()); myTermVectorsFormat = new MyTermVectorsFormat(); } // Use custom TermVectorsFormat, default everything else to Lucene42Codec public TermVectorsFormat termVectorsFormat() { return myTermVectorsFormat; } }
Here, we’re delegating to Lucene42Codec for everything except our special TermVectorsFormat.
Each of these individual formats are separate pieces responsible for serializing to a backing store during indexing and deserializing into memory when read back into memory. For many of the formats though, it’s a bit more than that. For example, for the postings format, the format responsible for storing the inverted index, it’s vital to be able to efficiently iterate the inverted index. Storage of the inverted index must be done in such a way that we can easily iterate all the indexed fields, then all the terms indexed into that field, then in turn the documents with term frequencies and positions that contain that term in that field.
You’ll find similar constraints as you implement the interfaces of the other pieces of the codec. Each of these pieces is a topic in its own right worth writing about. They all deserve their own blog articles. For now, I encourage you to explore the JavaDocs to see what might be fun to customize on the Lucene backend! Before I leave you to the Javadocs though, it’s important to tackle a few bits of plumbing – building & running Lucene’s tests against your codec.
Plumbing! Unit Tests & More
Let’s take care of a bit of plumbing. How do we setup a project for a codec? How do we run Lucene’s tests against our implementation to confirm Solr/Lucene will function with our changes?
Using maven to setup the project is fairly straight-forward. Luckily I’ve created a Lucene Codec hello world project on github to get you started. It captures setting up the project with Maven. Feel free to fork it to skip the first two steps below. You’ll still need to read below to learn how to run the Lucene tests against your codec.
First, we’ll start by creating a straightforward maven project with a pom that depends on lucene-core at the version you’re targeting your codec for.
Second we’ll need to publish via our
META-INF/services directory that we have a class that implements the Codec interface. This advertises our codec to Lucene’s class loader. Under
src/main/resources/services create a file called
org.apache.lucene.codecs.Codec. In the file should be a single line with the full name of your Codec class:
com.o19s.MyCodec
We’ll need to tell mvn to copy this into the target/META-INF by specifying it as a resource to be copied into the target folder:
<build> <resources> <resource> <directory>src/main/resources/services</directory> <targetPath>META-INF/services</targetPath> </resource> </resources> </build>
Third pull down the full Lucene/Solr source tree. Let’s test our codec from the command line!
Package your codec into a jar:
mvn package
Under the Lucene source tree, run a single Lucene Test. Pass it the codec to use with the -Dtests.codec argument. Pass the jar with the codec you just packaged up with the
lib argument. Executing this will prove that Lucene can find and load your codec. If Lucene can’t find load your codec, you’ll get an appropriate error right away.
C:\solr\solr-4.3.0\lucene>ant -Dtestcase=TestSegmentTermDocs - Dtests.codec=MyCodec –lib "C:\path\to\target\codec-1.0-SNAPSHOT.jar" test
Now Run all the tests!
C:\solr\solr-4.3.0\lucene>ant -Dtests.codec=MyCodec –lib "C:\path\to\target\codec-1.0-SNAPSHOT.jar" test
Fourth, Naturally it’s going to be convenient to debug Lucene unit tests running our codec in Eclipse. Here’s what we need to do.
- Load your codec and the Lucene source code into Eclipse.
- Create a new Junit debug configuration
- Select the Radio button for “Run all the tests in the selected project, package, or folder”
- Enter in the folder /path/to/lucene/core/src/test
- Select the JUNIT 4 test runner
In the arguments tab, for vm arguments specify:
-ea -Dtests.codec=MyCodec
In the “classpath” tab, make sure both your codec project and the solr/lucene projects are selected
Now you should be able to launch this debug configuration and go to town! Go forth and make some awesome codecs! Let us know about the codec you’re working on, love to hear about it!
Published at DZone with permission of Doug Turnbull , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/build-your-own-lucene-codec | CC-MAIN-2018-43 | refinedweb | 1,083 | 55.24 |
#include "mbed.h" #include "USBHID.h" //We declare a USBHID device. By default input and output reports are 64 bytes long. USBHID hid(true, 8, 8); Serial pc(USBTX, USBRX); //This report will contain data to be sent HID_REPORT send_report; HID_REPORT recv_report; DigitalOut l1(LED1); int main(void) { send_report.length = 8; while (1) { //Fill the report for (int i = 0; i < send_report.length; i++) send_report.data[i] = rand() & 0xff; //Send the report hid.send(&send_report); //try to read a msg if(hid.read_nb(&recv_report)) { l1 = !l1; for(int i = 0; i < recv_report.length; i++) { pc.printf("%d ", recv_report.data[i]); } pc("Got message %s" % data) ''' Gets all HIDs currently connected to host computer, and sets the first device with string "mbed" in its vendor name equal to variable mbed. This variable will be used to send data to the Mbed board. ''' all_devices = hid.find_all_hid_devices() mbeds = [dev for dev in all_devices if dev.vendor_name.find("mbed") >= 0] if len(mbeds) == 0: print("No HID devices found") exit(-1) mbed = mbeds[0] # Sends 8 bytes of data to the Mbed board # The Mbed board should receive the data "1 2 3 4 5 6 7 8" mbed.open() mbed.set_raw_data_handler(on_data) message = bytearray(9) message[1] = 1 message[2] = 2 message[3] = 3 message[4] = 4 message[5] = 5 message[6] = 6 message[7] = 7 message[8] = 8 mbed.find_output_reports()[0].send(message) | https://os.mbed.com/docs/mbed-os/v5.12/apis/usbhid.html | CC-MAIN-2020-40 | refinedweb | 231 | 67.45 |
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
xf86-video-via updated recently (thanks! :) ) but it was updated with a
critical bug, easily fixed. Ebuild =x11-drivers/xf86-video-via-0.2.1 dies
during startx with a "symbol 'assert' not found" and in dying it leaves the
video card in a nonfunctional state. To fix this problem, add:
#include <assert.h>
at the top of the file src/via_dri.c. After that fix, everything works
"perfectly". Someone with connections might push this upstream to the X11 via
driver developer too.
Created an attachment (id=84909) [edit]
Photograph of screen without assert.h
I can confirm that. Without assert.h screen looks more or less like in the
attachment (on Acer Apire 1362, K8N800 based laptop), with assert included
works fine.
Please file this upstream at bugs.freedesktop.org in the xorg product. Make it
block bug #5041, and post the URL here.
Thanks!
Did a bit of searching and finally found this upstream so here's the url:
Hope this helps as it seams this fix is still not in gentoo's portage.
It's not there since no one had brought it to our attention yet :D Thanks for
finding it.
Fixed in CVS. | http://bugs.gentoo.org/130320 | crawl-002 | refinedweb | 228 | 76.62 |
Compiling Python Code
July 12, 2003 | Fredrik Lundh
Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the source is updated, or when otherwise necessary.
To distribute a program to people who already have Python installed, you can ship either the PY files or the PYC files. In recent versions, you can also create a ZIP archive containing PY or PYC files, and use a small “bootstrap script” to add that ZIP archive to the path.
To “compile” a Python program into an executable, use a bundling tool, such as:
- Gordon McMillan’s installer (cross-platform)
- Thomas Heller’s py2exe (Windows)
- Anthony Tuininga’s cx_Freeze (cross-platform)
- Bob Ippolito’s py2app (Mac)
These tools puts your modules and data files in an archive file, and creates an executable that automatically sets things up so that modules are imported from that archive. Some tools can embed the archive in the executable itself.
If all you need is to wrap up a couple of Python scripts and modules into a single file, Squeeze might be what you need. For Windows, my ExeMaker tool can also be quite useful (on its own, or in combination with squeeze).
Compiling Python modules to byte code #
Python automatically compiles Python source code when you import a module, so the easiest way to create a PYC file is to import it. If you have a module mymodule.py, just do:
>>> import mymodule
to create a mymodule.pyc file in the same directory. A drawback is that it doesn’t only compile the module, it also executes it, which may not be what you want. (however, it does compile the entire script even if it fails to execute the script).
To do this programmatically, and without executing the code, you can use the py_compile module:
import py_compile py_compile.compile("mymodule.py")
There’s also a compileall module which can be used to compile all modules in an entire directory tree.
import compileall compileall.compile_dir("mylib", force=1)
More on byte code #
Python’s byte code is portable between platforms, but not necessarily between Python releases. The imp.get_magic() function returns a 4-byte string identifying the byte code format used by the current interpreter.
You can use the compile function and the marshal module to compile Python code into code objects, and convert such code objects to binary strings. To reverse this process, use marshal to convert from strings to code, and use exec to execute code.
Examples to be added. | http://effbot.org/zone/python-compile.htm | CC-MAIN-2015-14 | refinedweb | 432 | 60.85 |
C-programming - Assignment operator, C++ assignment operator
Assignment operatorThe assignment operator '=' is the operator used for assignment. Using the assignment operator, the value from the source (left side) is copied to the destination (right side).
The following program illustrates the usage of assignment operator
#include <iostream.h> #include <conio.h> int main( ) { char ch='J'; int i, j, k; float a, b, c; (a=(b=(c=7.5))); i=j=k=3; cout << "ch:" << ch << '\n' ; cout << "i:" << i << "j:" << j << "k" << k '\n' ; cout << "a:" << a << "b:" << b << "c" << c '\n' ; return 0; }
output
ch=J i=3 j=3 k=3 a=7.5 b=7.5 c=7.5
The topic on C-programming - Assignment operator is posted by - Sathya
Hope you have enjoyed, C-programming - Assignment operatorThanks for your time | http://www.techbluff.com/c-programming/Assignment-operator/ | CC-MAIN-2018-09 | refinedweb | 134 | 55.34 |
Decorators in Python can be a confusing topic, particularly for newer students. That's why we've made a four-part video course for you to go through, linked below.
I've also put together some written explanations of the important concepts, so if you're more of a reader, or if you just want more examples, you'll find all of the information you need below.
Higher order functions
Before learning about decorators, you must know a little bit about higher order functions. After all, all decorators are higher order functions (but not all higher order functions are decorators!).
So what is are higher order functions?
They're just functions that take other functions as arguments. Higher order functions usually call the functions passed to them, but they generally involve additional operations as well.
For example, let's say you have a function called
say_hello:
def say_hello(): user_name = input("Enter your name: ") print(f"Hello, {user_name}!")
Let's say that you want to create another function that runs this one, but also prints a welcome message before running.
You could do this:
def welcome_user(): print("Welcome to my application!") say_hello()
This is not a higher order function. It's just a function!
If you wanted to be able to print the welcome message before any arbitrary function, you should create a higher order function that takes in another function as an argument. Like so:
def welcome_user(func): print("Welcome to my application!") func()
The benefit of this is that now any function can be passed to
welcome_user, so it is very reusable. This particular example may not seem terribly useful, but we'll look at a more interesting one later on in this post!
You'd use this like so:
def welcome_user(func): print("Welcome to my application!") func() def say_hello(): user_name = input("Enter your name: ") print(f"Hello, {user_name}!") welcome_user(say_hello) # Calls both functions and prints both things.
What are decorators?
A decorator is a higher order function that doesn't directly call the argument; instead, it creates another function that does, and returns that.
That's a lot of "function" in one phrase, so let's break it down!
Here's what a decorator might look like:
def decorator(): def say_goodbye(): print("Goodbye!") return say_goodbye
The
decorator function defines an inner function,
say_goodbye, and then returns it. The inner function doesn't run until it is called. You could use it like this:
my_variable = decorator() my_variable() # Goodbye!
Although it seems that
my_variable is not a function (no
def keyword there!),
my_variable is very much a function.
Remember that the right side of an assignment is evaluated before the assignment operation takes place. As such, the return value of
decorator, the
say_goodbye function, is assigned to
my_variable.
So, is
decorator a decorator?
Not yet.
In order to be a decorator, it needs to take a function as an argument:
def decorator(func): def say_goodbye(): func() print("Goodbye!") return say_goodbye
You could then use this decorator like so:
def say_hello(): print("Hello!") greet = decorator(say_hello) greet() # Hello! and Goodbye!
Now
decorator is worthy of its name. It takes a function as an argument and returns a new function that essentially "extends" it. Instead of just calling the original function, the new
greet function does more.
Usually you'd use decorators to replace existing functions and simultaneously extend them:
def say_hello(): print("Hello!") say_hello = decorator(say_hello) say_hello() # Hello! and Goodbye!
In that last example, the
decorator function runs first since it's the right-hand side of the assignment. The original
say_hello function will be called only within the
say_goodbye function defined inside the decorator.
After line 4, the
say_hello variable in the global scope no longer refers to the original function. Instead it refers to the
say_goodbye function.
You can check this by printing out the
__name__:
def say_hello(): print("Hello!") say_hello = decorator(say_hello) print(say_hello.__name__) # say_goodbye
This is a drawback of these incomplete decorators, in that the old function's
__name__ and
__doc__ properties are replaced by those of the new function. At the end of the day, we're completely replacing the variable with a new value, so this makes sense.
However often when using decorators we want to extend the
say_hello function but let it keep its name and documentation (if it has any). This is where the built-in module
functools comes in.
If you do this, the function will keep its original name and documentation:
import functools def decorator(func): @functools.wraps(func) def say_goodbye(): func() print("Goodbye!") return say_goodbye
This now means the name is preserved:
def say_hello(): print("Hello!") say_hello = decorator(say_hello) print(say_hello.__name__) # say_hello
But, wait! What's that
@ syntax?
Well, let's learn about it!
The
@ syntax for decorators
The
@ syntax is used to apply a decorator. When we wrote
@functools.wraps(func) earlier, we applied the
wraps decorator to our
say_goodbye function.
We can use that syntax with our code too. At the moment, our code looks like this:
import functools def decorator(func): @functools.wraps(func) def say_goodbye(): func() print("Goodbye!") return say_goodbye def say_hello(): print("Hello!") say_hello = decorator(say_hello) say_hello()
But using the
@ syntax, it can be simplified to this:
import functools def decorator(func): @functools.wraps(func) def say_goodbye(): func() print("Goodbye!") return say_goodbye @decorator def say_hello(): print("Hello!") say_hello()
Note that we've gotten rid of the line that re-assigned
say_hello, and now instead we've placed
@decorator above the function definition.
This does exactly the same: it creates the function, and then passes it to the decorator, and re-assigns it.
If you run the code, you'll see that calling
say_hello() still prints out both "Hello!" and "Goodbye!".
A key benefit of this is that the function is immediately decorated, so it cannot be called accidentally before it has been decorated.
Decorating functions with parameters
At this point, our
say_hello function is being replaced with
say_goodbye. That means that if
say_hello had any parameters, those are lost when we replace the function. See this example:
import functools def decorator(func): @functools.wraps(func) def say_goodbye(): func() print("Goodbye!") return say_goodbye @decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Bob") # TypeError, say_goodbye() takes 0 positional arguments but 1 was given
Indeed if we were to do this, we would need to add the parameter to
say_goodbye as well:
def decorator(func): @functools.wraps(func) def say_goodbye(name): func(name) print("Goodbye!") return say_goodbye
But this is a bad idea, because it couples our decorator to our
say_hello function, and that means we cannot use that decorator with other functions that have different numbers of parameters.
Instead the recommended approach is to generalise our decorators by making them take any number of arguments, and pass arguments (if any) to the decorated function as well.
We'll use the standard syntax
*args, **kwargs in order to do that. If you haven't encountered them before, here's a quick guide:
def decorator(func): @functools.wraps(func) def say_goodbye(*args, **kwargs): func(*args, **kwargs) print("Goodbye!") return say_goodbye
Now this decorator can be used with any function, no matter how many parameters they have!
Writing decorators with parameters
In order to learn about decorators with parameters, let's take a look at another example. This example is also covered in the videos linked at the top of this post, so do check those out if you haven't already!
Let's say you have a function,
get_admin_password, that returns the password to the admin panel, and another function,
get_user_password, that returns the password to the user dashboard. They looks like this:
def get_admin_password(): return "1234" def get_user_password(): return "secure_password"
You can call one of these functions like so:
print(get_admin_password()) # 1234
But naturally, you'd like only administrators to be able to get the admin password, and users to be able to get the user panel password.
This is what your user looks like:
user = {"name": "Bob Smith", "access_level": "admin"}
So, let's write a decorator that secures the
get_password function so it's not exposed to any user!
We'll start by only allowing administrators to run the function:
def make_secure(func): def secure_func(*args, **kwargs): if user["access_level"] == "admin": return func(*args, **kwargs) return secure_func
A simple decorator, but uses everything we've talked about until now!
It defines an inner function, which will run the passed function,
func, only if the user's access level is "admin" at the time.
Here's the complete code:
import functools user = {"name": "Bob Smith", "access_level": "admin"} def make_secure(func): @functools.wraps(func) def secure_func(*args, **kwargs): if user["access_level"] == "admin": return func(*args, **kwargs) return secure_func @make_secure def get_admin_password(): return "1234" @make_secure def get_user_password(): return "secure_password" print(get_password("admin")) # 1234 print(get_password("user")) # None
Why does it print
None when we try to get the user panel password? Because the decorator never runs
return func(*args, **kwargs), so it just returns
None by default—as all Python functions do.
At the moment, the
make_secure decorator only allows users to run the function if their access level is
"admin". It does not allow users to run either function.
Indeed, we need two slightly different decorators, one that checks for an
"admin" level of permissions, and one that checks for a
"user" level of permissions.
But there would be a lot of duplication if we just define two decorators, so instead what we'll do is make them more dynamic by adding a parameter:
@make_secure("admin") def get_admin_password(): return "1234" @make_secure("user") def get_user_password(): return "secure_password"
If we are to do this, we need to make some changes to the decorator itself!
Something very important about this new bit of syntax is that
make_secure("admin") will run first, and then it will be applied as a decorator with the
@ syntax.
So our decorator must change into this:
def make_secure(access_level): def decorator(func): @functools.wraps(func) def secure_func(*args, **kwargs): if user["access_level"] == "admin": return func(*args, **kwargs) return secure_func return decorator
We have added one more level, because
make_secure is no longer a decorator per se. It is now a function that creates a decorator, and then that is applied to the functions with the 'at' syntax.
So when you run
@make_secure("admin"), that'll first of all execute the
make_secure function and create the
decorator function.
@decorator is then applied, but it already knows about the access level you provided.
This is all quite confusing, and it's one of the most convoluted pieces of code you'll see in Python. Very seldom do we have three-level deep nesting of functions one inside of another!
I'd recommend checking the video playlist for another explanation, with slightly different examples. The more you see this kind of structure, the more sense it makes, and the easier it is to understand!
Wrapping Up
If you're interested in improving your Python skills, and learning about many more Python topics, we'd love to have you on our Complete Python Course. It's a fully comprehensive course, over 30 hours long, covering all major Python topics! We think it's an awesome course, but if it's not for you, we also have a 30 day money back guarantee.
You can also sign up to our mailing list below, as we send discount codes to our subscribers every month!
Hope to see you there! | https://blog.tecladocode.com/decorators-in-python/ | CC-MAIN-2019-47 | refinedweb | 1,899 | 55.74 |
Subject: [boost] Boost.Sort library hierarchy and namespacing
From: Steven Ross (spreadsort_at_[hidden])
Date: 2014-12-09 06:30:52
For the Boost.Sort library, I'm planning to add these (non-detail) files:
boost/sort/sort.hpp
boost/sort/spreadsort/spreadsort.hpp
boost/sort/spreadsort/integer_sort.hpp
boost/sort/spreadsort/float_sort.hpp
boost/sort/spreadsort/string_sort.hpp
Should all of these be in the boost::sort namespace? It seems silly to
have a boost::sort::spreadsort namespace when there are only 5
publicly-visible functions in it. I actually can't imagine how of these
names will conflict with names in other boost libraries, but using a
boost::sort namespace appears conventional.
Are there any objections or concerns based on this?
Once this is done, I'd like to integrate this library into the boost build
and testing system for the next appropriate release (I test it currently
with modular boost).
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2014/12/218261.php | CC-MAIN-2021-39 | refinedweb | 174 | 51.75 |
LikeEdit
Here is an example of declaring an integer, which we've called some_number. (Note the semicolon at the end of the line; that is how your compiler separates one program statement from another.)
int some_number;:
int anumber, anothernumber, yetanothernumber;
We can also declare and assign some content to a variable at the same time.
int some_number=3;
This is called initialization.).
After declaring variables, you can assign a value to a variable later on using a statement like this:
some_number=3;
You can also assign a variable the value of another variable, like so:
anumber = anothernumber;
Or assign multiple variables the same value with one statement:
anumber = anothernumber = yetanothernumber = 3;
This is because the assignment x = y returns the value of the assignment. x = y = z is really shorthand for x = (y = z).
Naming VariablesEdit
Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit. Unlike some languages (such as Perl and some BASIC dialects), C does not use any special prefix characters on variable names.
Some examples of valid (but not very descriptive) C variable names:
foo Bar BAZ foo_bar _foo42 _ QuUx
Some examples of invalid C variable names:
2foo (must not begin with a digit) my foo (spaces not allowed in names) $foo ($ not allowed -- only letters, digits, and _) while (language keywords cannot be used as names)
As the last example suggests, certain words are reserved as keywords in the language, and these cannot be used as variable names.
In addition there are certain sets of names that, while not language keywords, are reserved for one reason or another. For example, a C compiler might use certain names "behind the scenes", and this might cause problems for a program that attempts to use them. Also, some names are reserved for possible future use in the C standard library. The rules for determining exactly what names are reserved (and in what contexts they are reserved) are too complicated to describe here[citation needed], and as a beginner you don't need to worry about them much anyway. For now, just avoid using names that begin with an underscore character.
The naming rules for C variables also apply to naming other language constructs such as function names, struct tags, and macros, all of which will be covered later.
LiteralsEdit
Anytime within a program in which you specify a value explicitly instead of referring to a variable or some other form of data, that value is referred to as a literal. In the initialization example above, 3 is a literal. Literals can either take a form defined by their type (more on that soon), or one can use hexadecimal (hex) notation to directly insert data into a variable regardless of its type.[citation needed] Hex numbers are always preceded with 0x. For now, though, you probably shouldn't be too concerned with hex.
The Four Basic Data TypesEdit
In Standard C there are four basic data types. They are
int,
char,
float, and
double.
We will briefly describe them here, then go into more detail in C Programming/Types.
The
int typeEdit
The int type stores integers in the form of "whole numbers". An integer is typically the size of one machine word, which on most modern home PCs is 32 bits (4 octets). Examples of literals are whole numbers (integers) such as 1,2,3, 10, 100... When int is 32 bits (4 octets), it can store any whole number (integer) between -2147483648 and 2147483647. A 32 bit word (number) has the possibility of representing any one number out of 4294967296 possibilities (2 to the power of 32).
If you want to declare a new int variable, use the int keyword. For example:
int numberOfStudents, i, j=5;
In this declaration we declare 3 variables, numberOfStudents, i and j, j here is assigned the literal 5.
The
char typeEdit
The
char type is capable of holding any member of the execution character set. It stores the same kind of data as an
int (i.e. integers), but typically has a size of one byte. The size of a byte is specified by the macro
CHAR_BIT which specifies the number of bits in a char (byte). In standard C it never can be less than 8 bits. A variable of type
char is most often used to store character data, hence its name. Most implementations use the ASCII character set as the execution character set, but it's best not to know or care about that unless the actual values are important.
Examples of character literals are 'a', 'b', '1', etc., as well as some special characters such as '
\0' (the null character) and '
\n' (newline, recall "Hello, World"). Note that the
char value must be enclosed within single quotations.
When we initialize a character variable, we can do it two ways. One is preferred, the other way is bad programming practice.
The first way is to write
char letter1 = 'a';
This is good programming practice in that it allows a person reading your code to understand that letter1 is being initialized with the letter 'a' to start off with.
The second way, which should not be used when you are coding letter characters, is to write
char letter2 = 97; /* in ASCII, 97 = 'a' */
This is considered by some to be extremely bad practice, if we are using it to store a character, not a small number, in that if someone reads your code, most readers are forced to look up what character corresponds with the number 97 in the encoding scheme. In the end,
letter1 and
letter2 store both the same thing – the letter 'a', but the first method is clearer, easier to debug, and much more straightforward.
One important thing to mention is that characters for numerals are represented differently from their corresponding number, i.e. '1' is not equal to 1. In short, any single entry that is enclosed within 'single quotes'.
There is one more kind of literal that needs to be explained in connection with chars: the string literal. A string is a series of characters, usually intended to be displayed. They are surrounded by double quotations (" ", not ' '). An example of a string literal is the "Hello, World!\n" in the "Hello, World" example.
The string literal is assigned to a character array, arrays are described later. Example:
const char MY_CONSTANT_PEDANTIC_ITCH[] = "learn the usage context.\n"; printf("Square brackets after a variable name means it is a pointer to a string of memory blocks the size of the type of the array element.\n");
The
float typeEdit
float is short for floating point. It stores real numbers also, but is only one machine word in size. Therefore, it is used when less precision than a double provides is required.
float literals must be suffixed with F or f, otherwise they will be interpreted as doubles. Examples are: 3.1415926f, 4.0f, 6.022e+23f.
float variables can be declared using the float keyword.
The double typeEdit
The double and float types are very similar. The float type allows you to store single-precision floating point numbers, while the double keyword allows you to store double-precision floating point numbers – real numbers, in other words, both integer and non-integer values. Its size is typically two machine words, or 8 bytes on most machines. Examples of double literals are 3.1415926535897932, 4.0, 6.022e+23 (scientific notation). If you use 4 instead of 4.0, the 4 will be interpreted as an int.
The distinction between floats and doubles was made because of the differing sizes of the two types. When C was first used, space was at a minimum and so the judicious use of a float instead of a double saved some memory. Nowadays, with memory more freely available, you do not really need to conserve memory like this – it may be better to use doubles consistently. Indeed, some C implementations use doubles instead of floats when you declare a float variable.
If you want to use a double variable, use the double keyword.
sizeofEdit
If you have any doubts as to the amount of memory actually used by any variable (and this goes for types we'll discuss later, also), you can use the sizeof operator to find out for sure. (For completeness, it is important to mention that sizeof is a unary operator, not a function.) Its syntax is:
sizeof object sizeof(type)
The two expressions above return the size of the object and type specified, in bytes. The return type is size_t (defined in the header <stddef.h>) which is an unsigned value. Here's an example usage:
size_t size; int i; size = sizeof(i);
size will be set to 4, assuming CHAR_BIT is defined as 8, and an integer is 32 bits wide. The value of sizeof's result is the number of bytes.
Note that when sizeof is applied to a char, the result is 1; that is:
sizeof(char)
always returns 1.
Data type modifiersEdit
One can alter the data storage of any data type by preceding it with certain modifiers.
long and short are modifiers that make it possible for a data type to use either more or less memory. The int keyword need not follow the short and long keywords. This is most commonly the case. A short can be used where the values fall within a lesser range than that of an int, typically -32768 to 32767. A long can be used to contain an extended range of values. It is not guaranteed that a short uses less memory than an int, nor is it guaranteed that a long takes up more memory than an int. It is only guaranteed that sizeof(short) <= sizeof(int) <= sizeof(long). Typically a short is 2 bytes, an int is 4 bytes, and a long either 4 or 8 bytes. Modern C compilers also provide long long which is typically an 8 byte integer.
In all of the types described above, one bit is used to indicate the sign (positive or negative) of a value. If you decide that a variable will never hold a negative value, you may use the unsigned modifier to use that one bit for storing other data, effectively doubling the range of values while mandating that those values be positive. The unsigned specifier also may be used without a trailing int, in which case the size defaults to that of an int. There is also a signed modifier which is the opposite, but it is not necessary, except for certain uses of char, and seldom used since all types (except char) are signed by default.
To use a modifier, just declare a variable with the data type and relevant modifiers:
unsigned short int usi; /* fully qualified -- unsigned short int */ short si; /* short int */ unsigned long uli; /* unsigned long int */
const qualifierEdit
When the const qualifier is used, the declared variable must be initialized at declaration. It is then not allowed to be changed.
While the idea of a variable that never changes may not seem useful, there are good reasons to use const. For one thing, many compilers can perform some small optimizations on data when it knows that data will never change. For example, if you need the value of π in your calculations, you can declare a const variable of pi, so a program or another function written by someone else cannot change the value of pi.
Note that a Standard conforming compiler must issue a warning if an attempt is made to change a const variable - but after doing so the compiler is free to ignore the const qualifier.
Magic numbersEdit
When you write C programs, you may be tempted to write code that will depend on certain numbers. For example, you may be writing a program for a grocery store. This complex program has thousands upon thousands of lines of code. The programmer decides to represent the cost of a can of corn, currently 99 cents, as a literal throughout the code. Now, assume the cost of a can of corn changes to 89 cents. The programmer must now go in and manually change each entry of 99 cents to 89. While this is not that big of a problem, considering the "global find-replace" function of many text editors, consider another problem: the cost of a can of green beans is also initially 99 cents. To reliably change the price, you have to look at every occurrence of the number 99.
C possesses certain functionality to avoid this. This functionality is approximately equivalent, though one method can be useful in one circumstance, over another.
Using the const keywordEdit
The const keyword helps eradicate magic numbers. By declaring a variable const corn at the beginning of a block, a programmer can simply change that const and not have to worry about setting the value elsewhere.
There is also another method for avoiding magic numbers. It is much more flexible than const, and also much more problematic in many ways. It also involves the preprocessor, as opposed to the compiler. Behold...
#defineEdit
When you write programs, you can create what is known as a macro, so when the computer is reading your code, it will replace all instances of a word with the specified expression.
Here's an example. If you write
#define PRICE_OF_CORN 0.99
when you want to, for example, print the price of corn, you use the word
PRICE_OF_CORN instead of the number 0.99 – the preprocessor will replace all instances of
PRICE_OF_CORN with 0.99, which the compiler will interpret as the literal
double 0.99. The preprocessor performs substitution, that is,
PRICE_OF_CORN is replaced by 0.99 so this means there is no need for a semicolon.
It is important to note that
#define has basically the same functionality as the "find-and-replace" function in a lot of text editors/word processors.
For some purposes,
#define can be harmfully used, and it is usually preferable to use
const if
#define is unnecessary. It is possible, for instance, to
#define, say, a macro
DOG as the number 3, but if you try to print the macro, thinking that
DOG represents a string that you can show on the screen, the program will have an error.
#define also has no regard for type. It disregards the structure of your program, replacing the text everywhere (in effect, disregarding scope), which could be advantageous in some circumstances, but can be the source of problematic bugs.
You will see further instances of the
#define directive later in the text. It is good convention to write
#defined words in all capitals, so a programmer will know that this is not a variable that you have declared but a
#defined macro. It is not necessary to end a preprocessor directive such as
#define with a semicolon; in fact, some compilers may warn you about unnecessary tokens in your code if you do.
ScopeEdit
In the Basic Concepts section, the concept of scope was introduced. It is important to revisit the distinction between local types and global types, and how to declare variables of each. To declare a local variable, you place the declaration at the beginning (i.e. before any non-declarative statements) of the block to which the variable is intended to be local. To declare a global variable, declare the variable outside of any block. If a variable is global, it can be read, and written, from anywhere in your program.
Global variables are not considered good programming practice, and should be avoided whenever possible. They inhibit code readability, create naming conflicts, waste memory, and can create difficult-to-trace bugs. Excessive usage of globals is usually a sign of laziness and/or poor design. However, if there is a situation where local variables may create more obtuse and unreadable code, there's no shame in using globals.
Other ModifiersEdit
Included here, for completeness, are more of the modifiers that standard C provides. For the beginning programmer, static and extern may be useful. volatile is more of interest to advanced programmers. register and auto are largely deprecated and are generally not of interest to either beginning or advanced programmers.
staticEdit
static is sometimes a useful keyword. It is a common misbelief that the only purpose is to make a variable stay in memory.
When you declare a function or global variable as static it will become internal. You cannot access the function or variable through the extern (see below) keyword from other files in your project.
When you declare a local variable as static, it is created just like any other variable. However, when the variable goes out of scope (i.e. the block it was local to is finished) the variable stays in memory, retaining its value. The variable stays in memory until the program ends. While this behaviour resembles that of global variables, static variables still obey scope rules and therefore cannot be accessed outside of their scope.
Variables declared static are initialized to zero (or for pointers, NULL) by default. They can be initialized explicitly on declaration to any constant value. The initialization is made just once, at compile time.
You can use static in (at least) two different ways. Consider this code, and imagine it is in a file called jfile.c:
#include <stdio.h> static int j = 0; void up(void) { /* k is set to 0 when the program starts. The line is then "ignored" * for the rest of the program (i.e. k is not set to 0 every time up() * is called) */ static int k = 0; j++; k++; printf("up() called. k= %2d, j= %2d\n", k , j); } void down(void) { static int k = 0; j--; k--; printf("down() called. k= %2d, j= %2d\n", k , j); } int main(void) { int i; /* call the up function 3 times, then the down function 2 times */ for (i= 0; i < 3; i++) up(); for (i= 0; i < 2; i++) down(); return 0; }
The j var is accessible by both up and down and retains its value. The k vars also retain their value, but they are two different variables, one in each of their scopes. Static vars are a good way to implement encapsulation, a term from the object-oriented way of thinking that effectively means not allowing changes to be made to a variable except through function calls.
Running the program above will produce the following output:
up() called. k= 1, j= 1 up() called. k= 2, j= 2 up() called. k= 3, j= 3 down() called. k= -1, j= 2 down() called. k= -2, j= 1
Features of
static variables :
1. Keyword used - static 2. Storage - Memory 3. Default value - Zero 4. Scope - Local to the block in which it is declared 5. Lifetime - Value persists between different function calls 6. Keyword optionality - Mandatory to use the keyword
externEdit
extern is used when a file needs to access a variable in another file that it may not have #included directly. Therefore, extern does not actually carve out space for a new variable, it just provides the compiler with sufficient information to access the remote variable.
Features of
external variable :
1. Keyword used - extern 2. Storage - Memory 3. Default value - Zero 4. Scope - Global (all over the program) 5. Lifetime - Value persists till the program's execution comes to an end 6. Keyword optionality - Optional if declared outside all the functions
volatileEdit
volatile is a special type ofEdit.
Features of
automatic variables :
1. Keyword used - auto 2. Storage - Memory 3. Default value - Garbage value (random value) 4. Scope - Local to the block in which it is defined 5. Lifetime - Value persists while the control remains within the block 6. Keyword optionality - Optional
registerEdit. Microsoft Visual C++ is an example of an implementation that completely ignores the register keyword.
Features of
register variables :
1. Keyword used - register 2. Storage - CPU registers (values can be retrieved faster than from memory) 3. Default value - Garbage value 4. Scope - Local to the block in which it is defined 5. Lifetime - Value persists while the control remains within the block 6. Keyword optionality - Mandatory to use the keyword | http://en.m.wikibooks.org/wiki/C_Programming/Variables | CC-MAIN-2014-52 | refinedweb | 3,381 | 63.59 |
C
Translate QML Type
Provides a way to move an item without changing its x or y properties. More...
Properties
Detailed Description
The Translate type provides independent control over position in addition to the Item's x and y properties.
The following example moves the Y axis of the Image items while still allowing the Row to lay the items out as if they had not been transformed:
import QtQuick Row { Image { source: "qrc:///bluerect.png" transform: Translate { y: 20 } } Image { source: "qrc:///redrect.png" transform: Translate { y: -20 } } }
Property Documentation
The translation along the X axis.
The default value is 0.0.
The translation along the Y axis.
The default value is 0.0.
Available under certain Qt licenses.
Find out more. | https://doc.qt.io/archives/QtForMCUs-1.1/qml-qtquick-translate.html | CC-MAIN-2021-21 | refinedweb | 123 | 59.7 |
kdeui
KListViewSearchLine Class ReferenceThis class makes it easy to add a search line for filtering the items in a listview based on a simple text search. More...
#include <klistviewsearchline.h>
Detailed DescriptionThis class makes it easy to add a search line for filtering the items in a listview based on a simple text search.
No changes to the application other than instantiating this class with an appropriate KListView should be needed.
If you want the clear button and the search label, you should take a look at the KListViewSearchLineWidget
- Note:
- { When iterating over items in the KListView, make sure that the iterator only includes visible items (for example, by adding QListViewItemIterator::Visible to the iterator flags). Otherwise, actions (such as deletion) may be taken on items that have been hidden by the search function. }
- Since:
- 3.3
Definition at line 47 of file klistviewsearchline.h.
Constructor & Destructor Documentation
Constructs a KListViewSearchLine with listView being the KListView to be filtered.
If listView is null then the widget will be disabled until a listview is set with setListView().
Definition at line 59 of file klistviewsearchline.cpp.
Constructs a KListViewSearchLine without any KListView to filter.
The KListView object has to be set later with setListView().
Definition at line 80 of file klistviewsearchline.cpp.
Destroys the KListViewSearchLine.
Definition at line 93 of file klist 291 of file klistviewsearchline.cpp.
Returns true if the search is case sensitive.
This defaults to false.
- See also:
- setCaseSensitive()
Definition at line 98 of file klistviewsearchline.cpp.
Re-implemented for internal reasons.
API not affected.
See QLineEdit::mousePressEvent().
Reimplemented from KLineEdit.
Definition at line 234 of file klistviewsearchline.cpp.
Returns true if item matches the search s.
This will be evaluated based on the value of caseSensitive(). This can be overridden in subclasses to implement more complicated matching schemes.
Definition at line 205 of file klistviewsearchline.cpp.
If this is true (the default) then the parents of matched items will also be shown.
- See also:
- setKeepParentsVisible()
Definition at line 108 of file klistviewsearchline.cpp.
Returns the listview that is currently filtered by the search.
- See also:
- setListView()
Definition at line 113 of file klistviewsearchline.cpp.
When keys are pressed a new search string is created and a timer is activated.
The most recent search is activated when this timer runs out if another key has not yet been pressed.
This method makes
- Parameters:
-
- See also:
- activateSearch()
Definition at line 284 of file klistviewsearchline.cpp.
Returns the current list of columns that will be searched.
If the returned list is empty all visible columns will be searched.
- See also:
- setSearchColumns
Definition at line 103 of file klistviewsearchline.cpp.
Make the search case sensitive or case insensitive.
- See also:
- caseSenstive()
Definition at line 163 of file klistviewsearchline.c.
- See also:
- keepParentsVisible
Definition at line 168 of file klistviewsearchline.cpp.
Sets the KListView that is filtered by this search line.
If lv is null then the widget will be disabled.
- See also:
- listView()
Definition at line 178 of file klistviewsearchline.cpp.
Sets the list of columns to be searched.
The default is to search all, visible columns which can be restored by passing columns as an empty list.
- See also:
- searchColumns
Definition at line 173 of file klistviewsearchline.cpp.
Updates search to only make visible the items that match s.
If s is null then the line edit's text will be used.
Definition at line 122 of file klistviewsearchline.cpp.
The documentation for this class was generated from the following files: | http://api.kde.org/3.5-api/kdelibs-apidocs/kdeui/html/classKListViewSearchLine.html | crawl-002 | refinedweb | 580 | 68.16 |
# The best is the enemy of the good

This article is the story how we once decided to improve our internal SelfTester tool that we apply to test the quality of the PVS-Studio analyzer. The improvement was simple and seemed to be useful, but got us into some troubles. Later it turned out that we'd better gave up the idea.
SelfTester
----------
We develop and promote the PVS-Studio static code analyzer for C, C++, C# and Java. To test the quality of our analyzer we use internal tools, generically called SelfTester. We created a separate SelfTester version for each supported language. It is due to specifics of testing, and it's just more convenient. Thus, at the moment we have three internal SelfTester tools in our company for C\C++, C# and Java, respectively. Further, I'll tell about Windows version of SelfTester for C\C++ Visual Studio projects, calling it simply SelfTester. This tester was the first in line of similar internal tools, it's the most advanced and complex of all.
How does SelfTester work? The idea is simple: take a pool of test projects (we're using real open source projects) and analyze them using PVS-Studio. As a result, an analyzer log is generated for each project. This log is compared with the *reference* log of the same project. When comparing logs, SelfTester creates a *summary* of logs comparing in a convenient developer-friendly way.
After studying the summary, a developer concludes about changes in the analyzer behavior according to the number and type of warnings, working speed, internal analyzer errors, etc. All this information is very important: it allows you to be aware of how the analyzer copes with its work.
Based on the summary of logs comparison, a developer introduces changes in the analyzer core (for example, when creating a new diagnostic rule) and immediately controls the result of his edits. If a developer has no more issues to a regular log comparing, he makes a *current* warnings log *reference* for a project. Otherwise, the work continues.
So, the task of SelfTester is to work with a pool of test projects (by the way, there are more than 120 of them for C/C++). Projects for the pool are selected in the form of Visual Studio solutions. It is done so in order to additionally check the analyzer's work on various Visual Studio versions, which support the analyzer (at this point from Visual Studio 2010 to Visual Studio 2019).
*Note:* further I'll separate the concepts *solution* and *project*, considering a project as a part of a solution.
SelfTester's interface looks as follows:

On the left there is a list of solutions, on the right — results of a check for each Visual Studio version.
Grey labels «Not supported» indicate that a solution doesn't support a chosen Visual Studio version or it wasn't converted for this version. Some solutions have a configuration in a pool, that indicates a specific Visual Studio version for a check. If a version isn't specified, a solution will be updated for all subsequent Visual Studio versions. An example of such a solution is on the screenshot — «smart\_ptr\_check.sln» (a check is made for all Visual Studio versions).
A green label «OK» indicates that a regular check hasn't detected differences with the reference log. A red label «Diff» indicates about differences. These labels have to be paid special attention. After clicking twice on the needed label, the chosen solution will be opened in a related Visual Studio version. A window with a log of warnings will also be open there. The control buttons at the bottom allow you to rerun the analysis of the selected or all solutions, make the chosen log (or all at once) reference, etc.
SelfTester's results are always duplicated in the html report (diffs report)
In addition to GUI, SelfTester also has automated modes for night build runs. However, the usual usage pattern repeated developer runs by a developer during the workday. Therefore, one of the most important SelfTester's characteristics is the speed of working.
Why speed matters:
1. Each step's performance is quite crucial in terms of night test runs. Obviously, the faster the tests pass, the better. At the moment, the average performance time of SelfTester exceeds 2 hours;
2. When running SelfTester during the day, a developer has to wait less for the result, which increases his workforce productivity.
It was performance speeding up that became the reason for refinements this time.
Multi-threading in SelfTester
-----------------------------
SelfTester was initially created as a multithreaded application with the ability to simultaneously test several solutions. The only limitation was that you couldn't simultaneously check the same solution for different Visual Studio versions, because many solutions need to be updated to certain versions of Visual Studio before testing. During the course of it, changes are introduced directly in files of the *.vcxproj* projects, which leads to errors during parallel running.
In order to make the work more efficient, SelfTester uses an intelligent task scheduler to set a strictly limited value of parallel threads and maintain it.
The planner is used on two levels. The first one is the level of *solutions*, it's used to start testing the *.sln* solution using the *PVS-Studio\_Cmd.exe* utility. The same scheduler, but with another setting of *parallelism degree*, is used inside *PVS-Studio\_Cmd.exe* (at the source *files* testing level).
The degree of parallelism is a parameter that indicates how many parallel threads have to be run simultaneously. *Four* and *eight* default values were chosen for the parallelism degree of the solutions and files level, respectively. Thus, the number of parallel threads in this implementation has to be 32 (4 simultaneously tested solutions and 8 files). This setting appears optimal to us for the analyzer work on an eight-core processor.
A developer can set other values of the parallelism degree himself according to his computer performance or current tasks. If a developer doesn't specify this parameter, the number of logical system processors will be chosen by default.
*Note:* let's further assume that we deal with the default degree of parallelism.
The scheduler *LimitedConcurrencyLevelTaskScheduler* is inherited from *System.Threading.Tasks.TaskScheduler* and refined to provide the maximum parallelism level when working over *ThreadPool*. Inheritance hierarchy:
```
LimitedConcurrencyLevelTaskScheduler : PausableTaskScheduler
{ .... }
PausableTaskScheduler: TaskScheduler
{ .... }
```
*PausableTaskScheduler* allows you to pause task performance, and in addition to this, *LimitedConcurrencyLevelTaskScheduler* provides intellectual control of the tasks queue and scheduling their performance, taking into account the parallelism degree, the scope of the scheduled tasks and other factors. A scheduler is used when running *LimitedConcurrencyLevelTaskScheduler* tasks.
Reasons for Refinements
-----------------------
The process described above has a drawback: it is not optimal when dealing with solutions of different sizes. And the size of solutions in the test pool is *very* diverse: from 8KB to 4GB — the size of a folder with a solution and from 1 up to several thousands of source code files in each one.
The scheduler puts solutions on the queue simply one after another, without any intelligent component. Let me remind you that by default not more than four solutions can be tested simultaneously. If four large solutions are currently tested (the number of files in each is more than eight), it's assumed that we work effectively because we use as many threads as possible (32).
But let's imagine a rather frequent situation, when several small solutions are tested. For example, one solution is large and contains 50 files (maximum number of threads will be used), while other three solutions contain three, four, five files each. In this case, we'll only use 20 threads (8 + 3 + 4 + 5). We get underutilization of processor's time and reduced overall performance.
*Note*:in fact, the bottleneck is usually the disk subsystem, not the processor.
Improvements
------------
The improvement that is self-evident in this case is ranking of tested solutions list. We need to get optimal usage of the set number of simultaneously performed threads (32), by passing to test projects with the correct number of files.
Let's consider again our example of testing four solutions with the following number of files in each: 50, 3, 4 and 5. The task that checks a solution of *three* files is likely to work out the fastest. It would be best to add a solution with eight or more files instead of it (in order to use maximum from the available threads for this solution). This way, we'll utilize 25 threads at once (8 + **8** + 4 + 5). Not bad. However, seven threads are still uninvolved. And here comes the idea of another refinement, which is to remove the four threads limit on testing solutions. Because we now can add not one, but several solutions, utilizing 32 threads. Let's imagine that we have two more solutions of three and four files each. Adding these tasks will completely close the «gap» of unused threads, and there will be32 (8 + 8 + 4 + 5 + **3** + **4**) of them.
Hopefully the idea is clear. In fact, the implementation of these improvements also didn't require much effort. Everything was done in one day.
We needed to rework the task class: inheriting from *System.Threading.Tasks.Task* and assignment of the field «weight». We use a simple algorithm to set weight to a solution: if the number of files is less than eight, the weight is equal to this number (for example, 5). If the number is greater or equal to eight, the weight will be equal to eight.
We also had to elaborate the scheduler: teach it to choose solutions with needed weight in order to reach maximum value of 32 threads. We also had to allow more than four threads for simultaneous solutions testing.
Finally, we needed a preliminary step to analyze all solutions in the pool (evaluation using MSBuild API) to evaluate and set weight of solutions (getting numbers of files with source code).
Result
------
I think after such a long introduction you've already guessed that nothing came of it.

It's good though that the improvements were simple and fast.
Here comes that part of the article, where I'm going to tell you about what «got us into many troubles» and all things related to it.
Side Effects
------------
So, a negative result is also a result. It turned out that the number of large solutions in the pool *far exceeds* the number of small ones (less than eight files). In this case, these improvements don't have a very noticeable effect, as they are almost invisible: testing small projects takes teeny-tiny amount of time comparing to time, needed for large projects.
However, we decided to leave the new refinement as «non-disturbing» and potentially useful. In addition, the pool of test solutions is constantly replenished, so in the future, perhaps, the situation will change.
And then…

One of the developers complained about the SelfTester's crash. Well, life happens. To prevent this error from being lost, we created an internal incident (ticket) with the name «Exception when working with SelfTester». The error occurred while evaluating the project. Although a large number of windows with errors indicated the problem back in the error handler. But this was quickly eliminated, and over the next week nothing crashed. Suddenly, another user complained about SelfTester. Again, the error of a project evaluation:

This time the stack contained much useful information — the error was in the xml format. It's likely, that when handling the file of the *Proto\_IRC.vcxproj* project (its xml representation) something happened to the file itself, that's why *XmlTextReader* couldn't handle it.
Having two errors in a fairly short period of time made us take a closer look at the problem. In addition, as I said above, SelfTester is very actively used by developers.
To begin with, we analyzed the last crash. Sad to say, we found nothing suspicious. Just in case we asked developers (SelfTester users) to keep an eye out and report about possible errors.
Important point: the erroneous code was reused in SelfTester. It was originally used to evaluate projects in the analyzer itself (*PVS-Studio\_Cmd.exe*). That's why attention to the problem has grown. However, there were no such crashes in the analyzer.
Meanwhile, the ticket about problems with SelfTester was supplemented with new errors:

*XmlException* again. Obviously, there are competing threads somewhere that work with reading and writing project files. SelfTester works with projects in the following cases:
1. Projects evaluation in the course of preliminary calculation of solutions' weights: a new step that initially aroused suspicion;
2. Updating projects to the needed Visual Studio versions: is performed right before testing (projects don't interfere) and it mustn't affect the working process.
3. Projects evaluation during testing: a well-established thread-safe mechanism, reused from *PVS-Studio\_Cmd.exe*;
4. Restoring project files (replacing modified *.vcxproj* files with initial reference files) when exiting from SelfTester, because project files can update to needed Visual Studio versions during the work. It's a final step, which has no impact on other mechanisms.
Suspicion fell on the new code added for optimization (weight calculation). But its code investigation showed that if a user runs the analysis right after the start of SelfTester, the tester always correctly waits till the end of the pre-evaluation. This place looked safe.
Again, we were unable to identify the source of the problem.
Pain
----
All next month SelfTester continued to crash ever and again. The ticket kept filling with data, but it wasn't clear what to do with this data. Most crashes were with the same *XmlException.* Occasionally there was something else, but on the same reused code from *PVS-Studio\_Cmd.exe*.

Traditionally, internal tools aren't imposed very high requirements, so we kept puzzling out SelfTester's errors on a residual principle. From time to time, different people got involved (during the whole incident six people worked on the problem, including two interns). However, we had to be distracted by this task.
*Our first mistake.* In fact, at this point we could've solved this problem once and for all. How? It was clear that the error was caused by a new optimization. After all, before it everything worked well, and the reused code clearly cannot be so bad. In addition, this optimization hadn't brought any benefit. So what had to be done? *Remove this optimization.* As you probably understand, it wasn't done. We continued to work on the problem, which we created ourselves. We continued searching for the answer: «HOW???» How does it crash? It seemed to be written correctly.
*Our second mistake.* *Other people got involved* in solving the problem*.* It's a very, very big mistake. Not only didn't it solve the problem but also required additional wasted resources. Yes, new people brought new ideas, but it took a lot of working time to implement (for nothing) these ideas. At some point, we had our interns writing test programs emulating evaluation of one and the same project in different threads with parallel modification of a project in another project. It didn't help. We only found out that MSBuild API was thread-safe inside, which we've already known. We also added mini dump auto saving when the *XmlException* exception occurs. We had someone who was debugging all this. Poor guy! There were discussions, we did other needless things.
*Finally, out third mistake.* Do you know how much time has passed from the moment the SelfTester problem occurred to the point when it was solved? Well, you can count yourself. The ticket was created on 17/09/2018 and closed on 20/02/2019. There were more than 40 comments! Guys, that's a lot of time! We *allowed ourselves* to be busy for five months with THIS. At the same time we were busy supporting Visual Studio 2019, adding the Java language support, introducing MISRA C/C++ standard, improving the C# analyzer, actively participating in conferences, writing a bunch of articles, etc. All these activities received less time of developers because of a stupid error in SelfTester.
Folks, learn from our mistakes and never do like this. We won't either.
That's it, I'm done.

Okay, it was a joke, I'll tell you what was the problem with SelfTester :)
Bingo!
------
Fortunately, there was a person among us with clear-eyed view (my colleague Sergey Vasiliev), who just looked at the problem from a very different angle (and also — he got a bit lucky). What if it's ok inside the SelfTester, but something from the outside crashes the projects? Usually we had nothing launched with SelfTester, in some cases we strictly controlled the execution environment. In this case, this very «something» could be SelfTester itself, but a different instance.
When exiting SelfTester, the thread that restores project files from references, continues to work for a while. At this point, the tester might be launched again. Protection against the simultaneous runs of several SelfTester instances was added *later* and now looks as follows:

But at that point we didn't have it.
Nuts, but true — during almost six months of torment no one paid attention to it. Restoring projects from references is a fairly fast background procedure, but unfortunately not fast enough not to interfere with the re-launch of SelfTester. And what happens when we launch it? That's right, calculating the weights of solutions. One process rewrites *.vcxproj* files while another tries to read them. Say hi to *XmlException*.
Sergey found out all this when he added the ability to switch to a different set of reference logs to the tester. It became necessary after adding a set of MISRA rules in the analyzer. You can switch directly in the interface, while the user sees this window:

After that, *SelfTester* restarts. And earlier, apparently, users somehow emulated the problem themselves, running the tester again.
Blamestorming and Conclusions
-----------------------------
Of course, we removed (that is, disabled) the optimization created earlier. In addition, it was much easier than doing some kind of synchronization between re-starts of the tester by itself. And everything started to work perfectly, as before. And as an additional measure, we added the above protection against the simultaneous launch of the tester.
I've already written above about our main mistakes when searching for the problem, so enough of self-flagellation. We're human beings, so we might be wrong. It is important to learn from your own mistakes and draw conclusions. The conclusions from this case are quite simple:
* We should monitor and estimate the task complexity;
* Sometimes we need to stop at some point;
* Try to look at the problem more broadly. Over time one can get tunnel vision of the case whereas it requires fresh perspective.
* Don't be afraid to delete old or unnecessary code.
That's it, this time I'm definitely done. Thank you for reading up to the end. I wish you bugless code! | https://habr.com/ru/post/466739/ | null | null | 3,341 | 57.06 |
[FIX][CSS3] Need to support '::' for pseudo-elements in the CSS parser
RESOLVED FIXED in mozilla1.5alpha
Status
()
▸
CSS Parsing and Computation
People
(Reporter: Marc Attinasi, Assigned: bz)
Tracking
({css3})
Firefox Tracking Flags
(Not tracked)
Attachments
(1 attachment, 5 obsolete attachments)
CSS3 proposes the use of :: for pseudo-elements instead of the : that was used for pseudo-elements and pseudo-classes in CSS2. We should put in support for :: in pseudo-elements now in preparation for CSS3. NOTE: we must support both : and :: for pseudo-element selectors, but only : for pseudo-classes. Daniel, feel free to take a stab at this if you arte bored ;)
Status: NEW → ASSIGNED
Note that we should only support ':' for four pseudo-elements: :before :after :first-line :first-letter All other pseudo-elements should only work with "::". That is, once CSS3 Selectors has been released. That should happen by 0.9, so that should not be a problem. However if CSS3 Selectors fails to go through last call, then we should not check a fix for this in until it has.
Keywords: css3, mozilla1.0
Even if the WD does not go to last call, it will be public and the test suite attached to the document will be public too... and people will run the last mozilla through them. Anyway, the code parsing pseudos probably needs a little cleaning : if ':ident' is not a pseudo-class, it is considered to be a pseudo-element (that pseudo can be unrecognized, of course). A pseudo-elem is added to the selector context using nsCSSSelector::AddPseudoClass... It is probably the occasion to separate a little bit the two notions. I am currently trying to work on it but no re-assignment please...
In pre-release builds we can do what we like. However, in a final, released version it is imperative that we do not implement features that have WD status in the same namespace as the final CR or REC. This is the whole point of the -vendor-XXX stuff for identifiers. In addition, there is the slight problem that convincing the Powers That Be that we should change this kind of bug back to the REC version at the last minute is an almost impossible task. Therefore, if we _do_ implement this, I would plead that it be either controlled by an #ifdef, or a pref, or an environment variable, and that the default be off. That way it is easy [for me] to test, it is easy to toggle on and off, and we can make the required changes much closer to the End Game. Now bearing all that in mind, I would love to see an experimental implementation of this CSS3 stuff, so go right ahead! :-D
Created attachment 20954 [details] [diff] [review] adds parsing of double-colons for pseudo-elements and refuses single-colon for pure css3 pseudo-elements
The patch above is intended for future use, when the CSS 3 Selectors Module will go to CR.
Created attachment 20955 [details] [diff] [review] one file was missing, one debug line removed...
This change looks good to me. Since the likelihood of this changing between now and the time css3 is published is nil, I don't even mind that it is no #ifdef'd out. The only result is that selectors written using the double-colon for pseudo-elements will be parsed as valid now, whereas technically they should not because CSS2 does not allow it. Because the CSS3 selector module is really close to being made public, I think we are safe here.
Call me a maniac but here is how I think these changes should be done... 1) The NS_CSS_GETINFO flags should be part of the declaration of the CSS_ATOMs. It means that nsCSSAtomList.h should declare at the same time the atom name and the NS_CSS_GETINFO flags, similarly to what we have in nsCSSPropList.h for the properties and the NS_STYLE_HINT. 2) Rewrite GetPseudoInfoMask() so that it takes into account these new declarations and so that we don't have to modify it each time we want to add a CSS3 pseudo. 3) Change the test in IsSinglePseudoClass from: if (!bFoundDoubleColon && (0 == (NS_CSS_GETINFO_CSS1 | NS_CSS_GETINFO_CSS2) & GetPseudoInfoMask(pseudo))) { to: if (!bFoundDoubleColon && (NS_CSS_GETINFO_CSS3 & GetPseudoInfoMask(pseudo))) {
Also, but I'm not sure it will ever be used because it doesn't seem to correspond to any standard, CSSParserImpl::GetInfoMask() should be updated to return NS_CSS_GETINFO_CSS1/CSS2/CSS3. I don't know what CSSP and CSS_FROSTING are for...
Agreed; but please note this is strictly independant of the original code proposal and the proposed css3 enhancement. Your last comment is more related to code cleanup...
css3...
Summary: Need to support '::' for pseudo-elements in the CSS parser → [CSS3] Need to support '::' for pseudo-elements in the CSS parser
Adding dependency to 52381 because for nsCSSSelector::ToString output of new css3 pseudo-elements...
Reassigning to Daniel since he has made the fix.
Assignee: attinasi → glazman
Status: ASSIGNED → NEW
oops; i thought I already had accepted this bug.... note : recent modifications will imply some changes in the attached patch.
Status: NEW → ASSIGNED
setting to moz1.0 for now
Target Milestone: --- → mozilla1.0
Created attachment 59513 [details] [diff] [review] patch v3 new patch for this bug. 1. Adds support for css3 "::" notation for pseudo-elements 2. Gathers all atoms for pseudos in nsCSSAtomList.h 3. Adds -moz- to proprietary pseudos 4. Comment out unused pseudo atoms 5. uses cpp magic in IsPseudoClass() Pierre, Marc and David, can you review please ?
Comment on attachment 59513 [details] [diff] [review] patch v3 Is the patch missing changes to the htmlAtoms table? It looks like that table has been changed but I don't see the diffs for that. Seems minor, so sr=attinasi anyway (assuming you either forgot the diff or I am mistaken)
Attachment #59513 - Flags: superreview+
Marc: right, just a bug in my cvs diff line ; there is nothing to worry about, I just move some atom definitions from nsHTMLAtoms to nsCSSAtoms.
Grumble *%$¤3!&£### !!! I have just discovered that there are definitions of pseudos in other header files in content/shared ; why the hell had we at least 3 places of atom definitions for css pseudos (or proprietary extensions) ? That kills me. Patch v3 is then obsolete.
Comment on attachment 59513 [details] [diff] [review] patch v3 missing other definitions of atoms ! That seems an endless story, pseudos all over the place.
Moving from Moz1.0 to future-P1. All bugs scheduled for Moz1.0 need to nominated using the nsbeta1 keyword.
Priority: P3 → P1
Target Milestone: mozilla1.0 → Future
cc'ing myself
Daniel, have you given up? :)
Whiteboard: [Hixie-P3]
I started some other pseudo cleanup work in bug 147887 (see also the dependencies of that bug). I wonder if the approach there would be better. I was never really sure if I liked it myself, though (which is one of the reasons I never finished the patch).
Created attachment 126221 [details] [diff] [review] Patch against current trunk This basically works and fixes this bug and bug 145968. Three things that sorta bother me about it: 1) I didn't attempt to mess with the fact that we parse all pseudos in ParsePseudoSelector and then pull out the pseudo-elements. It seems cumbersome, but it works.... 2) We have tons of selectors in ua.css where people just randomly made up -moz-* pseudos. I had to keep parsing them all as pseudo-elements as we used to; we are still allowing single-':' forms of these for backwards compat. 3) I don't really like hardcoding the list of CSS2 pseudo-elements in two different places. Thoughts?
Attachment #126221 - Flags: superreview?(dbaron)
Attachment #126221 - Flags: review?(glazman)
Daniel, feel free to assign the bug to me if you are OK with the general approach....
> We have tons of selectors in ua.css where people just randomly made up > -moz-* pseudos. I had to keep parsing them all as pseudo-elements as we > used to; we are still allowing single-':' forms of these for backwards > compat. The original reason for the split was that when Peter Linss was writing the pseudo parsing code, he wanted to be able to very easily decide whether something was a pseudo-class or a pseudo-element. Now that we can do that, we should -- if something starts with only one colon, it's a pseudo-class, otherwise, it's a pseudo-element. (With the four CSS2 exceptions.) Is there a good reason to continue supporting the old :-moz- pseudo-elements?
Comment on attachment 126221 [details] [diff] [review] Patch against current trunk > static PRBool IsTreePseudoElement(nsIAtom* aPseudo) > { > const char* str; > aPseudo->GetUTF8String(&str); > static const char moz_tree[] = ":-moz-tree-"; > return nsCRT::strncmp(str, moz_tree, PRInt32(sizeof(moz_tree)-1)) == 0; > } > #endif > >+static PRBool IsMozPseudoElement(nsIAtom* aPseudo) >+{ >+ const char* str; >+ aPseudo->GetUTF8String(&str); >+ static const char moz_pseudo[] = ":-moz-"; >+ return nsCRT::strncmp(str, moz_pseudo, PRInt32(sizeof(moz_pseudo)-1)) == 0; >+} Call me a maniac, but you could probably factorize those two statics into one only DoesPseudoNameStartWith() ? > void CSSParserImpl::ParsePseudoSelector(PRInt32& aDataMask, > nsCSSSelector& aSelector, > PRInt32& aParsingStatus, > PRInt32& aErrorCode, > PRBool aIsNegated) > { >- nsAutoString buffer; > if (! GetToken(aErrorCode, PR_FALSE)) { // premature eof > REPORT_UNEXPECTED_EOF(NS_LITERAL_STRING("name of pseudo-selector")); > aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; > return; > } In error reporting, could you please write "pseudo-class or pseudo-element" instead of "pseudo-selector" ? The latter does not exist in Selectors terminology. Thanks. >+ PRBool isTree = eCSSToken_Function == mToken.mType && >+ IsTreePseudoElement(pseudo); Could you just add parenthesis around the a == b ? Only for readability. Thanks. > #endif >- // the negation pseudo-class is a function >- (nsCSSPseudoClasses::notPseudo == pseudo) || >- // as is the lang pseudo-class >- (nsCSSPseudoClasses::lang == pseudo))) { >- REPORT_UNEXPECTED_TOKEN(NS_LITERAL_STRING("Expected identifier for pseudo-class selector not found")); >- UngetToken(); >- aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; >- return; >- } >+ PRBool isMozPseudo = IsMozPseudoElement(pseudo); >+ >+ // If it's a function token, it better be on our "ok" list >+ if (eCSSToken_Function == mToken.mType && >+#ifdef MOZ_XUL >+ !isTree && >+#endif >+ nsCSSPseudoClasses::notPseudo != pseudo && >+ nsCSSPseudoClasses::lang != pseudo) { // There are no other function pseudos >+ REPORT_UNEXPECTED_TOKEN(NS_LITERAL_STRING("Expected identifier for function pseudo-selector but found")); >+ UngetToken(); >+ aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; >+ return; >+ } Am I right if I say this is going to reject the following rule copied from CaScadeS ? treechildren:-moz-tree-cell-text(external) { font-style: italic ! important; } >+ // If it starts with "::", it better be a pseudo-element >+ if (parsingPseudoElement && >+ !isMozPseudo && >+ !nsCSSPseudoElements::IsPseudoElement(pseudo)) { >+ REPORT_UNEXPECTED_TOKEN(NS_LITERAL_STRING("Expected pseudo-element but found")); >+ UngetToken(); >+ aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; >+ return; > } I recommend an extra comment line saying that proprietary -moz-* pseudo-elements never start with a double colon. > if (nsCSSPseudoClasses::notPseudo == pseudo) { > if (aIsNegated) { // :not() can't be itself negated > REPORT_UNEXPECTED_TOKEN(NS_LITERAL_STRING("Negation pseudo-class can't be negated")); >+ UngetToken(); > aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; > return; > } > // CSS 3 Negation pseudo-class takes one simple selector as argument > ParseNegatedSimpleSelector(aDataMask, aSelector, aParsingStatus, aErrorCode); > if (SELECTOR_PARSING_ENDED_OK != aParsingStatus) { > return; > } >@@ -2180,29 +2216,47 @@ void CSSParserImpl::ParsePseudoSelector( > // XXX are there more pseudo classes which accept arguments ? > else { > aSelector.AddPseudoClass(pseudo); > } > if (SELECTOR_PARSING_ENDED_OK != aParsingStatus) { > return; > } > } >- else { >+ else if (nsCSSPseudoElements::IsPseudoElement(pseudo) || You are already checking nsCSSPseudoElements::IsPseudoElement(pseudo) above and could probably store its value in a boolean instead of calling twice such a lookup method. >+ isMozPseudo) { >+ // Pseudo-element. Make some more sanity checks. >+ > if (aIsNegated) { // pseudo-elements can't be negated > REPORT_UNEXPECTED_TOKEN(NS_LITERAL_STRING("Pseudo-elements can't be negated")); >+ UngetToken(); > aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; > return; > } >+ // CSS2 pseudo-elements are allowed to have a single ':' on them, as are >+ // various -moz-* pseudo-elements. Others (CSS3+ pseudo-elements) must >+ // have |parsingPseudoElement| set. >+ if (!parsingPseudoElement && >+ !isMozPseudo && >+ nsCSSPseudoElements::after != pseudo && >+ nsCSSPseudoElements::before != pseudo && >+ nsCSSPseudoElements::firstLetter != pseudo && >+ nsCSSPseudoElements::firstLine != pseudo) { >+ REPORT_UNEXPECTED_TOKEN(NS_LITERAL_STRING("This pseudo-element must use the \"::\" form: ")); >+ UngetToken(); >+ aParsingStatus = SELECTOR_PARSING_STOPPED_ERROR; >+ return; >+ } >+ > if (0 == (aDataMask & SEL_MASK_PELEM)) { > aDataMask |= SEL_MASK_PELEM; > aSelector.AddPseudoClass(pseudo); // store it here, it gets pulled later > > ; > } I wonder if you are not failing to check that the negation of a XUL pseudo-element is invalid. Again, is -moz-tree the only XUL pseudo-element ? What above -moz-tree-cell-text() I quoted above ? What about all the pseudos in nsCSSAnonBoxList.h ? >@@ -587,16 +588,23 @@ void nsCSSSelector::ToStringInternal(nsA > aString.Append(PRUnichar('*')); > } > if (1 < aNegatedIndex) { > NS_IF_NEGATED_END(aIsNegated, aString) > } > } else { > // Append the tag name, if there is one > if (mTag) { >+ if (aIsPseudoElem && >+ mTag != nsCSSPseudoElements::after && >+ mTag != nsCSSPseudoElements::before && >+ mTag != nsCSSPseudoElements::firstLine && >+ mTag != nsCSSPseudoElements::firstLetter) { >+ aString.Append(PRUnichar(':')); >+ } > nsAutoString prefix; > mTag->ToString(prefix); > aString.Append(prefix); > NS_IF_NEGATED_END(aIsNegated, aString) > } > // Append the id, if there is one > if (mIDList) { > nsAtomList* list = mIDList; Yeah. Unfortunately, there is no good way to determine if we should output the double-colon notation or not. I guess you have no other choice than the output of ":" for those pseudos to preserve backwards compatibility :-/ >-input[type=image]:focused { >+input[type=image]:focus { This is unrelated to the current bug, right ? Sorry, but the question about the XUL pseudos and their negations is important enough to ask you to clarify this issue. In the meantime, I don't r+ or r-, and wait for your answer.
Comment on attachment 126221 [details] [diff] [review] Patch against current trunk > In error reporting, could you please write "pseudo-class or pseudo-element" Sure. > Could you just add parenthesis around the a == b ? Done. > Am I right if I say this is going to reject the following rule copied from CaScadeS ? No. This rul falls under the isTree boolean (that's a prefix match on "-moz-tree-", recall). > I recommend an extra comment line saying that proprietary -moz-* pseudo-elements never start with a double colon. Well, they could. My patch, as-is, supports them both with a single colon and a double one, just like CSS2 pseudo-elements. > You are already checking nsCSSPseudoElements::IsPseudoElement(pseudo) above > and could probably store its value Indeed. > What about all the pseudos in nsCSSAnonBoxList.h ? Aha! That's what I was looking for! Patch using that coming up. > I wonder if you are not failing to check that the negation of a XUL > pseudo-element is invalid. I check that at the top of the block. Anything starting with ':' that's not a known pseudo-class (as tested by nsCSSPseudoClasses::IsPseudoClass) cannot be negated. > This is unrelated to the current bug, right ? It's totally related. The rule is supposed to say :focus. The only reason it was not caught before is that we did not reject unknown pseudo-class/pseudo-element selectors as we should have, so that there was no css error message. With this patch, there is.
Attachment #126221 - Attachment is obsolete: true
Attachment #126221 - Flags: superreview?(dbaron)
Attachment #126221 - Flags: review?(glazman)
Created attachment 126307 [details] [diff] [review] Better patch This more or less addresses my concerns #2 and #3 as well as Daniel's comments. The only qualm I have is the -moz-* things I marked as "CSS2 Selectors" in nsCSSPseudoElementList.h. Perhaps those should migrate to nsCSSAnonBoxList.h (except -moz-selection)?
Comment on attachment 126307 [details] [diff] [review] Better patch There is one more outstanding issue, which is line 540 of xul.css: the :-moz-deck-hidden selector that uses is not implemented anywhere and gives a parsing error with this patch; I am tempted to just remove that rule.
Attachment #126307 - Flags: superreview?(dbaron)
Attachment #126307 - Flags: review?(glazman)
Comment on attachment 126307 [details] [diff] [review] Better patch >Index: content/shared/public/nsCSSPseudoElementList.h The comments refer to CSS3_PSEUDO_ELEMENT, which doesn't exist. They also need to explain the difference between CSS_PSEUDO_ELEMENT and CSS2_PSEUDO_ELEMENT (i.e., that the latter allows single-colon). >+ // CSS2 pseudo-elements are allowed to have a single ':' on them, as are >+ // various -moz-* pseudo-elements (anonymous boxes). Others (CSS3+ >+ // pseudo-elements) must have |parsingPseudoElement| set. >+ if (!parsingPseudoElement && >+ !isAnonBox && >+ !nsCSSPseudoElements::IsCSS2PseudoElement(pseudo)) { The |isAnonBox| check should be temporary, and I think you should have an XXX comment that we'll fix that once we convert the users. Likewise for nsCSSPseudoElementList, where we should convert our internal callers and then change CSS2_PSEUDO_ELEMENT to CSS_PSEUDO_ELEMENT. You should probably include the moz-deck-hidden change in the patch. (I haven't read most of the patch yet, just the edges.)
> The comments refer to CSS3_PSEUDO_ELEMENT, which doesn't exist. That's because we don't implement any CSS3 pseudo-elements that are not in CSS2 yet.... I suppose we could just call all speudo-elements that are not CSS2 pseudo-elements CSS_PSEUDO_ELEMENT, but then we have to change things again when CSS4 (in the admittedly remote future) introduces something that only applies to CSS4 pseudo-elements.... Either way is fine with me; let me know which you prefer. Let me know whether you want an updated patch or whether it's OK to wait till after you've read the rest and had a chance to comment on the whole thing together.
Uh, yeah, I _really_ wouldn't worry too much about CSS4 at this point. :-)
Taking. I'd really like to get this in for 1.5a... One thing I've changed is that I have: if (IsPseudoElement(mTag) && !nsCSSPseudoElements::IsCSS2PseudoElement(mTag)) { aString.Append(PRUnichar(':')); } instead of: if (aIsPseudoElement && !nsCSSPseudoElements::IsCSS2PseudoElement(mTag)) { aString.Append(PRUnichar(':')); } because when the selector is "a:before", aIsPseudoElement is true when mTag is "a".... (so it would serialize as ":a:before").
Assignee: glazman → bzbarsky
Status: ASSIGNED → NEW
Summary: [CSS3] Need to support '::' for pseudo-elements in the CSS parser → [FIX][CSS3] Need to support '::' for pseudo-elements in the CSS parser
Target Milestone: Future → mozilla1.5alpha
I think I prefer just CSS_PSEUDO_ELEMENT and CSS2_PSEUDO_ELEMENT.
Comment on attachment 126307 [details] [diff] [review] Better patch > ; > } The indentation lies. What's up? Fix that (somehow), fix my previous comments, file a bug on transitioning of our internal use (for both anon-boxes and the things marked CSS2_PSEUDO_ELEMENT that shouldn't be), and r+sr=dbaron.
Attachment #126307 - Flags: superreview?(dbaron)
Attachment #126307 - Flags: superreview+
Attachment #126307 - Flags: review?(glazman)
Attachment #126307 - Flags: review+
Created attachment 127028 [details] [diff] [review] Patch with all the comments fixed The return should be inside the if statement there, so that we will do an end-of-selector check even after a tree pseudo-element.
Attachment #126307 - Attachment is obsolete: true
Bug 211657 on converting stylesheets to the '::' form; I'll also post to the relevant newsgroups (.style and .xpfe). Patch is checked in.
Status: NEW → RESOLVED
Last Resolved: 15 years ago
Resolution: --- → FIXED
What about netscape.public.dev.skins?
Didn't know that existed. Message posted there. | https://bugzilla.mozilla.org/show_bug.cgi?id=62843 | CC-MAIN-2018-26 | refinedweb | 3,027 | 56.25 |
-- | A word search solver library -- -- This solver is case sensitive; users should map data consistently to one case before using this library when such behavior is desired. {-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Text.WordSearchSolver ( -- * Types and containers WordSearch, ws_grid, ws_search , Grid , Search , Pos(..) , PosIndex , Match(..), m_dir, m_len, m_pos , Dir(..) -- * 'WordSearch' puzzles , readWordSearch , wordSearch , solveWordSearch , search , tryMatch -- * 'Grid' and 'Search' containers , readGrid , arrayToGrid , setToSearch , searchToSet -- * Operations on solutions and rendering 'Grid's , fillMatches , showGridInsert -- * 'Dir's , dirs , dirs' , dirsPos , dirsOpposite , dirToOffset , dirOpposite , dirUpdatePos -- * Helper functions , inRangeOf , posPlus ) where import Prelude hiding (id, (.), foldr, foldl, concat) import Control.Category import Control.Monad hiding (forM, forM_) import qualified Data.Map as M import qualified Data.Set as S import Data.Array import Data.Array.MArray import Data.Array.ST import Data.Data (Data) import Data.Foldable import Data.List hiding (foldr, foldl, foldl', concat) import Data.Record.Label import Data.Typeable (Typeable) --- Types and containers --- -- | Abstract container of a word search puzzle -- -- This can be created either from a 'Search' and a 'Grid' by the -- 'wordSearch' function or from a properly formatted 'String' by the -- 'readWordSearch' function. data WordSearch a = WordSearch { _ws_grid :: Grid a , _ws_search :: Search a } deriving (Data, Typeable, Eq, Ord, Show, Read) -- | A grid in which to search -- -- Constructors of this container usually assume that the grid is rectangular and properly sized; this precondition is \not\ checked. data Grid a = Grid { _g_array :: Array Pos a , _g_index :: GridIndex a } deriving (Data, Typeable, Eq, Ord, Show, Read) newtype GridIndex a = GridIndex { _gi_map :: M.Map a (S.Set Pos) } deriving (Data, Typeable, Eq, Ord, Show, Read) -- | A set of words or lists to search newtype Search a = Search { _s_set :: S.Set [a] } deriving (Data, Typeable, Eq, Ord, Show, Read) -- | A position of a grid newtype Pos = Pos (PosIndex, PosIndex) deriving (Data, Typeable, Eq, Ord, Ix, Show, Read) -- | The integral type used for 'Pos' type PosIndex = Integer -- | An individual value describing a match data Match = Match { _m_dir :: Dir , _m_len :: Integer , _m_pos :: Pos } deriving (Data, Typeable, Eq, Ord, Show, Read) data Dir = N | NW | W | SW | S | SE | E | NE deriving (Data, Typeable, Eq, Enum, Ord, Ix, Show, Read) $(mkLabels [''WordSearch, ''Grid, ''GridIndex, ''Search, ''Match]) -- | Constructs a 'WordSearch' container from a properly formatted 'String' -- -- The 'String' should contain two sections, separated by at least one empty -- line. The first section represents the grid, and thus is formatted as the -- String that 'readGrid' expects. The second section represents the search -- words; it contains each word on its own separate line. In the case that -- is ill-formed, Nothing is returned. The precondition that each grid row -- has equal length is \not\ checked. readWordSearch :: String -> Maybe (WordSearch Char) readWordSearch xs = do let (former, latter) = span (not . null) . lines $ xs grid = readGrid $ former searchTerms = Search . S.fromList . filter (not . null) $ dropWhile null latter guard $ (not . null $ former) return $ wordSearch grid searchTerms -- | Constructs a 'WordSearch' container from a 'Grid' and a 'Search' wordSearch :: Grid a -> Search a -> WordSearch a wordSearch g s = WordSearch {_ws_grid = g, _ws_search = s} -- | Constructs a 'Grid' from a formatted list of 'String's -- -- The 'String' should be formatted as expected: -- -- @[\"aoaoenxrcoedxncd\", -- \"aoesnitdaoeusntd\", -- \"itenohtneahuoteh\"]@ -- -- The precondition that each row has equal length is \not\ checked. readGrid :: [String] -> Grid Char readGrid xs = arrayToGrid . listArray (Pos (0, 0), Pos (pred . genericLength . head $ xs, pred . genericLength $ xs)) . concat . transpose $ xs -- | Constructs a 'Grid' from an 'Array' -- -- A grid array is indexed by (column, row) or (x, y), so users should be -- careful that a list is in the proper order if listArray is used. arrayToGrid :: (Ord a) => Array Pos a -> Grid a arrayToGrid a = Grid { _g_array = a , _g_index = gridIndex a } where gridIndex arr = GridIndex $ foldr step M.empty $ assocs arr step ~(p, v) acc = M.insertWith (flip S.union) v (S.singleton p) acc -- | Constructs a 'Search' from a set of lists setToSearch :: S.Set [a] -> Search a setToSearch = Search -- | Returns the set of search terms from a 'Search' container searchToSet :: Search a -> S.Set [a] searchToSet = getL s_set -- | Solves a 'WordSearch' and returns a set of matches together with a set of search terms for which a match was not found in a tuple -- -- This algorithm solves word search puzzles by looking at the first cell of each search term, and looking for a match by checking each direction from each position whose cell contains the starting cell of the search term until a match is found. The dictionary of individual cell values and sets of positions is part of the 'Grid' container; 'arrayToGrid' creates this dictionary automatically. solveWordSearch :: (Eq a, Ord a) => WordSearch a -> (S.Set Match, Search a) solveWordSearch ws = let (matches, nonmatches) = foldr step (S.empty, S.empty) . getL (s_set) $ getL ws_search ws in (matches, Search nonmatches) where step s (matches, nonmatches) = -- look at algorithm let match = foldr (flip mplus . search (getL ws_grid ws) s) Nothing $ positions positions = case M.lookup (head s) $ getL (gi_map . g_index . ws_grid) ws of (Just ps) -> ps (Nothing) -> S.empty in case match of (Just m) -> (m `S.insert` matches, nonmatches) (Nothing) -> (matches, s `S.insert` nonmatches) -- | Determines whether a given 'Search' term can be matched at a given position of a grid -- -- This is done by trying each direction for a match from the given location. search :: (Eq a) => Grid a -> [a] -> Pos -> Maybe Match search _ [] _ = Nothing search grid xs p = foldr mplus Nothing $ [tryMatch grid xs p d | d <- dirs] -- | If the location and the direction matches the 'Search' term, returns the 'Match'; otherwise, returns Nothing tryMatch :: (Eq a) => Grid a -> [a] -> Pos -> Dir -> Maybe Match tryMatch grid = tryMatch' 0 where arr = getL g_array grid tryMatch' i [] p d = let d' = dirOpposite d in Just $ Match {_m_dir = d', _m_len = i, _m_pos = dirUpdatePos d' p} tryMatch' i (x:xs) p d | not $ p `inRangeOf` arr = Nothing | arr ! p == x = tryMatch' (succ i) xs (dirUpdatePos d p) d | otherwise = Nothing -- | Creates a 'Grid' in which every cell that does not match is set to a default value fillMatches :: (Foldable t, Ord e) => e -> Grid e -> t Match -> Grid e fillMatches deft g ms = arrayToGrid . runSTArray $ do let a = getL (g_array) g ma <- thaw $ listArray (bounds a) $ repeat deft let fill ~m@(Match dir len pos) | len == 0 = return () | pos `inRangeOf` a = do writeArray ma pos $ a ! pos fill . modL m_pos (dirUpdatePos dir) . setL (m_len) (pred len) $ m | otherwise = return () forM_ ms $ fill return ma -- | Renders a 'Grid', appending a cell, usually a newline character, after every row showGridInsert :: a -> Grid a -> [a] showGridInsert ins g = let a = getL (g_array) g ~((Pos (0, 0)), Pos (w, h)) = bounds a step ~p@(x, _) acc | x == w = (a ! Pos p):ins : acc | otherwise = a ! Pos p : acc in foldr step [] $ [(x, y) | y <- [0..h], x <- [0..w]] --- Dir --- -- | Complete set of possible 'Grid' 'Match' directions dirs :: [Dir] dirs = [ N , NW , W , SW , S , SE , E , NE ] -- | More efficient (and real, unordered) 'Set' of 'dirs' dirs' :: S.Set Dir dirs' = S.fromList dirs -- | 'Map' of directions and 'Pos' offsets dirsPos :: M.Map Dir Pos dirsPos = M.fromList . map (\ ~(a, b) -> (a, Pos b)) $ [ (N, ( 0, -1)) , (NW, (-1, -1)) , (W, (-1, 0)) , (SW, (-1, 1)) , (S, ( 0, 1)) , (SE, ( 1, 1)) , (E, ( 1, 0)) , (NE, ( 1, -1)) ] -- | Bidirectional 'Map' of opposite directions dirsOpposite :: M.Map Dir Dir dirsOpposite = M.fromList $ [ (N, S) , (NW, SE) , (W, E) , (SW, NE) , (S, N) , (SE, NW) , (E, W) , (NE, SW) ] -- | Returns the appropriate offset of a direction dirToOffset :: Dir -> Pos dirToOffset d = case M.lookup d dirsPos of (Just p) -> p (Nothing) -> error "dirToOffset: unrecognized direction" -- This shouldn't happen, since the lookup should always succeed -- | Returns the opposite direction dirOpposite :: Dir -> Dir dirOpposite d = case M.lookup d dirsOpposite of (Just d') -> d' (Nothing) -> error "dirOpposite: unrecognized direction" -- This shouldn't happen, since the lookup should always succeed -- | Updates a position by one step in the given direction dirUpdatePos :: Dir -> Pos -> Pos dirUpdatePos d = (`posPlus` dirToOffset d) --- Helper Functions --- -- | Determines whether an index is within the range of the bounds of an array inRangeOf :: (Ix a) => a -> Array a e -> Bool i `inRangeOf` a = inRange (bounds a) i -- | Adds two positions posPlus :: Pos -> Pos -> Pos posPlus (Pos (ax, ay)) (Pos (ba, by)) = Pos (ax + ba, ay + by) | http://hackage.haskell.org/package/wordsearch-1.0.1/docs/src/Text-WordSearchSolver.html | CC-MAIN-2017-04 | refinedweb | 1,362 | 60.65 |
ATOI(3) BSD Programmer's Manual ATOI(3)
atoi - convert ASCII string to integer
#include <stdlib.h> int atoi(const char *nptr);
The atoi() function converts the initial portion of the string pointed to by nptr to integer representation. It is equivalent to: (int)strtol(nptr, (char **)NULL, 10);
atof(3), atol(3), strtod(3), strtol(3), strtonum(3), strtoul(3)
The atoi() function conforms to ANSI X3.159-1989 ("ANSI C").
atoi does no overflow checking, handles unsigned numbers poorly, and han- dles strings containing trailing extra characters (like "123abc") poorly. Careful use of strtol(3) and strtoul(3) can alleviate these problems, but strtonum(3) can be used to convert numbers from strings much more safely and easily.. | http://www.mirbsd.org/htman/sparc/man3/atoi.htm | CC-MAIN-2015-32 | refinedweb | 120 | 54.22 |
Weather Underground is a useful site and a fun place for weather enthusiasts. WU has a bunch of weather data (current and historical) from established weather stations, like at airports, and home stations setup by hobbyists. One problem: most of the data is in HTML tables instead of the CSV format that we like. I say most because you can download hourly data from a single day in CSV, but if you want say, temperature data over the past 5 years, you’re kind of at a loss.
But wait, there’s a solution. That solution is BeautifulSoup, an XML/HTML parser written in Python. Um, parse… what does that mean? Basically, the Python script will go through, or look at, a document extracting certain information from that document.
Back to WU. Like I said, there’s historical data in HTML tables like this. I just want the actual mean temperature in Fahrenheit for the past five years or so. I could go to every single page manually and record the temperature in Excel, but why do that when I can make the computer do it for me?
I’m not going to get into all of the details, but here’s the Python script I used to grab mean temperature from WU using BeautifulSoup.
import urllib2 from BeautifulSoup import BeautifulSoup # Create/open a file called wunder.txt (which will be a comma-delimited file) f = open('wunder-data.txt', 'w') # Iterate through year, month, and day for y in range(1980, 2007): for m in range(1, 13): for d in range(1, 32): # Check if leap year if y%400 == 0: leap = True elif y%100 == 0: leap = False elif y%4 == 0: leap = True else: leap = False # Check if already gone through month if (m == 2 and leap and d > 29): continue elif (m == 2 and d > 28): continue elif (m in [4, 6, 9, 10] and d > 30): continue # Open wunderground.com url url = ""+str(y)+ "/" + str(m) + "/" + str(d) + "/DailyHistory.html" page = urllib2.urlopen(url) # Get temperature from page soup = BeautifulSoup(page) dayTemp = soup.body.nobr.b.string # Format month for timestamp if len(str(m)) < 2: mStamp = '0' + str(m) else: mStamp = str(m) # Format day for timestamp if len(str(d)) < 2: dStamp = '0' + str(d) else: dStamp = str(d) # Build timestamp timestamp = str(y) + mStamp + dStamp # Write timestamp and temperature to file f.write(timestamp + ',' + dayTemp + '\n') # Done getting data! Close file. f.close()
The script goes through each day of the year from 1980 through 2007, parses the corresponding WU page, and stores the temperature data in wunder-data.txt, and there you go. Keep in mind, this was really just a proof of concept, and the script can be modified quite a bit to fit your needs.
The Main Point
Just because data isn’t in CSV format, doesn’t mean it’s unavailable. If it’s on the Web, it’s up for grabs.
Pingback: Flowing Data / Finding Weirdness in Temperature Data
This is exactly what I needed. Thank you!
Pingback: Spatial Data « Flirting with Data | https://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/ | CC-MAIN-2021-04 | refinedweb | 517 | 71.44 |
Source code for brian2.core.names
import uuid import re from brian2.utils.logger import get_logger from brian2.core.tracking import Trackable __all__ = ['Nameable'] logger = get_logger(__name__)[docs]def find_name(name, names=None): """ Determine a unique name. If the desired ``name`` is already taken, will try to use a derived ``name_1``, ``name_2``, etc. Parameters ---------- name : str The desired name. names : Iterable, optional A set of names that are already taken. If not provided, will use the names of all Brian objects as stored in `Nameable`. Returns ------- unique_name : str A name based on ``name`` or ``name`` itself, unique with respect to the names in ``names``. """ if not name.endswith('*'): # explicitly given names are used as given. Network.before_run (and # the device in case of standalone) will check for name clashes later return name name = name[:-1] if names is None: instances = set(Nameable.__instances__()) allnames = set(obj().name for obj in instances if hasattr(obj(), 'name')) else: allnames = names # Try the name without any additions first: if name not in allnames: return name # Name is already taken, try _1, _2, etc. i = 1 while f"{name}_{str(i)}" in allnames: i += 1 return f"{name}_{str(i)}"[docs]class Nameable(Trackable): """ Base class to find a unique name for an object If you specify a name explicitly, and it has already been taken, a `ValueError` is raised. You can also specify a name with a wildcard asterisk in the end, i.e. in the form ``'name*'``. It will then try ``name`` first but if this is already specified, it will try ``name_1``, `name__2``, etc. This is the default mechanism used by most core objects in Brian, e.g. `NeuronGroup` uses a default name of ``'neurongroup*'``. Parameters ---------- name : str An name for the object, possibly ending in ``*`` to specify that variants of this name should be tried if the name (without the asterisk) is already taken. If (and only if) the name for this object has already been set, it is also possible to call the initialiser with ``None`` for the `name` argument. This situation can arise when a class derives from multiple classes that derive themselves from `Nameable` (e.g. `Group` and `CodeRunner`) and their initialisers are called explicitely. Raises ------ ValueError If the name is already taken. """ def __init__(self, name): if getattr(self, '_name', None) is not None and name is None: # name has already been specified previously return self.assign_id() if not isinstance(name, str): raise TypeError(f"'name' argument has to be a string, is type " f"{repr(type(name))} instead") if not re.match(r"[_A-Za-z][_a-zA-Z0-9]*\*?$", name): raise ValueError(f"Name {name} not valid variable name") self._name = find_name(name) logger.diagnostic(f"Created object of class {self.__class__.__name__} " f"with name {self._name}")[docs] def assign_id(self): """ Assign a new id to this object. Under most circumstances, this method should only be called once at the creation of the object to generate a unique id. In the case of the `MagicNetwork`, however, the id should change when a new, independent set of objects is simulated. """ self._id = uuid.uuid4()name = property(fget=lambda self:self._name, doc=""" The unique name for this object. Used when generating code. Should be an acceptable variable name, i.e. starting with a letter character and followed by alphanumeric characters and ``_``. """) id = property(fget=lambda self:self._id, doc=""" A unique id for this object. In contrast to names, which may be reused, the id stays unique. This is used in the dependency checking to not have to deal with the chore of comparing weak references, weak proxies and strong references. """) | https://brian2.readthedocs.io/en/latest/_modules/brian2/core/names.html | CC-MAIN-2022-40 | refinedweb | 610 | 67.35 |
Felgo 2.14.0 adds Live Code Reloading for Desktop, iOS & Android. It allows you to run and reload apps & games within a second on iOS and Android from Windows and Linux. No Mac and Android SDKs required. It also updates the way we distribute Android & iOS updates. If you have Felgo for iOS or Android installed, make sure to follow the steps described here.
Live Code Reloading!
Try Live Code Reloading in your Browser
You want to test live code reloading right away, without installing Felgo? No problem!
You can also use live code reloading from the Web Editor. Just click Run This Example below. After you change your code, you can hit CTRL + S (CMD + S on macOS) to reload your app.
import Felgo 3.0 import QtQuick 2.8 App { id: app NavigationStack { Page { title: "Live Reloading" AppText { anchors.centerIn: parent text: "Change me!" } } } }
How to Use Felgo Live
1. Get the Latest Version of Felgo
If you haven’t installed Felgo yet, go get it on our download page. Felgo Live is available starting with this Felgo version, 2.14.0. If you are running an older Felgo version, WiFi. Once you run the Felgo Live App on your mobile device, it will connect to the Server. You will see this dialog in the Live Server:
Accept the mobile device connection on the Server. Now all code changes are automatically sent to your connected mobile device(s)..
Test on All Your Devices at Once
You can connect as many devices as you want, and every single one is updated simultaneously. We didn’t even include this in the calculation above.
Easy Setup
Setting up Felgo Live is as easy as it gets. In fact, there is nothing to set up. To connect your mobile devices, just download and install the Felgo Live App for Android or iOS.
iOS Deployment from Windows & Linux
With Felgo Live, you can test your Felgo projects on your iPhone and iPad, even from Windows or Linux. No more need to ask your office neighbor with that shiny Mac, to test you application on iOS.
No Native SDKs Required
You don’t need to install native mobile SDK for Android or iOS for developing and testing.
Debug Log Output on Mobile Devices
The Live Server displays debug log output from any connected client, including the mobile clients for iOS and Android. You can debug issues on different platforms even easier now.
Test Felgo Plugins Easily
Test Felgo Plugins like Admob Ads, Facebook Login, Google Analytics, Firebase or push notifications. With Felgo Live you can skip the individual setup steps.
Qt Quick / QML Applications
Felgo Live can also be used for Qt Quick applications and files without Felgo.
Your Source Code is Safe
Felgo Live works simple and safe, using your private local network. The Live Server is running locally on your development PC. You can connect your mobile devices using the Live Client app, available for Android and iOS. Your project files are transferred directly from your server to the clients, without ever leaving the local network.
Learn how to make your mobile app with custom expert Qt Training
Important Update Notes for existing Android & iOS Projects
With this update, developers for Android & iOS have a new “Felgo Kit” available. The benefit of this new solution is, that updating to future Felgo versions that use a different Qt version internally gets a lot easier, because the Qt version is now automatically updated for you.:
- Open the MaintenanceTool and select the Add or remove components option:
- Add the Felgo packages for Android and iOS:
- Unselect the Qt 5.9.2 package like shown below:
- In Qt Creator, now choose the new kit for Android and iOS based on Felgo packages:
Learn how to make an Android App on our Blog
Support for Xcode 9
With update 2.14.0, we updated all our wizards and examples to be compatible with iOS apps submitted to the App Store with Xcode 9. If you still use a previous version of Xcode, you can optionally perform these steps or do them as soon as you’re switching to Xcode 9.
Apps submitted with Xcode 9 need an Asset catalog. You can copy the Asset catalog we provide and modify it to your needs:
To migrate your existing project to the new format, perform steps described in this guide.
Besides the highlights mentioned above, there are many other fixes and improvements for the SDK. For a full list of improvements and fixes to Felgo in this update, please check out our change log!
More Posts Like This
How to Make Cross-Platform Mobile Apps with Qt – Felgo Apps | https://felgo.com/updates/release-2-14-0-live-code-reloading-for-desktop-ios-android | CC-MAIN-2019-39 | refinedweb | 781 | 64.1 |
So you’re back! In the last installment of this series, we created a JHipster application taking the monolithic route. It was the Red Pill route; life as pretty much you are accustomed to.
But maybe you like a challenge. Maybe you want to move beyond the Red Pill and try out the Blue Pill. In this case, the Blue Pill is the microservice JHipster approach.
In this blog, we are going to create a microservice architecture using JHipster’s available options for doing so. There is quite a bit more work to do with this approach, but in the end, I think it pays off. Get your favorite beverage and set aside some time. This will be pretty intensive.
Microservice Overview
What are these things anyways?
A “microservice” architecture splits the front end and the back end so that it’s easier for your application to scale and survive infrastructure issues.
The thought here is to decouple things as much as possible. You can create the back end(s) and run them without being tied to anything on the front end and vice versa. Each can have multiple instances and can spin up and down without affecting the end user. Possibly eliminating downtime to your application.
It gives it the ability to grow and expand over time with little architectural effort. The backend becomes more of something to consume and the front end is the output shown to the world. The front end can be just about anything you want. Traditional websites, mobile applications, or whatever else you can think of.
Microservice Path
The Blue Pill
So you’ve decided to take the gulp and swallow the Blue Pill. You want to give yourself a challenge, maybe? Let’s get started.
Gateway
A gateway is a JHipster-generated application (using application type microservice gateway when you generate it) that handles Web traffic, and serves an AngularJS application. There can be several different gateways, if you want to follow the Backends for Frontends pattern, but that’s not mandatory.
This will pretty much be the hub of all the activity. It will have a front end to it so you can see the calls, memory, etc. You can add/remove users, and all that fun stuff. That stuff is all fairly packaged up and you can look at it on your own. We won’t go into that much here.
Registry
The JHipster Registry is a runtime application, using the usual JHipster structure, on which all applications registers and get their configuration from. We won’t touch on this much more than just pulling it down and using it. It is just the home of “configuration” for the most part. Just clone the repo and move on. More info on this below.
Clone:
Microservice
Microservices are JHipster-generated applications (using application type microservice application when you generate them), that handle REST requests. They are stateless, and several instances of them can be launched in parallel to handle heavy loads.
Let’s Do This
Gateway
We will be pretty much following JHipster’s microservice guide for this exercise.
1. Start with
yo jhipster
2. Choose “Microservice gateway”
3. Answer all the questions
4. Coffee time!!!
This app is pretty much just a monolithic app with configuration to handle all the web flow traffic
Registry
Clone if you haven’t already. Add to your project space. Go ahead and fire it up.
Look for the Java file that has
@SpringBootApplication annotation and run it as a Java application. This applies to each step below.
Microservice App
First thing is to make a new directory. Call it what you like and then go into that directory. Now type
yo jhipster. See that pattern here?
This time, though, we will choose “Microservice Application.” Answer the questions.
This time, in two shakes of a dog’s tail, you’ll have your microservice!
Microservice In Action
Registry
If you haven’t spun up the registry, go ahead and launch it. It should run on. Visit it, and see the basic information it has for you. Then click on the “Applications” link. Notice that it is blank.
Gateway
Now it is time to spin up the gateway. You will see this output in the console.
---------------------------------------------------------- Application 'ExtendedDayGateway' is running! Access URLs: Local: External: ---------------------------------------------------------- 2016-09-13 14:19:29.643 INFO 10856 --- [ restartedMain] c.wwc.extendedday.ExtendedDayGatewayApp : ---------------------------------------------------------- Config Server: Connected to the JHipster Registry config server! ----------------------------------------------------------
Notice how it shows you the URL and it shows you that it has gotten its configuration from the JHipster Registry. Let’s also go take a look at the application.
Also, take a look at the Applications page again in the registry application..
Notice that our Gateway shows up now. It is self registered.
Microservice App
Now we have two out of three of the items running. It’s now time for what will definitely be the powerhouse, I think, of this scenario. We will add in the microservice app that will provide our “backend” to whatever requests it.
1. Create a Java class to be our “api” endpoint. In our case we will just have one that returns a static data set. Easy peasy.
@RestController @RequestMapping("/api") public class DemoResource {...
2. Add a method to return our “students.”
/** * GET /students : get all the students. * * @return the ResponseEntity with status 200 (OK) and the list of students in body */ @JsonView(Student.Info.class) @RequestMapping(value = "/demostudents", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<Student> getAllStudents() { log.debug("REST request to get all Students"); List<Student> userStudents = new ArrayList<Student>(); Student student = new Student(); student.setFirstName("Joe"); student.setLastName("Smith"); student.setSex(0); student.setGrade(3); userStudents.add(student); return userStudents; }
3. Save and spin up the microservice. It should look something like this:
---------------------------------------------------------- Application 'extendedDayAPI' is running! Access URLs: Local: External: ---------------------------------------------------------- 2016-09-14 11:36:13.927 INFO 13980 --- [ restartedMain] com.wwc.extendedday.ExtendedDayApiApp : ---------------------------------------------------------- Config Server: Connected to the JHipster Registry config server! ----------------------------------------------------------
4. Revisit again or refresh the view. Notice how our microservice has registered itself.
5. Go to your browser and type in. Note that you will be forbidden even if you have logged in.
6. Log out of
localhost:8080 and then back in with Chrome open.
Then inspect the login call and grab the token in “Authorization.” It should start with “Bearer…” and then a whole bunch of encoded stuff. Select it all.
You must pass this token with your request. There are many different ways to do this via your code. In our test scenario,
- Postman will suffice to show you the output.
- Open up postman
- Type in your API call from above
- Under “Headers” add in the “Authorization” key and paste in the token you grabbed.
You should see something like this:
Woo hoo!!! You have done it! You have created a microservice using jHipster.
Conclusion
We have stepped through creating a microservice architecture using JHipster’s available options for creating a microservice. I hope that you have found this information helpful.
At this point, we can add as many different microservices we want to. Each has its own port number and functionality. In a distributed environment, we would have many instances that could be spun up/down as we make changes to them. Hopefully you can see the benefits and flexibility in decoupling our different layers of our architecture. Each layer is not dependent upon another to run.
The topics of Microservices, gateways, registries and in using different front ends does begin to go outside of the basic how-to’s of using JHipster. For more information about these topics, check out the free Keyhole blogs and white paper.
Check back for Part 3 with tricks, tips and gotchas when using JHipster. Have a great day and continue being “Hip.” | https://keyholesoftware.com/2016/10/10/getting-started-with-jhipster-part-2/ | CC-MAIN-2017-09 | refinedweb | 1,300 | 68.87 |
- Performance Guidelines't. See #15607 for an example.
- Measure the performance of the code in a production environment such as GitLab.com (see the Tooling section below). Performance should be measured over a period of at least 24 hours.
- Add your findings based on the measurement period (screenshots of graphs, timings, etc) to the issue mentioned in step 1.
- Solve the problem.
- Create a merge request, assign the "Performance" label and assign it to @yorickpeterse for reviewing.
- Once a change has been deployed make sure to again measure for at least 24 hours to see if your changes have any impact on the production environment.
- Repeat until you're done.
When providing timings make sure to provide:
- The 95th percentile
- The 99th percentile
- The mean
When providing screenshots of graphs, make sure that both the X and Y axes and the legend are clearly visible. If you happen to have access to GitLab.com's own monitoring tools you should also provide a link to any relevant graphs/dashboards.
Tooling
GitLab provides built-in tools to aid the process of improving performance:
- Profiling
- GitLab Performance Monitoring
- Request Profiling
- QueryRecoder for preventing
N+1regressions.g., a Gem) tend to be biased in favour of the library. After all there's little benefit to an author publishing a benchmark that shows they perform worse than their competitors.
Benchmarks are only really useful when you need a rough (emphasis on "rough") understanding of the impact of your changes. For example, if a certain method is slow a benchmark can be used to see if the changes you're making have any impact on the method's performance. However, even when a benchmark shows your changes improve performance there's no guarantee the performance also improves in a production environment.
When writing benchmarks you should almost always use
benchmark-ips. Ruby's
Benchmark
module that comes with the standard library is rarely useful as it runs either a
single iteration (when using
Benchmark.bm) or two iterations (when using
Benchmark.bmbm). Running this few iterations means external factors (e.g. a
video streaming in the background) can very easily skew the benchmark
statistics.
Another problem with the
Benchmark module is that it displays timings, not
iterations. This means that if a piece of code completes in a very short period
of time it can be very difficult to compare the timings before and after a
certain change. This in turn leads to patterns such as the following:
Benchmark.bmbm(10) do |bench| bench.report 'do something' do 100.times do ... work here ... end end end
This however leads to the question: how many iterations should we run to get meaningful statistics?
The benchmark-ips Gem basically takes care of all this and much more, and as a
result of this should be used instead of the
Benchmark module.
In short:
- Don't trust benchmarks you find on the internet.
- Never make claims based on just benchmarks, always measure in production to confirm your findings.
- X being N times faster than Y is meaningless if you don't know what impact it will actually have on your production environment.
- A production environment is the only benchmark that always tells the truth (unless your performance monitoring systems are not set up correctly).
- If you must write a benchmark use the benchmark-ips Gem instead of Ruby's
Benchmarkmodule.
Profiling
By collecting snapshots of process state at regular intervals, profiling allows you to see where time is spent in a process. The StackProf gem is included in GitLab's development environment, allowing you to investigate the behaviour of suspect code in detail.
It's important to note that profiling an application alters its performance, and will generally be done in an unrepresentative environment. In particular, a method is not necessarily troublesome just because it is executed many times, or takes a long time to execute. Profiles are tools you can use to better understand what is happening in an application - using that information wisely is up to you!
Keeping that in mind, to create a profile, identify (or create) a spec that
exercises the troublesome code path, then run it using the
bin/rspec-stackprof
helper, e.g.:
$ LIMIT=10 bin/rspec-stackprof spec/policies/project_policy_spec.rb 8/8 |====== 100 ======>| Time: 00:00:18 Finished in 18.19 seconds (files took 4.8 seconds to load) 8 examples, 0 failures ================================== Mode: wall(1000) Samples: 17033 (5.59% miss rate) GC: 1901 (11.16%) ================================== TOTAL (pct) SAMPLES (pct) FRAME 6000 (35.2%) 2566 (15.1%) Sprockets::Cache::FileStore#get 2018 (11.8%) 888 (5.2%) ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_no_cache 1338 (7.9%) 640 (3.8%) ActiveRecord::ConnectionAdapters::PostgreSQL::DatabaseStatements#execute 3125 (18.3%) 394 (2.3%) Sprockets::Cache::FileStore#safe_open 913 (5.4%) 301 (1.8%) ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_cache 288 (1.7%) 288 (1.7%) ActiveRecord::Attribute#initialize 246 (1.4%) 246 (1.4%) Sprockets::Cache::FileStore#safe_stat 295 (1.7%) 193 (1.1%) block (2 levels) in class_attribute 187 (1.1%) 187 (1.1%) block (4 levels) in class_attribute
You can limit the specs that are run by passing any arguments
rspec would
normally take.
The output is sorted by the
Samples column by default. This is the number of
samples taken where the method is the one currently being executed. The
Total
column shows the number of samples taken where the method, or any of the methods
it calls, were being executed.
To create a graphical view of the call stack:
$ stackprof tmp/project_policy_spec.rb.dump --graphviz > project_policy_spec.dot $ dot -Tsvg project_policy_spec.dot > project_policy_spec.svg
To load the profile in kcachegrind:
$ stackprof tmp/project_policy_spec.dump --callgrind > project_policy_spec.callgrind $ kcachegrind project_policy_spec.callgrind # Linux $ qcachegrind project_policy_spec.callgrind # Mac
It may be useful to zoom in on a specific method, e.g.:
$ stackprof tmp/project_policy_spec.rb.dump --method warm_asset_cache TestEnv#warm_asset_cache (/Users/lupine/dev/gitlab.com/gitlab-org/gitlab-development-kit/gitlab/spec/support/test_env.rb:164) samples: 0 self (0.0%) / 6288 total (36.9%) callers: 6288 ( 100.0%) block (2 levels) in <top (required)> callees (6288 total): 6288 ( 100.0%) Capybara::RackTest::Driver#visit code: | 164 | def warm_asset_cache | 165 | return if warm_asset_cache? | 166 | return unless defined?(Capybara) | 167 | 6288 (36.9%) | 168 | Capybara.current_session.driver.visit '/' | 169 | end $ stackprof tmp/project_policy_spec.rb.dump --method BasePolicy#abilities BasePolicy#abilities (/Users/lupine/dev/gitlab.com/gitlab-org/gitlab-development-kit/gitlab/app/policies/base_policy.rb:79) samples: 0 self (0.0%) / 50 total (0.3%) callers: 25 ( 50.0%) BasePolicy.abilities 25 ( 50.0%) BasePolicy#collect_rules callees (50 total): 25 ( 50.0%) ProjectPolicy#rules 25 ( 50.0%) BasePolicy#collect_rules code: | 79 | def abilities | 80 | return RuleSet.empty if @user && @user.blocked? | 81 | return anonymous_abilities if @user.nil? 50 (0.3%) | 82 | collect_rules { rules } | 83 | end
Since the profile includes the work done by the test suite as well as the application code, these profiles can be used to investigate slow tests as well. However, for smaller runs (like this example), this means that the cost of setting up the test suite will tend to dominate.
It's also possible to modify the application code in-place to output profiles whenever a particular code path is triggered without going through the test suite first. See the StackProf documentation for details.
RSpec profiling
GitLab's.
Importance of Changes
When working on performance improvements, it's important to always ask yourself the question "How important is it to improve the performance of this piece of code?". Not every piece of code is equally important and it would be a waste to spend a week trying to improve something that only impacts a tiny fraction of our users. For example, spending a week trying to squeeze 10 milliseconds out of a method is a waste of time when you could have spent a week squeezing out 10 seconds elsewhere.
There is no clear set of steps that you can follow to determine if a certain piece of code is worth optimizing. The only two things you can do are:
- Think about what the code does, how it's used, how many times it's called and how much time is spent in it relative to the total execution time (e.g., the total time spent in a web request).
- Ask others (preferably in the form of an issue).
Some examples of changes that aren't really important/worth the effort:
- Replacing double quotes with single quotes.
- Replacing usage of Array with Set when the list of values is very small.
- Replacing library A with library B when both only take up 0.1% of the total execution time.
- Calling
freezeon every string (see String Freezing).
Slow Operations & Sidekiq
Slow operations be easier to test and maintain.
It's especially important to use Sidekiq as much as possible when dealing with Git operations as these operations can take quite some time to complete depending on the performance of the underlying storage system.
Git Operations
Care should be taken to not run unnecessary Git operations. For example,
retrieving the list of branch names using
Repository#branch_names can be done
without an explicit check if a repository exists or not. In other words, instead
of this:
if repository.exists? repository.branch_names.each do |name| ... end end
You can just write:
repository.branch_names.each do |name| ... end
Caching
Operations that will often return the same result should be cached using Redis, in particular Git operations. When caching data in Redis, make sure the cache is flushed whenever needed. For example, a cache for the list of tags should be flushed whenever a new tag is pushed or a tag is removed.
When adding cache expiration code for repositories, this code should be placed
in one of the before/after hooks residing in the Repository class. For example,
if a cache should be flushed after importing a repository this code should be
added to
Repository#after_import. This ensures the cache logic stays within
the Repository class instead of leaking into other classes.
When caching data, make sure to also memoize the result in an instance variable. While retrieving data from Redis is much faster than raw Git operations, it still has overhead. By caching the result in an instance variable, repeated calls to the same method won't end up retrieving data from Redis upon every call. When memoizing cached data in an instance variable, make sure to also reset the instance variable when flushing the cache. An example:
def first_branch @first_branch ||= cache.fetch(:first_branch) { branches.first } end def expire_first_branch_cache cache.expire(:first_branch) @first_branch = nil end
Anti-Patterns
This is a collection of anti-patterns that should be avoided unless these changes have a measurable, significant and positive impact on production environments.
String, for example:
SOME_CONSTANT = 'foo'.freeze 9000.times do SOME_CONSTANT end
The only reason you should be doing this is to prevent somebody from mutating the global String. However, since you can just re-assign constants in Ruby there's nothing stopping somebody from doing this elsewhere in the code:
SOME_CONSTANT = 'bar'
Moving. | https://docs.gitlab.com/ee/development/performance.html | CC-MAIN-2018-30 | refinedweb | 1,838 | 59.3 |
Java MySQL FAQ: Can you share an example of a Java MySQL UPDATE example (using a Java PreparedStatement object)?
Sure. I just worked up a Java MySQL UPDATE example, using the Java
PreparedStatement class, and a sample MySQL database table we can work with.
The first thing we need for our Java UPDATE example is a sample. In particular, the field "num_points" is a little unusual. I made it up so I could show an int data type in this table, and I was thinking of those websites where points are awarded for giving correct answers.
Other than that, this MySQL database table is relatively normal, though it is greatly simplified.
Given that MySQL database table design, let's assume that we just want to update one record in this table. To do so, we just need to follow these steps:
Connectionto our MySQL database.
PreparedStatementsyntax.
PreparedStatementobject.
PreparedStatement.
I've tried to document the following Java MySQL UPDATE UPDATE example. * Demonstrates the use of a SQL UPDATE statement against a * MySQL database, called from a Java program. * * Created by Alvin Alexander, * */ public class JavaMysqlPreparedStatementUpdateExample { public static void main(String[] args) { try { // create a java mysql database connection String myDriver = "org.gjt.mm.mysql.Driver"; String myUrl = "jdbc:mysql://localhost/test"; Class.forName(myDriver); Connection conn = DriverManager.getConnection(myUrl, "root", ""); // create the java mysql update preparedstatement String query = "update users set num_points = ? where first_name = ?"; PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setInt (1, 6000); preparedStmt.setString(2, "Fred"); // execute the java preparedstatement preparedStmt.executeUpdate(); conn.close(); } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } } }
Note that this SQL UPDATE query is a little unusual, but not totally uncommon. Typically in a database program like this you'll end up updating rows based on the primary key of the database table. Specifically, in this example, you'd probably already know the "id" for the user Fred, and when you go to update Fred's data, you would normally do it like this:
update users set num_points = 6000 where id = 2;
but because this is a sample program, I decided to show the query this way.
After this Java MySQL UPDATE query runs, you can verify that it worked by looking at the data from the MySQL command prompt, running a SELECT query like this:
select * from users;
where you will see some output like this:
+----+------------+-----------+---------------------+----------+------------+ | id | first_name | last_name | date_created | is_admin | num_points | +----+------------+-----------+---------------------+----------+------------+ | 2 | Fred | Flinstone | 2010-06-23 14:02:00 | 0 | 6000 | +----+------------+-----------+---------------------+----------+------------+ 1 row in set (0.00 sec)
In "real world" Java database programs I almost always use the Spring JDBC libraries to access a database, but when you're first getting started, or working on small programs, I think it's important to see examples like this so you can understand how things work under the covers.
In summary, this example demonstrated:
PreparedStatement.
PreparedStatement.
PreparedStatement.
I hope this Java MySQL UPDATE example (using a
Java PreparedStatement) makes sense. As usual, if you have any questions or comments about this example, just use the Comment form below.
Data?
Don't you need some data in the database before the query will work? Perhaps in the create box you could also include some inserts to load demo rows?
Adding INSERT data
Yes, you do need some data in the database table before performing an UPDATE. I'll add an INSERT statement or two to the initial CREATE statement. Thanks.
Post new comment | http://alvinalexander.com/java/java-mysql-update-query-example | CC-MAIN-2015-18 | refinedweb | 575 | 54.52 |
json_object_convert 0.0.2
w# json_object_convert: json_object_convert: ^0.0.2
2. Install it
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
3. Import it
Now in your Dart code, you can use:
import 'package:json_object_convert/json_object_convert.dart';
We analyzed this package on Jan 17, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.0
- pana: 0.13.2
Health suggestions
Fix
lib/src/hook/hook.dart. (-3.45 points)
Analysis of
lib/src/hook/hook.dart reported 7 hints, including:
line 11 col 3: Omit type annotations for local variables.
line 41 col 15: Unnecessary new keyword.
line 42 col 13: Prefer single quotes where they won't require escape sequences.
line 45 col 7: Omit type annotations for local variables.
line 46 col 7: Omit type annotations for local variables.
Maintenance issues and suggestions
Support latest dependencies. (-20 points)
The version constraint in
pubspec.yaml does not support the latest published versions for 2 dependencies (
analyzer,
build).
Use constrained dependencies. (-20 points)
The
pubspec.yaml contains 1 dependency without version constraints. Specify version ranges for the following dependencies:
json_object_convert_help.
Package is getting outdated. (-24.38 points)
The package was last published 64. | https://pub.dev/packages/json_object_convert | CC-MAIN-2020-05 | refinedweb | 223 | 54.18 |
The LauncherView class provides the base for any type of laucnher view used by Qtopia. More...
#include <LauncherView>
Inherits QWidget.
Inherited by ApplicationLauncherView, ArchiveViewer, ContentSetLauncherView, DocumentLauncherView, and TaskManagerLauncherView.
The LauncherView class provides the base for any type of laucnher view used by Qtopia.
This class is part of the Qt Extended server and cannot be used by other Qt Extended applications.
See also ApplicationLauncherView and DocumentLauncherView.
Create a LauncherView instance with the given parent and flags.
Destroys the LauncherView.
Adds app to the view. resort is ignored at this stage.
See also removeItem().
Clears the current selection.
This signal is emitted whenever the user clickes on an item. The activated item is passed as content object.
Returns a new launcher view instance with the given parent and flags. name is the name of the LauncherView subclass to be created.
New launcher view subclasses can be registered via the UIFactory class and UIFACTORY_REGISTER_WIDGET().
//customlauncherview.cpp #include "uifactory.h" #include "launcherview.h" class CustomLauncherView : public LauncherView { }; UIFACTORY_REGISTER_WIDGET(CustomLauncherView); //code.cpp LauncherView *view = LauncherView::createLauncherView( "CustomLauncherView", parent, flags );
Launcher view instances should be created via this factory method whenever the caller doesn't intend to actually include the declaration for CustomLauncherView.
This function returns a null pointer if name doesn't exist.
This slot is called when a new item becomes the current item. The previous current item is specified by the previous index, and the new item by the current index.
Returns the index of the currently selected item.
Returns the currently selected item.
Returns the direction the items layout should flows.
See also setFlow() and QListView::flow().
This event handler can be reimplemented in a subclass to react when a mouse button is clicked with the specified item. item will be selected if setCurrentIndex is true.
This event handler can be reimplemented in a subclass to react when a mouse button is pressed with the specified item.
This event handler can be reimplemented in a subclass to react to Enter or Return key press on the current item. The default implementation emits the clicked() signal.
Returns the size of icons the given widget should use if it is a launcher view in list mode. This can be used to make other list views look consistent with launcher views.
Returns the content model that the view is presenting.
See also setModel().
Removes all items from the view
Removes app from the view.
See also addItem().
This function can be reimplemented by subclasses to adjust the way how the view is reset. The default implementation selects the first item in the view.
This signal is emitted when the user clciks on content with the right mouse button. This signal may be used in conjunction with a context menu.
filter acts as an auxiliary filter besides the main filter.
Sets the busy state of the currently selected item to on. This indicates to the user that the current selection is processed.
Sets the number of columns. This value defaults to 1.
The view will be adjusted according to filter.
Sets the direction the items layout should flow.
This property only affects the Icon view mode.
See also flow() and QListView::setFlow().
Sets the item delegate for the contained view and its model to delegate. The old delegate is deleted in the process.
See also QAbstractItemView::setItemDelegate().
Sets a new model for this view. Any existing model will be deleted.
See also model().
Sets the viewmode of the contained item view to m.
See also viewMode() and QListView::setViewMode().
Only items that are of category filter will be shown.
filter is applied in addition to the main filter.
See also setFilter().
Returns the used view mode.
See also setViewMode() and QListView::viewMode(). | https://doc.qt.io/archives/qtextended4.4/launcherview.html | CC-MAIN-2019-26 | refinedweb | 617 | 70.5 |
Bug #16842open
`inspect` prints the UTF-8 character U+0085 (NEXT LINE) verbatim even though it is not printable
Description
The UTF-8 character U+0085 (NEXT LINE) is not printable, but
inspect prints the character verbatim (within double quotation):
0x85.chr(Encoding::UTF_8).match?(/\p{print}/) # => false 0x85.chr(Encoding::UTF_8).inspect #=> "\" \""
My understanding is that non-printable characters are not printed verbatim with
inspect:
"\n".match?(/\p{print}/) # => false "\n".inspect #=> "\"\\n\""
while printable characters are:
"a".match?(/\p{print}/) # => true "a".inspect # => "\"a\""
I ran the following script, and found that U+0085 is the only character within the range U+0000 to U+FFFF that behaves like this.
def verbatim?(char) !char.inspect.start_with?(%r{\"\\[a-z]}) end def printable?(char) char.match?(/\p{print}/) end (0x0000..0xffff).each do |i| begin char = i.chr(Encoding::UTF_8) rescue RangeError next end puts '%#x' % i unless verbatim?(char) == printable?(char) end
Updated by jeremyevans0 (Jeremy Evans) about 1 year ago
- Assignee set to duerst (Martin Dürst)
- Status changed from Open to Assigned
Behavior here seems to be dependent on the encoding:
$ LC_ALL=C ruby -e "p 0x85.chr(Encoding::UTF_8).inspect.b" "\"\\u0085\"" $ LC_ALL=en_US.UTF-8 ruby -e "p 0x85.chr(Encoding::UTF_8).inspect.b" "\"\xC2\x85\""
I've submitted a pull request to fix the behavior, though the implementation is rather crude:
@duerst (Martin Dürst) Is there a better fix by handling the unicode properties differently?
Updated by naruse (Yui NARUSE) about 1 year ago
Why U+0085 is categorized as
I'm neutral about the change, but I want the change should have detailed comment or link to this ticket.
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/16842 | CC-MAIN-2022-21 | refinedweb | 281 | 58.38 |
1. Before you begin
This codelab teaches you how to create a high-volume geospatial data visualization using the Maps JavaScript API and deck.gl, an open-source, WebGL-accelerated, data-visualization framework.
Prerequisites
What you'll do
- Integrate Google Maps Platform with deck.gl.
- Import a dataset to a map from BigQuery.
- Define the data points on the map.
What you'll need
- A Google Account
- A text editor or IDE of your choice
- Basic knowledge of JavaScript, HTML, and CSS
2. Set up your environment
If you haven't used Google Maps Platform before, follow these steps:
- Create a billing account.
- Create a project.
- Enable Google Maps Platform APIs and SDKs.
- Generate an API key.
Download Node.js
If you don't already have it, go to, and download and install the Node.js runtime on your computer.
Node.js includes npm, a package manager that you need to install the dependencies for this codelab.
Set up the starter project
To save you time, the starter project for this codelab includes all the boilerplate code that you need to instantiate a map.
To get started, follow these steps:
- Clone or download this repository.
- From the command line, navigate to the
/starterdirectory, which contains the basic file structure that you need to complete this codelab.
- Install dependencies from npm by running the following command:
npm install
- Run the starter project in your browser with Webpack Dev Server by running the following command:
npm start
The starter app opens in your browser and displays a map.
- Open the project in your IDE and navigate to the
/starter/srcdirectory.
- Open the
app.jsfile.
You'll do all your coding in this section of the code in the file:
const googleMapsAPIKey = 'YOUR API KEY'; loadJSAPI(); function runApp() { // Your code goes here }
You won't do anything with the rest of the code in the file, which loads the Maps JavaScript API and map:
/* API and map loader helpers */ function loadJSAPI() { const googleMapsAPIURI = `{googleMapsAPIKey}&callback=runApp`; const script = document.createElement('script'); script.src = googleMapsAPIURI; script.defer = true; script.async = true; window.runApp = runApp; document.head.appendChild(script); } function initMap() { const mapOptions = { center: { lat: 40.75097, lng: -73.98765 }, zoom: 14, styles: mapStyle }; const mapDiv = document.getElementById('map'); return new google.maps.Map(mapDiv, mapOptions); }
- Replace
YOUR API KEYwith your actual API key, which you generated when you set up your environment:
const googleMapsAPIKey = 'YOUR API KEY';
3. Export data from BigQuery
BigQuery offers many public datasets that you can use for data analysis or experimental purposes.
Use BigQuery to export a publicly available dataset that includes location data for New York City's Citi Bike, a bikeshare program with 14,500 bikes and 900 locations, by following these steps:
- Go to Cloud Console.
- Click Navigation menu
> BigQuery.
- In the Query editor, enter the following query and click Run:
SELECT longitude, latitude, name, capacity FROM `bigquery-public-data.new_york_citibike.citibike_stations`
- After the query completes, click Save Results, then select JSON (local file) to export the result set. Name the file
stations.jsonand save it in the
/srcdirectory.
Now that you obtained your data, you can create your first visualization with deck.gl.
4. Define the visualization
deck.gl is an open source data-visualization framework that uses WebGL to produce high-resolution 2D and 3D renderings of extremely large datasets. It can handle hundreds of thousands of data points and, when optimized, it can even handle millions of them.
To create a visualization, you need two classes—
GoogleMapsOverlay and one of deck.gl's many visualization layers.
To start, create an instance of
ScatterplotLayer—which renders data points as circles on the map:
- Import deck.gl's
ScatterplotLayerclass by adding the following to the top of
app.js:
import { ScatterplotLayer } from '@deck.gl/layers';
- Set your layer properties by choosing from the two types of properties available for deck.gl's scatterplot layer.
Setter properties provide the visualization with the information that it needs to render, such as the position and radius of data points. Styler properties let you customize the visualization's style.
Here's a breakdown of the properties that you use in the following code snippet:
idallows the renderer to identify layers for various reasons, such as repaints and other updates to the visualization. All deck.gl layers require a unique ID, which you assign.
dataspecifies the data source of the visualization. Set it to
‘./stations.json' to use the dataset that you exported from BigQuery.
getPositionretrieves each object's position from the data source. Notice that the value of the property is a function. deck.gl uses the function to iterate over every row in the dataset. The function tells the renderer how to access the latitude and longitude of the data point in each row. In this dataset, the data in each row is a JSON object with the position set in the latitude and longitude properties, so the function that you provide to
getPositionis
d => [parseFloat(d.longitude), parseFloat(d.latitude)].
getRadiusdefines each object's radius in meters. In this case, the radius is set to
d => parseInt(d.capacity), which sets the size of the data points based on each station's capacity.
strokedsets whether the rendered data points have a stroke on their outer edges.
getFillColorsets the fill color of each data point as an RGB color code.
getLineColorsets the stroke color of each data point as an RGB color code.
radiusMinPixelssets the minimum pixel width for each data point. As users zoom in and out, deck.gl automatically resizes the scale of data points to keep the visualization clearly visible on the map. This property lets you control the extent to which this resizing occurs.
radiusMaxPixelssets the maximum pixel width for each data point. };
- Create an instance of deck.gl's
ScatterplotLayerclass:
const scatterplotLayer = new ScatterplotLayer(layerOptions);
After you complete this section, your code should look like this:
import { ScatterplotLayer } from '@deck.gl/layers'; const googleMapsAPIKey = 'YOUR API KEY'; loadJSAPI(); function runApp() { const map = initMap(); const layerOptions = { id: 'scatterplot',); }
5. Apply the visualization to the map
Now you can apply your
ScatterplotLayer instance to the map with the
GoogleMapsOverlay class, which uses the Maps JavaScript API
OverlayView API to inject a WebGL context on top of the map.
Once that's in place, you can pass any of deck.gl's visualization layers to
GoogleMapsOverlay, which renders the layer and syncs it with the map.
To apply your
ScatterplotLayer to the map, follow these steps:
- Import deck.gl's
GoogleMapsOverlayclass:
import { GoogleMapsOverlay } from '@deck.gl/google-maps';
- Create an instance of the
GoogleMapsOverlayclass and pass it the
scatterplotLayerinstance that you created earlier in the
layersproperty of an object:
const googleMapsOverlay = new GoogleMapsOverlay({ layers: [scatterplotLayer] });
- Apply the overlay to the map:
googleMapsOverlay.setMap(map);
After you complete this section, your code should look like this:
import { GoogleMapsOverlay } from '@deck.gl/google-maps'; import { ScatterplotLayer } from '@deck.gl/layers'; const googleMapsAPIKey = 'YOUR API KEY'; loadJSAPI(); function runApp() { const map = initMap();); const googleMapsOverlay = new GoogleMapsOverlay({ layers: [scatterplotLayer] }); googleMapsOverlay.setMap(map); }
Go back to your browser, where you should see an awesome data visualization of all the Citi Bike stations in New York City.
6. Congratulations
Congratulations! You produced a high-volume data visualization of New York City's Citi Bike data with Google Maps Platform and deck.gl.
Learn more
The Maps JavaScript API gives you access to everything Google Maps Platform offers for the web. Learn more about working with Google Maps Platform on the web by checking out these links:
deck.gl offers numerous data-visualization layers that you can use to display data to your users. Learn more about using deck.gl with the Maps JavaScript API by checking out these links: | https://developers.google.com/codelabs/maps-platform/maps-deck-gl?hl=zh-tw | CC-MAIN-2021-49 | refinedweb | 1,287 | 57.98 |
10 September 2010 15:06 [Source: ICIS news]
TORONTO (ICIS)--?xml:namespace>
Royal Bank of
“While Canada's second-quarter growth put real GDP close to its pre-recession high, concerns in the US and nervousness about the health of the global economy are weighing on the outlook for the second half of the year," said Craig Wright, the bank’s senior vice-president and chief economist.
US GDP growth had sharply weakened in the second quarter and recent reports on that country’s housing and labour markets had disappointed, Royal Bank said. The
The bank forecast that
The labour market had recovered 94% of the jobs lost during the recession and the unemployment rate is expected to decline to 7.3% by the end of 2011.
In a related report,
Royal Bank also lowered its 2011 GDP forecast for
Government infrastructure spending would be exhausted in the first quarter of 2011, putting pressure on the private sector to fill the void and sustain economic growth, the bank said.
Earlier this week, the country’s central Bank, the Bank of Canada, raised its benchmark lending rate to 1%, the third increase in a row since June | http://www.icis.com/Articles/2010/09/10/9392623/canada-2010-gdp-forecast-cut-to-3.3-amid-us-concerns.html | CC-MAIN-2014-35 | refinedweb | 196 | 61.6 |
mvcConf 2 - Glenn Block: Take some REST with WCF
- Posted: Feb 09, 2011 at 11:21PM
- 79,875 views
- 11 comments
![if gt IE 8]> <![endif]>
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
In WCF, we’re serious about HTTP and we’re serious about REST. We’re making deep investments in WCF to provide more natural support for HTTP and for building RESTful systems. If you want to exposing your APIs in a web friendly manner that leverages all the richness, scale and evolve-ability that HTTP has to offer then this talk is for you., really cool. I don't know enough about other MVC REST packages to compare this against, but I really like what I see.
I have not yet looked at the sample, but for Atom/RSS feeds, I'd ideally want to set what fields get to be the pub date, title, content, etc. in addition to that custom namespace I saw in the video (m:properties). I hope we can do that; I assume we can.
Hi Kamran
Glad you like what you are seeing.
The sample Is showed was using a new library which returns OData (which derives from Atom). It allows you full control of the other fields.
The mechanism itself allows you to return whatever you want however, so you could use a SyndicationFeed for example in a custom formatter instead of the OData library if you just want pure Atom.
I am planning to make the sample available hopefully this weekend, I just need to muster the energy to write the blog post.
Thanks for the feedback.
Thanks
Glenn
Where i may find source code from your talk?
We currently use WCF / WIF (SSO) for our SOAP API. Would love to use it for a REST api as well. Does WCF offer a binding that supports both WIF/SSO and REST? If not, is this on the radar?
This looks exciting! I would like to try out the WCF REST sample based on the MVC music store. Where is your source code? I can't wait to get my hands-on mixing WCF REST, MVC, and Odata feed, and JQuery AJax. These are my favorate MS technologies, along with EF codefirst. I highly appreciate your effort to release this WCF REST soon.
Guys, I am working on getting the souce out there. There was an issue regarding the OData pieces, as the lib was no availalble to be released. As it is now out there on Codeplex, I am working on getting this done.
Thanks for your patience!
Glenn
@scott_m we are working with the WIF team to integrate our new web apis for things like OAuth. Shoot me a mail with your scenarios and I'll follow up.
Thanks
Glenn
Hi Glenn,
Was this WCF REST released as a part of Visual Studio Service Pack 1? Thanks.
Jay, no. The new web api has not shipped yet. It is still in development. You can get the latest community preview at wcf.codeplex.com.
Hi Glenn,
I have been waiting for the MVC music store sample you used for the mvc conference. Do you have the mvc music store sample code available? I really like like to use the WebAPI in my MVC application. Thanks.
hi, i have tried this in a sample mvc3 project. The only problem is that am able to run and access the service when the application is configured to run in full trust but not under a medium trust environment.
Remove this comment
Remove this threadClose | https://channel9.msdn.com/Series/mvcConf/mvcConf-2-Glenn-Block-Take-some-REST-with-WCF?format=smooth | CC-MAIN-2015-48 | refinedweb | 614 | 82.44 |
P-value calculations and interpretations depend on the alternative hypothesis of a test, a description of the difference from expectation that we are interested in.
For example, let’s return to the 10-coin-flip example from earlier. Suppose that we flipped a coin 10 times and observed only 2 heads. We might run a hypothesis test with the following null and alternative hypotheses:
- Null: the probability of heads is 0.5
- Alternative: the probability of heads is less than 0.5
This hypothesis test asks the question: IF the probability of heads is 0.5, what’s the probability of observing 2 or fewer heads among a single sample of 10 coin flips?
Earlier, we used a for-loop to repeatedly (10000 times!) flip a fair coin 10 times, and store the number of heads (for each set of 10 flips) in a list named
outcomes. The probability of observing 2 or fewer heads among 10 coin flips is approximately equal to the proportion of those 10000 experiments where we observed 0, 1, or 2 heads:
import numpy as np outcomes = np.array(outcomes) p_value = np.sum(outcomes <= 2)/len(outcomes) print(p_value) #output: 0.059
This calculation is equivalent to calculating the proportion of this histogram that is colored in red:
We estimated that the probability of observing 2 or fewer heads is about 0.059 (5.9%). This probability (0.059) is referred to as a one-sided p-value.
Instructions
The code you wrote to generate
null_outcomes is available to you in script.py. Use
null_outcomes to estimate the p-value for a binomial hypothesis test with the following null and alternative hypotheses:
- Null: the probability of a purchase was 10%
- Alternative: the probability of a purchase rate was LESS THAN 10%
In other words, calculate the proportion of values in
null_outcomes that are less than or equal to 41 (the observed number of purchases that we calculated earlier). Save this number as a variable named
p_value and print it out.
Try pressing “Run” a few times; You should see slightly different values of
p_value each time. What do you think the true probability is? | https://www.codecademy.com/courses/hypothesis-testing-python/lessons/simulating-a-binomial-test/exercises/calculating-a-p-value-part-i | CC-MAIN-2021-39 | refinedweb | 359 | 54.42 |
Concurrent set based on sorted singly linked list
Set is an abstract data structure that can store certain values, without any particular order, and no repeated values. Static sets that do not change with time, and allow only query operations while mutable setsallow also the insertion and/or deletion of elements from the set.
Wikipedia
Though set definition says it doesn’t imply particular of values it is referred to how consuming code treats set. One legitimate way (though not the most efficient one) to implement set is to use sorted singly linked list that will allow us to eliminate duplicate values. Other ways include but not limited to self-balancing binary search tree, skip lists or hash table.
As the title says we are about to explore algorithm for concurrent set. Taking this into account we can use ConcurrentDictionary<TKey, TValue> to implement concurrent set. Assuming it is done =) let’s take a look at other options. At this point .NET Framework has to support for concurrent self-balancing binary search tree or skip lists and building those is quite tricky. On the other hand concurrent sorted singly linked list is still feasible solution. This well known algorithm contains useful techniques.
For mutable sets at least the following operations must be supported: add, remove, contains. The simplest way to do this is to wrap any list modifications with lock leading to coarse-grained synchronization. However under high contention this single lock will become a bottleneck taking into account that all operations has O(n) time complexity and thus serializing them will lead to significant performance hit.
Consider list with the following contents: 1->3->4->6->7. Operations Add(2) and Add(5) even when run concurrently do not interfere as they modify distinct areas of the list 1->(2)->3->4->(5)->6->7. Add operation affects two consequent nodes where new node must be added in between. The same is true for remove operation (it affects two consequent nodes: the node to be removed and its predecessor).These nodes will be used as sync roots to make thread safe modifications of the list. In order to prevent deadlocks nodes are locked always in the same order (predecessor first and than its successor).
What if we need to add new node either at the beginning or at the end? In that case we do not have a pair nodes. To work around this the list will contain two sentinel nodes (head and tail sentinels that remain in the list forever and any value is more than value in the head and less than value in the tail). Basically any list looks like h->x0->x1->…->xn->t assuming h contains negative infinity and t contains positive infinity values.
Let’s assume we have a list: h->1->2->5->6->t. Two threads (A and B) execute operations Add(3) and Add(4) respectively concurrently. Both of them need to add new node between nodes that contain 2 and 5 (h->1->2->(x)->5->6->t). One of them will be first who will succeed in locking both nodes. After nodes are successfully locked it will proceed with adding new node (let’s assume thread A succeeded). Once thread A finished with list modifications the list will be h->1->[2]->4->[5]->6->t yet thread B is trying to lock nodes in brackets. Thread B eventually will succeed in locking but his expectations may not be true anymore as it happens in this case (node that holds value 2 no longer points to node that holds 5).
Because between the moment a thread starts his attempt to lock pair of nodes and the moment it eventually succeeds in doing so the list can be modified by other thread as it tries to lock two nodes which is not atomic. Thus after a thread succeeds in locking it must do validation that its expectations are still true.
However dealing with node removal is even more tricky. Assume we have a list h->1->2->5->6->t and thread A attempts to Add(3) concurrently with thread B trying to Remove(2) or Remove(5) and thread B succeeds to be first. In that case once thread A will lock nodes that contain 2 and 5 it may observe list that is now h->1->5->6->t or h->1->2->6->t meaning of the locked nodes is no longer in the list and adding new value in between will lead to lost value (if predecessor was removed) or resurrected value (if successor was removed and now new nodes points to it).
Thus once a thread succeeds in locking both nodes it must check that locked nodes are still not removed from the list and predecessor still points to its observed previously successor. If the validation fails the operation must fallback and start again.
Well if the node is removed from the list how do we know that? One way to make removed node’s next reference null. However this is a bad idea because in that case other thread traverses list without locks (and this is deliberate behavior) may observe unexpected null reference. For example, assume we have a list h->1->2->3->6->t. Thread A tries to Add(4) while thread B tries to Remove(2). Assume that thread A while searching for 3->6 pair of nodes (to add 4 in between) moved its current reference to the node that contains 2 and it was preempted. Then thread B succeeds in Remove(2). If thread B set removed node next reference to null once thread B will wake up it will miserably fail though there are still sought nodes in the list. Thus list node’s next reference must always be non-null.
So how do we remove nodes. We must preserve next pointers even if the node is removed. Thus the node is simply marked as removed and then its predecessor’s next is updated. Thus a node to remove is no longer reachable but still points other list nodes. Thus any traverses in-progress won’t break. From memory perspective we rely on garbage collector to reclaim memory occupied by non reachable nodes.
Because of the mechanism chosen for nodes remove we can safely traverse the list with no locks. And this is true for all three operations. Contains operation just need to validate found nodes.
Now let’s code the thing.
public class ConcurrentSet<T> { private readonly IComparer<T> m_comparer; // Sentinel nodes private readonly Node m_head; private readonly Node m_tail; public ConcurrentSet(IComparer<T> comparer) { m_comparer = comparer; // Sentinel nodes cannot be removed from the // list and logically contain negative and // positive infinity values from T m_tail = new Node(default(T)); m_head = new Node(default(T), m_tail); } // Adds item to the set if no such item // exists public bool Add(T item) { // Continue attempting until succeeded // or failed while (true) { Node pred, curr; // Find where new node must be added Find(item, out pred, out curr); // Locks nodes starting from predecessor // to synchronize concurrent access lock (pred) { lock (curr) { // Check if found nodes still // meet expectations if (!Validate(pred, curr)) continue; // If the value is already in the // set we are done if (Equal(curr, item)) return false; // Otherwise add new node var node = new Node(item, curr); // At this point new node becomes // reachable pred.m_next = node; return true; } } } } // Removes item from the list if such item // exists public bool Remove(T item) { // Continue attempting until succeeded // or failed while (true) { Node pred, curr; // Find node that must be removed and // its predecessor Find(item, out pred, out curr); // Locks nodes starting from predecessor // to synchronize concurrent access lock (pred) { lock (curr) { // Check if found nodes still // meet expectations if (!Validate(pred, curr)) continue; // If the value is not in the set // we are done if (!Equal(curr, item)) return false; // Otherwise mark node as removed curr.m_removed = true; // And make it unreachable pred.m_next = curr.m_next; return true; } } } } // Checks if given item exists in the list public bool Contains(T item) { Node pred, curr; Find(item, out pred, out curr); return !curr.m_removed && Equal(curr, item); } // Searches for pair consequent nodes such that // curr node contains a value equal or greater // than given item void Find(T item, out Node pred, out Node curr) { // Traverse the list without locks as removed // nodes still point to other nodes pred = m_head; curr = m_head.m_next; while (Less(curr, item)) { pred = curr; curr = curr.m_next; } } static bool Validate(Node pred, Node curr) { // Validate that pair of nodes previously // found still meets the expectations // which essentially is checking whether // nodes still point to each other and no one // was removed from the list return !pred.m_removed && !curr.m_removed && pred.m_next == curr; } bool Less(Node node, T item) { return node != m_tail && m_comparer.Compare(node.m_value, item) < 0; } bool Equal(Node node, T item) { return node != m_tail && m_comparer.Compare(node.m_value, item) == 0; } class Node { internal readonly T m_value; internal volatile Node m_next; internal volatile bool m_removed; internal Node(T value, Node next = null) { m_value = value; m_next = next; } } }
This algorithm uses fine grained synchronization that improves concurrency and with lazy nodes removal allows us to traverse list with no locks at all. This is quite important as usually Contains operation is used more frequent than Add and Remove.
Hope this pile of bits makes sense to you =). | https://docs.microsoft.com/en-us/archive/blogs/dhuba/concurrent-set-based-on-sorted-singly-linked-list | CC-MAIN-2020-05 | refinedweb | 1,575 | 59.74 |
$39.20.
Premium members get this course for $23.20.
Premium members get this course for $62.50.
Premium members get this course for $4.00.
Otherwise the clock would roll over in less than a day.
Did you try something like
tlater += (long)( 7 * 24 * 60 * 60);
or
tlater += ( (long)7 * 24 * 60 * 60);
It could be your compiler doing the rounding.
Actually, I think I'll take that back. I've been through some weeks that were a LOT longer....;-)
With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.
time_t tlater;
char timestr2[64];
struct tm *st2;
time(&tlater);
tlater += ( 7 * 24 * 60 * 60);
st2 = localtime(&tlater);
strftime(timestr2, 64, "%d %b %y %H%MZ", st2);
strupr(timestr2);
weektime.SetFormatText(tim
When I print it out, the time is only 5 hours later. (like you, I've worked weeks like that);
I'm working with a subset of "C" provided by the authoring package Quest.
#include <time.h>
#include <stdio.h>
void main( void )
{
struct tm when;
time_t now, result;
int days;
time( &now );
when = *localtime( &now );
printf( "Current time is %s\n", asctime( &when ) );
printf( "How many days to look ahead: " );
scanf( "%d", &days );
when.tm_mday = when.tm_mday + days;
if( (result = mktime( &when )) != (time_t)-1 )
printf( "In %d days the time will be %s\n",
days, asctime( &when ) );
else
perror( "mktime failed" );
}
?
Then you're probably running into a 16/32 bit truncation issue. 7 * 24 * 60 * 60 is too large to fit in a 16 bit. The total is 0x00093A80. If you toss the upper 16 bits, you get 0x3A80 = 14976. That's a bit over 4 hours.
Could this be what's happening? I'm not familiar with the Quest package but you might read up on the 16 vs. 32 bit arithmetic.
(at least thats what they claim in MSDN).
It appears that it is now supposed to be a 32 bit integer, and that the days are in the small end of the upper 16 bits.
So, you might try adding
7 * 65536 = 458752 to your current time_t.
To jkr: The problem with that is it doen't account for days greater that that allowed for a particular month and you get dates like Feb. 34. I had already tried that, but I'd like to eliminate the need for the large case statement to catch day overflows, month and year changes. That is why I was trying to modify the output from time. Thank you for the suggestion.
They say elsewhere
." | https://www.experts-exchange.com/questions/10295495/How-do-I-modify-results-of-function-time-to-get-next-week's-time.html | CC-MAIN-2018-09 | refinedweb | 445 | 83.76 |
This is the mail archive of the cygwin@cygwin.com mailing list for the Cygwin project.
On Thu, Apr 26, 2001 at 02:26:05PM -0400, Christopher Faylor wrote: > On Thu, Apr 26, 2001 at 10:47:09AM +0200, Corinna Vinschen wrote: > >On Wed, Apr 25, 2001 at 10:37:53PM -0700, Karl M wrote: > >> Hi Corinna... > >> > >> The make died. What would you like me to do? > > > >Just as a workaround (the problem is actually in Cygwin, but for now) > >add the following to the offending source file: > > > >#ifdef HAVE_CYGWIN > >#undef S_IXUSR > >#undef S_IXGRP > >#undef S_IXOTH > >#define S_IXUSR 0100 > >#define S_IXGRP 0010 > >#define S_IXOTH 0001 > >#endif > > That probably won't do the right thing. That will cause cygwin not to > detect executable files. Sure. It was just a suggestion to get the test running. I had the (futile) hope that the error we've found on Monday would help solving the problem which some boxes have using socketpairs. Corinna -- Want to unsubscribe from this list? Check out: | https://cygwin.com/ml/cygwin/2001-04/msg01697.html | CC-MAIN-2018-47 | refinedweb | 167 | 80.92 |
WordArt to a Microsoft Word Document
If you’ve read our columns or viewed one of our webcasts, you no doubt see the Scripting Guys as serious, no-nonsense types, writers who just like to give you the facts and then call it good. Well, believe it or not the Scripting Guys do have a lighter side; once in a while we like to let our hair down and do something just because it’s kind of fun or kind of cool, and not because it has any real practical value. Hey, all work and no play, right?
Which brings us to today’s Office Space column: adding WordArt to a Microsoft Word document. In the great scheme of system administration life, adding WordArt to a document is probably not as important as backing up file servers or creating user accounts. But that’s all right: sometimes you should do things just because you can, not because it will change your life in any way.
On the other hand, some of that WordArt is pretty cool, so who can really say whether or not it will change your life?
If you aren’t familiar with WordArt, in Microsoft Word go to the Insert menu, point to Picture, and then click WordArt. You be rewarded for that effort by seeing a dialog box like this one:
Basically WordArt is a way to add some snazzy-looking text to a document; as a system administrator, you might want to use it to, say, slap an eye-catching cover on a report generated by your script. It’s kind of fun and it might even be worth doing … provided, of course, that adding this WordArt was quick and easy. Well, guess what:
That’s all you have to do. The script starts out by creating an instance of the Word.Application object and setting the Visible property to True. We then use the Add method to create a new document to work with.
Following that we create an instance of the Selection object, then use the TypeParagraph() method to enter a blank paragraph return (equivalent to pressing ENTER on the keyboard). Why do we do that? Well, by default our WordArt will be “anchored” to the first paragraph in the document. If that first paragraph contains text and we add more text to the document, the WordArt will drift: as the text moves down the page the WordArt will follow it. As a result, our snazzy-looking title ends up in the middle of the page instead of at the top. An easy way to guard against that is to anchor the WordArt to a blank paragraph, which is exactly what we’ve done.
Now we get to the good stuff:
What we’ve done here is call the AddTextEffect method, a method belonging to the document’s Shapes collection. In addition, we pass AddTextEffect the following parameters:
And here’s what we get when we run the script:
That’s got to be more fun than backing up file servers!
You might have noticed that when we call the AddTextEffect method we actually create an object reference using the variable name objShape:
We had a good reason for doing that. WordArt is just another shape within a Microsoft Word document; that means we can further modify and manipulate our WordArt after it’s been inserted. (In other words, you aren’t stuck with the 30 styles shown in the WordArt dialog box.) We won’t run through all the possible ways to modify a Word shape, but here’s a cool one you can try. Just add this line of code to the bottom of your script:
You should get back a document that looks like this, with the individual letters in Script Center “filled” with the picture Sunset.jpg (assuming you copied Sunset.jpg to your C:\Scripts folder):
You can also use code like this to change the “flow” of the text:
The number 9 in the preceding line of code represents the index number from the shapes found in this dialog box:
In this dialog box, the first shape in the first row is number 1, the second shape in the first row is number 2, and so on. We’re using shape 9, the first shape in the second row. Give the script a try and see for yourself. Hey, it’ll be fun. | http://technet.microsoft.com/en-us/library/ee692903(d=printer).aspx | CC-MAIN-2014-15 | refinedweb | 736 | 74.32 |
table of contents
- bullseye 7.74.0-1.3+deb11u1
- bullseye-backports 7.81.0-1~bpo11+1
- testing 7.81.0-1
- unstable 7.81.0-1
NAME¶
CURLOPT_USERAGENT - set HTTP user-agent header
SYNOPSIS¶
#include <curl/curl.h>
CURLcode curl_easy_setopt(CURL *handle, CURLOPT_USERAGENT, char *ua);
DESCRIPTION¶
Pass a pointer to a null-terminated string as parameter. It will be used to set the User-Agent: header in the HTTP request sent to the remote server. This can be used to fool servers or scripts. You can also set any custom header with CURLOPT_HTTPHEADER(3).
The application does not have to keep the string around after setting this option.
DEFAULT¶
NULL, no User-Agent: header is used by default.
PROTOCOLS¶
HTTP, HTTPS
EXAMPLE¶
CURL *curl = curl_easy_init(); if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "");
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Dark Secret Ninja/1.0");
curl_easy_perform(curl); }
AVAILABILITY¶
As long as HTTP is supported
RETURN VALUE¶
Returns CURLE_OK if HTTP is supported, CURLE_UNKNOWN_OPTION if not, or CURLE_OUT_OF_MEMORY if there was insufficient heap space.
SEE ALSO¶
CURLOPT_REFERER(3), CURLOPT_HTTPHEADER(3), | https://manpages.debian.org/bullseye/libcurl4-doc/CURLOPT_USERAGENT.3.en.html | CC-MAIN-2022-05 | refinedweb | 174 | 52.76 |
This post will provide an overview of multi-GPU training in Pytorch, including:
- training on one GPU;
- training on multiple GPUs;
- use of data parallelism to accelerate training by processing more examples at once;
- use of model parallelism to enable training models that require more memory than available on one GPU;
- use of DataLoaders with num_workers > 0 to enable multi-process data loading;
- training on only a subset of available devices.
Training on One GPU
Let’s say you have 3 GPUs available and you want to train a model on one of them. You can tell Pytorch which GPU to use by specifying the device:
- device = torch.device(‘cuda:0’) for GPU 0
- device = torch.device(‘cuda:1’) for GPU 1
- device = torch.device(‘cuda:2’) for GPU 2
Training on Multiple GPUs
To allow Pytorch to “see” all available GPUs, use:
device = torch.device(‘cuda’)
There are a few different ways to use multiple GPUs, including data parallelism and model parallelism.
Data Parallelism
Data parallelism refers to using multiple GPUs to increase the number of examples processed simultaneously. For example, if a batch size of 256 fits on one GPU, you can use data parallelism to increase the batch size to 512 by using two GPUs, and Pytorch will automatically assign ~256 examples to one GPU and ~256 examples to the other GPU.
Using data parallelism can be accomplished easily through DataParallel. For example, let’s say you have a model called “custom_net” that is currently initialized as follows:
import torch, torch.nn as nn
model = custom_net(**custom_net_args).to(device)
Now, all you have to do to use data parallelism is wrap the custom_net in DataParallel:
model = nn.DataParallel(custom_net(**custom_net_args)).to(device)
You’ll also want to increase the batch size to make use of all your available devices to their fullest extent.
For more information on data parallelism, see this article.
Model Parallelism
You can use model parallelism to train a model that requires more memory than is available on one GPU. Model parallelism allows you to distribute different parts of the model across different devices.
There are two steps to using model parallelism. The first step is to specify in your model definition which parts of the model should go on which device. Here’s an example from the Pytorch documentation:
The second step is to ensure that the labels are on the same device as the model’s outputs when you call the loss function.
For example, you may want to start out by moving your labels to device ‘cuda:1’ and your data to device ‘cuda:0’. Then you can process your data with a part of the model on ‘cuda:0’, then move the intermediate representation to ‘cuda:1’ and produce the final predictions on ‘cuda:1’. Because your labels are already on ‘cuda:1’ Pytorch will be able to calculate the loss and perform backpropagation without any further modifications.
For more information on model parallelism, see this article.
Pytorch’s DataLoader provides an efficient way to automatically load and batch your data. You can use it for any data set, no matter how complicated. All you need to do is first define your own Dataset that inherits from Pytorch’s Dataset class:
The only requirements on your Dataset are that it defines the methods __len__ and __getitem__.
- The __len__ method must return the total number of examples in your dataset.
- The __getitem__ method must return a single example based on an integer index.
How you actually prepare the examples and what the examples are is entirely up to you.
Once you’ve created a Dataset, you need to wrap that Dataset in Pytorch’s Dataloader as follows:
from torch.utils.data import Dataset, DataLoader
dataset_train = MyComplicatedCustomDataset(**dataset_args)
train_dataloader = DataLoader(dataset_train, batch_size=256, shuffle=True, num_workers = 4)
In order to get batches all you have to do is iterate through the DataLoader:
for batch_idx, batch in enumerate(train_dataloader):
do stuff
If you want to accelerate data loading, you can use more than one worker. Notice in the call to DataLoader you specify a number of workers:
train_dataloader = DataLoader(dataset_train, batch_size=256, shuffle=True, num_workers = 4)
By default, num_workers is set to 0. Setting num_workers to a positive integer turns on multi-process data loading in which data will be loaded using the specified number of loader worker processes. (Note that this isn’t really multi-GPU, as these loader worker processes are different processes on the CPU, but since it’s related to accelerating model training I decided to put it in the same article).
Note that more worker processes is not always better. If you set num_workers too high, it can actually slow down your data loading. There are also no great rules about how to choose the optimal number of workers. There are numerous online discussions about it (e.g. here) but no conclusive answers. The reason there aren’t any great rules about how to choose the number of workers is that the optimal number of workers depends on what kind of machine you are using, what kind of data set you are using, and how much on-the-fly pre-processing your data requires.
A good way to choose a number of workers is to run some small experiments on your data set in which you time how long it takes to load a fixed number of examples using different numbers of workers. As you increase num_workers up from 0, you will first see an increase in data loading speed, followed by a decrease in data loading speed once you hit “too many workers.”
For more information see “Multi-process data loading” on this page.
Model Parallelism and Data Parallelism Simultaneously
If you want to use both model parallelism and data parallelism at the same time, then the data parallelism will have to be implemented in a slightly different way, using DistributedDataParallel instead of DataParallel. For more information, see “Getting Started with Distributed Data Parallel.”
Training on a Subset of Available Devices
What if you want to use model parallelism or data parallelism but you don’t want to take up all available devices for a single model? In that case, you can restrict which devices Pytorch can see for each model . Within your code, you’ll set the device as if you want to use all GPUs (i.e. using device = torch.device(‘cuda’)) but when you run the code you’ll restrict which GPUs can be seen.
Let’s say you have 6 GPUs and you want to train Model A on 2 of them and Model B on 4 of them. You can do that as follows:
CUDA_VISIBLE_DEVICES=0,1 python model_A.py
CUDA_VISIBLE_DEVICES=2,3,4,5 python model_B.py
Or, if you have 3 GPUs and you want to train Model A on 1 of them and Model B on 2 of them, you could do this:
CUDA_VISIBLE_DEVICES=1 python model_A.py
CUDA_VISIBLE_DEVICES=0,2 python model_B.py
Happy multi-GPU training!
About the Featured Image
The featured image is a painting called “Harvesters” by Anna Ancher. It is in the public domain. Source: Wikipedia. | https://glassboxmedicine.com/2020/03/04/multi-gpu-training-in-pytorch-data-and-model-parallelism/ | CC-MAIN-2021-39 | refinedweb | 1,192 | 52.29 |
The Q3ListBoxText class provides list box items that display text. More...
#include <Q3ListBoxText>
This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information.
Inherits: Q3ListBoxItem.
The Q3ListBoxText class provides list box items that display text.
The text is drawn in the widget's current font. If you need several different fonts, you must implement your own subclass of Q3ListBoxItem.
See also Q3ListBox and Q3ListBoxItem.
Constructs a list box item in list box listbox showing the text text.
Constructs a list box item showing the text text.
Constructs a list box item in list box listbox showing the text text. The item is inserted after the item after, or at the beginning if after is 0.
Destroys the item.
Reimplemented from Q3ListBoxItem::height().
Returns the height of a line of text in list box lb.
See also paint() and width().
Reimplemented from Q3ListBoxItem::paint().
Draws the text using painter.
Reimplemented from Q3ListBoxItem::rtti().
Returns 1.
Make your derived classes return their own values for rtti(), and you can distinguish between listbox items. You should use values greater than 1000 preferably a large random number, to allow for extensions to this class.
Reimplemented from Q3ListBoxItem::width().
Returns the width of this line in list box lb.
See also paint() and height(). | http://doc.trolltech.com/main-snapshot/q3listboxtext.html | crawl-003 | refinedweb | 235 | 79.06 |
Provided by: libfuntools-dev_1.4.4-6_amd64
NAME
FunOpen - open a Funtools data file
SYNOPSIS
#include <funtools.h> Fun FunOpen(char *name, char *mode, Fun ref);
DESCRIPTION
The FunOpen() routine opens a Funtools data file for reading or appending, or creates a new FITS file for writing. The name argument specifies the name of the Funtools data file to open. You can use IRAF-style bracket notation to specify Funtools Files, Extensions, and Filters. A separate call should be made each time a different FITS extension is accessed: Fun fun; char *iname; ... if( !(fun = FunOpen(iname, "r", NULL)) ){ fprintf(stderr, "could not FunOpen input file: %s\n", iname); exit(1); } If mode is "r", the file is opened for reading, and processing is set up to begin at the specified extension. For reading, name can be stdin, in which case the standard input is read. If mode is "w", the file is created if it does not exist, or opened and truncated for writing if it does exist. Processing starts at the beginning of the file. The name can be stdout, in which case the standard output is readied for processing. If mode is "a", the file is created if it does not exist, or opened if it does exist. Processing starts at the end of the file. The name can be stdout, in which case the standard output is readied for processing. When a Funtools file is opened for writing or appending, a previously opened Funtools reference handle can be specified as the third argument. This handle typically is associated with the input Funtools file that will be used to generate the data for the output data. When a reference file is specified in this way, the output file will inherit the (extension) header parameters from the input file: Fun fun, fun2; ... /* open input file */ if( !(fun = FunOpen(argv[1], "r",, in the above example, the output FITS binary table file will inherit all of the parameters associated with the input binary table extension. A file opened for writing with a Funtools reference handle also inherits the selected columns (i.e. those columns chosen for processing using the FunColumnSelect() routine) from the reference file as its default columns. This makes it easy to open an output file in such a way that the columns written to the output file are the same as the columns read in the input file. Of course, column selection can easily be tailored using the FunColumnSelect() routine. In particular, it is easy to merge user-defined columns with the input columns to generate a new file. See the evmerge for a complete example. In addition, when a Funtools reference handle is supplied in a FunOpen() call, it is possible also to specify that all other extensions from the reference file (other than the input extension being processed) should be copied from the reference file to the output file. This is useful, for example, in a case where you are processing a FITS binary table or image and you want to copy all of the other extensions to the output file as well. "c" mode, giving users the option of copying all other extensions: /* open input file -- allow user copy of other extensions */ if( !(fun = FunOpen(argv[1], "rc",, funtable supports either of these command lines: # copy only the EVENTS extension csh> funtable "test.ev[EVENTS,circle(512,512,10)]" foo.ev # copy ALL extensions csh> funtable "test.ev[EVENTS+,circle(512,512,10)]" foo.ev Use of a Funtools reference handle implies that the input file is opened before the output file. However, it is important to note that if copy mode ("c" or "C") is specified for the input file, the actual input file open is delayed until just after the output file is opened, since the copy of prior extensions to the output file takes place while Funtools is seeking to the specified input extension. This implies that the output file should be opened before any I/O is done on the input file or else the copy will fail. Note also that the copy of subsequent extension will be handled automatically by FunClose() if the output file is closed before the input file. Alternatively, it can be done explicitly by FunFlush(), but again, this assumes that the input file still is open. Upon success FunOpen() returns a Fun handle that is used in subsequent Funtools calls. On error, NULL is returned.
SEE ALSO
See funtools(7) for a list of Funtools help pages | http://manpages.ubuntu.com/manpages/trusty/man3/funopen.3.html | CC-MAIN-2019-18 | refinedweb | 752 | 60.75 |
Visualize Python profiles in the browser
Project description
Performance analysis for Python.
tuna is a modern, lightweight Python profile viewer inspired by SnakeViz. It handles runtime and import profiles, has no Python dependencies, uses d3 and bootstrap, and avoids certain errors present in SnakeViz.
Create a runtime profile with
python -mcProfile -o program.prof yourfile.py
or an import profile with
python -X importtime yourfile.py 2> import.log
and show it with
tuna program.prof
Why tuna doesn't show the whole call tree
The whole timed call tree cannot be retrieved from profile data. Python developers made the decision to only store parent data in profiles because it can be computed with little overhead. To illustrate, consider the following program.
import time def a(t0, t1): c(t0) d(t1) return def b(): return a(1, 4) def c(t): time.sleep(t) return def d(t): time.sleep(t) return if __name__ == "__main__": a(4, 1) b()
The root process (
__main__) calls
a() which spends 4 seconds in
c() and 1 second
in
d().
__main__ also calls
b() which calls
a(), this time spending 1 second in
c() and 4 seconds in
d(). The profile, however, will only store that
c() spent a
total of 5 seconds when called from
a(), and likewise
d(). The information that the
program spent more time in
c() when called in
root -> a() -> c() than when called in
root -> b() -> a() -> c() is not present in the profile.
tuna only displays the part of the timed call tree that can be deduced from the profile:
Installation
tuna is available from the Python Package Index, so simply type
pip3 install tuna --user --upgrade
to install or upgrade.
Testing
To run the tuna unit tests, check out this repository and type
pytest
License
tuna is published under the MIT license.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/tuna/ | CC-MAIN-2019-51 | refinedweb | 334 | 63.9 |
Mock SSH server for testing purposes
Project description
mock-ssh-server packs a Python context manager that implements an SSH server for testing purposes. It is built on top of paramiko, so it does not need OpenSSH binaries to be installed.
Sample usage
import os from pytest import yield_fixture import mockssh @yield_fixture() def server(): users = { "sample-user": "/path/to/user-private-key, } with mockssh.Server(users) as s: yield s def test_ssh_session(server): for uid in server.users: with server.client(uid) as c: _, stdout, _ = c.exec_command("ls /") assert stdout.read() def test_sftp_session(server): for uid in server.users: target_dir = tempfile.mkdtemp() target_fname = os.path.join(target_dir, "foo") assert not os.access(target_fname, os.F_OK) with server.client(uid) as c: sftp = c.open_sftp() s(__file__, target_fname, confirm=True) assert os.access(target_fname, os.F_OK)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/mock-ssh-server/ | CC-MAIN-2021-04 | refinedweb | 166 | 54.59 |
This article continues the one published two weeks ago: Top 101 mistakes done by novice programmers C, Top 101 mistakes done by novice programmers C – part 2 and Top 101 mistakes done by novice programmers C – part 3
13. Pointers mistakes
13.a Not assigning a pointer to memory address before using it
The following is the most common mistake:
int *x;
*x = 100;
x must be allocated (consider using a malloc)
13.b Not releasing memory
Normally I test my algorithms using a simple program, for example:
int main(int arc, char **argv)
{
char *myPointer;
myPointer = (char *)malloc(100);
// some code working on the pointer….
// ….
exit(0);
}
so when I've tested my code I can copy and paste into my real project…… In this case when the execution of the program reaches the exit statement, the OS release the allocated memory, when I copy the code in a function nobody will take care of this problem, so I MUST add a free statement as follows
int function(void)
{
char *myPointer;
myPointer = (char *)malloc(100);
// some code working on the pointer….
// ….
free(myPointer);
return;
}
13.c Assigning Value to Pointer Variable
int * ptr , m = 100 ;
ptr = (int *) malloc(1);
ptr = m ; // Error on This Line
the correct way is:
int * ptr , m = 100 ;
ptr = (int *) malloc(1);
*ptr = m ; // or ptr = &m; depending on what do you want to do
13.d Not Dereferencing Pointer Variable
int * ptr , m = 100 ;
ptr = &m ;
printf("%d",ptr); // Error on this Line
In the above code you are print the address of m, not its content. To print the content 9you have to do:
int * ptr , m = 100 ;
ptr = &m ;
printf("%d",*ptr);
13.e Many C library functions malloc's memory which MUST be freed: i.e.: strdup(),
char *oldString = "Old String";
char *newStrig = strdup(oldString);
...
...
...
...
free(newString);
13.f Free only allocated pointers.
Take a look to the following code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p;
int i=0;
printf("%d\n", i);
free(p);
exit(0);
}
the p pointer has not been allocated, so when you'll execute the program it will crash and produce a core dumped message.
Part five in the next fifteen days.
Gg1 | http://www.xappsoftware.com/wordpress/2012/12/17/top-101-mistakes-done-by-novice-programmers-c-part-4/ | CC-MAIN-2020-10 | refinedweb | 373 | 66.78 |
Pod::PP - POD pre-processor
# normally used via the podpp script require Pod::PP; my $pp = Pod::PP->make( -incpath => ['h', 'h/sys'], -symbols => { DIR => "/var/www", TMPDIR => "/var/tmp" }, ); $pp->parse_from_filehandle(\*STDIN); $pp->parse_from_file("file.pp");
The
Pod::PP module is a POD pre-processor built on top of
Pod::Parser. The helper script podpp provides a pre-processor command for POD, whose interface is very much like cpp, the C pre-processor. However, unlike C, the
Pod::PP processing is not normally invoked when parsing POD.
If you wish to automate the pre-processing for every POD file, you need to write
.pp files (say) instead of
.pod files, and add the following make rules to your
Makefile:
PODPP = podpp PP_FLAGS = .SUFFIXES: .pp .pod .pp.pod: $(PODPP) $(PP_FLAGS) $< >$*.pod
Those teach make how to derive a
.pod from a
.pp file using the podpp pre-processor.
Pod::PP uses the
P<> notation to request symbol expansion. Since it processes text, you need to tag the symbols to be expanded explicitely. Expansion is done recursively, until there is no more expansion possible.
If you are familiar with cpp, most directives will be easy to grasp. For instance, using the
== prefix to make shorter commands:
==pp include "common.pp" ==pp define DIR /var/www ==pp define TMP /tmp ==pp ifdef SOME_COMMON_SYMBOL ==pp define FOO common foo ==pp else ==pp define FOO P<DIR> ==pp endif
The
== notation is not standard POD, but it is understood by
Pod::Parser and very convenient when it comes to writing things like the above block, because there's no need to separate commands by blank lines. Since the code is going to be processed by podpp anyway, there's no problem, and podpp will always emit legitimate POD. That is, given the following:
==head1 NAME Some data
it will re-emit:
=head1 NAME Some data
thereby normalizing the output. It is guaranteed that after a podpp pass, the output is regular POD. If you make errors in writing the
Pod::PP directives, you will not get the expected output, but it will be regular POD.
The pre-processing directives can be given in two forms, depending on whether you wish to process your POD files containing
Pod::PP directives with the usual POD tools before or after having run podpp on them:
=for ppform before all commands, you ensure that regular POD tools will simply ignore those. This might result in incorrect processing though, if you depend on the definition of some symbols to produce different outputs (i.e. you would need a podpp pass anyway).
=ppform before all commands, you require that podpp be run on your file to produce regular POD that can be then processed via regular POD tools.
Here are the supported directives, in alphabetical order:
=pp commentcomment
A comment. Will be stripped out upon reading.
When
Pod::PP encounters an error whilst processing a directive, e.g. an include with a file not found, it will leave a comment in the output, albeit using the
=for pp form so that it is properly ignored by standard POD tools.
=pp definesymbol [value]
Defines symbol to be value. If there's no value, the symbol is simply defined to an empty value. There may be an arbitrary amount of spaces or tabs between symbol and value.
A symbol can be tested for defined-ness via
=pp ifdef, used in expressions via
=pp if, or expanded via
P<sym>.
=pp elifexpr
Alternate condition. There may be as many
=pp elif as needed, but they must precede any
=pp else directive, and follow a leading
=pp if test. See
=pp if below for the expr definiton.
Naturally, within an
=pp if test, the expression expr is evaluated only if the
if condition was false.
=pp else
The else clause of the
=pp if or
=pp ifdef test.
=pp endif
Closes the testing sequence opened by last
=pp if or
=pp ifdef.
=pp ifexpr
Starts a conditional text sequence. If expr evaluates to true, the remaining up to the matching
=pp elif or
=pp else or
=pp endif is included in the output, otherwise it is stripped.
Within an expression, you may include any symbol, verbatim, and form any legal Perl expression. For instance:
==pp define X 4 ==pp define LIMIT 100 =pp if X*X < LIMIT Include this portion if X*X < LIMIT =pp else Include this portion if X*X >= LIMIT =pp endif
would yield, when processed by podpp:
Include this portion if X*X < LIMIT
since the condition is true with the current symbol values.
You may also use the
defined() operator in tests, as in cpp:
=pp if defined(X) || !defined(LIMIT)
A bad expression will result in an error message, but you must know that your expressions are converted into Perl, and then are evaluated within a
Safe compartment: the errors will be reported relative to the translated Perl expressions, not to your original expressions.
=pp ifdefsymbol
Tests whether a symbol is defined. This is equivalent to:
=pp if defined(symbol)
only it is shorter to say.
=pp ifndefsymbol
Tests whether a symbol is not defined. This is equivalent to:
=pp if !defined(symbol)
but it is shorter to say.
=pp image[<center>] "path"
This directive is not a regular pre-processing directive in that it is highly specialized. It's there because I historically implemented
Pod::PP to pre-process that command in my PODs.
It's a high-level macro, that is hardwired because
Pod::PP is not rich enough yet to be able to support the definition of that kind of macro.
It is expanded into two POD directives: one for HTML, one for text. An example will be better than a lengthy description:
=pp image <center> "logo.png"
will expand into:
=for html <P ALIGN="center"><IMG SRC="logo.png" ALT="logo"></P> =begin text [image "logo.png" not rendered] =end text
The <center> tag is optional, and you may use <right> instead to right-justify your image in HTML.
=pp include"file"
Includes
"file" at the present location, through
Pod::PP. That is, the included file may itself use
Pod::PP directives.
The algorithm to find the file is as follows:
1. The file is first looked for from the location of the current file being processed.
2. If not found there, the search path is traversed. You may supply a search path with the -I flag in podpp or via the
-incpath of the creation routine for
Pod::PP.
3. If still not found, an error is reported.
=pp require"file"
Same as an
=pp include directive, but the
"file" is included only once. The absolute path of the file is used to determine whether it has already been included. For example, assuming we're in file
dir/foo, and that
dir/foo/file.pp exists, the following:
==pp require "file.pp" ==pp require "../dir/file.pp"
will result in only one inclusion of
"file.pp", since both require statements end up requesting the inclusion of the same path.
=pp undefsymbol
Undefines the target symbol.
Pod::PP uses
Log::Agent to emit its diagnostics. The podpp script leaves
Log::Agent in its default configuration, thereby redirecting all the errors to STDERR. If you use the
Pod::PP interface directly in a script, you can look at configuring alternatives for the logs in Log::Agent.
Whenever possible,
Pod::PP leaves a trail in the output marking the error. For instance, feeding the following to podpp:
=pp include "no-such-file"
would print the following error to STDERR:
podpp: error in Pod::PP directive 'include' at "example", line 17: cannot find "no-such-file"
and leave the following trail:
=for pp comment (at "example", line 17): Following "=pp" directive failed: cannot find "no-such-file" =pp include "no-such-file"
which will be ignored by all POD tools.
You will normally don't care, since you will be mostly interfacing with
Pod::PP via the podpp script. This section is therefore only useful for people wishing to use
Pod::PP from within a program.
Since
Pod::PP inherits from
Pod::Parser, it conforms to its interface, in particular for the
parse_from_filehandle() and
parse_from_file() routines. See Pod::Parser for more information.
The creation routine
make() takes the following mandatory arguments:
-incpath=> array_ref
The additional include search path (
"." is always part of the search path, and always the first thing looked at). The array_ref provides a list of directories to look. For instance:
-incpath => ["h", "/home/ram/usr/podpp"]
would add the two directories, in the order given.
-symbols=> hash_ref
Provides the intial set of defined symbols. Each key from the hash_ref is a symbol for the pre-processor:
-symbols => { DIR => "/var/tmp" TMP => "/tmp" }
Given the above, the following input:
dir is "P<DIR>" and tmp is "P<TMP>"
would become after processing:
dir is "/var/tmp" and tmp is "/tmp"
as expected.
The
=pp image directive is a hack. It should not be implemented at this level, but it was convenient to do so.
Raphael Manfredi <Raphael_Manfredi@pobox.com>
This software is currently unmaintained. Please look at:
if you wish to take over maintenance. I would appreciate being notified, so that I can transfer the PAUSE (CPAN) ownership to you.
Pod::Parser(3). | http://search.cpan.org/dist/Pod-PP/PP.pm | CC-MAIN-2017-26 | refinedweb | 1,548 | 64.41 |
My wife playing the simple platformer. She immediately worked out how to break it…
If you’re at all interested in developing video games then you should definitely check out Unity. Unity is a 2D and 3D game engine as well as an IDE and builder tool that makes it possible to make professional caliber games with very little in the way of programming knowledge.
Many of the most popular games on the Play Store were made in Unity, including Tomb Raider: GO, Angry Birds and more. So it may come as a surprise just how easy it is to get started with. Often it’s as simple as dragging and dropping various elements around the screen. This guide will show you how to make a 2D platformer and you should be able to create something basic in a couple of hours.
To learn more about why Unity is great, check out my introduction to Unity post. This will also help you to get set up, but to recap: you need to download Unity 5 itself, Visual Studio for your coding and the Android SDK which will come in handy at the end. You also need to sign up for a free account.
Getting started
Once you’ve downloaded and installed Unity and Visual Studio, you’ll be able to launch the software and select ‘New’ to get started.
You’ll then be taken to the next page where you can choose the name for your project and the directory you want to save your files in. You’ll also be able to decide here if you want your project to be 3D or 2D. For the purposes of this particular guide, you’ll select ‘2D’. Now click ‘Create Project’.
I’m calling my project ‘Rushdy Worm’ which is the name of a character I used to draw – and also the first full game I ever created!
Adding sprites
Once you’ve loaded up your new project, you’ll be greeted with a blank screen like so:
Your windows might be arranged slightly differently but you should always have the same selection to start with. The first thing you’re going to need is the ‘Project’ pane which is down the bottom for me. This is where you can see all the folders containing your various files. Select the ‘Assets’ folder and it will open to the right. Now right click in that folder and select ‘Create > Folder’. You’re going to call this new folder ‘Sprites’. Can you guess what it’s going to contain?
For this first version of the game, I’ve created two sprites: ‘ground’ and ‘rushdy’ which represent the floor tile and the main character respectively. You can use mine by right clicking and saving, or you can create your own (I won’t be offended…). Once you’ve created your ‘Sprites’ folder, you can simply drag and drop sprites there from your file explorer. It’s then a matter of dragging them into your ‘Scene’ pane at which point they become part of the game. This is where you can arrange all your individual elements in a level. You can also drag things around the screen or scroll the page by holding ‘alt’ and dragging. Pinch or use your scroll wheel to zoom in and out. Essentially a ‘scene’ is a level, though in future it might also be a menu page or another screen in the game. You can also use the ‘Game’ view in order to see what your camera will see at the starting point in the level.
Click ‘Play’ now and you’ll be greeted with your character and your ground tile hovering in space. It’s not terribly fun at this point…
Adding physics
Now comes the part where you’re amazed at just how simple and easy Unity makes everything… First, click on your ground tile in the scene view. This will present you with some information in another window called the ‘Inspector’. This tells you the attributes pertaining to that particular game object (like the size and angle) and lets us tweak them to our heart’s desire.
First, you need to choose ‘Add Component’ and then ‘Physics 2D > Box Collider 2D’. This should create a thin green highlight around your ground tile. This will set where the collision detection will begin and end for that object. If you had a more detailed object then you could select ‘Edge Collider’, which would create a less uniform collider.
Now do the same thing for your player sprite. My player sprite is essentially a rectangle, which is going to make life nice and easy for me. I also chose a sprite that faces forward so I can get away without animating him.
At this point, our two objects are now ‘solid’ as far as Unity is concerned but there’s no gravity. To change that, select your main character and choose ‘Add Component’ and then ‘Rigidbody 2D’ which adds 2D physics to your given item. Click play and you’ll see the character drop out of the air and land on the ground. It’s still not that fun but it’s starting to resemble a game…
Adding controls
Most games require some form of input to be fun, so let’s add some controls to our little character. To do this we’re going to try our first bit of code. Don’t worry, it’s pretty easy at this point.
First, create a new folder in Assets and call it ‘Scripts’. Now in this directory, right click and select ‘Create > C# Script’. Call it ‘Controls’ and then double click on it to launch Visual Studio for editing. You will be presented with a screen like this one:
Coding in C# isn’t worlds apart from coding in Java for those who are familiar with it. You will still need to end every line with a semi colon and you still use curly brackets for your ‘IF’ statements and likewise for functions.
The basic bit of structure you’re presented with also makes things quite simple. Anything that happens inside Start will deploy as soon as the related object gets created (for our purposes, this will be when the level/game starts). The Update function meanwhile runs continuously and anything you put in here will happen continuously each time the scene refreshes.
If you’re willing to learn some basic C# then you can start doing all manner of fancy things with your game. But otherwise, you can get by just as easily by borrowing code from other people – either by looking online or by using the ‘Asset Store’ that lets you find scripts, assets, sounds and more created by the community. Some of this is free, some of it you will have to pay for. A surprising number of things don’t require any scripting at all either.
In this case, you can use the code I’ve created to add very simple controls to your character:
public class Controls : MonoBehaviour { public Rigidbody2D rb; public float movespeed; void Start () { rb = GetComponent<Rigidbody2D>(); } void Update () { if (Input.GetKey(KeyCode.LeftArrow)) { rb.velocity = new Vector2(-movespeed, rb.velocity.y); } if (Input.GetKey(KeyCode.RightArrow)) { rb.velocity = new Vector2(movespeed, rb.velocity.y); } } }
Here we are creating a floating point variable called movespeed and making it public so that we can access it outside of this script. We’re also creating a reference to the RigidBody2D that we added to our character and calling that rb. You’ll be able to set the value for your public variables using the inspector for the game object to which the script is attached.
In the ‘Start’ function, we tell Unity that rb is the RigidBody2D component attached to our game object. In ‘Update’ we’re listening for the left arrow or right arrow input and then adding velocity to that rigidbody. Basically, we’re telling the physics attached to our player that it now has some momentum heading either left or right.
Now all you need to do is to head back to Unity and drag the ‘Controls’ script onto your player. This is something you’ll need to do a lot – and you’ll find its very easy to forget! Don’t forget to change movespeed to ‘3’ in the inspector either (or whatever speed you like!). Now when you hit play, you’ll be able to control the character left and right with the arrow keys. We’ll be adding touch input later on.
A little polish
Now I’m going to make a few more small changes. First, I’m going to drag my platform from the left corner to the right to make it much wider. I purposefully designed a sprite here that wouldn’t look ‘stretched’ which will make designing levels nice and easy. You can also do this by selecting the resize tool along the top left of the interface, or by changing the scale in the Inspector. Choices.
Next, I’m going to take my camera in the left ‘hierarchy’ pane and drag it to drop it on my player game object (called ‘rushdy’ in my case). This makes the ‘Main Camera’ a ‘child’ of Rushdy (congratulations, it’s a baby camera!). Essentially, this means that the camera will now move when the character moves. I’ve also dropped my camera right into the center of the player by clicking on it in the scene view and then selecting the move tool in the top left. This now allows us to walk past the right of the screen without losing sight of the character.
When you create a real game, you’ll want to give your camera more complex controls to enhance the gameplay. For now though, this will suffice. (If you want to learn more about 2D cameras, check out this article on The Theory and Practice of Cameras in Side-Scrollers.)
Except there’s a small issue we need to change. Right now, if you walk off the edge of the platform the character will spin out of control and the camera will spin with them! This makes for a rather nauseous experience, so click on your player character and then tick ‘Freeze Position Z’ under ‘RigidBody 2D > Constraints’. Now Rushdy will fall without spinning around – like a normal platform character. Rushdy is a weird enough thing to begin with; he doesn’t need any more quirks for the other game characters to tease him about…
I’ve also decided to add a background to my scene so that it looks a little nicer. I’m borrowing a ‘stars’ backdrop I created for another game and I’ve simply added this the same way I added the other sprites. The only difference is that I’ve set the scale (in the Inspector) to 10×10 and I’ve set the ‘order in layer’ to -1. This means that it will be drawn behind the other elements on the screen.
I’ve also set the ‘Z’ position to 20 and changed the Main Camera slightly by setting ‘Projection’ to ‘Perspective’. This means that the background will now appear further away than the foreground and thus move more slowly as we scroll. Thus we have depth.
Adding touch controls
This hardly qualifies as a game at this point, but we now have a little character that can move around the screen, which is more than enough to impress our Mums. The next step then is to install this on our Android devices – but before we can do that we need to add some touch-screen controls.
(For those wondering… yes the current system would work with a Bluetooth keyboard!)
To add these controls, go to GameObject and select ‘UI > Image’. When you do this, you’ll create a new image and at the same time you’ll create a ‘canvas’ which is a floating layer that will appear over your scene and house your UI elements (controls, health, lives etc.). Anything that you want to act as a UI element needs to be a child of your canvas.
Select your new image and use the button in the top left of the inspector to anchor it to the bottom right of the screen. Now copy and paste that image and anchor the new one to the bottom left. I’ve created an arrow sprite too which I dragged and dropped into the ‘Source Image’ box in the inspector. I used the same arrow image for both but set the scale to ‘-1’ for the left one so that it would appear reversed.
You also need to make sure these arrows are the right size and in the right position. You can check this by clicking play to see how it looks. We’re also going to add both of these arrows to an additional ‘container’ object by right clicking on the canvas and choosing ‘Create Empty’. Anchor this object to the bottom and click ‘stretch’ to make it as wide as the screen. Now drag your two arrows into here.
I called my container ‘TouchController’ because I lack imagination. Don’t worry if it takes a little fiddling around to get everything right. By the end, it should all look something like this:
Next we’re going to add two new public booleans (true or false variables) to our Controls script called moveright and moveleft. Then add this snippet of code to the Update function:
if (moveright) { rb.velocity = new Vector2(movespeed, rb.velocity.y); } if (moveleft) { rb.velocity = new Vector2(-movespeed, rb.velocity.y); }
Make sure when you do this that your code isn’t inside any of your ‘if’ statements. Now, every time the scene refreshes our character will move left or right accordingly so long as the relevant boolean is ‘true’. We have to do it this way because we can only detect the buttons going down or being released – we can’t check if they’re currently being held.
Your code should look like this:
Next up, we’re creating another new script in our scripts folder and calling it ‘Touch’. Don’t worry, we’re nearly there!
using UnityEngine; using System.Collections; public class Touch : MonoBehaviour { private Controls player; void Start() { player = FindObjectOfType<Controls>(); } public void LeftArrow() { player.moveright = false; player.moveleft = true; } public void RightArrow() { player.moveright = true; player.moveleft = false; } public void ReleaseLeftArrow() { player.moveleft = false; } public void ReleaseRightArrow() { player.moveright = false; } }
Notice that this code is referencing the public booleans attached to our Controls script called moveright and moveleft. We have created functions to set these as true/false and now we just have to map them to our controls.
Drag the ‘Touch’ scrip you just created and drop it on the ‘TouchController’ empty object (which is a child of your canvas and parent of your two arrow images remember). Now select your right button and in the inspector go to ‘Add Component > Event > Event Trigger’. Create two event triggers by selecting ‘Add New Event Type’ and make these ‘Pointer Down’ and ‘Pointer Up’. These represent the images being clicked and released respectively.
Next drag and drop the TouchController container (not the script) into the box that says ‘None (Object)’. You can now choose a function by select ‘Touch’ (your script) from the drop down menu and then choosing the Public Void you created for that purpose. So for your ‘Pointer Down’ event trigger on the right arrow, you want to pick the public void RightArrow and for ‘Pointer Up’ you need to choose ReleaseRightArrow. This will then run the code you added to that function and edit your moveright and moveleft booleans accordingly. Do the same thing for the left arrow.
Now if everything works correctly, then you can run the game and you should be able to control the character by either clicking on the on-screen controls or using the keyboard!
Whew! Now all that is left is for us to create an APK…
Creating an APK
To create our APK, we need to first make sure we’ve saved our scene which you can do by clicking on ‘File’ and then ‘Save Scene’. This will automatically save the scene in your Assets folder but for the sake of organization you may want to also create a ‘Scenes’ folder to drop them into.
Now select ‘File > Build Settings’ and make sure to drag the scene you just saved into ‘Scenes In Build’. When you have multiple scenes, the one at the top will be the one that shows first when you load your app (so this will eventually be a menu or a title screen). You’ll also need to select your platform here, which will be ‘PC, Mac and Linux Standalone’ by default. Select ‘Android’ and then click ‘Switch Platform’.
Now press ‘Player Settings’ and you’ll see a bunch more options open up in the Inspector. This is where you can create your private key sign and package name (‘bundle identifier’) just as you would do in Android Studio. You’ll also need to show Unity where your Android SDK is located, which you do by going to ‘Edit > Preferences > External Tools’. Make sure when choosing the API Level that you have the correct Android Platform installed.
Click ‘Build’ to create your APK and you can try it out on your device!
You can try it for yourself by checking out the project on GitHub. And you can also find the APK there if you don’t want to make it yourself. Then you can have hours of fun moving left and right against a star-filled sky. We could always claim this is an artistic indie game?
It’s not hard though to imagine the few extra elements this would need to become a fun experience. So next time I’ll be discussing how to add multiple levels, lives, collectibles and who-knows what else. Stay tuned! | https://www.androidauthority.com/create-a-2d-platformer-for-android-in-unity-693550/ | CC-MAIN-2020-16 | refinedweb | 2,996 | 78.79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.