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
|
|---|---|---|---|---|---|
How to Prevent Instances in Java
Sometimes you want to create a Java class that can’t be instantiated at all. Such a class consists entirely of static fields and methods. A good example in the Java API is the
Math class.
Its methods provide utility-type functions that aren’t really associated with a particular object. You may need to create similar classes yourself occasionally. You might create a class with static methods for validating input data, for example, or a database access class that has static methods to retrieve data from a database. You don’t need to create instances of either of these classes.
You can use a simple trick to prevent anyone from instantiating a class. To create a class instance, you have to have at least one public constructor. If you don’t provide a constructor in your class, Java automatically inserts a default constructor, which happens to be public.
All you have to do to prevent a class instance from being created, then, is provide a single private constructor, like this:
public class Validation
{
private Validation() {} // prevents instances
// static methods and fields go here
}
Now, because the constructor is private, the class can’t be instantiated.
Incidentally, the
Math class uses this technique to prevent you from creating instances from it. Here’s an actual snippet of code from the
Math class:
public final class Math {
/**
* Don’t let anyone instantiate this class.
*/
private Math() {}
If this trick is good enough for the folks who wrote the
Math class, it’s probably good enough for you.
|
https://www.dummies.com/programming/java/prevent-instances-java/
|
CC-MAIN-2019-13
|
refinedweb
| 262
| 53.1
|
Opened 10 years ago
Closed 8 years ago
Last modified 8 years ago
#2782 closed defect (fixed)
mod_python's request.META["SERVER_PORT"] is always set to 0
Description (last modified by )
I have found small bug in core/handlers/modpython.py.
Namely,
request.META["SERVER_PORT"] under mod_python is always set to 0.
This is because it's set to
self._req.server.port in modpython.py, on line 88.
mod_python's docs say --
port Integer. TCP/IP port number. Same as CGI SERVER_PORT. This member appears to be 0 on Apache 2.0, look at req.connection.local_addr instead (Read-Only)
So I think it should be:
'SERVER_PORT': str(self._req.connection.local_addr[1]),
Because
self._req.connection.local_addr[1] is an integer, I think it should be string as other headers are.
Change History (13)
comment:1 Changed 10 years ago by
comment:2 Changed 10 years ago by
(In [3866]) Fixed #2782 -- Fixed incorrect request.METASERVER_PORT? for mod_python.
comment:3 Changed 8 years ago by
This bug is not fixed, or no longer fixed, in Django version=[0.97-pre-SVN-unknown]. I have applied the fix myself, and it works fine. Please, apply the fix to the SVN repository file again.
Django Version
$ python manage.py --version
0.97-pre-SVN-unknown
FILE: django/core/handlers/modpython.py
Change:
'SERVER_PORT': self._req.server.port,
TO...
'SERVER_PORT': str(self._req.connection.local_addr[1]),
comment:4 Changed 8 years ago by
This is not fixed in the 1.0 release.
comment:5 Changed 8 years ago by
The fix made in r3866 was reverted in r3927 because of the report it caused a crash in #2865. Now, that crash actually looks like a mod_python built with the wrong apr or something -- but to put this back in I think we need some evidence that it won't cause a crash with current levels of Apache/mod_python generally used on Macs. Anyone got a Mac to test on?
comment:6 Changed 8 years ago by
In #2865, most likely problem was that mod_python version used was compiled against a newer version of Apache/APR than what it was then loaded in to.
Even at that time, mod_python 3.2.8 was old as well and definitely not the latest version. Anyone still using mod_python 3.2.X should be shot as it has lots of bugs in it. Latest mod_python 3.3.1 has lots less bugs and not in areas where most would tread. ;-)
comment:7 Changed 8 years ago by
On Leopard (Mac OSX 10.5.5), mod_python 3.3.1 built for bundled-out-of-the-box Apache 2.2.8/Python 2.5.1,
I tested the following urls.py:
# coding: utf-8 """ This urls.py should yield following results: Pre-#2782 ( ModPythonRequest._req.server.port ): 0 Post-#2782 ( ModPythonRequest._req.connection.local_addr[1] ): 80 """ from django.conf.urls.defaults import * from django.http import HttpResponse from django.template import Template, Context urlpatterns = patterns('', (r'', lambda request: HttpResponse( Template("Pre-#2782 ( ModPythonRequest._req.server.port ): " \ "{{ pre2782 }}\n" \ "Post-#2782 ( ModPythonRequest._req.connection.local_addr[1] ): "\ "{{ post2782 }}") .render(Context(dict(pre2782=request._req.server.port, post2782=request._req.connection.local_addr[1]))), mimetype='text/plain')), )
The result yielded:
Pre-#2782 ( ModPythonRequest._req.server.port ): 0 Post-#2782 ( ModPythonRequest._req.connection.local_addr[1] ): 80
Seems to be working fine.
comment:8 Changed 8 years ago by
Interesting. The problem is not recreatable on the first box I tried (a Windows test box). It's running Apache/2.2.8 (Win32) mod_python/3.3.1 Python/2.5.2, and the current SVN code correctly sets the port number. Since the doc referenced mentions Apache 2.0, I figured it was fixed by Apache 2.2. However after you reported seeing port 0 returned on Apache 2.2.8, I tried it on my Linux box, running Apache/2.2.4 (Ubuntu) mod_python/3.3.1 Python/2.5.1 and sure enough it reports port 0 with the current code. So it seems more common than not (granted based on an unscientific 3-random-machine test) that the existing code doesn't work. In neither case I tried did the patch code cause any problem, so I'm inclined to put it back in.
comment:9 Changed 8 years ago by
comment:10 Changed 8 years ago by
comment:11 Changed 8 years ago by
Malcolm, OK, so I was going to re-commit the old fix, but I tested it first, with this little test view I had used earlier:
def portno(request): return HttpResponse("Port number in request is %d" % request.META["SERVER_PORT"])
This fails (TypeError) with the previously-applied fix because it casts to a str for consistency with the other headers. However until now this particular header has been an int, so I think it now needs to stay that way? Or because till now it has been mostly useless (except on this Windows machine I've got where the old code does report the real port number) are we OK changing the type? I'm tending to think not, and that we need to keep the same type it has been so far...but wondering if you have a different opinion?
(And I'd be interested in one of you magic crystal balls that reports who's who when posting anonymously...)
Fixed formatting of description.
|
https://code.djangoproject.com/ticket/2782
|
CC-MAIN-2016-44
|
refinedweb
| 900
| 69.28
|
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
The Protium Project talks about Diarmuid Pigott's programming language that I had the opportunity to peek at several years ago and was definitely interesting from a language perspective - the keyword being pasigraphic.
The site, however, has been down for a long time now and Diarmuid (who's been an LtU member for a while) has been unreachable.
Any leads anyone?
G'day everyone
My name is Bruce Axtens. I'm one of the members of The Protium Project, working as a Software/QA Engineer.
Protium is alive and well.
For an idea of where Protium is at, please check out the following postings on my Codeaholic blog: templating, asserting and splitting.
Other recent postings on the blog are related to providing tools for, or testing, the Protium engine itself.
Kind regards,
Bruce.
Great to hear about Protium again! Are you making available any trial downloads now? I'd love to play with it.
Is there a more bottom up or introductory write up available? I checked all the pages except the actual download and the forum, which has some sort of server side scripting error.
If by accessible you mean something to download, sorry, not yet.
If you mean in the sense of a gentle introduction ... well there's the Protium website.
Beyond that, you'll have to wait for me to write something and post it. Diarmuid and I did a "Master Class" early last year. I should find, polish and post that, as it's a good introduction.
hi,
a) if i write in German can it then be turned into English so everybody can write in their own language but still work with people using their own language?
b) but then it sounds like there is either a claim that all languages share some internal way of modeling things so they can all work for Protium, or a claim that each language has its own neat way of looking at the world which can be brought to Protium to make life less robotic. i'm not sure which is claimed and if either one would really work or make sense to me on the face of it.
i'm not trying to be obnoxious, i'm more trying to ask for a simple explanation to break through some terminology on the site which is a little opaque to my simple mind :-)
"Protium's inter-translatability is based on the theory of the Natural Semantics Metalanguage, and draws on the natural problem-solving expressions that every culture has enshrined in their language. It matches this with ideas from the various general purpose programming systems that have been overwhelmed in the past by the bare-bones reductive approach of algorithmically derived languages. This approach to communication of problems draws on the great heritage started by Wilkins and Leibniz in the time of the enlightenment, and which underlies so much of scientific and cultural discourse today."
sincere thanks for any edification.
I tried working through one of the blog posts on web service generation but found the syntax confusing; there was enough going on that it seemed the post assumed background knowledge of the system that I did not have. However, as far as I could tell, the post was about some macro style metaprogramming, so I could not discern what was novel beyond the syntax as the semantics were unclear. If you are not reinventing the wheel, is there some explanation relative to existing work or terminology of the project? If you are, perhaps some insight how?
I find vague. For example, does multilingual just mean namespaces/ontologies, or something stronger out of statistical nlp? Or, as a stretch, that several programming language styles (logic, contraint, data flow, non-algol-like imperative...) are natively implemented? Does context sensitivity imply dynamic scope, staged computation, constraint based systems, reactive & introspective capabilities, a loose parser, ...?
I cannot tell what is novel and what is more about the choice of features, probably because I cannot tell what any of the features concretely are. The intent may be to be opaque at this point, which is fine. Srikumar is excited due to what he saw, but I have no idea over what strictly going by the provided information. A calculus where operations maintain normal form can be claimed pasigraphic, but what's the point? In terms of programming language semantics or more generally, the software design process, what is meant by pasigraphy being featured in this project, or any of the bullet points listed on the language design page? [Maybe Srikumar can be more specific?]
This discussion was premature, so I'll probably just ask again if/when you guys decide to disclose something I'm more capable of understanding but still don't sufficiently comprehend. It seems a lot of work has been put into the project, so good luck!
You may be right that this discussion is premature. Several years back (maybe 3?), Diarmuid gave a demo in Singapore in which I was present. I'll try to recall my impression then, so that at least I can put it behind me until Diarmuid chooses to write/talk/publish more about Protium.
1. Protium is multilingual in the real sense of the word - you can program meaningfully using symbols in any human language. If you glance at the few examples that are on Bruce Axten's blog, you'll see that the heads of terms such as <@DEFVARLIT> consist of combinations of 3-letter instructions - DEF, VAR and LIT in this case. Diarmuid claims that support for such concatenation can be transported meaningfully into any human language. I also felt that its a good idea to let people express programs in their own native language as well. If you believe that language is a tool for thought, supporting world languages can trigger fresh thinking. Code is, in a sense, poetry or literature and every language deserves to have its own body of literature. Protium is the only language that tries to be multilingual as far as I know.
2. I was impressed by the brevity of some of the code I saw. At one point, D showed a fairly complex decision table implemented in under a page of code. Though I didn't understand it line by line, the overall structure was not too difficult to see. I could actually hope to understand it one day. Context sensitivity seemed to be paying off.
3. D's work on HOPL is a truly impressive piece of documentation. If I recall right, that site - with the cross referencing and searching - is run on Protium (my memory is unclear, maybe Bruce Axtens can help clarify). It was clear that D had done his homework :)
There is a reason why math is communicated through symbols.
Ok, I'll bite:
And programming is just math? If that was the case, I would agree. Given a mathematic, imperative, or functional model of computation, then I think natural language wouldn't be very effective and would look like some ugly form of psuedo-code. However, given a more declarative programming model, why not?
I am not against natural language, I am against native language, i.e. the same code looking different according to each person's native language.
If you say 'foo bar' and I say 'bar foo' and we mean the same thing, how are we going to communicate?
So your problem isn't symbols being taken from natural language, it's grammar? Funny thing is the mathematicians change their minds too. Sometime in the last week I was talking to a friend who's revising for exams about which operations varying notations for function application are designed to emphasise or make easy.
And an awful lot of the identifiers in the code I write, and the libraries I use, are derived from my native language...
I work in an international setting (including Greeks, French and recently Norwegians), and I have to say that if we used identifiers taken from our native languages (even if written in latin), the situation would be problematic.
I've seen code written in french and I had a great deal of problem parsing the code, so my opinion is that using multiple languages, even if automatic translation is available, is the wrong way to go.
To quote Spiderman, "with power comes great responsibility." To be honest, most languages are already half-way multilingual. Or, at least for languages with alphabets close to english. What's stopping somebody from naming their variables and functions in french, or spanish, or german? In the end, your problem boils down to "if you add that, it will (might?) be misused in my workplace!"
Think about it from the perspective of somebody from another country. Let's say you're working on a project with 4 other people for in-house purposes. You're going to write it in your language, there's no doubt about that. The only choice in the matter is whether you're able to use your language for everything or just for variable/function names.
maybe doing something which looks natural but isn't that completely free-form and thus impossible to implement?
.. so I can read/write "foo bar" and you can read/write "bar foo"?
Unfortunately, it will not.
For example, imagine a mailing list for a library based on such a language...how would it be possible to exchange comments on pieces of code, if we speak different language?
I don't see using English as a problem. No one has been bothered by it, from what I have seen so far.
... although mathematicians certainly use symbols as shorthand and for manipulation.
For example, consider the Heine-Borel theorem:
For a subset S of Euclidean space Rn, the following two statements are equivalent:
S is closed and bounded;
S is compact (every open cover of S has a finite subcover).
For a subset S of Euclidean space Rn, the following two statements are equivalent:
In a quick sampling of readily-available statements and proofs of H-B, each of the statements had roughly the same language-to-symbol ratio as the above (mostly language, with a symbol or two thrown in to refer to a previously defined entity). There was more variation in the proofs, ranging from roughly half-and-half (statements in language, sprinkled with symbolic illustrations or abbreviation) to almost entirely verbal explanations.
While many mathematical activities are performed using symbols, my experience is that Mathematics is frequently communicated in language. The above (totally unscientific) experiment is consistent with that experience.
I certainly believe that symbols and diagrams have tremendous economy and expressive power. But asking the author of a diagram or line of symbols, "What does that mean?", (again, in my experience) is more likely to produce a burst of language than simply another diagram or line of symbols.
Okay, here's the link for the first of the two Master Class postings.
Shall have the next posting ready by tomorrow or the day after, God willing.
G'day everyone.
The second half of the Master Class is up for your perusal.
|
http://lambda-the-ultimate.org/node/2586
|
CC-MAIN-2018-39
|
refinedweb
| 1,878
| 62.38
|
COMPANHIA BRASILEIRA CARBURETO DE CALCIO - CBCC, ET AL., PLAINTIFFS,v.APPLIED INDUSTRIALMATERIALS CORP., ET AL., DEFENDANTS.
The opinion of the court was delivered by: Rosemary M. Collyer United States District Judge
MEMORANDUM OPINION
In 1992, certain participants in the U.S. ferrosilicon*fn1
industry filed an anti-dumping petition with the
International Trade Commission ("ITC"), causing the ITC to impose
import duties on foreign producers of ferrosilicon and in turn causing
Plaintiffs, who are foreign producers, to withdraw from the U.S.
market. Subsequently, the Department of Justice investigated, charged,
and convicted U.S. ferrosilicon producers of price fixing. Based on
the price fixing convictions, the ITC reviewed its decision to impose
duties on foreign producers, and in 1999, the ITC reversed itself. In
2001, Plaintiffs brought these consolidated cases against the
following U.S. ferrosilicon producers: CC Metals & Alloys, Inc. ("CC
Metals"); Elkem Metals, Inc. ("Elkem"); and Applied Industrial Materials Corporation
("AIMCOR").*fn2 Plaintiffs allege that CC Metals,
Elkem, and AIMCOR (collectively "Defendants") conspired to file
fraudulent antidumping petitions with the ITC in violation of the
Sherman Antitrust Act, 15 U.S.C. § 1, and the Racketeer Influenced and
Corrupt Organizations Act ("RICO"), 18 U.S.C. § 1962(c) & (d).
Defendants filed a joint memorandum in support of their separate motions to dismiss. They argue lack of personal jurisdiction, the statute of limitations, lack of standing, and failure to state a claim. As explained below, the motions will be denied.
I. FACTS
A. Factual Background
In May 1992, AIMCOR, American Alloys Inc., Globe Metallurgical Inc. ("Globe"), and unions representing Elkem and CC Metals employees petitioned the ITC to impose import tariffs on foreign ferrosilicon for alleged unfair "dumping" of those products at low prices in the United States. Compl. [Dkt. 1] ¶ 20;*fn3 Opp'n [Dkt. 114], Ex. A ("1999 ITC Decision") at 13. The ITC was persuaded, and the Department of Commerce imposed duties on ferrosilicon from various foreign countries in 1993 and on ferrosilicon from Brazil in 1994. This allegedly caused Plaintiffs, Brazilian ferrosilicon producers,*fn4 to withdraw from the U.S. market.
Beginning in 1993, the Department of Justice investigated the domestic silicon products industry for illegal price fixing. That investigation resulted in a guilty plea and two convictions. On September 22, 1995, Elkem pleaded guilty to conspiracy to engage in price fixing; on April 18, 1996, American Alloys pleaded guilty to the same charge; and on March 17, 1997 CC Metals' predecessor (SKW) and its senior vice president (Charles Zak) were convicted of the same charge.*fn5
As a result of the criminal case, in 1998, Plaintiffs requested that the ITC review its ruling on the antidumping petition. The ITC did so and in August of 1999 reversed its prior decision. See 1999 ITC Decision. In 2001, Plaintiffs brought these consolidated cases alleging that the Defendants conspired to file fraudulent antidumping petitions with the ITC, causing the imposition of antidumping duties that harmed Plaintiffs. The Complaint alleges that Defendants violated section 1 of the Sherman Antitrust Act, 15 U.S.C. § 1 (Count 1) as well as RICO, 18 U.S.C. § 1962(c) & (d) (Counts II and III).*fn6
B. Procedural Background
These consolidated cases were stayed while the 1999 ITC Decision lifting the import tariffs was appealed. After almost ten years of litigation, the Court of International Trade and the Federal Circuit both affirmed. See Elkem Metals Co. v. United States, No. 99-00627, 2008 WL 4097463 (C.I.T. Sept. 5, 2008) (affirming the ITC's fourth remand determination),aff'd without op., No. 2009-1007, 2009 WL 1285837 (Fed. Cir. May 11, 2009).
The cases here then resumed. In 2010, this Court dismissed the case for lack of personal jurisdiction over the Defendants, holding that the government contacts doctrine barred Plaintiffs from relying on Defendants' participation in the ITC proceedings as a basis for personal jurisdiction.*fn7 Plaintiffs appealed to the D.C. Circuit. The Circuit certified to the D.C. Court of Appeals the question of whether, under District of Columbia law, a petition sent to a federal government agency in the District provides a basis for establishing personal jurisdiction over the petitioner when the plaintiff has alleged that the petitioner fraudulently induced unwarranted government action against the plaintiff. Companhia Brasileira Carbureto de Calcio v. Applied Indus. Materials Corp., 640 F.3d 369, 373 (D.C. Cir. 2011). When the D.C. Court of Appeals answered in the affirmative, see Companhia Brasileira Carbureto de Calcio v. Applied Indus. Materials Corp., 35 A.3d 1127 (D.C. 2012), the D.C. Circuit vacated the judgment of this Court with regard to personal jurisdiction and remanded for further proceedings. Companhia Brasileira Carbureto de Calcio v. Applied Indus. Materials Corp., 464 Fed. Appx. 1, 2012 WL 555650 (D.C. Cir. Feb. 10, 2012).*fn8
Hence, jurisdiction returned to this Court. Elkem and CC Metals immediately moved to dismiss for lack of personal jurisdiction. The Court denied the motion. See Order [Dkt. 109]; Op. [Dkt. 110]. Now, all remaining Defendants (Elkem, CC Metals and AIMCOR) have moved to dismiss, arguing lack of personal jurisdiction, the statute of limitations, lack of standing, and failure to state a claim. Dismissal is not warranted.
II. LEGAL STANDARD
A. Rule 12(b)(1)
Pursuant to Federal Rule of Civil Procedure 12(b)(1), a defendant may move to dismiss a complaint, or any portion thereof, for lack of subject-matter jurisdiction. Fed. R. Civ. P. 12(b)(1). When reviewing a motion to dismiss for lack of jurisdiction, a court must review]court accept plaintiff's legal conclusions." Speelman v. United States, 461 F. Supp. 2d 71, 73 (D.D.C. 2006). both an Article III and a statutory requirement. Akinseye v. Dist. of Columbia, 339 F.3d 970, 971 (D.C. Cir. 2003). The party claiming subject matter jurisdiction bears the burden of demonstrating that such jurisdiction exists. Kokkonen v. Guardian Life Ins. Co. of America, 511 U.S. 375, 377 (1994); Khadr v. United States, 529 F.3d 1112, 1115 (D.C. Cir. 2008).
B. Rule 12(b)(6)
|
http://dc.findacase.com/research/wfrmDocViewer.aspx/xq/fac.20120820_0000742.DDC.htm/qx
|
CC-MAIN-2017-13
|
refinedweb
| 1,013
| 50.33
|
Hi,
I have got a task to work in an existing project which is half done, and i have to do another half, i have got the source code of PHP from existing project which is write in MVC architecture , but i am not familiar at all with MVC architecture , therefore it is difficult for me to make any changes and sometime i even cant recognize which files/how should i change, since it is in MVC architecture therefore the structure of viewing any objects is bit different to me
do you have any tips for me please ?
Does it use an existing 3rd-party MVC framework (CodeIgniter, CakePHP, Symfony, etc.) or is it a custom framework?
"Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch
How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)
My Blog
cwrBlog: simple, no-database PHP blogging framework
yes, i think so, it is done with Phpstorm , but i dont know which tools exactly has been used but before most of the code code there is extension like that : \mvc\ImageHide::$view = ... ;
it has been done with phpstorm, and before most of the code there is extension like : \mvc\SecSite::$contents['second'] = "Image";
for example , normally if i want to add a new name into a form , then i can simple add like Username:<br />
<input type="text" name="username" value=...
but in my file i need to do that like : mvc\SecSite::$contents['second'] = "Username ";
its too difficult for me to go through all the codes and made changes
have you any suggestion please ?
It may be time to read up on PHP namespaces.
Hi, how could i learn MVC design pattern in PHP?
Have you tried Google yet?
APress has a book on PHP/MVC:
And again, if you are using a specific 3rd-party MVC framework, assuming it's one of the several popular ones, there are bound to be books, forums, tutorials, etc. dedicated specifically to that framework.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Forum Rules
|
http://www.webdeveloper.com/forum/showthread.php?267345-Simple-question-about-adding-up-numbers-in-a-text-file&goto=nextnewest
|
CC-MAIN-2017-30
|
refinedweb
| 353
| 64.14
|
0
Hi it's my first post here!
I've got a question using active x in vc++. What i have done yet:
i successfully imported a active x dll and created an object of the class in the dll. so everything works fine.
now my problem is that i have a exe file. so i imported the exe file instead of the dll and compiled it. A tlh and tli file was created with the correct id's. here is some code where i get bad return values:
hresult=CLSIDFromProgID(OLESTR("namespace.class"), &clsid); //retrieve CLSID of component - i get s_ok hresult=CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,__uuidof(_class),(LPVOID *) &t); // here it returns that the class is not registered
so i looked into my registry and at ole-com object viewer and my exe is definitely registered.
i dont know what to do now hope to get some ideas.
thx in advance.
lucky greetings from germany.
|
https://www.daniweb.com/programming/software-development/threads/281245/problem-using-activex-in-c
|
CC-MAIN-2016-40
|
refinedweb
| 157
| 67.96
|
I'm not familiar with Python.
Could anyone help me to convert the following 2 functions into Matlab or languages like C#, C++ or pascal?
- Code: Select all
def nabla(I):
h, w = I.shape
G = np.zeros((h, w, 2), I.dtype)
G[:, :-1, 0] -= I[:, :-1]
G[:, :-1, 0] += I[:, 1:]
G[:-1, :, 1] -= I[:-1]
G[:-1, :, 1] += I[1:]
return G
def nablaT(G):
h, w = G.shape[:2]
I = np.zeros((h, w), G.dtype)
# note that we just reversed left and right sides
# of each line to obtain the transposed operator
I[:, :-1] -= G[:, :-1, 0]
I[:, 1: ] += G[:, :-1, 0]
I[:-1] -= G[:-1, :, 1]
I[1: ] += G[:-1, :, 1]
return I
Thanks a lot!
|
http://www.python-forum.org/viewtopic.php?p=14470
|
CC-MAIN-2016-40
|
refinedweb
| 122
| 93.85
|
For this project you'll just need a BBC micro:bit, as this comes with an accelerometer, commonly used in mobile devices to determine device orientation and screen rotation. In this tutorial we shall use the micro:bit as an input device that reacts to gestures.
It's worth checking out our how to get started with the BBC Micro Bit guide if you haven't read that before you start on this project.
We begin in the Mu editor and as always our first line imports the micro:bit library:
from microbit import *
Now we use an infinite loop to contain the code that we wish to run while True.
The accelerometer embedded in the micro:bit has its own series of functions that can be used to query the position of the board in space. We can detect the full x,y and z co-ordinates of the board for fine control but there are times where we do not need such precision, and that is where gestures provide a quick solution.
Gestures are motions that have been predetermined, for example shaking, tilting and flipping the micro:bit. We can use these gestures for simple input and in this project we're going to use a conditional statement that will check to see which gesture has been made and react accordingly.
The first test is to see if the accelerometer has been tilted upwards. The output from this test is either True or False, but if True then the code indented below is activated. Clearing the screen before scrolling text across the micro:bit LED matrix. Lastly there is a 0.1 second pause before the code checks again.
First, type
if accelerometer.was_gesture('up'):
Then type the following, making sure each line is indented by pressing the Tab key on your keyboard.
display.clear()
display.scroll("Dogs cannot look up")
sleep(100)
Our next test is called "Else If.." abbreviated in the Python coding language to "elif". In this test we check to see if the micro:bit has been pointed towards the floor. First type:
elif accelerometer.was_gesture('down'):
Then again make each following line indented using the Tab key.
display.clear()
display.scroll("I feel sick")
sleep(100)
We repeat this process for two more tests that will cover tipping the micro:bit left and right. The syntax for this code is identical to the down gesture, but refers to 'left' and 'right'.
Our last gesture is a shaking motion, which when detected will trigger the final section of code to be activated. Write:
elif accelerometer.was_gesture('shake'):
Then underneath, again with each line indented:
display.clear()
display.scroll("Stop shaking me!")
sleep(100)
With the code now complete, save your work and then click on Flash to flash the code on to the attached micro:bit. After the yellow LED on the reverse of the micro:bit stops flashing you are ready to use the controller.
Start by tipping the micro:bit forwards, backwards and side to side. Last, shake the micro:bit to test the shake gesture.
- Enjoyed this article? Expand your knowledge of Linux, get more from your code, and discover the latest open source developments inside Linux Format. Read our sampler today and take advantage of the offer inside.
|
http://www.techradar.com/how-to/computing/how-to-use-the-bbc-micro-bit-accelerometer-1317568
|
CC-MAIN-2017-04
|
refinedweb
| 548
| 64.2
|
When you use the
--pch command-line option,
automatic PCH processing is enabled. This means that the compiler
automatically looks for a qualifying PCH file, and reads it if found.
Otherwise, the compiler creates one for use on a subsequent compilation.
When the compiler creates a PCH file, it takes the name of
the primary source file and replaces the suffix with
.pch.
The PCH file is created in the directory of the primary source file,
unless you specify the
--pch_dir option.
See Ordering command-line options for more information.
The PCH file contains a snapshot of all the code that precedes
a header stop point. Typically, the header
stop point is the first token in the primary source file that does
not belong to a preprocessing directive. In the following example,
the header stop point is
int and the PCH file
contains a snapshot that reflects the inclusion of
xxx.h and
yyy.h:
#include "xxx.h" #include "yyy.h" int i;
You can manually specify the header stop point with
#pragma
hdrstop. You must place this before the first token that
does not belong to a preprocessing directive. In this example, place
it before
int. See Controlling PCH processing for more information.
If the first non-preprocessor token, or a
#pragma
hdrstop, appears within a
#if block,
the header stop point is the outermost enclosing
#if.
For example:
#include "xxx.h" #ifndef YYY_H #define YYY_H 1 #include "yyy.h" #endif #if TEST int i; #endif
In this example, the first token that does not belong to a
preprocessing directive is
int, but the header
stop point is the start of the
#if block containing
it. The PCH file reflects the inclusion of
xxx.h and,
conditionally, the definition of
YYY_H and inclusion
of
yyy.h. It does not contain the state produced
by
#if TEST.
A block
or a
#define that is started within a header
file.
The processing that precedes the header stop point must not have produced any errors.
Warnings and other diagnostics are not reproduced when the PCH file is reused.
No references to predefined macros
__DATE__ or
__TIME__ must
appear.
No instances, the
#line preprocessing
directive must appear.
#pragma no_pch must not appear.
The code preceding the header stop point must have introduced a sufficient number of declarations to justify the overhead associated with precompiled headers.
More than one PCH file might apply to a given compilation. If so, the largest is used, that is, the one representing the most preprocessing directives from the primary source file. For instance, might be created.
In automatic PCH processing mode the compiler indicates that a PCH file is obsolete, and deletes it, under the following circumstances:
if the PCH file is based on at least one out-of-date header file but is otherwise applicable for the current compilation
if the PCH file has the same base name as the source
file being compiled, for example,
xxx.pch and
xxx.c,
but is not applicable for the current compilation, for example,
because you have used different command-line options.
These describe some common cases. You must delete other PCH files as required.
|
http://infocenter.arm.com/help/topic/com.arm.doc.dui0205h/Chdifcac.html
|
CC-MAIN-2015-48
|
refinedweb
| 525
| 57.87
|
A bit of background
It all began in 2011: Xamarin, now a Microsoft-owned company, came up with a solution for hybrid mobile apps through its signature product, Xamarin SDK with C#. And thus began the revolution of hybrid mobile applications, the ease in writing one code base for many platforms.
Ionic sprung up in 2013 with its first release by Drifty Co. Ionic helped web developers use their existing skills in the growing mobile app industry. In 2015, Facebook used React.js to reinvent it for mobile app developers. They gave us React Native, a completely JavaScript code base relying on native SDK’s.
And these aren’t the only ones, but a few of many hybrid mobile frameworks. More info can be found here.
Now we can watch Google’s turn at putting its fingers in the pie with Flutter.
What is Dart?
Google had its first ever release of Flutter 1.0 last December, after having it in beta mode for over 18 months. Dart is the programming language used to code Flutter apps. Dart is another product by Google and released version 2.1, before Flutter, in November. As it is starting out, the Flutter community is not as extensive as ReactNative, Ionic, or Xamarin.
A while back, I discovered a liking for JavaScript. I was ecstatic to be working on a ReactNative mobile app for my internship. I enjoy coding hybrid mobile apps too, so wanted to give Flutter a try, as I had done Xamarin sometime last year.
At my first glance of Flutter (and Dart), I felt befuddled and couldn’t seem to understand anything. They even had a section on their docs for developers moving from React Native. So, I took to digging deeper on all things Dart.
Dart looks a bit like C and is an object-oriented programming language. So, if you prefer the C languages or Java, Dart is the one for you, and you’ll likely be proficient in it.
Dart is not only used for mobile app development but is a programming language. Approved as a standard by Ecma (ECMA-408), it’s used to build just about anything on the web, servers, desktop and of course, mobile applications (Yes, the same people who standardized our favorites ES5 and ES6.)
Dart, when used in web applications, is transpiled to JavaScript so it runs on all web browsers. The Dart installation comes with a VM as well to run the .dart files from a command-line interface. The Dart files used in Flutter apps are compiled and packaged into a binary file (.apk or .ipa) and uploaded to app stores.
What does coding in Dart look like?
Like most ALGOL languages (like C# or Java):
- The entry point of a Dart class is the
main()method. This method acts as a starting point for Flutter apps as well.
- The default value of most data types is
null.
- Dart classes only support single inheritance. There can be only one superclass for a particular class but it can have many implementations of Interfaces.
- The flow control of certain statements, like if conditions, loops (for, while and do-while), switch-case, break and continue statements are the same.
- Abstraction works in a similar manner, allowing abstract classes and interfaces.
Unlike them (and sometimes a bit like JavaScript):
- Dart has type inference. The data type of a variable need not be explicitly declared, as Dart will “infer ”what it is. In Java, a variable needs to have its type explicitly given during declaration. For example,
String something;. But in Dart, the keyword is used instead like so,
var something;. The code treats the variable according to whatever it contains, be it a number, string, bool or object.
- All data types are objects, including numbers. So, if left uninitialized, their default value is not a 0 but is instead null.
- A return type of a method is not required in the method signature.
- The type
numdeclares any numeric element, both real and integer.
- The
super()method call is only at the end of a subclass’s constructor.
- The keyword
newused before the constructor for object creation is optional.
- Method signatures can include a default value to the parameters passed. So, if one is not included in the method call, the method uses the default values instead.
- It has a new inbuilt data type called Runes, that deal with UTF-32 code points in a string. For a simple example, see emojis and similar icons.
And all these differences are just a few in the many that you can find in the Dart Language tour, which you can check out here.
Dart also has inbuilt libraries installed in the Dart SDK, the most commonly used being:
- dart:core for core functionality; it is imported in all dart files.
- dart:async for asynchronous programming.
- dart:math for mathematical functions and constants.
- dart:convert for converting between different data representations, like JSON to UTF-8.
You can find more information on Dart libraries here.
Using Dart in Flutter
Flutter has more app-specific libraries, more often on user interface elements like:
- Widget: common app elements, like the Text or ListView.
- Material: containing elements following Material design, like FloatingActionButton.
- Cupertino: containing elements following current iOS designs, like CupertinoButton.
You can find Flutter specific libraries here.
Setting up Flutter
So, to get this thing into gear, follow the Flutter docs. It gives details on installing the Flutter SDK and setting up your preferred IDE; mine would be VS code. Setting up VS code with the Flutter extension is helpful. It comes with inbuilt commands, as opposed to using the terminal.
Follow the docs again to create your first app. In my case, run the extension command Flutter: New Project. Afterward, type the project name and pick the destination folder.
If you prefer using the terminal, move to the destination folder of the app. Then use the command
flutter create <app_name> to create the app folder. This generates the entire app folder, including the Android and iOS project folder. To open these folders, use Android Studio and XCode, for building the app.
In the root of the project, you find
pubspec.yaml. This file contains the app's dependencies. This includes both external libraries/modules and assets like images and config files. It works like a
package.json, containing all external modules of the app. To install these packages, enter the package name and version under the
dependencies: section of the
pubspec.yaml. Run the command
flutter packages get. Include the assets of the app inside the
flutter: section of the same file.
The entry point of the app is
main.dart, found inside the lib folder. This folder also contains all Dart classes (app pages or reusable components). On creation of the app, the
main.dart file comes with a simple pre-written code. Before running this code, a device is either connected to the PC, with USB debugging enabled. Afterward, run the command flutter run on the terminal.
A First Look at the Flutter App
The app currently looks like this now:
Building the user interface of a Flutter app makes use of Widgets.
Widgets work in a similar way to React. A widget uses different components to describe what the UI should look like. They can be either Stateful or Stateless. In Stateful components, the widget rebuilds due to state changes, to accommodate the new state.
When we look at the current code for the Home page, we see that it’s a Stateful page. If the counter variable increases, the framework tries to find the least expensive way to re-render the page. In this case, find the minimal difference between the current widget description and the future one. It takes into account the changed state.
The Scaffold class is a material design layout structure and is the main container for the Home page. The AppBar, also a material design element is the title bar found at the top of the page. All other components, like the floating button and two text tags, fall under the body of the page. The Center class is a layout class that centers its child components vertically and horizontally.
The Column class, another layout widget, lists each child element vertically. Each of its child elements is added to an array and put underneath the children: section.
The two texts speak for themselves. The first displays the text ‘You have pushed.’ The second one displays the current value in the
_counter variable.
The FloatingActionButton is part of the Material design widgets. It displays a + icon and triggers the increment of the
_counter variable.
Hot Reloading
Another plus point of using Flutter is the hot reloading feature. It lets you see changes made to the code in real time, without restarting the build process. Type ‘r’ on the same console that you ran the
flutter run command.
Altering the current code
As we can see, when you click the button, the _counter variable value increases. This re-renders the page and the new value is displayed on the body of the page.
I’m going to change that up a bit. For every button click, we will display a custom Card component with the item number.
Creating the Custom Card Component
So, to start off, we make a new .dart file inside the lib folder. I created mine in a subfolder
commonComponents and named it
customCard.dart.
import 'package:flutter/material.dart'; class CustomCard extends StatelessWidget { CustomCard({@required this.index}); final index; @override Widget build(BuildContext context) { return Card( child: Column( children: <Widget>[Text('Card $index')], ) ); } }
This component will be a stateless widget and will only display the value that we send to it, in the Text widget.
Displaying a List of Custom Cards
Import the above component to the
main.dart like so:
import 'commonComponents/customCard.dart';
I then replace the code of the home page body, from the one above to this:
body: Center( child: Container( child: ListView.builder( itemCount: _counter, itemBuilder: (context, int index) { return CustomCard( index: ++index, ); }, ) ), ),
It now displays a List of
CustomCard elements, up to the number of times the button is clicked. The
itemCount is used to define the number of elements the
ListView must display. The
itemBuilder returns the actual item that is displayed.
And that’s a simple example of using Flutter.
In conclusion…
Before my interest turned to JavaScript, I worked with Java. If I had encountered Dart around that time, I might have been able to understand it easier than I did now. All in all, It wasn’t too difficult but took a bit of time to get the hang of it. I could see myself using it in time.
Find the code repo, here.
Find the commit for this post, here.
|
https://www.freecodecamp.org/news/https-medium-com-rahman-sameeha-whats-flutter-an-intro-to-dart-6fc42ba7c4a3/
|
CC-MAIN-2021-31
|
refinedweb
| 1,803
| 66.94
|
Given a string, write a function that will recursively remove all adjacent duplicates.
Example 1
INPUT :
s = “abssbe”
OUTPUT :
“ae”
In the above example, after removing ‘s’ duplicates string becomes “abbe”, this string contains adjacent duplicates, so after removing ‘b’ duplicates the output string is “ae”
Example 2
INPUT :
s = “adaaacad”
OUTPUT :
“adcad”
Time Complexity : O(n^2)
In this method the main idea is to first remove duplicates from the input string and if there are any duplicates in output string remove them recursively until we have no duplicates in output string.
Algorithm
1. Add all the unique characters of input string to output string, if the length of input string is same as output string then stop, else
2. Take the output string as the input string to the function
C++ Program
#include <iostream> #include <string.h> using namespace std; // This function recursively removes duplicates // and returns modified string char* removeAdjDup(char * s, int n) { int i; int k = 0; // To store index of result // Start from second character for (i=1; i< n; i++) { // If the adjacent chars are different //then add to output string if (s[i-1] != s[i]) s[k++] = s[i-1]; else // Keep skipping (removing) characters // while they are same. while (s[i-1] == s[i]) i++; } // Add last character and terminator s[k++] = s[i-1]; s[k] = '\0'; // Recur for string if there were some removed // character if (k != n) removeAdjDup(s, k);// Shlemial Painter's Algorithm // If all characters were unique else return s; } int main() { char str1[] = "abssbe"; cout << removeAdjDup(str1, strlen(str1)) << endl; char str2[] = "adaaacad"; cout << removeAdjDup(str2, strlen(str2)) << endl; }
Time Complexity : O(n)
Algorithm
1. Start from the leftmost character and if there are any duplicates in left corner remove them
2. Now, the first character is different from its adjacent character, recur for the remaining string of length n-1
3. After the recursive call, all the duplicates are removed from the remaining string, call it as rem_str Now, we have first character and rem_str,
a. If first character of rem_str matches with the first character of original string, remove the first character from rem_str.
b. Else if the last removed character in recursive calls is same as the first character of the original string. Ignore the first character of original string and return rem_str.
c. Else, append the first character of the original string at the beginning of rem_str.
4. Return rem_str.
C++ Program
#include <iostream> #include <string.h> using namespace std; // Recursively removes adjacent duplicates from s and returns // new string. last_removed is a pointer to last removed character char* recRemoveAdjDup(char *s, char *last_removed) { // If length of string is 1 or 0 if (s[0] == '\0' || s[1] == '\0') return s; // Remove leftmost same characters and recur for remaining // string if (s[0] == s[1]) { *last_removed = s[0]; while (s[1] && s[0] == s[1]) s++; s++; return recRemoveAdjDup(s, last_removed); } //recursively remove adj duplicates in remaining string char* rem_str = recRemoveAdjDup(s+1, last_removed); //a) If first character of rem_str matches with the first character of original string, //remove the first character from rem_str. if (rem_str[0] && rem_str[0] == s[0]) { *last_removed = s[0]; return (rem_str+1); // Remove first character } //b) If remaining string becomes empty and last removed character // is same as first character of original string. if (rem_str[0] == '\0' && *last_removed == s[0]) return rem_str; //c) If the two first characters of s and rem_str don't match, // append first character of s before the first character of // rem_str. rem_str--; rem_str[0] = s[0]; return rem_str; } char *removeAdjDup(char *s) { char last_removed = '\0'; return recRemoveAdjDup(s, &last_removed); } int main() { char s1[] = "abssbe"; cout << removeAdjDup(s1) << endl; char s2[] = "adaaacad"; cout << removeAdjDup(s2) << endl; return 0; }
|
https://www.tutorialcup.com/interview/string/recursively-remove-adjacent-duplicates.htm
|
CC-MAIN-2020-10
|
refinedweb
| 627
| 52.23
|
The "Hail Mary Cloud" Is Growing
Soulskill posted more than 3 years ago | from the like-a-zombie-chia-pet dept.
.'"
Why Is This The Linux Section?!! (-1, Offtopic)
Anonymous Coward | more than 3 years ago | (#30106722)
I don't see any relevant of this to Linux whatsover.
Are you guys really running out of news to put in there?
Re:Why Is This The Linux Section?!! (2, Informative)
Suzuran (163234) | more than 3 years ago | (#30107338)
Re:Why Is This The Linux Section?!! (0)
Anonymous Coward | more than 4 years ago | (#30113618)
SSH is Linux specific? That is "Score:4, Informative"?
Re:Why Is This The Linux Section?!! (1)
Suzuran (163234) | more than 4 years ago | (#30114188)
Re:Why Is This The Linux Section?!! (1)
jabelli (1144769) | more than 4 years ago | (#30119492)
Um, what about this [itefix.no] ? Or would you say that cygwin counts as "unix?"
What has to happen? (1, Flamebait)
Opportunist (166417) | more than 3 years ago | (#30106740):What has to happen? (0)
Anonymous Coward | more than 3 years ago | (#30106832)
What? Tell me, please, what has to happen?
You have to start praying the Hail Mary obviously...
Hail Mary, full of grace
The LORD is with thee
Blessed art thou among women
And blessed is the fruit of thy womb, Jesus...
Re:What has to happen? (1)
Jeremy Erwin (2054) | more than 3 years ago | (#30107318):What has to happen? (1, Informative)
Anonymous Coward | more than 3 years ago | (#30107784)
The link the author provides in the story is about the Hail Mary pass [wikipedia.org] . Sure, the Hail Mary pass itself goes back to the prayer, but you're skipping a layer of analogy (and an interesting bit of trivia).
Re:What has to happen? (1)
Jeremy Erwin (2054) | more than 3 years ago | (#30108498)
I don't watch much football. Can the quarterback throw as many balls as he wants, in the hope that at least one of his receivers catches it?
Re:What has to happen? (0)
Anonymous Coward | more than 3 years ago | (#30106982)
Clearly, for most people the damage so far hasn't outweighed the costs of properly securing their systems, or at least hasn't outweighed the benefits of using Windows (or their goddamn iPhones, in this case).
This is just the free market at work.
That said, those of us who aren't fucktards are making use of OpenBSD, which actually takes security somewhat seriously, unlike virtually every other operating system out there.
Re:What has to happen? (0)
Anonymous Coward | more than 3 years ago | (#30109762)
I do apologise, I just wanted to edit a text file.
Re:What has to happen? (1, Insightful)
FunPika (1551249) | more than 3 years ago | (#30107172)
? (4, Insightful)
Opportunist (166417) | more than 3 years ago | (#30108464):What has to happen? (2, Insightful)
herojig (1625143) | more than 4 years ago | (#30112294)
Re:What has to happen? (1)
Proteus Child (535173) | more than 4 years ago | (#30119324)
Just was has to happen to make people realize (or make lawmakers force them to) that securing your boxes is a necessity?
The Infocalypse?
Put in denyhosts... (2, Interesting)
Tangential (266113) | more than 3 years ago | (#30106762)
Re:Put in denyhosts... (1, Funny)
Anonymous Coward | more than 3 years ago | (#30106794)
denyhosts is security through obscurity much like changing the default port for SSH... or so I'm told.
Re:Put in denyhosts... (1)
Gerald (9696) | more than 3 years ago | (#30107124)
Using Denyhosts and changing your default port adds layers of obscurity on top of existing security. Both are damn useful for reducing the number of real-world intrusion attempts on your system.
Re:Put in denyhosts... (1)
fwarren (579763) | more than 4 years ago | (#30111226) knocking with a non-standard port and have a complex password are you safe?
Yes and No.
Yes, no one over the Internet randomly looking for hosts is going to find you let alone attempt to crack you.
No, because at that point anyone who wants into your network is going switch to more physical methods or social engineering. What is the cost of cracking a 9 digit password? 50,000? You could hire a decent thief for $50,000 who could disable an alarm, get past the cameras and guards, and mirror a hard drive. How much work would it be to find out where all your IT staff lives, and if any of them bring a laptop home from work. What would it take to break into their house and get access to the laptop? The possibility that you could have them "win" a set of tickets to a show and then "vist" there place while they are at a show. Or pay some chick to hit up on one of the techs. Be creative for $50,000 it would cost to use the cloud to break a password if you could even find an ssh port to attack, there are lots of "outside of the box" ways to get the password from the inside of the company.
Re:Put in denyhosts... (2, Informative)
sjames (1099) | more than 3 years ago | (#30108200)
Actually, no it isn't. It is a tool to limit the number of attempts at password guessing. Knowing it's there won't help the attacker at all (they still can't just blast away from a dictionary).
Re:Put in denyhosts... (4, Informative)
jofer (946112) | more than 3 years ago | (#30108330):Put in denyhosts... (1)
Cozminsky (452030) | more than 4 years ago | (#30113110)... (5, Informative)
Anonymous Coward | more than 3 years ago | (#30106826):Put in denyhosts... (2, Informative)
masshuu (1260516) | more than 3 years ago | (#30106868)... (5, Informative)
Predius (560344) | more than 3 years ago | (#30107822):Put in denyhosts... (1)
Culture20 (968837) | more than 3 years ago | (#30109230)
Re:Put in denyhosts... (0)
Anonymous Coward | more than 3 years ago | (#30109794)
Baww. Linux people don't give everything for free.
How unamerican of them.
Re:Put in denyhosts... (1)
doug (926) | more than 4 years ago | (#30112074)
Oh, I get it. We build a cloud to fight their cloud.
Re:Put in denyhosts... (1)
the_humeister (922869) | more than 3 years ago | (#30106916)
Better would be to use public key/private key pairs and disallow username/password logins.
Re:Put in denyhosts... (3, Interesting)
l2718 (514756) | more than 3 years ago | (#30106980):Put in denyhosts... (1)
ottothecow (600101) | more than 3 years ago | (#30107088)... (3, Funny)
David Gerard (12369) | more than 3 years ago | (#30107134)
Re:Put in denyhosts... (4, Informative)
MrMr (219533) | more than 3 years ago | (#30107470)
or fix your filesystem clients.
Re:Put in denyhosts... (-1, Troll)
Anonymous Coward | more than 3 years ago | (#30107756)
The main role of Denyhosts is to lock you out of your own box if you're using an ssh-based file system, which applies your incorrect password multiple times rather than once. I've spent way too much time going into my hosted box via somewhere else to let myself back in.
Dude, you're such a fucking genius. A normal person would have that happen one time and then they'd just learn how to correctly use an ssh-based file system. Or they'd remember their own passwords. But not you! No, you push the envelope and you defy the edge by letting that happen more than once so you can practice letting yourself back in. Brilliant! With all that practice I bet you can let yourself back in your own machine in half the time it would take me!
Re:Put in denyhosts... (1)
emurphy42 (631808) | more than 3 years ago | (#30107426)
Re:Put in denyhosts... (5, Informative)
jimicus (737525) | more than 3 years ago | (#30107472):Put in denyhosts... (2, Interesting)
v1 (525388) | more than 3 years ago | (#30107640) a blank password or same-as-login password. I had it set to autoban the IP at 5 of any sort of failed attempts in a row. I had to do it this way unlike your above example because the guesses kept changing the username, and most traditional "delayed authentication failure" responses nowadays are only effective after multiple attempts on the same username, and they were running a username dictionary, not a password dictionary.
But your method is 100% worthless against this attack.
Nowadays, my servers listen on a nonstandard port, and rsa key login is manditory. End of problem.
How to ID an Infected Computer (1)
derrickh (157646) | more than 3 years ago | (#30106776)
So is there any way other than looking at the packets on your router to know if a system is compromised? This is a question thats been asked many times before but Ive yet to see a straight answer.
Re:How to ID an Infected Computer (1)
elsJake (1129889) | more than 3 years ago | (#30106804)
Re:How to ID an Infected Computer (4, Interesting)
geekboy642 (799087) | more than 3 years ago | (#30106886):How to ID an Infected Computer (1, Funny)
certain death (947081) | more than 3 years ago | (#30106932)
Re:How to ID an Infected Computer (2, Informative)
ceoyoyo (59147) | more than 3 years ago | (#30107798)
Sure. Whenever I'm at home the phone connects via wifi through an Airport. When at work it connects via wifi through the university's secure wifi network.
Wet Nuns (5, Funny)
byrdfl3w (1193387) | more than 3 years ago | (#30106788)
Denyhosts (0)
EllisDees (268037) | more than 3 years ago | (#30106798):Denyhosts (2, Insightful)
turtleshadow (180842) | more than 3 years ago | (#30106872) not "do" enough to protect its own resources from attack.
Re:Denyhosts (1)
geekboy642 (799087) | more than 3 years ago | (#30106914)
The iPhone bit was a hook to draw eyeballs. The smartphones are no more or less susceptible than any other machine running SSH, all of whom should have a more sensible password policy.
Re:Denyhosts (2, Insightful)
ToasterMonkey (467067) | more than 3 years ago | (#30107606) authentication. Maybe even offer to pop up an accept dialog before allowing access? Just a thought..
Sorry, I just can't understand how the phone and users continue to be blamed because in free software land developers are void of any and all quality concerns. At some point.. not the developers involved, but "free software" is going to get rap it deserves. It is what everyone makes it. Look after your own, if you see a free turd, call it a turd.
why ssh on phones? (1)
reiisi (1211052) | more than 4 years ago | (#30113118):why ssh on phones? (1)
Eunuchswear (210685) | more than 4 years ago | (#30115040)
Tomorrow? I log in to my servers from my phone around 5-6 times a day.
You don't have putty on your phone? Why not?
Re:Denyhosts (1, Funny)
TheRaven64 (641858) | more than 3 years ago | (#30106960)
Re:Denyhosts (0)
Anonymous Coward | more than 3 years ago | (#30107186)
Does Denyhosts actually sit between the public Internet and sshd, or are you just making stuff up?
Re:Denyhosts (2, Interesting)
causality (777677) | more than 3 years ago | (#30107240) not have a valid login cannot get a shell without first guessing valid login credentials. The Python script makes it infeasible for a single host to brute-force those login credentials assuming a reasonably strong password. Thus, it addresses a security issue that is actually beyond the scope of SSHD.
Personally I prefer SSHGuard because it will use iptables to drop packets from offending hosts. In my opinion that's a better approach than adding the hosts to a hosts.deny file. A host listed in hosts.deny can still try to connect to your daemon; it will just be immediately disconnected. By contrast, anything firewalled by iptables and set to DROP won't even get so much as a momentary TCP connection. Not a big difference, but I say let them wonder if you're even online anymore. There's also no dependency on the robustness of tcpwrappers (well-tested though they may be).
Re:Denyhosts (2, Informative)
ceoyoyo (59147) | more than 3 years ago | (#30107824):Denyhosts (2, Informative)
Web Goddess (133348) | more than 4 years ago | (#30112166)
try this
cat logfile | cut -d " " -f [fill in the field with the IP ] | sort | uniq -c | sort -n
(and if need be, add ' | tail -20')
This will show you whether there are repeat IP addresses in the log.
Webgoddess
Re:Denyhosts (1)
ceoyoyo (59147) | more than 4 years ago | (#30125194)
Not on OS X it doesn't. No cut -d.
A quick grep shows that a sample IP address does try about two or three times a day, which suggests several thousand unique addresses gracing me with their attention.
Bad or good matters not here... (0)
Anonymous Coward | more than 3 years ago | (#30106814)
...because if the password is pre-set, default, and known to everyone accessing the software, then, yeah, exactly, you dumb s**t of an article author.
Re:Bad or good matters not here... (1)
badger.foo (447981) | more than 3 years ago | (#30106882)
DenyHosts will not save you; disable passwords (4, Interesting)
Radhruin (875377) | more than 3 years ago | (#30106950):DenyHosts will not save you; disable passwords (1)
0123456 (636235) | more than 3 years ago | (#30107070):DenyHosts will not save you; disable passwords (1)
marcansoft (727665) | more than 3 years ago | (#30108138) 'standard' leetspeak on a dictionary word). Plain numbers are significantly weaker, but even an 8-digit number is unlikely to be guessed in a network SSH attack, though I wouldn't recommend relying on it.
Realistically speaking, 6 characters of pure random, 8 characters of pronounceable random, or 10-15 characters of something coherent but mangled are basically secure for SSH. SSH attacks are over the network, which means you can't get even close to the number of tries per second of local password hash cracking attempts. The number of passwords that are going to be tried are in the thousands or millions over the long term, not the billions of possible combinations.
I use public keys to access some remote systems and they certainly are a lot better security-wise, but I keep my home boxes and my main server accessible via passwords, since I don't usually carry my private keys around when I need to log in from another box.
user names, too (2, Informative)
reiisi (1211052) | more than 4 years ago | (#30113062) -- rename the root something obscure. Maybe the name of your favorite vegetable with some leetspeak thrown in, or turned backwards, or scrambled, or, think of you own way to make it obscure.
Use initials instead of single names. Or, better, use initials in combination with simple names, or job titles in combination with something like the first name and an initial. Or multiple names.
(If you might have someone specifically targeting your servers for something valuable, don't use names or initials or job titles at all, of course. Sometimes, you might even want to generate the usernames randomly, or at least partially randomly.)
In fact, if you disable, or just don't have root or admin or pguser or web, etc., you can be really, really sure that an attempt to log in with such names indicates someone who really shouldn't be allowed to even try to log in.
The point is, it's much harder to brute-force a system when the attacker doesn't even know what user names to start with, whether hail mary or machine-gun.
And then you make the password reasonably long and obscure, and you're pretty safe.
(User names, at least, usually won't need to be changed every six months.)
Oh, and don't forget the port, either. (1)
reiisi (1211052) | more than 4 years ago | (#30113080)
Get off the default ports, too.
tarpit port 22, just for fun.
Re:DenyHosts will not save you; disable passwords (1)
Bert64 (520050) | more than 4 years ago | (#30113790) passwords these days, and nothing stopping them from all being the same... And these passwords are stored, used and recovered in various ways...
Some places will store the password unencrypted (or reversibly encrypted) and happily email it to you in the clear, while others will do a proper one way hash and the only recovery procedure possible will set a new password.
Some places will ask security questions like "mothers maiden name" or "your first school" - which is easily available information...
There are a million and one ways to get users to disclose a password, the traditional attacks with a fake paypal/bank/ebay/etc website might be easy to detect, but how about a site that offers you something legitimate looking and free, which just requires you to give an email address and set a password so you can adjust your settings in future... How many people would use the same password/email here as they do elsewhere?
Re:DenyHosts will not save you; disable passwords (1)
RobertLTux (260313) | more than 3 years ago | (#30107350)
and you could also have a flash key with your SSH utility that could be used to login from any other computer (heck with the price of flashkeys these days you could have your entire software stack on the key and a good bit of data)
Re:DenyHosts will not save you; disable passwords (1)
ceoyoyo (59147) | more than 3 years ago | (#30107866):DenyHosts will not save you; disable passwords (1)
nurb432 (527695) | more than 3 years ago | (#30107740)
And if a machine that has your public key on it is compromised ?
Re:DenyHosts will not save you; disable passwords (2, Informative)
mr_flea (776124) | more than 3 years ago | (#30107936)
Re:DenyHosts will not save you; disable passwords (1)
nedlohs (1335013) | more than 3 years ago | (#30109216)
Do you know what the word "public" means?
Can you see how it makes that irrelevant?
Re:DenyHosts will not save you; disable passwords (1)
dkf (304284) | more than 3 years ago | (#30109530) inability of javascript implementors to grasp what a sane security policy is, but sometimes you just have to compromise. Or carry two laptops around with you...)
Re:DenyHosts will not save you; disable passwords (1)
shentino (1139071) | more than 3 years ago | (#30108486) (3, Interesting)
damn_registrars (1103043) | more than 3 years ago | (#30107026):The cloud attack isn't new (2, Insightful)
zigziggityzoo (915650) | more than 3 years ago | (#30107376)
Re:The cloud attack isn't new (1)
damn_registrars (1103043) | more than 3 years ago | (#30109266) next week, then a whitelist could result in me locking myself out of my own system when I need it most.
In short, your solutions may work well for you; and if so that is great. However some of us can't make use of those approaches practically.
Though in my case, I happen to enjoy watching the hack attempts fail. I find the resulting information interesting. I do after-the-fact armchair-quarterbacking on the logs to critique the botnets (or clouds) on how they failed to get into my system. I can also use the logs to see how their approaches are changing over time, to make sure that I am taking the correct precautions should they get more intelligent in their technique.
Re:The cloud attack isn't new (1)
Eunuchswear (210685) | more than 4 years ago | (#30115158)
Sounds like made up numbers. You claim that one in 20 ssh login attempts was coming in on a non ssh port? Which port was it exactly?
Re:The cloud attack isn't new (1)
Daimanta (1140543) | more than 3 years ago | (#30107412):The cloud attack isn't new (0)
Anonymous Coward | more than 3 years ago | (#30107680)
Run "John The Ripper" against your user list to detect poor passwords before someone else does.
Re:The cloud attack isn't new (1)
ceoyoyo (59147) | more than 3 years ago | (#30107922):The cloud attack isn't new (1)
flyingfsck (986395) | more than 3 years ago | (#30109406)
Re:The cloud attack isn't new (1)
Bert64 (520050) | more than 4 years ago | (#30113864):The cloud attack isn't new (0)
Anonymous Coward | more than 4 years ago | (#30112012)
In which alternate reality is brute-forcing RSA passwords possible? Do people there use roo>t accounts? Else, that single point is more than enough to protect your system.
What if I have a user called god, and they have a list that goes (root,john,ken,god,rms,...)?
Then their brute-forcing instead of taking more than the lifespan of our universe x nPossibleUserNames, it will take more than the lifespan of our universe x 4. I feel so insecure.
If you don't want to have the SSH server working overtime move it away from port 22 but as far as security goes it is only nPorts x better.
Re:The cloud attack isn't new (1)
TheEden (1213710) | more than 4 years ago | (#30142158)
Re:The cloud attack isn't new (1)
damn_registrars (1103043) | more than 4 years ago | (#30143050)
How do these two parts relate? (1)
damn_registrars (1103043) | more than 3 years ago | (#30107062)
Re:How do these two parts relate? (1)
ceoyoyo (59147) | more than 3 years ago | (#30107946):How do these two parts relate? (1)
Bert64 (520050) | more than 4 years ago | (#30113870)
Most likely the hail mary bots will have successfully compromised a few iphones with default passwords, tho their intrusion will be less obvious than a picture of rick astley.
Re:How do these two parts relate? (1)
ceoyoyo (59147) | more than 4 years ago | (#30123812)
You don't need a hail mary bot to compromise a well known default password.
Most likely a bunch of jailbroken iPhones are compromised, just like lots of routers with default passwords.
Translation for non-retards: (2, Insightful)
Hurricane78 (562437) | more than 3 years ago | (#30107230)
s/cloud/network/
There. Done it for ya. Was that so hard?
We should make a Greasemonkey script out of it.
:)
Re:Translation for non-retards: (1)
wiredlogic (135348) | more than 3 years ago | (#30109366)
For the sake of tradition we should call it a Beowulf cluster. Imagine that.
Re:Translation for non-retards: (1)
Hurricane78 (562437) | more than 3 years ago | (#30110230):Translation for non-retards: (1)
Hurricane78 (562437) | more than 4 years ago | (#30110298)
LOL. I just thought I had misspelled it as "unClusteredThinking", until I noticed that I already had the script installed. Just shows how well it works. ^^
Re:Translation for non-retards: (1)
RyuuzakiTetsuya (195424) | more than 4 years ago | (#30112414)
Then reading Final fantasy VII faqs and Meterology websites would get really strange.
Re:Translation for non-retards: (1)
Hurricane78 (562437) | more than 4 years ago | (#30123876)
It's limited to Slashdot for that very reason.
:)
Plaintext passwords over ssh (1)
m.dillon (147925) | more than 3 years ago | (#30107382)
DenyHosts is not security through obscurity! (0)
Anonymous Coward | more than 3 years ago | (#30107656)
It bans or denies connection to IPs that have repeatedly failed to login. That is real security, not obscurity. That being said, it is totally useless against today's threats.
Set sshd to listen on a non-standard port (0)
Anonymous Coward | more than 3 years ago | (#30108896)
I've try a number of things, ssh-anti-brute.pl worked well at least initially (when receiving multiple failed logins from the same destination address) but my drop chain was starting to get kinda lengthy.
I've recently moved sshd off port 22 and it seems to be doing the trick.
hairy business (0)
Anonymous Coward | more than 3 years ago | (#30109220)
Am I the only one who misread the title as "The 'Hairy Mail Cloud' is Growing"?
Disable Password Logins!! (0)
Anonymous Coward | more than 4 years ago | (#30116284)
Using an RSA or DSA Pubkey will effectively stop these..
Add on top of that a firewall rule blocking high volume of requests to your server (I have it set at 4 per minute
:)) works well for this.
I *NEVER* setup an SSH server using password auth..
Oh, and of course TURNING OFF SSH on your iphone when not needed is ALWAYS a good idea.
Four simple things (1)
skeeto (1138903) | more than 4 years ago | (#30116338), let alone a correct password. It tries names like root, admin, apache, samba, so if you have these make sure they can't log in with ssh.
Two, use a decent password. A lot of people will tell you to take the inconvenient route of disabling password logins, saying they are dangerous. However, guessing over ssh is extremely slow, compared to a brute force attempt on a local machine. This means they really only get a chance to guess the most obvious passwords. If you trust all the passwords on the system to have decent strength, which is the case if, say, you are the only person logging into the machine, then you don't need to disable password logins.
Three, in case they did somehow figure out the name of an account that can log in, run DenyHosts. This will stop non-distributed attacks in their tracks, as they only get a few guesses.
Four, move the ssh port to something other than the default 22. I moved mine to 443 (https), since it's accessible from highly firewalled networks behind which I may be trapped, and people are already used to seeing encrypted traffic on that port. Ever since I did this, I haven't seen a single login attempt on my server other than myself. This means my server also wastes less time rejecting remote logins.
The ssh brute force bots I've seen are very stupid. I'm not really sure what the bot operators are doing. In my ssh honeypot where I have the root password set to "password", most bots won't ever guess it after thousands of attempts. Of the ones that do eventually guess the right password, most log out right away, then go right back to guessing root passwords again! Maybe trying to detect if it's a honeypot? Then there are ones that do log in and stop guessing, but they immediately log out and don't ever return (that is, no one has ever shown up and logged in without making guesses). Security researchers? Maybe marked my honeypot down for some future abuse? Maybe detected that it was a honeypot? I'm not sure what's going on with that.
I may be missing something (1)
k1773re7f (828030) | more than 4 years ago | (#30133992)
|
http://beta.slashdot.org/story/127262
|
CC-MAIN-2014-41
|
refinedweb
| 4,402
| 70.73
|
In this post, we are sharing Docker image for OpenCV 3.4.3, and the recently released OpenCV 3.4.4 and OpenCV 4.0. In addition to OpenCV, the image also has dlib and a Facial Landmark Detection example code.
Every day we receive a few emails and comments on our posts about OpenCV and Dlib installation. Even with the detailed and tested instructions, sometimes it is tough for people to get a system up and running. So, we have been thinking of providing a solution for people who have struggled with installation issues.
One way to solve this problem is to provide a Virtual Machine (VM) with all the libraries installed. A huge downside of using a VM is the large file people need to download. Sometimes it can be 10s of GBs.
A smarter and newer way to solve this problem is to provide a Docker image. Typically a Docker image size is much smaller than a VM. Our Docker image, for example, is just 1 GB in size (compressed size). In addition, it starts much faster than a VM and typically runs applications much faster compared to a VM. Docker is just one of those minimal things that can make your life exceedingly simple.
Also, as we’ll see, the same docker image can be used on Windows, Ubuntu and MacOS. If you are stuck with OpenCV installation or if you want to try out the new OpenCV-3.4.4 and OpenCV-4.0 ( released on 20th November 2018 ), without actually installing it on your system, this docker image is the perfect match for you.
This post is split into five sections
- Section 1: How to install Docker on Linux, MacOS and Windows.
- Section 2: How to use Docker image for OpenCV. This image also comes with dlib pre-installed.
- Section 3: How to run Facial Landmark Detection demo code on Docker Image
- Section 4: How to make changes to a Docker image.
1. Docker Installation
In this section, we will learn how to install Docker on Ubuntu, MacOS, and Windows.
1.1 Installing Docker on Ubuntu
- To install docker on Ubuntu 16.04, following:
- Finally, install Docker:
sudo apt-get install -y docker-ce
1.2 Installing on MacOS
- To install Docker on MacOS desktop, first go to the Docker Store and download Docker Community Edition for Mac.
- Double-click Docker.dmg to open the installer, then drag Moby the whale to the Applications folder.
- Double-click Docker.app in the Applications folder to start Docker.
- You are prompted to authorise Docker.app with your system password after you launch it. Privileged access is needed to install networking components and links to the Docker apps.
The whale in the top status bar indicates that Docker is running, and accessible from a terminal.
1.3 Installing Docker Toolbox in Windows 7 or above
- Download and install Docker Toolbox for Windows. The installer adds Docker Toolbox, VirtualBox, and Kitematic to your Applications folder.
- On your Desktop, find the Docker QuickStart Terminal icon.
- Double click the Docker QuickStart icon to launch a pre-configured Docker Toolbox terminal.
- Press enter and the installation will be automatically started. Once done, the file will be present in
\users\username\.docker\machine\cache\boot2docker.iso.
- If the system displays a User Account Control prompt to allow VirtualBox to make changes to your computer, choose Yes.
The terminal does several things to set up Docker Toolbox for you. When it is done, the terminal displays the $ prompt.
bash Running pre-create checks... (default) No default Boot2Docker ISO found locally, downloading the latest release... (default) Latest release for github.com/boot2docker/boot2docker is v18.06.1-ce (default) Downloading C:\Users\imsau\.docker\machine\cache\boot2docker.iso from
2 Install Docker OpenCV Image
To use the docker image, use the following instructions:
docker pull spmallick/opencv-docker:opencv
Once, the image is downloaded, we can start it using the following command
docker run --device=/dev/video0:/dev/video0 -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -p 5000:5000 -p 8888:8888 -it spmallick/opencv-docker:opencv /bin/bash
Let’s take a moment to examine this command in detail:
- –device=/dev/video0:/dev/video0 allows use of webcam
- -v /tmp/.X11-unix:/tmp/.X11-unix helps in X11 forwarding so that we can use functions like cv::imshow.
- -e is used to pass an environment variable.
- -it starts an interactive session
- -p sets up a port forward. This flag maps the container’s port to a port on the host system.
- /bin/bash runs .bashrc file on startup
The image has OpenCV 3.4.3 installed in /usr/local, OpenCV 3.4.4 in ~/installation/OpenCV-3.4.4 and OpenCV 4.0.0 in ~/installation/OpenCV-master.
To use Python environments:
For OpenCV 3.4.3,
workon OpenCV-3.4.3-py3 ipython
Once you are in the iPython prompt, do
import cv2 cv2.__version__ exit()
To deactivate the virtual environment use
deactivate
Similarly for OpenCV 3.4.4 and OpenCV 4.0.0,
workon OpenCV-3.4.4-py3 ipython
Once you are in the iPython prompt, do
import cv2 cv2.__version__ exit()
To deactivate the virtual environment type
deactivate
workon OpenCV-master-py3 ipython
Once you are in the iPython prompt, do
import cv2 cv2.__version__ exit()
3 Run Facial Landmark Detection on Docker Image
To test the installation of OpenCV and dlib on the docker image, we have provided a Facial Landmark detection example that you can try out.
- First, we make sure that we have the latest docker image.
docker pull spmallick/opencv-docker:opencv
- Next, we run the docker image as specified in the earlier sections.
docker run --device=/dev/video0:/dev/video0 -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -p 5000:5000 -p 8888:8888 -it spmallick/opencv-docker:opencv /bin/bash
- Once the docker container is created and is running, you will find 3 folders in /root/ – common, demo and installation. The demo folder contains C++ and Python version of the Facial Landmark Detection code.
- To run the Python script, follow the steps given below. The instructions are for OpenCV-4.0.0. For OpenCV-3.4.3 and OpenCV-3.4.4 just change the environment as discussed earlier.
cd ~/demo/python
source activate OpenCV-master-py3 python facialLandmarkDetector.py source deactivate
- To run the C++ code, follow the steps given below:
cd ~/demo/cpp/
You will find 3 folders, one for each OpenCV version installed. The CMakeLists.txt file present in the folders can be used as a reference for building codes for that particular OpenCV version.
cd OpenCV-3.4.4/build cmake .. cmake --build . --config Release cd .. ./build/facialLandmarkDetector
4 How to commit changes to Docker Image
To commit changes made to the docker image, we need to follow the steps below. We will refer to the image of the terminal below as an example
- Find the Container ID: The easiest way to find it out is to note the text following [email protected] in your docker container. For example, in the image above, the docker container ID is 56a07cf4614c. Also, note that Container ID will vary every time you use docker run to create a new container.
- Make a change: In the example above, we create a simple file HelloUser.sh that outputs some text when run from the command line.
- Exit: Once the changes have been made, we need to exit the container using exit command.
- Commit changes: Finally, to commit the changes made to the docker image use the following command
sudo docker commit CONTAINER_ID NAME_OF_DOCKER_IMAGE
In our example, we use
sudo docker commit 56a07cf4614c my-docker-image
- Check image: You want to make sure the committed docker image shows up when you run the following command
docker images
- Use image: Next time when you want to use this docker image, just use the following command:
docker run --device=/dev/video0:/dev/video0 -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -p 5000:5000 -p 8888:8888 -it NAME_OF_DOCKER_IMAGE /bin/bash
In our specific example, we use
docker run -u 0 -it -p 8888:8888 -p 5000:5000 my-docker-image /bin/bash
Hope you have fun hacking with Docker! 🙂 If you have any queries, comment below and we will get back to you as soon as possible.
Subscribe & Download Code
If you liked this article and would like to download code (C++ and Python) and example images used in other posts of this blog, please subscribe to our newsletter. You will also receive a free Computer Vision Resource Guide. In our newsletter, we share OpenCV tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.
References
- Docker for Data Science: Building Scalable and Extensible Data Infrastructure Around the Jupyter Notebook Server by Joshua Cook
- Techrepublic: How to commit changes to a docker image
|
https://learnopencv.com/install-opencv-docker-image-ubuntu-macos-windows/
|
CC-MAIN-2022-21
|
refinedweb
| 1,490
| 57.16
|
On Oct 4, 9:59 pm, Karlo Lozovina <_karlo_ at _mosor.net> wrote: > Hi all, > > this is my problem: lets say I have a arbitrary long list of attributes > that I want to attach to some class, for example: > > l = ['item1', 'item2', 'item3'] > > Using metaclasses I managed to create a class with those three > attributes just fine. But now I need those attributes to be properties, > so for example if 'A' is my constructed class, and 'a' an instance of > that class: > > a = A() > > Now if I write: > > a. print a.item1 > > I want it to be actually: > > a.setitem1('something') > print a.getitem1 > > Any idea how to do that with metaclasses and arbitrary long list of > attributes? I just started working with them, and it's driving me nuts :). No metaclasses, but how about this? def make_class(name, attributes): # Build class dictionary. d = dict(_attributes=list(attributes)) # Add in getters and setters from global namespace. for attr in attributes: d[attr] = property(globals()['get' + attr], globals()['set' + attr]) # Construct our class. return type(name, (object,), d) # Test code: def getitem1(self): return self._fred + 1 def setitem1(self, value): self._fred = value A = make_class('A', ['item1']) a = A() a.item1 = 19 print a.item1 >> 20 You didn't say where the getters and setters (here 'getitem1', 'setitem1', etc.) come from. I've assumed from the global namespace but you probably want to change that. -- Paul Hankin
|
https://mail.python.org/pipermail/python-list/2007-October/446648.html
|
CC-MAIN-2014-10
|
refinedweb
| 237
| 75.71
|
So as I have been developing increasingly more Revit plug-ins these days, I finally came to realization that the stupid security warning about Untrusted Publisher that Revit shows on startup really annoys me.
. Harry talked about basic setup in this post: BoostYourBim and Jeremy Tammik chimed in on why one needs to sign their plug-ins over at Autodesk Forum. Please give it a try. Now, let’s get to it.
!!!— I, by no means endorse KSoftware or Comodo in this post. They are just one of the many companies that offer this service, so feel free to make your own choice. I did make mine based on the fact that Harry used them, and it worked for him so I just went with that. —!!!
!!!—This is important. KSoftware/Comodo issue your certificate using the internet browser (exactly the keygen functionality). It is critical to the whole process that you place the order, using a compatible browser. Chrome is not. Neither is Edge. Basically make sure you are using Firefox or Internet Explorer for every step of the way. —!!!
- First you need to place an order with KSoftware. They will ask you to verify your company. One of the many ways that you can do that is to sign up with yet another company (which I am not endorsing either) by the name of Dun & Bradstreet. Now, they will require you to submit paperwork that proves that you are who you are and that you own the company etc. etc. To obtain the DUN’s number you will just have to register your company with them, and wait for like 2 weeks. They will try to sell you stuff, so beware of that. You can just decline and wait for them to issue the free number.
- Once you get that out of the way, you will get an email that says that your certificate has been issued, and you need to collect it. It will look like this:
- Again, make sure that you are using the same compatible browser as when you were placing the order or this can possibly fail. Otherwise just follow their link and you should get a message asking if you want to install your certificate. If you were to use the wrong browser (let’s say latest Chrome), it would instead just download a certificate file. That’s not what you want. You want it installed, so that when you go to Internet Options>Content>Certificates it will show like this:
- Now that you have your certificate installed you can export it. You basically want to export it to a PFX file that is encrypted with a password, so that you can store it safely on your computer and use it to sign your DLLs. Here are the steps to get it exported. Please follow these and you will get a PFX file. Export steps.
- Now that we have the certificate exported, we can use a signtool.exe that ships with Visual Studio to sign your DLLs after they are being compiled. The way to do that is to add a Post Build Event to your assembly. You can do it by right clicking on the project in your Solution browser and navigating to Properties:
- Then under Post Build Events you can add a line of code that asks the signtool.exe to sign your plug-in using the PFX file you previously exported. It looks like this:
- The actual code is this:
Now, this will not take away the Revit warning on the first try. However this time it will show it with your credentials, and you can choose to launch your plug-in. It should take it away on every subsequent Revit opening event. Also, when adding your sign command to the Post Build Event, please remember to sign your code first before moving your DLL somewhere else. I usually use copy commands there as well to copy my DLLs to appropriate Revit folders, so just make sure they are signed before they are moved.
This should do the trick. Let me know if you have any questions, and huge thanks to Harry Mattison and Jeremy Tammik for their initial posts. They were great at getting me through this process.
Cheers!
Ps. From reading comments on Boost Your Bim post, it seems like on some machines you might have to open Internet Explorer before launching Revit. I am not sure why that would be, but I am just putting it here if someone runs into trouble.
Autodesk have a two-tier system. If you develop directly for the RevitAPi you need to sign the assemblies.
If you create zero touch nodes for Dynamo you don’t. Even though you can access the RevitAPI and import any namespace you like.
I look at the average price of an Exchange app and the number of positive comments for such an app and I wonder how the publishers break even. Given all these costs Autodesk insist on. Out of principle I’m not going to pay for someone to investigate and prove I am who I am.
The fact one CA charges a small amount and another charges a large amount just points to the likely inconsistency in their vetting process. One is investigating what you eat for breakfast and the other is just subletting their certificate.
Well, you can also get a free certificate for Open Source projects etc. I don’t think that Autodesk’s aim here is to truly vet people that post plug-ins to their Exchange App, but rather to put a small little obstacle in a way that would discourage malicious activities. After all, something as simple as Captcha can stop people from posting spam (yeah I know it’s goal is to mainly stop bots from posting spam but either way you get my point). Also, you don’t have to buy these certificates. It’s not a mandatory requirement. You can still publish and share Revit plug-ins without it, except that your users will be annoyed by the warnings. That’s it.
I’m not sure what the restrictions are on the Exchange App Store. However if you write an install shield package then you get to choose if certificates are installed on the local PC trusted root. As the install shield can be made to require elevated privileges. So there is no real security in the certificates system for those intent on doing harm.
Thanks for the reply.
|
http://archi-lab.net/code-signing-of-your-revit-plug-ins/
|
CC-MAIN-2018-09
|
refinedweb
| 1,083
| 71.65
|
Board index » VBA
All times are UTC
FOR CONTACTS: Dim conOutLook As Outlook.ContactItem Set conOutLook = MAPIFolder5.Items.GetFirst
Do Until conOutLook Is Nothing conOutLook.Delete Set conOutLook = MAPIFolder5.Items.GetNext Set conOutLook = MAPIFolder5.Items.GetFirst Loop
FOR DISTRIBUTION LISTS: Dim distOutlook As Outlook.DistListItem Set conOutLook = MAPIFolder5.Items.GetFirst
Your help would be appreciated.
Thanks
Todd
example.
Dim myObject As Object Dim colItems As Outlook.Items Dim lngCount as Long Dim lngLoopCounter As Long
Set colItems = Application.Getnamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
lngCount = colItems.Count
For lngLoopCounter = lngCount To 1 Step -1 Set myObject = colItems.Item(lngLoopCounter) If myObject Is Nothing Then ' Else myObject.Delete End If
Next lngLoopCounter
Set myObject = Nothing Set colItems = Nothing
-- /Neo
How do I delete Contact Items and Distribution Lists from within the same MAPI folderusing a Loop command. My code below will only delete one or the other and stays in and endless loop because either contacts or distribution lists still remain (depending on which code I use)... see code below
1. Delete Contacts from "Contact " Folder Automatically
2. NEWBIE: to delete distrbution list from contact list
3. Adding/Deleting Contacts in Public Folders
4. problem when deleting contact folder with VB
5. How make list of the other folder contact ?
6. Members property of contact folder distribution lists - returns gobbledygook in lovely looking array
7. Getting Contact list from another FOLDER
8. Distribution lists in the Contacts Folder
9. Using VBA to Create a Contact Folder Distribution List from MS Access
10. Set Contact Folder to be E-Mail Address List in Code
11. Get list of all Contact folder names
12. Public Folder Contact List
|
http://computer-programming-forum.com/1-vba/a49ef3a76f11b032.htm
|
CC-MAIN-2020-40
|
refinedweb
| 274
| 54.18
|
I?
I?
Just a thought - this is almost like creating a TIN (triangulated irregular network), but without the vertical dimension. Maybe someone can run with this - I'm can't quite figure out the rest (not enough caffeine yet ) - would it be possible to go from a TIN to polygons then to lines?
Chris Donohue, GISP
Hi Travis,
You could do this using python. Below is an example that performs this on a feature class called 'testPts' and creates a line feature class (i.e. Line_A, Line_B, ...).
import arcpy from arcpy import env env.workspace = r"D:\temp\python\test.gdb" env.overwriteOutput = 1 fc = "testPts" idList = [] with arcpy.da.SearchCursor(fc, ["ID"]) as cursor: for row in cursor: idList.append(row[0]) del cursor for id in idList: arcpy.MakeFeatureLayer_management("testPts", "testPtsLyr", "ID = '{0}'".format(id)) coordList = [] features = [] with arcpy.da.SearchCursor("testPtsLyr", ["ID", "SHAPE@XY"]) as cursor: for row in cursor: geom = row[1] del cursor firstTime = True with arcpy.da.SearchCursor("testPts", ["ID", "SHAPE@XY"]) as cursor: for row in cursor: if row[0] != id: coordList.append(geom) coordList.append(row[1]) feature_info = map(list, coordList) feature_info2 = [] feature_info2.append(feature_info) for feature in feature_info2: # Create a Polyline object based on the array of points # Append to the list of Polyline objects features.append(arcpy.Polyline(arcpy.Array([arcpy.Point(*coords) for coords in feature]))) if firstTime: # Create polyline feature class (i.e. Line_A) arcpy.CopyFeatures_management(features, "Line_" + str(id)) firstTime = False else: # Append additional lines to feature class arcpy.Append_management(features, "Line_" + str(id)) features = [] coordList = [] del cursor
I'd go with Python, too, although you can simplify it down to:
>>> fc = 'points' # feature class ... sr = arcpy.Describe(fc).spatialReference # spatial reference ... lines = [] # output line list ... geoms = [i[0] for i in arcpy.da.SearchCursor(fc,'SHAPE@',spatial_reference=sr)] # point geometries ... for geom1 in geoms: # loop through points ... for geom2 in geoms: # compare to points ... if not geom1.equals(geom2): # if not the same ... lines.append(arcpy.Polyline(arcpy.Array([[geom1.centroid,geom2.centroid]]),sr)) # create line ... arcpy.CopyFeatures_management(lines,r'in_memory\lines') # output to feature class
Of course, this removes the feature of a line ID.
Thank you both Darren and Jake. I have never used Python but have some basic programming skills (R). I have been playing around with this, but seem to be stuck on Darren's code at the loop. I am using ArcGIS 10, and I don't think I can loop with the arcpy.SearchCursor function. Any advice on a workaround for this method. Thanks again for helping out with this.
The only tool (I think) in the current toolbox would be XY table to Line.
But for that to work you need a FromXY and ToXY in the same row of each record.
So, what I would do would be a little MS access magic.
Get your point data into a pgdb (access).
Use AddXY or Calculate geometry to get 2 columns in the attribute table of the XY coordinates.
Open the db in access.
Create a query by adding the attribute table twice with no join.
If you view this you will see you have a cross join where all records are linked to all records.
Filter this so you don't have A -> A.
In the output make table query, do some column name changes so you have columns like FromX, FromY, ToX, ToY etc.
Bring the new table into ArcMap and use the XY table to Line tool.
Be aware that if you have a lot of input records, the cross join will create input record length ^ 2 output records.
|
https://community.esri.com/thread/180404-is-there-a-way-to-connect-all-points-in-a-shapefile-to-each-other-with-lines
|
CC-MAIN-2019-43
|
refinedweb
| 603
| 68.26
|
Ok, I have worked the program out a little bit more. But when I run it it is not printing out the users name.
My New Program is this:
import java.util.Scanner;
public class...
Ok, I have worked the program out a little bit more. But when I run it it is not printing out the users name.
My New Program is this:
import java.util.Scanner;
public class...
Norm, because I am a beginner I am not sure how to do that. I tried to put something like
private String usersName = ' '; but not sure how to ask the question.
Yes, Only once.
I commented it out because I think I need these statements in the code but I am not sure where I need to put them. I need to be able to ask the user their name at the beginning of the program and...
I have been working on this program for about a week now and I think I have it down pack. The issue I am having when I ask the user at the beginning of the game (human vs computer) every time I run...
Yes, absolutely.
My output should look something like this...
Percent gain / loss: 250.0%
Amount gain / loss: $125,000.00
I think I have a cluster of a mess here and was wondering if someone could help me in the right direction. I am trying to write a small program that will calculate the gain and/or loss of the sale of...
Ok GregBrannon, Thank you for your response. I made the changes but the errors that pop up is that the system wants to make them 'static'. Is that right?
Ok. so I just added
int i inside the (). I actually looking at it not I already had it once as a method. My output after making the change looks like this:
Expected Count: 1 -----> Actual...
I believe I have this program CounterTester.java down but in my output the program is increasing the way I want it to but it is not decreasing the way I want it to.
:confused:
Would someone...
Just wanted to let you know I solved the problem. Thank you for your help.
Thank you for your direction.
Hello, I am trying to create a java file that will print out the temperature in Fahrenheit. This is my code.
import java.util.Scanner;
public class TemperatureConverter
{
public static...
|
http://www.javaprogrammingforums.com/search.php?s=27ff4573ae09a175831299375d6e7378&searchid=1584488
|
CC-MAIN-2015-22
|
refinedweb
| 404
| 85.49
|
Model Management
Domino lets you publish R or Python models as web services and invoke them using our REST API, so you can easily integrate your data science projects into existing applications and business processes without involving engineers or devops resources.
Overview
A model is a REST API Endpoint that is a wrapper on top of a function in your code. The arguments to the API are the arguments to your function; the response from the API includes the return value from your function. Typically this function will make a prediction or classification given some input.
When. We have a short video (coming soon!) to demonstrate how models are published.
Key Model Management Features
- Production-Grade Infrastructure - Models are vertically and horizontally scalable, and are highly reliable. See this for more details.
- Versioning and Reproducibility - Models are versioned and each version can be redeployed giving you the ability to revert to previous good states. Models depend on V2 Environments which gives you full reproducibility.
- Discoverability & Access Control - A model is also a top level entity that is separate from projects.
- The Models tab on the top level nav allows users to discover and view models that they have access to.
- Models have their own set of permissions which allows for organizations to split out the group that develops models from the one that deploys or maintains them. See this for more details
- Models also come with audit logs so you can track who took which actions
- You can control whether your model is publicly invocable or requires an access token. See this for more details
- Promote to Production Workflow - We support an advanced routing mode which allows you to have a promote to production workflow where you can test with one version and take production traffic on another version. See this for more details.
- Flexibility - Models can be deployed from multiple projects though we expect most people to deploy from a single project.
Setting up your Compute Environment
Environment Selection
The Model Manager requires a V2 Environment to work. When you deploy the model manager it will only give you V2 environments in the environment selection dropdown. If your project is currently set to a classic or V1 environment, you will need to select or create a V2 environment that has three specific packages for Model Manager to work. These three packages can be added by adding the line
RUN pip install flask==0.12 jsonify==0.5 uwsgi==2.0.14
to a new V2 environment based off of your existing V1 or V2 environment. If you need help with this, please contact us.
A note about requirements.txt
Model Manager does not read your requirements.txt. If your project currently uses requirements.txt to install certain packages or repositories, you must add them to your V2 environment. This allows your model to build and run faster and centralizes a single source of truth for the compute environment needed to run reproducible, versioned models.
Once you have created your V2 environment, you can choose to update your project to point to it, so that your runs and models use the same environment. At that point you can also get rid of your requirements.txt and instead update and rebuild your environment whenever you need to make changes.
Environment Variables
Your model does not inherit the environment variables set at the project level but you can set model specific environment variables on the Settings/Environment tab. This is intended to decouple the management of projects and models. See this for more details.
Publishing your Model
Your script has access to your project's files, including serialized model files (e.g., pickle or Rda). So you can save a model with a long-running training task, and then read it into memory with your endpoint script for classification.
There are three ways to publish a model: (1) through the UI; (2) through a scheduled run; and (3) COMING SOON programmatically through the Domino API or CLI; .
- In the UI, click on "Publish" on the left-hand sidebar. Click over to the Models tab. This brings you to a page where you can input the name of your model, name of the script and function you wish to publish.
- Scheduled runs can automatically update your model. So you can set up scheduled, long-running training tasks to re-deploy with the latest version of your model.
- COMING SOON To programmatically re-publish a model after a run, start a run from the CLI using the flag --publish-model:
domino run --publish-model command arguments
- COMING SOON Alternatively, use the Domino API to start a run and set the publishModel parameter to true. If the run is successful it will be deployed to your project's endpoint.
Calling your Model
The Model Manager supports a couple of different ways of setting up your API's endpoint URL. See this for more details.
On the Overview page of a model, we have a model tester. It gives you examples of how to call your model. On the first tab, the "Tester" you can type in your input query and see the model response directly. On the tester tab you do not need to add your access token.}}, or
{"parameters": [1, 2, 3]}
If you're using a dictionary in your function definition, for example:
my_function(dict)
and your function then uses dict["x"], dict["y"] etc, you can use only a parameter array:
{"parameters": [{"x": 1, "y": 2, "z": 3}]}
to call your model.
In Python, you can also use **kwargs to pass in a variable number of arguments. If you do this:
my_function(x, **kwargs)
and your function then uses kwargs["y"] and kwargs["z"], you can use the data dictionary to call your model:
{"data": {"x": 1, "y": 2, "z": 3}}
Other tabs give you example code snippets of how to call your model in different languages though it currently does not fill in your API specific formatted inputs.
Domino will take care of converting the inputs to the proper types in the language of your endpoint function:
The model's output is contained in the result object which can be a literal, array or dictionary.
Updating your Model
You can publish a new version of your model at any time. For example, you may want to re-train the model with new data, or switch to a different machine learning algorithm.
You can also unpublish the model and Domino will stop serving it. Note that if you are using advanced routing, and you have a promoted model, you cannot currently unpublish it.
Examples in Python and R
The example referenced here is found in this project:. Feel free to fork it and try for yourself.
Python
The model is first trained using train.py, and stored at results/classifier.pkl:
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn import svm from sklearn import cross_validation import time import joblib train = pd.read_csv("./winequality-red.csv", sep=";") cols = train.columns[:11] clf = RandomForestClassifier(n_estimators=100, max_features=5, min_samples_split=5) start = time.time() clf.fit(train[cols], train.quality) print "training time:", time.time() - start print "cross validation scores", cross_validation.cross_val_score(clf, train[cols], train.quality, cv=5) joblib.dump(clf, 'results/classifier.pkl')
The endpoint is bound to the predict(...) function, defined in predict.py (which loads and uses results/classifier.pkl):
import joblib import numpy as np clf = joblib.load("results/classifier.pkl") def predict(features): return np.asscalar(clf.predict(features))
R
The model is trained using train.R, and stored at classifier.Rda:
library(randomForest) df <- read.csv("./winequality-red.csv", h=T, sep = ";") df$quality <- factor(df$quality) cols <- names(df)[1:11] system.time({ clf <- randomForest(df$quality ~ ., data=df[,cols], ntree=30, nodesize=4, mtry=8) }) save(clf, file="classifier.Rda") save(cols, file="cols.Rda")
The endpoint is bound to the predictQuality(...) function, defined in predict.R (which loads and uses classifier.Rda):
library(randomForest) load("classifier.Rda") load("cols.Rda") predictQuality <- function(features) { to_predict <- as.data.frame(features) colnames(to_predict) <- cols prediction <- predict(clf, to_predict) cbind(prediction)[1] }
Example API Request
In either case, once published, a request might look something like this:
curl -v -X POST '<modelId>/latest/model' \
-H 'Content-Type: application/json' \
-u 'YOUR_API_KEY:YOUR_API_KEY' \
-d '{"parameters": [[5.6, 0.615, 0, 1.6, 0.089, 16, 59, 0.9943, 3.58, 0.52, 9.9]]}'
Note that the version of your API endpoint is included in the API response.
Example API Response
The API call above returns the following JSON. The model's output is returned in the "result" object while the "release" object contains information about the version of your API endpoint and the file and function which powers it.
{ "release": { "model_version": "591b2d598c943ee48d869ce4",
"model_version_number": 2 }, "result": 5 }
Common issues, pitfalls, and other tips, described in this Stack Overflow answer. as described in this Stack Overflow answer. For NumPy data types, convert the values to Python primitives. An easy way to do this is to call
numpy.asscalar as described above.
|
https://support.dominodatalab.com/hc/en-us/articles/115001488023-Model-Manager-Overview-
|
CC-MAIN-2017-26
|
refinedweb
| 1,513
| 57.37
|
Darren New <dnew at san.rr.com> wrote: | Phlip wrote: | > Ruby trumps Python in the simple matter of | > closures (imagine my shock when I discovered Python didn't have them). | | Can someone summarize the important difference between closures and object | instances? Other than convenience, I mean, it would seem that something like | | class yadda: | def __init__(self, a, b): | self.a = a ; self.b = b | def __call__(self, x, y): | return (self.a + x * self.b * y) | | would seem to be quite a lot like a closure with a and b bound and x and y | free? Don't underestimate convenience. :-) If you had to declare each string value in your program as a class like the above, it would make strings less useful in a practical sense although they'd still be equivalent in a theoretical sense. C++ suffers from this when it comes to container types -- building a list or array takes a lot more syntax than just "[1, 2, 3]" so people use them less casually. Function objects in C++ are even worse, although perhaps the "Lambda library" () may help. - Amit -- -- Amit J Patel, Computer Science Department, Stanford University
|
https://mail.python.org/pipermail/python-list/2001-March/109872.html
|
CC-MAIN-2018-05
|
refinedweb
| 192
| 74.29
|
Components in React JS day#2
Hello, guys welcome back today. In the previous article, we see how to write hello world using react. In this, we going to see components
Components in React JS
what are components?
components are the building blocks of the react. It used to separate our web page functionality into different components.
Components are simply taken props as an argument to the constructor and return the react element from the render function inside the class component. It used to increase the reusable of our code on the web page.
Let’s understand with an example.
Consider the code speedy website blog page.
It has the following thing
- Navigation at the top.
- Footer at the bottom.
- Displays the blogs on the website in the middle.
- The search bar, Advertisement, and Latest articles are on the right side.
Divide the website into components as follows
- Navigation (It has a list of text with links).
- Blog list (It has blog title, author, and description).
- Search bar (It has an input box and button).
- Advertisement (It simply displays the ads).
- Latest article (It list all the latest articles).
- Footer (It also similar to the header has a list of text with links associated with it).
You can divide it as your wish but I divide it like this for our understanding purpose.
Each component has its own HTML element and its functionality.
If you take the search bar it has an input box and a search button. When the user clicks it. The function of the search button to search for a blog contains a name that the user entered and display.
Now you get some idea about components.
Types of react components
In react it has two types of components
- Class component
- Function component
We are only going to see about the class component.
Class component
The class component in react is must satisfied the following condition
- The class component is must extend the React.Component class.
- Must pass the props to React.Component in the constructor by using a super function if you passing props to children.
- Must have a function name with render and must return the react element that is JSX.
Let’s understand it by our game program.
First, see how to play the game. It is so simple first player need to enter his name and register for the battle once the player register he gets into the battlefield.
He has to play with the bot. He has three options he can choose rock or paper or scissors once the user-chosen bot will choose a random weapon and we check the logic and find who is a winner and increase their score.
The player needs to play until he scores 5 points or bot score 5 points so who score the first 5 points will be the winner.
Divide our game into component
You get the idea about the game now let’s divide our game into the component below
- App
- Header
- Player
- Weapon
1.App
This is just a container for our game it contains all other components in it and renders them.
2.Header
It just a simple component used to display the game name at the top.
3.Register
It has an input box and button where the user must register their name to play a game. It has a player component as a child and it only renders its if a user registers to play the game.
4.Player
This is the most important component. It holds the logic for our game and it has a child weapon component.
5.Weapon
It just a simple component it displays the rock paper scissor weapons.
Now you get some ideas about our game. It’s time to write some code.
Removing unwanted file
In a previous article, we see how to write hello world program in react. In that program, we have some unwanted files that no need for our game so first we delete that file.
The files that are no need are given below just delete that files.
rpsbattle ├── public │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src ├── App.test.js ├── logo.svg ├── serviceWorker.js └── setupTests.js
Now create folder components under the src directory and create a file for our component similar to the given below.
rpsbattle └── src ├──components └────── Header.js └────── Header.css └────── Register.js └────── Register.css └────── Player.js └────── Player.css └────── Weapon.js └────── Weapon.css
This is the best always separate our components from our app so it is easy to handle.
Note: The filename of the component must be in uppercase for the first letter.
Header components
Now take look at the Header component it is the simple class component that simply returns a P tag.
Header.js
import React from "react"; class Player extends React.Component { render() { return( <div className='header'> <p> RPS Battle</p> </div> ); } } export default Header;
We are importing react because we using React.component and we export our Header component so only we can use that in other files.
Now import our Header component in App.js.
App.js
import React from 'react'; import Header from "./components/Header"; class App extends React.Component{ render() { return( <div> <Header/> </div> ); } }
Now run our code by the command
npm start
It will start the development server and run our code in the browser you will get similar output as below.
we will see about other components in upcoming articles.
Conclusion
Ok guys that’s enough for today. We learn about components in react JS in this article. In the next article, we learn about how to add style to our component.
All the best guys for upcoming days keep learning.
|
https://www.codespeedy.com/components-in-react-js-day2/
|
CC-MAIN-2021-17
|
refinedweb
| 949
| 66.33
|
Dear Joseph Weston,
yes you are right.
"I am trying to create a system with translational symmetry, and that each Kwant *site* corresponds to a single atom."
We know according to the nanoribbon, we have a scattering region that is attached to the leads. I want to find the number of kwant site (which I mentioned as atom) in the scattering region (which I mentioned as unit cell).
Please look at the following example for the graphene nanoribbon:
import kwant
from math import sqrt
import matplotlib.pyplot as plt
import tinyarray
import numpy as np
import math
import cmath
import matplotlib
d=1.42;
a1=d*math.sqrt(3)
t=-3.033;
latt = kwant.lattice.general([(a1,0),(a1*0.5,a1*math.sqrt(3)/2)],
[(a1/2,-d/2),(a1/2,d/2)])
a,b = latt.sublattices
syst= kwant.Builder()
#...................................................................................
def rectangle(pos):
x, y = pos
z=x**2+y**2
return -2.9*a1<x<2.9*a1 and -7.5*d<y<7.5*d
syst[latt.shape(rectangle, (1,1))]=0
syst[[kwant.builder.HoppingKind((0,0),a,b)]] =t
syst[[kwant.builder.HoppingKind((0,1),a,b)]] =t
syst[[kwant.builder.HoppingKind((-1,1),a,b)]] =t
ax=kwant.plot(syst);
sym = kwant.TranslationalSymmetry(latt.vec((-5,0)))
sym.add_site_family(latt.sublattices[0], other_vectors=[(-1, 2)])
sym.add_site_family(latt.sublattices[1], other_vectors=[(-1, 2)])
lead = kwant.Builder(sym)
def lead_shape(pos):
x, y = pos
return -7.5*d<y<7.5*d
lead[latt.shape(lead_shape, (1,1))] = 0
lead[[kwant.builder.HoppingKind((0,0),a,b)]] =t
lead[[kwant.builder.HoppingKind((0,1),a,b)]] =t
lead[[kwant.builder.HoppingKind((-1,1),a,b)]] =t
syst.attach_lead(lead,add_cells=0)
syst.attach_lead(lead.reversed(),add_cells=0)
ax=kwant.plot(syst);
def plot_bands(syst):
fsys = syst.finalized()
plt.figure()
kwant.plotter.bands(fsys.leads[0], args=(dict(gamma=1., ep=0.),))
plt.xlabel("K")
plt.ylabel("band structure (eV)")
plt.ylim((-4.0,4.0))
plt.show()
plot_bands(syst)
Here we have a main region such that the whole system can be made by repeating this region. I want to know the number of site in the main region.
."
When we plot the band structure, we have a Hamiltonian (the dimension is N*N) in terms of K point. So, we have N eigenvalues for each K point. How we can find these eigenvalues for each K point. How is it shown in Kwant? Would you please help me.
Best,
Sajad
From: "Joseph Weston" <joseph.weston08@gmail.com>
To: "Saj.ZiaBorujeni" <saj.ziaborujeni.sci@iauctb.ac.ir>, kwant-discuss@kwant-project.org
Sent: Thursday, Aban 30, 1398 3:59:57 PM
Subject: Re: [Kwant] Access to eigenvalue, eigenvector and number of points in each unit cell
Hi..
Posting a complete code example is useful because it is more precise than describing your problem with words.
Happy Kwanting,
Joe
|
https://mail.python.org/archives/list/kwant-discuss@python.org/message/JYA4EFDUCAXXA6LTNUO5T4VNBP7BZ57C/attachment/2/attachment.htm
|
CC-MAIN-2022-40
|
refinedweb
| 483
| 54.59
|
Hello all,
I wrote this program to work out monthly payment for personal loan. Say, you borrow 15000 (principal) at 7.50% APR for 4 years?
So my formula is (maybe wrong):-
1. months = 4 * 12;
2. interest = principal * 7.50 / months;
3. monthlypayment = (principal + Interest) / months;
My monthly payment comes out as 361.38, is this correct?
What is correct formula to do this?
Here is my program, just in case you want to see it. Thanks.
Code:// Calculating loan payment/interest #include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { char again; do { system("CLS"); double amount, //amount per month principal, //loan amount rate, //interest rate interest, //total interest months, //months years, //years term totalpayment; // set the floating-point number format cout << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 2 ); cout << "Enter amount of loan: "; cin >> principal; cout << "Enter rate ( APR % ): "; cin >> rate; cout << "Enter number of years: "; cin >> years; //some calculation months = years * 12; interest = principal * rate / months; amount = (principal + interest) / months; totalpayment = principal + interest; //display cout << endl << "LOAN CALCULATION:"; cout << endl << "=================" << endl; cout << "Total Loan : " << setw( 8 ) << principal << endl; cout << "Rate APR % : " << setw( 8 ) << rate << endl; cout << "Total years : " << setw( 8 ) << years << endl; cout << "Total interest : " << setw( 8 ) << interest << endl; cout << "Monthly payment : " << setw( 8 ) << amount << endl; cout << "Total Payment : " << setw( 8 ) << totalpayment << endl << endl; cout << "Again y/n? "; cin >> again; } while (again == 'y' ); return 0; }
|
http://cboard.cprogramming.com/cplusplus-programming/25897-loan-calculation-formula.html
|
CC-MAIN-2013-48
|
refinedweb
| 231
| 62.58
|
In the previous chapter you were introduced to some basic object-oriented programming terms. This chapter will expand on these terms, and introduce you to some new ones, while concentrating on how they apply to the Objective-C language and the GNUstep base library. First let us look at some non OO additions that Objective-C makes to ANSI C.
Objective-C makes a few non OO additions to the syntax of the C programming language that include:
BOOL) capable of storing either of the values
YESor
NO.
BOOLis a scalar value and can be used like the familiar
intand
chardata types.
BOOLvalue of
NOis zero, while
YESis non-zero.
//) to mark text up to the end of the line as a comment.
#importpreprocessor directive was added; it directs the compiler to include a file only if it has not previously been included for the current compilation. This directive should only be used for Objective-C headers and not ordinary C headers, since the latter may actually rely on being included more than once in certain cases to support their functionality.
Object-oriented (OO) programming is based on the notion that a software system can be composed of objects that interact with each other in a manner that parallels the interaction of objects in the physical world.
This model makes it easier for the programmer to understand how software works since it makes programming more intuitive. The use of objects also makes it easier during program design: take a big problem and consider it in small pieces, the individual objects, and how they relate to each other.
Objects are like mini programs that can function on their own when requested by the program or even another object. An object can receive messages and then act on these messages to alter the state of itself (the size and position of a rectangle object in a drawing program for example).
In software an object consists of instance variables (data) that represent the state of the object, and methods (like C functions) that act on these variables in response to messages.
As a programmer creating an application or tool, all you need do is send messages to the appropriate objects rather than call functions that manipulate data as you would with a procedural program.
The syntax for sending a message to an object, as shown below, is one of the additions that Objective-C adds to ANSI C.
Note the use of the square [ ] brackets surrounding the name of the object and message.
Rather than 'calling' one of its methods, an object is said to 'perform' one of its methods in response to a message. The format that a message can take is discussed later in this section.
Objective-C defines a new type to identify an object:
id, a type that
points to an object's data (its instance variables). The following code
declares the variable '
button' as an object (as opposed to
'
button' being declared an integer, character or some other data type).
When the button object is eventually created the variable name '
button'
will point to the object's data, but before it is created the variable could
be assigned a special value to indicate to other code that the object does not
yet exist.
Objective-C defines a new keyword
nil for this assignment, where
nil is of type
id with an unassigned value. In the button
example, the assignment could look like this:
which assigns
nil in the declaration of the variable.
You can then test the value of an object to determine whether the object exists, perhaps before sending the object a message. If the test fails, then the object does not exist and your code can execute an alternative statement.
The header file
objc/objc.h defines
id,
nil, and other
basic types of the Objective-C language. It is automatically included in your
source code when you use the compiler directive
#include
<Foundation/Foundation.h> to include the GNUstep Base class definitions.
A message in Objective-C is the mechanism by which you pass instructions to objects. You may tell the object to do something for you, tell it to change its internal state, or ask it for information.
A message usually invokes a method, causing the receiving object to respond in some way. Objects and data are manipulated by sending messages to them. Like C-functions they have return types, but function specific to the object.
Objects respond to messages that make specific requests. Message expressions are enclosed in square brackets and include the receiver or object name and the message or method name along with any arguments.
To send a message to an object, use the syntax:
[receiver messagename];
where
receiver is the object.
The run-time system invokes object methods that are specified by messages. For example, to invoke the display method of the mySquare object the following message is used:
[mySquare display];
Messages may include arguments that are prefixed by colons, in which
case the colons are part of the message name, so the following message
is used to invoke the
setFrameOrigin:: method:
[button setFrameOrigin: 10.0 : 10.0];
Labels describing arguments precede colons:
[button setWidth: 20.0 height: 122.0];
invokes the method named
setWidth:height:
Messages that take a variable number of arguments are of the form:
[receiver makeList: list, argOne, argTwo, argThree];
A message to
nil does NOT crash the application (while in Java messages
to
null raise exceptions); the Objective-C application does nothing.
For example:
[nil display];
will do nothing.
If a message to
nil is supposed to return an object, it will return
nil. But if the method is supposed to return a primitive type such as
an
int, then the return value of that method when invoked on
nil, is undefined. The programmer therefore needs to avoid using the
return value in this instance.
Polymorphism refers to the fact that two different objects may respond differently to the same message. For example when client objects receive an alike message from a server object, they may respond differently. Using Dynamic Binding, the run-time system determines which code to execute according to the object type.
A class in Objective-C is a type of object, much like a structure definition in C except that in addition to variables, a class has code - method implementations - associated with it. When you create an instance of a class, also known as an object, memory for each of its variables is allocated, including a pointer to the class definition itself, which tells the Objective-C runtime where to find the method code, among other things. Whenever an object is sent a message, the runtime finds this code and executes it, using the variable values that are set for this object.
Most of the programmer's time is spent defining classes.
Inheritance helps reduce coding time by providing a convenient way of
reusing code.
For example, the
NSButton class defines data (or instance variables) and methods to create button objects of a certain type, so a subclass of
NSButton could be produced to create buttons of another type - which may perhaps have a different border colour. Equally
NSTextField can be used to define a subclass that perhaps draws a different border, by reusing definitions and data in the superclass.
Inheritance places all classes in a logical hierarchy or tree structure that
may have the
NSObject class at its root. (The root object may be
changed by the developer; in GNUstep it is
NSObject, but in "plain"
Objective-C it is a class called "
Object" supplied with the runtime.)
All classes may have subclasses, and all except the root class do have
superclasses. When a class object creates a new instance, the new object holds
the data for its class, superclass, and superclasses extending to the root
class (typically
NSObject). Additional data may be added to classes so
as to provide specific functions and application logic.
When a new object is created, it is allocated memory space and its data in the
form of its instance variables are initialised. Every object has at least one
instance variable (inherited from
NSObject) called
isa, which is
initialized to refer to the object's class. Through this reference, access is
also afforded to classes in the object's inheritance path.
In terms of source code, an Objective-C class definition has an:
Typically these entities are confined to separate files
with
.h and
.m extensions for Interface and Implementation files,
respectively. However they may be merged
into one file, and a single file may implement multiple classes.
Each new class inherits methods and instance variables from another class. This results in a class hierarchy with the root class at the core, and every class (except the root) has a superclass as its parent, and all classes may have numerous subclasses as their children. Each class therefore is a refinement of its superclass(es).
Objects may access methods defined for their class, superclass, superclass' superclass, extending to the root class. Classes may be defined with methods that overwrite their namesakes in ancestor classes. These new methods are then inherited by subclasses, but other methods in the new class can locate the overridden methods. Additionally redefined methods may include overridden methods.
Abstract classes or abstract superclasses such as
NSObject define
methods and instance variables used by multiple subclasses.
Their purpose is to reduce the development effort required to
create subclasses and application structures.
When we get technical, we make a distinction between a pure abstract
class whose methods are defined but instance variables are not,
and a semi-abstract class where instance variables are defined).
An abstract class is not expected to actually produce functional instances since crucial parts of the code are expected to be provided by subclasses. In practice, abstract classes may either stub out key methods with no-op implementations, or leave them unimplemented entirely. In the latter case, the compiler will produce a warning (but not an error).
Abstract classes reduce the development effort required to create subclasses and application structures.
A class cluster is an abstract base class, and a group of private, concrete subclasses. It is used to hide implementation details from the programmer (who is only allowed to use the interface provided by the abstract class), so that the actual design can be modified (probably optimised) at a later date, without breaking any code that uses the cluster.
Consider a scenario where it is necessary to create a class hierarchy to define objects holding different types including chars, ints, shorts, longs, floats and doubles. Of course, different types could be defined in the same class since it is possible to cast or change them from one to the next. Their allocated storage differs, however, so it would be inefficient to bundle them in the same class and to convert them in this way.
The solution to this problem is to use a class cluster: define an abstract superclass that specifies and declares components for subclasses, but does not declare instance variables. Rather this declaration is left to its subclasses, which share the programmatic interface that is declared by the abstract superclass.
When you create an object using a cluster interface, you are given an object of another class - from a concrete class in the cluster.
In GNUstep,
NSObject is a root class that provides a base
implementation for all objects, their interactions, and their integration in
the run-time system.
NSObject defines the
isa instance variable
that connects every object with its class.
In other Objective-C environments besides GNUstep,
NSObject will be
replaced by a different class. In many cases this will be a default class
provided with the Objective-C runtime. In the GNU runtime for example, the
base class is called
Object. Usually base classes define a similar set
of methods to what is described here for
NSObject, however there are
variations.
The most basic functions associated with the
NSObject class (and
inherited by all subclasses) are the following:
In addition,
NSObject supports the following functionality:
In fact, the
NSObject class is a bit more complicated than just
described. In reality, its method declarations are split into two components:
essential and ancillary. The essential methods are those that are needed by
any root class in the GNUstep/Objective-C environment. They are declared
in an "
NSObject protocol" which should be implemented by any other
root class you define (see Protocols). The ancillary
methods are those specific to the
NSObject class itself but need not be
implemented by any other root class. It is not important to know which
methods are of which type unless you actually intend to write an alternative
root class, something that is rarely done.
Recall that the
id type may be used to refer to any class of object.
While this provides for great runtime flexibility (so that, for example, a
generic
List class may contain objcts of any instance), it prevents the
compiler from checking whether objects implement the messages you send them.
To allow type checking to take place, Objective-C therefore also allows you to
use class names as variable types in code. In the following example, type
checking verifies that the
myString object is an appropriate type.
Note that objects are declared as pointers, unlike when
id is used.
This is because the pointer operator is implicit for
id. Also, when
the compiler performs type checking, a subclass is always permissible where
any ancestor class is expected, but not vice-versa.
Static typing is not always appropriate. For example, you may wish to store
objects of multiple types within a list or other container structure. In
these situations, you can still perform type-checking manually if you need to
send an untyped object a particular message. The
isMemberOfClass:
method defined in the
NSObject class verifies that the receiver is of a
specific class:
The test will return false if the object is a member of a subclass of the
specific class given - an exact match is required. If you are merely
interested in whether a given object descends from a particular class, the
isKindOfClass: method can be used instead:
There are other ways of determining whether an object responds to a particular method, as will be discussed in Advanced Messaging.
As you will see later, classes may define some or all of their instance
variables to be public if they wish. This means that any other object or
code block can access them using the standard "
->" structure access
operator from C. For this to work, the object must be statically typed (not
referred to by an
id variable).
In general, direct instance variable access from outside of a class is not recommended programming practice, aside from in exceptional cases where performance is at a premium. Instead, you should define special methods called accessors that provide the ability to retrieve or set instance variables if necessary:
While it is not shown here, accessors may perform arbitrary operations before returning or setting internal variable values, and there need not even be a direct correspondence between the two. Using accessor methods consistently allows this to take place when necessary for implementation reasons without external code being aware of it. This property of encapsulation makes large code bases easier to maintain.
Classes themselves are maintained internally as objects in their own right in Objective-C, however they do not possess the instance variables defined by the classes they represent, and they cannot be created or destroyed by user code. They do respond to class methods, as in the following:
Classes respond to the class methods their class defines, as well as those defined by their superclasses. However, it is not allowed to override an inherited class method.
You may obtain the class object corresponding to an instance object at runtime
by a method call; the class object is an instance of the "
Class"
class.
Classes may also define a version number (by overriding that defined in
NSObject):
int versionNumber = [NSString version];
This facility allows developers to access the benefits of versioning for classes if they so choose.
Class names are about the only names with global visibility in Objective-C.
If a class name is unknown at compilation but is available as a string at run
time, the GNUstep library
NSClassFromString function may be used to
return the class object:
The function returns
Nil if it is passed a string holding an invalid
class name. Class names, global variables and functions (but not methods)
exist in the same name space, so no two of these entities may share the same
name.
The following lists the full uniqueness constraints on names in Objective-C.
There are also a number of conventions used in practice. These help to make code more readable and also help avoid naming conflicts. Conventions are particularly important since Objective-C does not have any namespace partitioning facilities like Java or other languages.
Strings in GNUstep can be handled in one of two ways. The first way is the C
approach of using an array of
char. In this case you may use the
"
STR" type defined in Objective-C in place of
char[].
The second approach is to rely on the
NSString class and associated
subclasses in the GNUstep Base library, and compiler support for them. Using
this approach allows use of the methods in the
NSString API. In addition, the
NSString class provides the means to initialize strings using
printf-like formats.
The
NSString class defines objects holding raw Unicode character
streams or strings. Unicode is a 16-bit worldwide standard used to define
character sets for all spoken languages. In GNUstep parlance the Unicode
character is of type unichar.
A static instance is allocated at compile time. The creation of a static
instance of
NSString is achieved using the
@"..." construct
and a pointer:
Here,
w is a variable that refers to an
NSString object
representing the ASCII string "Brainstorm".
The class method
stringWithFormat: may also be used to create instances
of
NSString, and broadly echoes the
printf() function in the C
programming language.
stringWithFormat: accepts a list of arguments
whose processed result is placed in an
NSString that becomes a return
value as illustrated below:
The example will produce an
NSString called
gprsChannel
holding the string "The GPRS channel is 5".
stringWithFormat: recognises the
%@ conversion specification
that is used to specify an additional
NSString:
The example assigns the variable
two the string "Our trading name is
Brainstorm." The
%@ specification can be used to output an object's
description - as returned by the
NSObject
-description method),
which is useful when debugging, as in:
When a program needs to call a C library function it is useful to convert
between
NSStrings and standard ASCII C strings (not fixed at compile
time). To create an
NSString using the contents of the returned C
string (from the above example), use the
NSString class method
stringWithCString::
To convert an
NSString to a standard C ASCII string,
use the
cString method of the
NSString class:
NSStrings are immutable objects; meaning that once they are created,
they cannot be modified. This results in optimised
NSString code. To
modify a string, use the subclass of
NSString, called
NSMutableString. Use a
NSMutableString wherever a
NSString could be used.
An
NSMutableString responds to methods that modify the string directly -
which is not possible with a generic
NSString.
To create a
NSMutableStringuse
stringWithFormat::
While
NSString's implementation of
stringWithFormat: returns
a
NSString,
NSMutableString's implementation returns an
NSMutableString.
Note. Static strings created with the
@"..." construct are
always immutable.
NSMutableStrings are rarely used because to modify a string, you
normally create a new string derived from an existing one.
A useful method of the
NSMutableString class is
appendString:,
which takes an
NSString argument, and appends it to the receiver:
This code produces the same result as:
The the GNUstep Base library has numerous string manipulation features,
and among the most notable are those relating to writing/reading
strings to/from files. To write the contents of a string to a file,
use the
writeToFile:atomically: method:
writeToFile:atomically: returns YES for success, and NO for. This is a useful feature, which should be enabled.
To read the contents of a file into a string, use
stringWithContentsOfFile:, as shown in the following
example that reads
@"/home/Brainstorm/test":
This document was generated by Richard Frith-Macdonald on July, 26 2013 using texi2html 1.76.
|
https://www.gnu.org/software/gnustep/resources/documentation/Developer/Base/ProgrammingManual/manual_2.html
|
CC-MAIN-2015-35
|
refinedweb
| 3,404
| 50.67
|
Assign a group to values
I have a pandas dataframe with several columns(20) and rows (16404). One the columns is ['age']. I would like to be able to plot other metrics such as ['Income'] over a category of age. Ex: What's the income for all the Males under 20 years old or Females aged between 20 and 40.
I tried this type of condition:
for i in range(len(df['age'])): if df['age'][i]<25 and df['Gender'][i]==1: df['group'][i]=1
But I get the following error:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
Could you please indicate me how to assign a group to a row depending on these conditions please?
All the series are int64
Best
- Ambiguous error can be solved by
(df['age'] < 25) & (df['Gender'] == 1)Note that I used an
&instead of
and.
- if you did that, you are evaluating an entire column and assigning an entire column for every row which is very wasteful.
Do this to get booleans
df['group'] = df['age'].lt(25) & df['Gender'].eq(1)
you can convert that to integers
0 and
1 in many ways
df['group'] = df['group'].astype(int)
[PDF] Grouping Values in Web Intelligence 4.1, Web Intelligence 4.1 allows you to create Grouping variables to group your data, Check Automatically Group to assign a group name for all ungrouped values. So, if you assign each of the 5001 values 0, 0.001, 0.002,, 4.999, 5 to 128 ranges, the numbers of elements per range will at best vary between 39 and 40. Suggestion: Use 5/128=0.0390625 as the interval length, right-open intervals, but assign 5 to group 128 (so as to avoid a 129th group for value 5 alone).
You should use apply method instead (see doc):
def your_function(row): if row['age']<25 and row['Gender']==1: return 1 else: return 0 df['group'] = df.apply(your_function,axis=1)
Excel formula: Randomly assign data to groups, To randomly assign people to groups or teams of a specific size, you can use a helper column with a value generated by the RAND function, together with a Assign each customer a group number. Results: Each record will be assigned a group number. Each customer will have a unique group number. In order to allow future sorting, you copy the formulas in column A and use Home, Paste dropdown, Paste Values to convert the formulas to numbers.
cond_1 = df['age'] < 25 cond_2 = df['Gender'] == 1 df['group'] = np.where(cond_1 & cond_2, 1, 0)
It will assign
1 where both conditions are satisfied and
0 everywhere else.
Taking into account your comments, this method doesn't have to be binary. You can include as many conditions as you need and you can substitute the
1 for any int or str you want. Moreover, you can change the
0 to
np.nan.
Organizing values by groups and sets – Zendesk help, Creating groups. A group is a way to organize your attribute values. A group has the following advantages over a set: You can use groups to Stack Overflow Public questions and answers; Assign value to group based on condition in column. group date value newValue 1 1 1 3 2 2 1 2 4 2 3 1 3 3 2 4 2 4
Make Group Tool, The Make Group tool takes data relationships and assembles the L and M make their own group, L as they do not relate to the other values in Group A. By this logic, the Make Group tool would assign the following groups: Assign a value or category based on a number range with formula The following formulas can help you to assign a value or category based on a number range in Excel. Please do as follows.
Solved: How to assign group name to range of non-numeric v , Solved: Need help in assigning a group to a set of data using a range of values. The groups and ranges are defined in data set #1. The values If you need to group by number, you can use the VLOOKUP function with a custom grouping table. This allows you to make completely custom or arbitrary groups. This formula uses the value in cell D5 for a lookup value, the named range "age_table" (G5:H8) for the lookup table, 2 to indicate "2nd column", and TRUE as the last argument indicate
Creating data groups, If you selected a numeric column, set the groups in the following way: Each group is automatically assigned an equal number of values. When you change the Here is the solution using ngroup from a comment above by Constantino, for those still looking for this function (the equivalent of dplyr::group_indices in R, or egen group() in Stata) if you were trying to search with those keywords like me).
|
http://thetopsites.net/article/51747326.shtml
|
CC-MAIN-2020-34
|
refinedweb
| 825
| 69.01
|
On 02/08/2016 20:52, Wesley Hayutin wrote: > > > On Tue, Aug 2, 2016 at 1:51 PM, Arie Bregman <abregman redhat com > <mailto:abregman redhat com>> wrote: > > On Tue, Aug 2, 2016 at 3:53 PM, Wesley Hayutin <whayutin redhat com > <mailto:whayutin redhat com>> wrote: > > > > > > On Tue, Aug 2, 2016 at 4:58 AM, Arie Bregman <abregman redhat com > <mailto:abregman redhat com>> wrote: > >> > >> It became a discussion around the official installer and how to > >> improve it. While it's an important discussion, no doubt, I actually > >> want to focus on our automation and CI tools. > >> > >> Since I see there is an agreement that collaboration does make sense > >> here, let's move to the hard questions :) > >> > >> Wes, Tal - there is huge difference right now between infrared and > >> tripleo-quickstart in their structure. One is all-in-one project and > >> the other one is multiple micro projects managed by one project. Do > >> you think there is a way to consolidate or move to a different model > >> which will make sense for both RDO and RHOSP? something that both > >> groups can work on. > > > > > > I am happy to be part of the discussion, and I am also very > willing to help > > and try to drive suggestions to the tripleo-quickstart community. > > I need to make a point clear though, just to make sure we're on > the same > > page.. I do not own oooq, I am not a core on oooq. > > I can help facilitate a discussion but oooq is an upstream tripleo > tool that > > replaces instack-virt-setup [1]. > > It also happens to be a great tool for easily deploying TripleO > end to end > > [3] > > > > What I *can* do is show everyone how to manipulate > tripleo-quickstart and > > customize it with composable ansible roles, templates, settings etc.. > > This would allow any upstream or downstream project to override > the native > > oooq roles and *any* step that does not work for another group w/ > 3rd party > > roles [2]. > > These 3rd party roles can be free and opensource or internal only, > it works > > either way. > > This was discussed in depth as part of the production chain > meetings, the > > message may have been lost unfortunately. > > > > I hope this resets your expectations of what I can and can not do > as part of > > these discussions. > > Let me know where and when and I'm happy to be part of the discussion. > > Thanks for clarifying :) > > Next reasonable step would probably be to propose some sort of > blueprint for tripleo-quickstart to include some of InfraRed features > and by that have one tool driven by upstream development that can be > either cloned downstream or used as it is with an internal data > project. > > > Sure.. a blueprint would help everyone understand the feature and the > motivation. > You could also just plug in the feature you are looking for to oooq and > see if it meets > your requirements. See below. > > > > OR > > have InfraRed pushed into tripleo/openstack namespace and expose it to > the RDO community (without internal data of course). Personally, I > really like the pluggable[1] structure (which allows it to actually > consume tripleo-quickstart) so I'm not sure if it can be really merged > with tripleo-quickstart as proposed in the first option. > > > The way oooq is built one can plugin or override any part at run time > with custom playbooks, roles, and config. There isn't anything that > needs to be > checked in directly to oooq to use it. > > It's designed such that third parties can make their own decisions to > use something > native to quickstart, something from our role library, or something > completely independent. > This allows teams, individuals or whom ever to do what they need to with > out having to fork or re-roll the entire framework. > > The important step is to note that these 3rd party roles or > (oooq-extras) incubate, mature and then graduate to github/openstack. > The upstream openstack community should lead, evaluate, and via > blueprints vote on the canonical CI tool set. > > We can record a demonstration if required, but there is nothing stopping > anyone right now from > doing this today. I'm just browsing the role library for an example, I > had no idea [1] existed. > Looks like Raoul had a requirement and just made it work. Yes, this is working on quickstart and it's part of the CI process we're using to test HA stuff. But another example that can be made is the ansible-role-tripleo-baremetal-undercloud role, which basically is another thing we created to make our requirement (baremetal) satisfied. >From this point of view I find quickstart (in truth everything for me started with C.A.T.) very open in terms of potential contribution one could make. If you guys think it can be useful I can fill up a document in which I explain how one can add something to quickstart to satisfy a requirement, I just don't know if this is what we are looking for in this discussion. -- Raoul Scarazzini rasca redhat com > Justin, from the browbeat project has graciously created some > documentation regarding 3rd party roles. > It has yet to merge, but it should help illustrate how these roles are > used. [2] > > Thanks Arie for leading the discussion. > > [1] > [2] > > > > > > > > I like the second option, although it still forces us to have two > tools, but after a period of time, I believe it will be clear what the > community prefers, which will allow us to remove one of the projects > eventually. > > So, unless there are other ideas, I think the next move should be > made by Tal. > > Tal, I'm willing to help with whatever is needed. > > [1] > > > > > Thanks > > > > [1] > > [2] > > > > > [3[ > > > > > >> > >> > >> Raoul - I totally agree with you, especially with "difficult for > >> anyone to start contributing and collaborate". This is exactly why > >> this discussion started. If we can agree on one set of tools, it will > >> make everyone's life easier - current groups, new contributors, folks > >> that just want to deploy TripleO quickly. But I'm afraid some > >> sacrifices need to be made by both groups. > >> > >> David - I thought WeiRDO is used only for packstack, so I apologize I > >> didn't include it. It does sound like an anther testing project, is > >> there a place to merge it with another existing testing project? like > >> Octario for example or one of TripleO testing projects. Or does it > >> make sense to keep it a standalone project? > >> > >> > >> > >> > >> On Tue, Aug 2, 2016 at 11:12 AM, Christopher Brown > <cbrown2 ocf co uk <mailto:cbrown2 ocf co uk>> > >> wrote: > >> > Hello> > >> >> > >> > -- > >> > Regards, > >> > > >> > Christopher Brown > >> > OpenStack Engineer > >> > OCF plc > >> > > >> > Tel: +44 (0)114 257 2200 <tel:%2B44%20%280%29114%20257%202200> > >> > Web: <> > >> > Blog: blog.ocf.co.uk <> > >> > Twitter: @ocfplc > >> > > >> > Please note, any emails relating to an OCF Support request must > always > >> > be sent to support ocf co uk <mailto. > >> > > >> > _______________________________________________ > >> > rdo-list mailing list > >> > rdo-list redhat com <mailto:rdo-list redhat com> > >> > > >> > > >> > To unsubscribe: rdo-list-unsubscribe redhat com > <mailto:rdo-list-unsubscribe redhat com> > >> > >> > >> > >> -- > >> Arie Bregman > >> Red Hat Israel > >> Component CI: > > > > > > > > -- > Arie Bregman > Red Hat Israel > Component CI: > > > > > _______________________________________________ > rdo-list mailing list > rdo-list redhat com > > > To unsubscribe: rdo-list-unsubscribe redhat com >
|
https://listman.redhat.com/archives/rdo-list/2016-August/msg00038.html
|
CC-MAIN-2021-25
|
refinedweb
| 1,196
| 66.37
|
Matplotlib inline plot size
Matplotlib Set Font Size Legend. and annotations can be added to the plot the loc argument may be omitted and Matplotlib. %matplotlib inline from matplotlib.Understand the basic components of a plot. %pylab inline %matplotlib inline ipython notebook --pylab=inline ipython notebook. The default figue size. In [42].
Tag: matplotlib Matplotlib Histogram. A line chart can be created using the Matplotlib plot() function. ax. legend (loc = 'upper center', bbox_to_anchor = (0.5.% matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import. # fixed bin size # Plot a histogram of. plt. legend (loc.4. Text and Annotation. An important part of making readable plots is labeling and annotating the axes. a matplotlib-based Python environment.
CME193: IntroductiontoScientificPython Lecture5: NumpyEasy Stacked Charts with Matplotlib. % matplotlib inline import. The end result is a new dataframe with the data oriented so the default Pandas stacked plot.
Simple Plotting » Matplotlib: legend;. legend (loc = (1.03, 0.2)) show (). one can change the legend.size property in the matplotlib rc parameters file.matplotlib legend location numbers. How do you change the size of figures drawn with matplotlib?. How to make IPython notebook matplotlib plot inline. 10.ipython and matplotlib does not plot in console. Hi,. //. in the new jupyter version the matplot inline is also.Basic Plotting with Pylab. The second specifies that figures should be shown inline,..
matplotlib Line Charts | Examples | PlotlyWe provide the basics in pandas to easily create decent looking plots. See the ecosystem section for visualization libraries that go beyond the basics documented here.
Scatterplot In MatPlotLib - chrisalbon.com
Matplotlib Cheat SheetTag: matplot Matplotlib legend. Matplotlib supports plots with time on the horizontal (x). If you want another size change the number of bins.Move legend outside of figure in matplotlib. % matplotlib inline from matplotlib import. See how legend overlaps with the plot. Fortunately matplotlib allows me.
. including figure size.legend(loc=0) # let matplotlib. %matplotlib inline It is also possible to activate inline matplotlib plotting with: %pylab inline.. etc. Alternatively, the loc argument may be omitted and Matplotlib puts. to font size and plot. for Matplotlib. This documents all plotting.%matplotlib inline import matplotlib.pyplot as plt import math x = range(0,100). plt.plot(x,y1,label='$x$') plt.legend(loc='best') Python Olmo S. Zavala Romero.Matplotlib: plotting. You can control the defaults of almost every property in matplotlib: figure size and dpi, line width. (loc = 'upper left').
import matplotlib as mpl mpl.rc("savefig", dpi=dpi) Where dpi is some number that will control the size/resolution of the inline plots. I believe the inline default is 80, and the default elsewhere with matplotlib is 100.This code might be useful to others struggling w/ scatter plots in matplotlib for python. It works except for this one problem. I have poured over many help topics on.
adding suggestions to reduce figure size for. The easiest way to get started with plotting using matplotlib is often to. and activating the %matplotlib inline.
I'm attempting to decrease the size of my figures with a title and legend attached. Matplotlib subplots Figure size. Included in an example of one of my plots.
Matplotlib cheat sheets: collection of code snippets, tips and tricks for Numpy open source Python numerical library.Setting the Title, Legend Entries, and Axis Titles in matplotlib How to set the title, axis-titles, and axis limits in matplotlib and plotly.
%matplotlib inline in a Notebook causes plots to be shown as static images, only 1 call to %matplotlib inline is required. %matplotlib notebook in a Notebook enables.
Memory leak with %matplotlib inline · Issue #7270
Histograms In MatPlotLib - chrisalbon.com
How to find threshold – Roy Huang – MediumThen delete "%matplotlib inline. is there any way to get inline plots. So the amount of leak per iteration is significantly smaller than the image size.
Adding Axis Labels to Plots With pandas - dataquest.ioPlace a legend on the axes at location loc. Labels are a. when creating a legend entry for a scatter plot/ matplotlib. size (legend, xdescent, ydescent.The matplotlib function gridspec allows subplots of unequal size to. as gridspec % matplotlib inline. to plot subplots of unequal sizes by.
matplotlib | Portable Document Format | CartesianXKCD-style plots in Matplotlib. f3 gives the size of the filter xaxis_loc, yaxis_log:. % pylab inline Welcome to pylab,.
matplotlib.rcParams Python Example - ProgramCreek
Modifying Matplotlib Figure in. we will see how we can convert a Matplotlib's Plot to a Plotly. % matplotlib inline import pprint import numpy as np...
Contour Plots; Python Image. Adding Legends and Annotations. it may be best to use 'best' as the argument for loc. Matplotlib will automatically try to.savefig() as PNG get a different result than the image shown in ipython notebook(SVG probably) #5859.
Easy Matplotlib Bar Chart. Making a bar plot in matplotlib is super simple,. car_sales_sorted.index.size]): ax.text.
ipython and matplotlib does not plot in console : Forums
Plotting in Python with matplotlib - chuck.emich.edumatplotlib.pyplot.legend. Controls the font size of. The number of marker points in the legend when creating a legend entry for a scatter plot/ matplotlib.Sometimes you may want to change the width or height or both of the plot figure generated by Matplotlib. For example, you may want the X-axis to be stretched out a.
Intro to Matplotlib. Matplotlib is a plotting Python library. import numpy as np import matplotlib.pyplot as plt % matplotlib inline. Plot Data.In this article, we show how to add a legend to a graph in matplotlib with Python. A legend is a very useful thing if you have multiple plots on a single graph. A.plot | Line Charts in matplotlib How to make a plot in matplotlib. Examples of the plot function, line and marker types, custom colors, and log and semi-log axes.
Matplotlib: adjusting image size — SciPy CookbookData Visualization with Python and Matplotlib. Matplotlib legend inside. (loc = 'upper center', bbox_to_anchor =. Matplotlib legend on top.This page provides Python code examples for matplotlib.rcParams.% matplotlib inline import matplotlib. Parameters ----- loc:. creating a legend entry for a scatter plot/:class:`matplotlib.collections.
Matplotlib Colors and Colormaps | Examples | Plotly
Legend guide ¶ This legend guide. The location of the legend can be specified by the keyword argument loc. Along with handlers for complex plot types such as.
# import matplotlib and set inline import matplotlib
Customizing Plot Legends | Python Data Science Handbook
Easy Stacked Charts with Matplotlib and Pandas – pstblog
|
http://jualforedi.tk/nywy/matplotlib-inline-plot-size-1546.php
|
CC-MAIN-2018-43
|
refinedweb
| 1,074
| 62.54
|
Python 3, which has been endorsed as the future of Python, was released in late 2008 and is currently under development. The goal is to address and fix Python 2’s legacy design flaws, clean up code base redundancy, and pursue a single best practice for performing tasks.
At first, the fact that Python 3 is not backward-compatible led to slow adoption by users, unfriendly to beginners. However, thanks to the efforts and determination of the Python community, there were 21903 Packages available to support Python 3.5 now, including most of the most popular Packages libraries. At the same time, a growing number of Packages libraries (e.g. Django, Numpy) indicated that their new versions would no longer support Python 2.
Python 2.7 will be released after 3.0 on July 3, 2010, and is scheduled to be the last version of 2.x. The historical task of Python 2.7 is to make it easier for Python 2.x users to port code to Python 3.x by providing compatibility measures between 2 and 3. So if you want your code to be compatible with two different versions, you need to at least make it work on Python 2.7。
1. Difference And Compatibility.
The __future__ module is the first thing we need to know, and the main purpose of this module is to support importing modules and functions in P2 that only work in P3. Is a very good compatibility tool library, and many examples of compatibility tips given below rely on it.
1.1 _future__ feature list.
1.2 Unified not equal grammar.
- Python 2 supports the use of <> and != to indicate not equal.
- Python 3 only supports use != to indicate not equal.
- Compatibility skills : All use ! = grammar only.
1.3 Unified integer type.
- The integer types in Python 2 can be subdivided into short int and long int.
- Python 3 eliminates short integers and use int for long integers only.
- Compatibility skills :
# Python 2 only k = 9223372036854775808L # Python 2 and 3: k = 9223372036854775808
# Python 2 only bigint = 1L # Python 2 and 3 from future.builtins import int bigint = int(1)
1.4 Unified integer division.
Python 2’s division/symbol actually has two functions.
- When both operands are integer objects, floor division (truncation of fractional parts) is performed to return the integer object.
- When two operands have at least one floating-point object, true division (preserving the fractional part) is performed to return the floating-point object.
The division/symbol of Python 3 only has the function of true division, while the function of floor division is left to //
Compatibility skills :
# Python 2 only: assert 2 / 3 == 0 # Python 2 and 3: assert 2 // 3 == 0 “True division” (float division):
# Python 3 only: assert 3 / 2 == 1.5 # Python 2 and 3: from __future__ import division # (at top of module)
1.5 Unified indentation syntax.
- Python 2 can indent using a mixture of TAB and space (1 TAB == 8 Spaces), but not all ides support this feature, so the same code won’t run across the ide.
- Python 3 use tabs as indentation uniformly. If tab and space exist at the same time, an exception will be triggered:
TabError: inconsistent use of tabs and spaces in indentation.
- Compatibility skills : Use tabs as indentation.
1.6 Unified class definition.
- Python 2 supports both new style (object) and old style classes.
- Python 3 use the new style class uniformly, and multiple inheritance can only be applied to new style class.
- Compatibility skills : Use new style classes uniformly.
1.7 Unified character encoding types.
- Python 2 uses ASCII character encoding by default, but since ASCII supports only a few hundred characters and is not flexible enough for non-english characters, Python 2 also supports Unicode, a more powerful character encoding. However, since Python 2 supports two sets of character encoding at the same time, some identification and conversion problems are unavoidable.
- Python 3 use unicode character encoding uniformly, which saves developers time and makes it easy to input and display more kinds of characters in the program.
- Compatibility skills : Use the prefix u in all string assignments, or introduce the unicode_literals character module.
# Python 2 only s1 = 'Hello World' s2 = u'Hello World' # Python 2 and 3 s1 = u'Hello World' s2 = u'Hello World' # Python 2 and 3 from __future__ import unicode_literals # at top of module s1 = 'Hello World' s2 = 'Hello World'
1.8 Unified import module path search.
- When Python 2 imports a module, it first searches the current directory (cwd) and, if not, the environment variable path (sys. path). This feature often brings troubles to developers, and i believe that everyone has encountered it, especially when the custom module and system module are renamed.
- To solve this problem, Python 3 only searches for environment variable paths by default. When you need to search for custom modules, you can add project paths to environment variables in package management mode, and then import them using absolute paths and relative paths (at the beginning).
- Compatibility skills : Unified use of absolute path for custom module import.
1.9 Fixed variable scope leaks in list derivation.
- Variables in the list of Python 2 can be leaked to global scope, for example:
import platform print('Python', platform.python_version()) i = 1 print('before: I = %s' % i) print('comprehension: %s' % [i for i in range(5)]) print('after: I = %s' % i) # OUT Python 2.7.6 before: i = 1 comprehension: [0, 1, 2, 3, 4] after: i = 4
- Python 3 solves this problem, and the variables in the list are no longer exposed to the global scope.
import platform print('Python', platform.python_version()) i = 1 print('before: i =', i) print('comprehension:', [i for i in range(5)]) print('after: i =', i) # OUT Python 3.4.1 before: i = 1 comprehension: [0, 1, 2, 3, 4] after: i = 1
1.10 Fixed an illegal comparison operation exception.
- Python 2 can compare two objects of different data types.
import platform print('Python', platform.python_version()) print("[1, 2] > 'foo' = ", [1, 2] > 'foo') print("(1, 2) > 'foo' = ", (1, 2) > 'foo') print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
- Below is the execution result.
Python 2.7.6 [1, 2] > 'foo' = False (1, 2) > 'foo' = True [1, 2] > (1, 2) = False
However, this seemingly convenient feature is actually a time bomb, because you can’t determine what causes the return value to be False (either data comparison or data type inconsistency). Python 3 corrects this, and a TypeError exception is triggered if the comparison operand types are inconsistent.
Compatibility skills : Never compare objects with inconsistent data types.
1.11 Unified exception throwing syntax.
- Python 2 supports both the old and new exception triggering syntax.
raise IOError, "file error" # Old raise IOError("file error") # New
- Python 3 use the new exception trigger syntax uniformly, otherwise SyntaxError exception will be triggered.
raise IOError("file error")
- Compatibility skills :
### throw exception # Python 2 only: raise ValueError, "dodgy value" # Python 2 and 3: raise ValueError("dodgy value") ### use traceback to throw exception # Python 2 only: traceback = sys.exc_info()[2] raise ValueError, "dodgy value", traceback # Python 3 only: raise ValueError("dodgy value").with_traceback() # Python 2 and 3: option 1 from six import reraise as raise_ # or # from future.utils import raise_ traceback = sys.exc_info()[2] raise_(ValueError, "dodgy value", traceback) # Python 2 and 3: option 2 from future.utils import raise_with_traceback raise_with_traceback(ValueError("dodgy value")) ### process exception chain # Setup: class DatabaseError(Exception): pass # Python 3 only class FileDatabase: def __init__(self, filename): try: self.file = open(filename) except IOError as exc: raise DatabaseError('failed to open') from exc # Python 2 and 3: from future.utils import raise_from class FileDatabase: def __init__(self, filename): try: self.file = open(filename) except IOError as exc: raise_from(DatabaseError('failed to open'), exc)
1.12 Unified exception handling syntax.
- Python 2 exception handling implementation can also support two kinds of grammar.
try: let_us_cause_a_NameError except NameError, err: # except NameError as err: print err, '--> our error message'
- Exception handling in Python 3 forces the use of the as keyword.
try: let_us_cause_a_NameError except NameError as err: print err, '--> our error message'
- Compatibility skills : Unified use of as keyword exception handling.
1.13 Unified input function.
- Python 2 supports raw_input and input two input functions, except that the raw_input function returns only string-type objects, while the input function returns both numeric and string data type objects, and implicitly calls an eval function to return the result of its execution result when the input is an expression. Obviously, using input is a more flexible way to write it.
- Therefore, Python 3 uniformly uses the input function for input processing.
- Compatibility skills : Unified use of input built-in functions.
# Python 2 only: input("Type something safe please: ") # Python 2 and 3 from future.builtins import input eval(input("Type something safe please: "))
1.14 Unified output function.
- Print in Python 2 is both a key word and a built-in function. Print’Hello world!’ is a statement and print (‘Hello world!’) is a function call.
- The prototype of Python 3 is as follows. This change makes the output processing of Python 3 more concise, powerful and elegant. The complex code in Python 2 can be replaced by the transfer of parameters.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- Compatibility skills :
### print single string in single line # Python 2 only: print 'Hello' # Python 2 only: print 'Hello' ### print multiple string in single line # Python 2 only: print 'Hello', 'Guido' # Python 2 and 3: from __future__ import print_function # (at top of module) print('Hello', 'Guido') ### output redirection # Python 2 only: print >> sys.stderr, 'Hello' # Python 2 and 3: from __future__ import print_function print('Hello', file=sys.stderr) ### print and return a new line # Python 2 only: print 'Hello', # Python 2 and 3: from __future__ import print_function print('Hello', end='')
1.15 Unified file manipulation functions.
- Python 2 supports file manipulation using the file and open functions.
- Python 3 uniformly use open for file operation.
- Compatibility skills : Use the open function uniformly.
# Python 2 only: f = file(pathname) # Python 2 and 3: f = open(pathname)
1.16 Unified List Iterator Generation Function.
- Python 2 supports the use of range and xrange functions to generate iteratable objects. The difference is that the former returns a list-type object, while the latter returns an iteration object similar to a generator (lazy evaluation), which supports infinite iteration. So when you need to generate a large sequence, it is recommended to use xrange, because it does not allocate all the memory space needed for the sequence at beginning. The xrange function is obviously more efficient if the sequence is read only, but if you want to modify the elements of the sequence or add or delete elements to the sequence, you had better generate a list object by the range function.
- Python 3 uniformly uses the range function to generate iterable objects, but in fact, the range of Python 3 is more like the xrange of Python 2. So in Python 3 if you want a list object that can be modified, you need to do like this:
list(range(1,10)) [1, 2, 3, 4, 5, 6, 7, 8, 9]
- Compatibility skills : Use the range function uniformly.
# Python 2 only: for i in xrange(10**8): ... # Python 2 and 3: forward-compatible from future.builtins import range for i in range(10**8): ... # Python 2 and 3: backward-compatible from past.builtins import xrange for i in xrange(10**8): ...
1.17 Unified iterator iteration function.
- Python 2 supports the use of built-in function next and the iterator object’s next() instance method to obtain the next element of the iterator object. Therefore, when implementing a custom iterator object class, the next() method must be implemented:
# Python 2 only class Upper(object): def __init__(self, iterable): self._iter = iter(iterable) def next(self): # Py2-styface iterator interface return self._iter.next().upper() def __iter__(self): return self itr = Upper('hello') assert itr.next() == 'H' # Py2-style assert list(itr) == list('ELLO')
- However, in Python 3, it is unified to use the next built-in function to get the next element, and if you try to call the object’s next() method, the AttributeError exception is triggered. So, to implement a custom iterator in Python 3 you should implement the special __next__ method.
- Compatibility skills :
# Python 2 and 3: option 1 from future.builtins import object class Upper(object): def __init__(self, iterable): self._iter = iter(iterable) def __next__(self): # Py3-style iterator interface return next(self._iter).upper() # builtin next() function calls def __iter__(self): return self itr = Upper('hello') assert next(itr) == 'H' # compatible style assert list(itr) == list('ELLO') # Python 2 and 3: option 2 from future.utils import implements_iterator @implements_iterator class Upper(object): def __init__(self, iterable): self._iter = iter(iterable) def __next__(self): # Py3-style iterator interface return next(self._iter).upper() # builtin next() function calls def __iter__(self): return self itr = Upper('hello') assert next(itr) == 'H' assert list(itr) == list('ELLO')
|
https://www.code-learner.com/python2-and-python3-differences-and-compatibility-tips/
|
CC-MAIN-2021-43
|
refinedweb
| 2,174
| 56.45
|
This.
5.>
6. Create your patch authoring in the sample root called Patch.wxs with the following contents:
<?xml version="1.0" encoding="UTF-8"?><Wix xmlns=""> <Patch AllowRemoval="yes" Manufacturer="Dynamo Corp"=.
If you would like to receive an email when updates are made to this post, please register here
RSS
Small update:
Instructions for building a Patch using the sample:
Step 4:
> pyro.exe Patch\Patch.wixout -out Patch\Patch.msp -t RTM
should be
> pyro.exe Patch\Patch.wixmsp -out Patch\Patch.msp -t RTM
Yes, good catch. I've updated the instructions. Thanks!
Hello, i'm trying the patching system i have a quite big installer.
I only changed one file from..
<Component Id="copie_de_newactor.x_1" Guid="{A16E95E6-B27D-411B-A376-96A93B635445}">
<File Id="copie_de_newactor.x_1" Name="Copie de newActor.x" KeyPath="yes" Source="x:\Data\common\3d\animation\Copie de newActor.x" DiskId="1" />
</Component>
to
<Component Id="copie_de_newactor.x_1" Guid="{A16E95E6-B27D-411B-A376-96A93B635445}">
<RemoveFile Id="copie_de_newactor.x_1" On="install" KeyPath="yes" Name="Copie de newActor.x" />
to generate a patch and i have the error
error PYRO0243 : Component 'copie_de_newactor.x_1' has a changed keypath. Patches cannot change the keypath of a component.
So i looked in the Patch\Diff.Wixmst and the line <row op="modify" sectionId="{955BA1D1-594E-4678-AD9B-785038FEBC47}/{955BA1D1-594E-4678-AD9B-785038FEBC47}" sourceLineNumber="X:\pipeline-onyx\Main\QA\Installers\OnyxSetup\OnyxSetup2.wxs*46"><field>copie_de_newactor.x_1</field><field>{A16E95E6-B27D-411B-A376-96A93B635445}</field><field>animation_1</field><field>0</field><field /><field modified="yes" /></row>
Shouldn't be a op="delete" ?
I did test with op="delete" and i have the message pyro.exe : error PYRO0252 : No valid transforms were provided to attach to the patch.
i'm starting using pyro. I'm sure i missed something somewhere.
Thanks you
Best regards,
Patrice
The first error you got was accurate. You cannot change the keypath file of a component using a patch. This means you cannot delete the file either because the presence of the file is what dictates whether the component is installed. If you want to remove a keypath file, you need to remove the entire component which means you need to remove the entire feature that contains it. Its better just to leave the file there.
Hello,
Thanks for the reply. I have some error when i generate my Setup.msi. My variables are duplicated. I can remove the duplicate from the wixout and it's work.
We are building a setup with 60K files. Currently we use a script to generate our wxs file. We have one component per file and one feature with all the component inside. There is surely a better way to handle our wxs. We set KeyPath="yes" by default without really knowing what it does.
Do you have any "wxs" strategy we should use?
thanks alots,
======
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="">
<Product Id="{955BA1D1-594E-4678-AD9B-785038FEBC47}" Language="1033" Manufacturer="Blabla Inc." Name="v1.05.00" UpgradeCode="{DD431266-3725-4BBB-902A-936CDFD95CA5}" Version="1.05.00">
<Package Compressed="yes" InstallerVersion="300" />
<Upgrade Id="{DD431266-3725-4BBB-902A-936CDFD95CA5}">
<UpgradeVersion OnlyDetect='yes' Property='PATCHFOUND' Minimum='1.05.00' IncludeMinimum='yes' Maximum='1.05.00' IncludeMaximum='yes' />
<UpgradeVersion OnlyDetect='yes' Property='NEWERFOUND' Minimum='1.05.00' IncludeMinimum='no' />
</Upgrade>
<Directory Id='TARGETDIR' Name='SourceDir'>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
<Directory Id='Blabla' Name='Blabla'>
<Directory Id='INSTALLDIR' Name='Bla'>
<Directory Id="data_1" Name="Data">
<Component Id="bla.build_1" Guid="{6CB5A96B-2470-4F61-A237-8B8FC9853BCC}">
<File Id="bla.build_1" Name="bla.build" KeyPath="yes" Source="x:\Data\bla.build" DiskId="1" />
</Component>
<Component Id="bladata.build_1" Guid="{7743C10F-109D-4209-9B67-361D24AB3D21}">
<File Id="bladata.build_1" Name="blaData.build" KeyPath="yes" Source="x:\blaData.build" DiskId="1" />
<Component Id="bladata.ds.build_1" Guid="{FD92FBF9-BAF0-4730-A263-CC646B91914D}">
<File Id="bladata.ds.build_1" Name="blaData.DS.build" KeyPath="yes" Source="x:\blaData.DS.build" DiskId="1" />
......
<Feature Id="bla" Level="1" Title="Bla 1.05.00">
<ComponentRef Id="log4net.appender.appenderskeleton.activateoptions.html_1" />
<ComponentRef Id="banksinmultibootdlg.cpp_1" />
<ComponentRef Id="gxtevbias.html_1" />
<ComponentRef Id="log4net.core.logimpl.errorformat_overload_3.html_1" />
<ComponentRef Id="t_5_025.cpp_1" />
<ComponentRef Id="test_list.vcproj_1" />
<ComponentRef Id="doc2.htm_1" />
Peter Marcu posted a couple of items on his blog recently that I wanted to link to here so hopefully
The duplicate variable problem is a known issue with a complex fix. Noone has gotten to fixing it yet...
I tried to reproduce the sample and everything worked (files were generated and no warnings or errors) until the last step with pyro. I get this message:.
I don't see more log information than that.
Are there differences in the text files you created in the first steps 3 and 4? Also, make sure your Patch authoring has the PatchBaseline set to "RTM" and that you are passing the transform on the command line with RTM as the baseline to tie it to.
Are you using the sample as is or have you customized anything? When Pyro is reducing the transform down to only the changes, if it ends up reducing everything out then you end up getting this error.
I had the source code unchanged.
The text file sample.txt in the sudirs differ a lot.
The only difference, I see, is that I put the object files not in the two subdirs, but I generated Product10.wixobj anbd Product11.wixobj.
I worked with Wix V3 3.0.3120.0.
Is "torch -p ..." a must? I thought -xi automatically includes -xo and -o.
-p is a must. It tells torch to persist all data, including the unchanged data. That data is where the information about what files to compare later on. Without it, you can produce a transform but pyro doesnt know where to grab changed files to put them in your patch.
I fixed the duplicate wix variable problem in a recent build of wix. Try grabbing the latest.
"Your WiX toolset version should be at least 3.0.3001.0"
Where can I find the 3.0.3001.0 binaries? Do have to build WiX myself? The latest version I see on sourceforge is 3.0.2925.0.
nevermind I am just now seeing the 'weekly releases'
Hi there. I'm on v3.0.3307.0 and I am trying to do above. Everything is good to the last command.
pyro.exe Patch\Patch.WixMsp -out Patch\Patch.msp -t RTM
Getting the following error:
pyro.exe : error PYRO0001 : Index was outside the bounds of the array.
Exception Type: System.IndexOutOfRangeException
Stack Trace:
at Microsoft.Tools.WindowsInstallerXml.Tools.Pyro.ParseCommandLine(String[] a
rgs)
at Microsoft.Tools.WindowsInstallerXml.Tools.Pyro.Run(String[] args)
TIA
I'm using 3.0.3412.0 and seeing the same thing as Tony.
Unfortunately, because the line wraps, the sample is a bit misleading. The -t flag requires 2 arguments. the command line shoudl look like this (notice the path to the mst at the end): pyro.exe Patch\Patch.WixMsp -out Patch\Patch.msp -t RTM Patch\Diff.wixmst
Thanks for the clarification. I figured that little bit of personal idiocy out yesterday afternoon. Thank you very much for taking the time to put together the article series on patch building.
Me again,
This may seem obvious to others, but I'm newish to WIX and patching in general. In my base msi I have 60+ components. In the patch, only one has been updated.
My question is, in the Patch.wxs file will the <PatchFamily> element only contain a reference to the component that is being updated?
Thanks,
Paul
Think of references inside a <PatchFamily> as a way of selecting exactly what you want in your patch.
You have 2 options:
1: No <PatchFamilies> with references inside them will result in all the differences between your target and upgrade being included.
2: Including <PatchFamilies> with references inside them will result in only those things that are referenced being included in the patch.
Does that answer your question?
Thanks, that answers my question perfectly.
My new team is using WiX v3.0 to create the MSI-based setups for the upcoming XNA Game Studio 2.0 product
Can't seem to get this to work with 3.0.2925.0. I changed it a little, but I don't think I've changed it enough to break it. I'm getting the following:
pyro.exe : error PYRO0001 : startIndex cannot be larger than length of string.
Parameter name: startIndex
Exception Type: System.ArgumentOutOfRangeException
at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length,
Boolean fAlwaysCopy)
at Microsoft.Tools.WindowsInstallerXml.Patch.BuildPairedTransform(String patc
hId, Output mainTransform, MediaRow mediaRow, String& productCode)
at Microsoft.Tools.WindowsInstallerXml.Patch.AttachTransforms(ArrayList trans
forms)
Any ideas?
Sorry... Missed the line that says "Your WiX toolset version should be at least 3.0.3001.0"
DOH! I'll get a newer version and give it a try.
Not off hand. What did you change? I also need to post an updated sample that matches the current tools and shows how PatchFamilies work.
I'd get the latest. Lots of stuff is being fixed in the patching feature. As recently as this thursday...
I have a problem for creating patch file :
warning PYRO1079 : The cabinet 'RTM.cab' does not contain any files. If this installation contains no files, this warning can likely be safely ignored.Otherwise, please add files to the cabinet or remove it.
error PYRO0227 : The transform being built did not contain any differences so it could not be created.
I certainly two files *.wixout are different.
What differences are there? What are you expecting to show up in your patch?
Anyone run accross something like this:
C:\tst\Beta6.1+Patch2>"C:\Program Files\wix-3.0.3711.0-binaries\pyro.exe" -
delta patchFull.wixmsp -out patchFull.msp -t RTM diffFull02.wixmst -t PATCH1 dif
fFull12.wixmst
Microsoft (R) Windows Installer Xml Patch Builder Version 3.0.3711.0
pyro.exe : error PYRO0001 : Specified argument was out of the range of valid val
ues.
Parameter name: managed
at Microsoft.Tools.WindowsInstallerXml.PatchAPI.PatchInterop.PatchAPIMarshale
r.CreateArrayOfStringA(String[] managed)
r.MarshalPOD(Object managedObj)
r.MarshalManagedToNative(Object ManagedObj)
at Microsoft.Tools.WindowsInstallerXml.PatchAPI.PatchInterop.CreatePatchFileE
xW(UInt32 oldFileCount, PatchOldFileInfoW[] oldFileInfoArray, String newFileName
, String patchFileName, UInt32 optionFlags, PatchOptionData optionData, PatchPro
gressCallback progressCallback, IntPtr context)
at Microsoft.Tools.WindowsInstallerXml.PatchAPI.PatchInterop.CreateDelta(Stri
ng deltaFile, String targetFile, String targetSymbolPath, String targetRetainOff
sets, String[] basisFiles, String[] basisSymbolPaths, String[] basisIgnoreLength
s, String[] basisIgnoreOffsets, String[] basisRetainLengths, String[] basisRetai
nOffsets, PatchSymbolFlagsType apiPatchingSymbolFlags, Boolean optimizePatchSize
ForLargeFiles, Boolean& retainRangesIgnored)
at Microsoft.Tools.WindowsInstallerXml.BinderExtension.ResolvePatch(FileRow f
ileRow, Boolean& retainRangeWarning)
at Microsoft.Tools.WindowsInstallerXml.CabinetBuilder.CreateCabinet(CabinetWo
rkItem cabinetWorkItem)
at Microsoft.Tools.WindowsInstallerXml.CabinetBuilder.ProcessWorkItems()
C:\tst\Beta6.1+Patch2>
Please log a bug with full details on SourceForge so we can take a look at this and hopefully get it fixed. The more information you can provide to help us reproduce this, the better. If you dont want to share your source with the world but are willing to provide it just to me, let me know.
This all worked great, so I tried an experiment. I download and with the intention of creating a patch. After renaming the files I performed these steps:
torch -xo wix3_20080125.msi wix3_20080201.msi -out diff.wixmst
candle patch.wxs
light patch.wixobj -out patch.wixmsp
pyro patch.wixmsp -out patch.msp -t RTM diff.wixmst
When I run torch I get the warning shown below, which I guess is why pyro fails with a NullReferenceException. Any chance you could provide an example of how to build a patch from these two MSI files?
torch.exe : warning TRCH1099 : Changing the ProductCode in a patch is not recommended because the patch cannot be uninstalled nor can it be sequenced along with other patches for the target product.
The servicing story for the Wix3 msi is major upgrade and not patch. They are not designed to be patched. The product code changes build to build. This does not mean it couldnt be patched but probably shouldnt be. The other problem you are hitting is probably because the patching tools work for two msi's built with the same version of WiX. There are often changes between wix builds that make patching not possible. This is probably the reason you are seeing the exceptions while patching. Can you file a bug on Sourceforge with more details of the exception so we can try to figure out how to provide a better error message? Thanks!
There is a problem in creating patch of an uncompressed installation. pyro always adds the Compressed attribute while creating a patch. On an uncompressed installation it causes Error 2920 while applying the patch, because MSI tries to uncompress the patched file (because the patch transform marked it as compressed) from media - that fails, because there is no such file in the media. Pyro also adds the PatchAdded attribute to every changed file - I don't know if that's right, but I suppose it's not.
There is no such problem while applying first patch, it occurs after applying second patch, when trying to "Repair" or while applying a series of two patches with one msiexec call.
There is a similar problem in patchwiz.dll, but there it was caused by invalid FileSequenceStart value. Patches created with pyro using right Media.@Id don't have that problem, although the Media.@Id must be chosen carefully.
I'm not quite sure I followed the first paragraph. Are you saying you are trying to produce a patch that is not compressed? Or are you trying to apply a patch to a layout that you built uncompressed.
For the last paragraph, we could add error checks in pyro to assure that the added media sequences for a patch do not overlap with the msi. This would be good. Can you file a bug on SF for that one?
I try to produce a patch that will be applied to a layout that I built uncompressed. Maybe I do something wrong, but the same patch made with InstallShield leaves the Attribute column of File table unchanged for the files the patch changes. Pyro changes this value by ORing 0x5000. Patches made by IS work while those from pyro fail.
Hi all, my problem is that I have a few custom actions in my base installer(rtm) and have the same ones in my latest one, the differences are just base in the files contain within it(add, erased or update) but I keep having thir error:
torch.exe : error TRCH0001: Item has already been added. Key in dictionary: 'InstallExecuteSequence/ConfigureIIs' Key being added: 'InstallExecuteSequence/ConfigureIIs'
I thought that if the custom action is present in both installer it's shouldn't be taken as a difference by torch... am I right?
I would really appreciate the help
Hi, I'm having a few issues with a particular patch. We're trying to automate patch generation, given two msi's. First question: how important is it that the files retain their component ids? At any rate, two added files (each with their own component ids again) don't get added, and only some of the updated files get updated. The patch claims to have been applied ok, so I'm sifting through the log output, but it's not making a tonne of sense. We're using WiX 3.0.3210.0, so hopefully it has all the latest and greatest stuff...
Thanks for any help you can render, or just pointers to Somewhere Else to go.
The build you are using is about 7 months old. I always recommend getting the latest version.
Have you tried using orca to view the patch applied to the product. It will let you see the diff between your target product and patch.
It is very important to keep identifiers the same when building patches. Also, there are a lot of rules around patching. Do you have one file per component? If not, which one is the keypath and which one are you updating. If you are not updating the keypath, nothing in the component will be updated.
Yes, we have one file per component, which seems a little like overkill to me but is easy to generate for; and it looks like easy to make sure we get all the modifications too. And Orca shows exactly what I would expect, but then when the time comes to actually DO the patch, it didn't work.
Convincing the people generating the package to actually use the same component ids for the same files has made everything work a GREAT DEAL better. ie it seems to work great!
Is there a good list of the rules somewhere, or will it just come to me as I continue to peruse the msdn stuff about installer etc.? Right now my knowledge is more holes than frame, so extra knowledge mostly falls through rather than filling in, but over time I'm absorbing more.
Ya, I noticed there are Later and Greater things; I just assumed we were ok because our release is beyond the 'release' release for 3.x. I may see about using a newer version, with its binary-delta support...
The main question I now have is about the type of patch; all the documentation I have seen about patching says there are: minor update, minor upgrade, and major upgrade (I believe); the Patch element has a classification that seems to specify something else entirely... I'm not trying to do major upgrades (ie new product code, new major version number), and I'm just wondering if the classification AFFECTS the type of patch, or if pyro (I would guess?) determines the type based on the transforms given to it?
Anyway, thanks for all your help, and for all the great work on Wix!
I'm still getting." with WiX 3.0.4123.0 when I change the torch command line to this:
torch.exe -p -xo 1.0\product.msi 1.1\product.msi -out patch\diff.wixmst
Something is different in the generated diff.wixmst file when comparing .msi instead of .wixpdb. Seems like a bug in the torch tool. Or am I missing a command line switch?
Is there a way to generate a .msp patch package when you only have to .msi files using the WiX toolset?
producing the wixmst from two msi's is not going to get you all the data you need. That does look like a bug.
You can use the -ax [binry file location]switch on torch to point at two admin images which you can create from your msi's using msiexec /a.
With the way you are doing it currently, it cant compare any of of the files because I'm guessing they are embedded in the msi. Making the admin image expands the files out.
Many times people want to take advantage of the Wix v3 patch building features but didnt build their
I have tried this example and works fine with .net assemblies and executables.
but how about the assemblies in the GAC if I did not change the assembly version but file version is changed?
it does not replace. please advice.
Replacing files in the GAC should work. I do it all the time. Is the file you are trying to update the KeyPath of the component?
I am considering switching to a new patching system and I wonder how does it deal with, in my case, troublesome file sequence numbers?
Namely, I have so many files changing between the versions (but changes themeselves are typically very small) that I am afraid I will hit a 16-bit integer limit on file index.
There is a way to upgrade this field to 32 bit integer but I have no idea how to accomplish that in WiX?
Wishful thinking: could it be that we are automagically spared from having to think about the file sequence numbers with this new system? Just use it and everything will be just fine ... dreaming ...
Sequences in your upgrade are ignored and any files with differences are put in the media entry you authored in your patch. This media entry should be higher than your last sequence.
Wix v3 automatically sets the column type of the sequence to i4 so you shouldnt have any problems with a large number of files.
Could you, please, elaborate a bit more on 'this media entry should be higher than your last sequence' ?
If I start with media at 5000 and patch 10 files my next entry should be 5010? Then, the next patch, if there are 15 files to be patched, would push this number to 5025?
It needs to be higher than the last sequence in the baseline you are targeting. So if the last sequence in your original product is 5000 then you need to make the media at least 5001 for all patches that apply to the original product. The more I think about this the more I think that we can do the right thing for you in the tools but right now, this is something you have to handle.
I envy the people who seem to be able to use new patching system. Judging by one WiX bug submission it seems thet there is at least one such person.
Me, on the other hand, have problems even with the simplest things like running equivalents (on my patch system) of these sample commands:
> candle.exe -dVersion=1.0 product.wxs
> light.exe -sval Product.wixobj -out 1.0\Product.msi
Is this one missing -xo option?
> candle.exe -dVersion=1.1 product.wxs
> light.exe -sval -xo Product.wixobj -out 1.1\Product.msi
This one has -xo option but is Product.msi a MSI file? Orca can't open it. So it is not. What is it then? wixout or wixpdb?
Where do wixpdb's come from, all of a sudden?
Are they somehow the byproduct of the build process above? Should I rename MSIs above to have wixpdb extension and use them as input to torch? It turns out that torch doesn't like them with wipdb extension but accepts wixout extension.
However Pyro never sees anything to create transform from when passed Diff.Wixmst created this way. No patching!
Would some good soul please post a downloadable batch file or a set of commands that work on some sample that can be downloaded and tested to work with one of the relatively recent WiX weekly releases?!
I fixed my post. There should not have been a -xo on the second command line to light. The wixpdb is a bi-product of the build. You do not need to specify to have output. It should have an identical name as the msi you are outputting. Think of a dll and its matching pdb when you build a C# project. The wixpdb's that are output are what you should pass to torch. Let me know if this helps.
Yes, that helps, thanks! However, I didn't explain why did I stick to using -xo option.
It is because I wanted wixpdb that includes binaries, as I can't exactly reproduce original MSI build environment paths when patching.
However light help says:
-bf bind files into a wixout (only valid with -xo option)
So I guess I would have to start working with administrative image and -ax option to torch.
Yes, if you didn't keep your original build around then you are likely going to find admin image patching to be more friendly to you.
Also, if you build a product that you would like to create patches for, you should not update to a newer version of WiX when you build the upgrades or patches. Stick to exactly the same toolset or you are likely to hit problems.
some time ago I bothered you about a a patching problem without getting an answer. Now I investigated the problem by myself.
In short - error 1328 or 2920 occurs while trying to repair a patched installation. 1328 occurs when the package is compressed and 2920 occurs when it's not.
The error doesn't occur always. It occurs if there are at least two patches applied to the product and both of them change the same file. Above that, the patches have to be made with -delta switch and... the changed file has to be large enough(!).
The problem lies in making a delta patch, which is somehow "intelligent". If the file is small or can be compressed to a small size (I don't know the limit). The delta for this file is not computed. Instead the whole file is included. But if the file is large enough and the delta is computed, it is put into Patch table. I haven't found this documented anywhere...
Pyro always adds PatchAdded and Compressed attributes on modified files as if they were whole included (lines 1854-1857 Binder.cs), so the installer always looks for the replacement of whole file instead of using the delta in Patch table.
When I commented out these lines and recompiled WiX, my patches started to work, but of course, it is not a resolution for this issue, because it fails for small files.
Is there a good resolution for this?
When I'm using your sample above everything works fine. My problem starts wth the second patch (version 1.2). When I build the diff against version 1.1, patch 1.2 patches version 1.1 correctly but cannot patch the base version 1.0. When I build the diff against version 1.0, patch 1.2 patches version 1.0 correctly but cannot patch version 1.1. What am I doing wrong?
Thanks Herbert
You need to have multiple baselines in your Patch. Also, your command line to pyro should have multiple "-t [Baseline] [wixmst]" arguments. One for each baseline you want to target.
3. Create the transform between your products:
in the above step where we get Product.wixpdb file? i haven't found any such file.
Plesae tell me what are those files?
They should be output next to your msi automatically. If they aren't, you probably dont have a high enough version of WiX v3.
I have installed Wix version 3.0.2925.
is is not enough? Plesae let me know which version i have to install.
I was trying to build an msp from 2 msi files built by votive integrated with TFS.
I keep getting this.
commands look like this..
torch.exe -p old.msi new.msi -out Diff.Wixmst
candle.exe Patch.wxs
light.exe Patch.wixobj -out Patch.WixMsp
pyro.exe Patch.WixMsp -out Patch.msp -t RTM Diff.Wixmst
Is the folder structure important?
and also I will be having only the 2 msi files, old and new, to create the differnce.
Hi Peter,
Good post! I'm seeing a strange problem occur in my patch. The patch is adding additional components that are not been referenced by the patch family. Both the WixMsp and wixobj files are showing the correct components. I can't seem to understand why these other components have been added.
And I'll answer my own post.....
The PatchFamily filters on components and the fragments they are contained within. E.g. if you reference a component thats contained within a fragment with 10 other components. The patch will contain all 11 components.
I think I need to break up my fragments into smaller modules
Yes, you are correct. If you already shipped a product with large fragments, its not always straight forward to refragment for the upgrade build. You can use the admin image patching feature which auto-fragments your components into their own fragments if that makes your likfe easier.
Hi
I have a problem
pyro.exe : warning PYRO1097 : File 'FL_protlib.dll' in Component 'SauClt' was changed, but the KeyPath file 'FL_saupg.exe' was not. This file will not be patched on the target system if the REINSTALLMODE does not contain 'A'. The KeyPath file should also be changed and included in your patch.
That warning is correct. You need to make a change to the keypath file in the component if you want anything in the component to be updated.
Hello,
We've updated our install to be 100% WiX and now we'd like to update our patching to WiX as well. I'm able to build and run the above example but when I try to apply it to our install I get pyro.exe : error PYRO0252. I've read a few different blogs about not having compressed files or having the build version of the file in question updated. Are these things necessary? The file I'm attempting to patch has a baseline version of 12.6.2671.0 and the patch version is 12.6.2671.9001. The only mod I made to Patch.wxs was to update the ComponentRef. Is that sufficient for my simple test?
Thanks
Can you give me more details about the command you passed to Pyro and Id of the PatchBaseline\@Id?
Feel free to email me the patch.wxs and the command line you passed to pyro. Can you also send me the wixmst file you got when diffing your baseline and upgrade?
I sent email (not sure if I have the correct address). Here is the command:
C:\Wix_3.0.4909.0>pyro c:\WiXPatching\Patch\patch.wixmsp -out c:\WiXPatching\Patch\patch.msp -t RTM c:\WiXPatching\Patch\diff.wixmst
Microsoft (R) Windows Installer Xml Patch Builder version 3.0.4909.0
Here is the Patch.wxs:
<?xml version="1.0" encoding="UTF-8"?>
<Patch
AllowRemoval="yes"
Manufacturer="Symantec Corporation"="bengine.exe.06609F4A_77E8_4877_8B18_0B805D349FD8"/>
</PatchFamily>
</Fragment>
</Wix>
Not sure how to attach the wixmst??
Tom and I worked through email and it turns out that the file that needed patching was included via a Merge Module. In order to patch files from merge modules you have to do one of the two following options:
1. Follow the steps to patch admin images rather than using the wixpdb. I wrote the steps here:
2. Use the melt tool (melt.exe) to decompile your msm into a component group that you can reference directly into your WiX authoring.
Peter -
I have a question about the source attribute:
Source=".\$(var.Version)\Sample.txt"
If your going from v1.0 to v1.1, and the file is new to v1.1, how do you keep a build of v1.0 from aborting? I am having a hard time figuring out how to structure my versioning folders, where files are introduced in subsequent minor versions, while keeping a common set of wxs files. Using $(var.Version) seems to be part of the answer...
- Troy
Hi Troy,
One option would be to use the preprocessor to only include the new content in the higher version.
Not sure if this xml sample is going to come through.
<?if $(var.Version) > 1.0 ?>
Put your added content here.
<?endif ?>
If that doesn't make things easier for you, I can try to think of other ways.
Hi Peter -
This worked! Thanks. However I ran into another small issue. It seems like the patch process will only work for new or existing files .. meaning we are pushing the entire file. It appears my ComponentRefs, which reference util:XmlConfig patches, are not being applied when I pass in the msp. Is there some trick to getting these applied? I am wondering if the "diff" process, using torch, somehow skips these?
Thanks.
How to remove a file with a minor or small upgrade patch?
Hello, Peter:
I am working on how to make a patch for a product. I have a baseline installation which install a file 123.jar; now I want to make a patch to remove this jar file, how to do?
Wait for your reply, thank you!
Lucky you! I actually had a post written about remove files in patches that I never published. Here it is:
Troy, sorry, I glanced over your question. Can you share your wix files with me? Are you using PatchFamilies? If so, are you referencing something in the same Fragment as the XmlConfig entries?
I have a multi-language installer and want to make a corresponding multi-language patch. I went through your posts about patching with WiX v3. I'm wondering if the patching system in WiX v3 is able to produce a multi-language patch. If so, could you list the step-by-step instructions based on the example in this blog entry? Thank you.
What method are you using to create your multi-language installer? Are you using language transforms applied to the database at runtime? If so, are you using a bootstrapper to apply the right transform?
Unfortunately, I haven't seen a good answer to shipping multi-language patches that doesn't involve writing a bunch of customactions to apply localized data to the patch at runtime depending on the current locale.
Hi Peter, Thank you for the quick reply.
Yes, I'm using language transforms to build a multi-language installer and using a bootstrapper at runtime to install the right language depending on the locale.
Could you elaborate a little more on what the custom actions would do in a multi-language patch? In my case, there would be updated localized strings and updated locale-dependent data in the patch.
I read another of your posts: WiX: Patching something you didnt build with WiX using WiX.
If I understand correctly, torch can take msi as input for base product and upgraded product, but the msi must be admin image where locale has been chosen. My qeustion here is, if the input msi has transforms embedded, would torch be able to accept the transforms? In this case, locale is not chosen yet and thus no admin image is available to torch.
Recently (in last couple days) in the WiX-user maillist 'General discussion for Windows Installer XML toolset', some people asks 'Passing TRANSFORMS into MSI patch'. I would have the same question except that I intend to pass language transforms into MSI patch. Would you give us some insights on that subject as well?
Thank you very much for your time and help!
Harry
Sorry it took so long to reply. I've been extremely busy lately.
If you create an admin image with the transform already applied, you will get a transform for the locale you applied.
I've never actually done this but if you created a transform for each locale by creating base and upgrade images with the locale transform applied, you could run torch on them. Then you could pass all those transforms to pyro and get them all embedded in the patch.
When installing the patch, the transform validation settings should pick the right transform to apply based on product language for the installed product.
Hope this helps...
Peter,
I have to say that this is really helpfull.
What about patching an MSI file created with Visual Studio 2005 and we don't have the product.wxs for it ??
Glad it's helped...
Take a look at this post:
I've done a bit of searching and I still can't find the solution for this: when I try to change the text file in the example to an executable, the executable does not get updated when I run the patch. Do I have to set some attributes and/or compile the files differently so that executables get patched properly?
Is there a difference between the executables? If there is no difference, it will be dropped from the patch.
The executables are different; the body of the 1.0 executable looks like:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MessageBox.Show("broken");
Application.Run(new Form1());
whereas the body of the 1.1 executable looks like:
MessageBox.Show("fixed");
When I run the patch and then run the executable in the Program Files directory, I see the "broken" MessageBox and then the form window, thus indicating that the executable was not updated.
Oddly enough, if I make the 1.1 code look like the 1.0 code except for the MessageBox argument, then pyro complains that there are no differences in the patch even though the executables do differ in a string literal.
Finally, I get a warning in Product.wxs(11): warning LGHT1079 : The cabinet 'product.cab' does not contain any files. If this Installation contains no files, this warning can likely be safely ignored. Otherwise, Please add files to the cabinet or remove it.
Is this related to the executable not being updated?
Can you email me the .wixpdb that is output next to the patch as well as your Patch.wxs authoring?
Yi, it looks like you are not seeing the updated assembly installed because it has an equal version number. It is in the patch.
Here is the relevant line from the verbose install log:
MSI (s) (34:54) [08:58:01:456]: File: C:\Program Files (x86)\Patch Sample Directory\MyApplication.exe; Won't Overwrite; Won't patch; Existing file is of an equal version
|
http://blogs.msdn.com/pmarcu/archive/2007/06/28/sample-patch.aspx
|
crawl-002
|
refinedweb
| 6,224
| 68.57
|
My Sql Most of them are in green ( Decompression version ) Then sign up for the service Easy and convenient .
however . Configuration file is a headache .
First configuration mysql Environment variables of .
mySQL environment variable ( My computer - Right click properties - senior - environment variable )
MYSQL_HOME( Decompression path ):E:\MYSQL\mysql-5.6.23-winx64
path: Add... At the end ;%MYSQL_HOME%\bin Pay attention to the semicolon
No environment variables CMD It's not an internal or external command .
It's for the owner .5.6.23 edition .
my-default.ini The contents are as follows
[mysqld]
#skip-grant-tables This can be root Login with forgotten password mysql Very low security .
# port
port=3306
# In some cases default-character-set=utf8 Can solve the problem of Chinese garbled
# Don't use it here default-character-set=utf8 Will report directly to 1067 error
character-set-server=utf8
# Pay attention to whether this should be added or not client database results All are GBK or latin1
init_connect='SET NAMES utf8'
#show variables like 'char%'; Look at the database code set
# Database storage engine Some versions default-storage-engine=MyISAM Will start normally Otherwise it will be reported 1067
default-storage-engine=INNODB
# Set up basedir Point to mysql Installation path for
basedir=E:\MYSQL\mysql-5.6.23-winx64
datadir=E:\MYSQL\mysql-5.6.23-winx64\data
[client]
default-character-set=utf8
#password =1234
port=3306
[mysql]
port=3306
default-character-set=utf8
------------------------------------------------------------------------------- Don't copy this line
Basically, there is no garbled code problem .
Get into mysq...bin\ Run as an administrator
Specify profile , Add service
mysqld --install MySQL --defaults-file="E:\MYSQL\mysql-5.6.23-winx64\my-default.ini"
start-up mysql
net start mysql
mysql -u root -p The default is empty.
Use Navicat for MySQL Join database .
Registration code :NAVH-WK6A-DMVK-DKW3
Switch to use mysql
select * from mysql.user;
You'll see similar records
You can get in without a password . Kill first localhost The first 4 Bar record .( Anonymous logins )
If you don't change the table . There will be the following picture
Delete paragraph 4 After .
It's time to verify . Prompt for user name
Remember my-default.ini Of skip-grant-tables Don't drive .
modify root Default password ( Switch to the root directory )
1.set password for root@localhost = password('111');
2.update user set password=password("111") where user="root";
Close test available . Restart the service
When you log in . It's about the password
Enter the just 111 Just the password .
Be careful :
If you use cmd Please login in the following format
mysql -u root -p111
Remember not to use :
mysql -u root -p 111
Otherwise it will prompt :
Here we go first . Coding problem Installation services , The password problem has been solved .
I hope I can help my friends in need . It's really a headache if we don't solve the coding problem .chinese
1067 chart .
If the relevant properties have been configured before . Please put mysql-data- All the following non folder files will be deleted . Start it up
The End...
My Sql 1067 Error and coding problem solving more related articles
- java project Deposit in mysql after Change question mark MySql 5.6 (X64) Decompression version 1067 Solutions to errors and coding problems
[ Reference resources ]MySQL 5.7.19 Forget the password Reset password my.ini Example Stop after service start Environmental Science Java Environmental Science JDK1.8 installed mysql-5.6.38-winx64 idea2016(64) ...
- [ Reprint ]MySQL5.5 The configuration file my.ini 1067 error
Link to the original text : decompression mysql-5.5.22-win32.zip In the following table of contents are 5 individual my-xx ...
- MYSQL Startup Report 1067 error , In the system log is “ service mysql The accident stopped ” Mysql In the journal, it's :“Plugin \'FEDERATED\' is disabled”
MYSQL Startup Report 1067 error , In the system log is " service mysql The accident stopped " Mysql In the journal, it's :"Plugin \'FEDERATED\' is disabled&quo ...
- Plugin 'FEDERATED' is disabled or 1067 error Startup error and “ service mysql The accident stopped ” resolvent
MYSQL Startup Report 1067 error , In the system log is “ service mysql The accident stopped ” Mysql In the journal, it's :“Plugin 'FEDERATED' is disabled” I found a solution on the Internet :1. stay MY.I ...
- mysql Of 1067 error - 2
Last blog post <mysql Of 1067 error > Due to the log configuration problem in 1067 error . Due to upgrade MySQL To V5.6, So copy my.ini And data files to the new system . When starting the service , Again 1067 error ! ...
- Batch command -- Configure install free mysql 5.6.22, as well as 1067 A solution to the mistake
mysql Service startup appears 1067 A solution to the mistake : When the service starts 1067 When it's wrong , You can see “windows Event viewer ”, Found similar error prompt Can't find messagefile 'F:\ ...
- solve mysql Start failure report 1067 error
Recently do project use mysql database , Because of unloading Master Lu, the database file is missing . reinstall mysql After starting the database, it appears 1067 error , Details are as follows I checked the cause of the mistake on the Internet , take my.ini The default search engine under the file is changed to myi ...
- Oracle Error summary and problem solving ORA
Reference address ORA-00001: Violate the only constraint (.) Mistakes show : When you type a duplicate value on the column corresponding to the unique index , This exception is triggered .ORA-00017: Request session to set trace events ORA-00018: Exceeded the maximum number of sessions O ...
- start-up mysql appear 1067 error
0. open mysql\bin\my.ini, lookup [mysqld], stay [mysqld] Add a line below ,skip-grant-tables I.e. composition [mysqld] skip-grant-tables[ ...
Random recommendation
- Here's an Android version for you easyradius SMS prompt client
It's like Mu you wrote a blog , Send you a small software , It will be updated later It is mainly convenient for some users who use their mobile phones to send expired short messages to users Download address :
- ( turn ) Voting system , change ip Brush ticket
Preface I believe you will receive the link from your friends , Open it up , Oh , Need to vote . After voting, a page pops up ( Congratulations , You have voted ), When I click again, I find , Ah , Your IP(***.***.***.***) I've already voted , No ...
- C# Ini The configuration file
public class INIUserAccound { static IniFile Ini = new IniFile(AppDomain.CurrentDomain.BaseDirectory ...
- etrace track nginx And HTTP Request flow
curl 127.0.0.1 | | | \--ngx_epoll_process_events | | | | \--ngx_time_update | | | | | \--ngx_gmtime ...
- Java Class loading principle analysis
See : 2 Java The structure of virtual machine class loader 2.1 JVM 3、 ... and ...
- HTTP Protocol literacy ( Two )HTTP The request method of the protocol 、 Request headers and response headers
One .HTTP Request method Http The protocol defines many ways to interact with the server , The most basic ones are 4 Kind of , Namely GET,POST,PUT,DELETE. One URL Address is used to describe resources on a network , and HTTP Medium GET, POST ...
- elasticsearch health yellow
csdn Blog address ( It has been tested ): Official address : ...
- vue-cli webpack elementary analysis
I've been working on scaffolding webpack I'm interested in configuration . Cut a long story short , First from npm start Start . open package.json find scripts You can see start Running dev, dev Again from build/ ...
- window.location API
summary I despised myself today , I can't use it window.location.search Page value transfer . Now to sum up window.location API, Record it for reference in future development , I believe it works for others . Page pass ...
- Infinite classification mysql Design
|
https://chenhaoxiang.cn/2021/06/20210604131942587g.html
|
CC-MAIN-2022-05
|
refinedweb
| 1,270
| 57.57
|
0
Is there a reliable, cross-platform way to pause a program for a set amount of time? The getch() function will wait for user input, but I would like to be able to pause for say 3 seconds. If a for loop is used like so:
#include <iostream> using namespace std; int main() { for(i = 0, i < 10000, i++) { } return 0; }
There will be no garuntee that on a machine running a quad-core the code will always pause for 3 seconds.
Is there an easy way to time using <ctime>? I saw AncientDragons' post about subtracting the system start time from the current time and that could be used, but is there an easier way?
|
https://www.daniweb.com/programming/software-development/threads/143686/timer
|
CC-MAIN-2018-13
|
refinedweb
| 117
| 73.71
|
Numpy is the best python module for array creation and manipulation. In this entire tutorial you will learn numpy linspace implementation with examples.
What does np linspace do ?
Numpy linspace creates an array whose elements are evenely spaced between the two interverals. Here you specify a starting point and end point. Then the elements are breaked according with the the line break( integer type).The np.linspace() method has more than 6 parameters. Below is the syntax and parameters explaination of this function.
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
parameters:
start: The starting value of the sequence.
stop : The end value of the sequence.
num: The number of samples you want. Default is 50. It should be negative.
endpoint: The default is true. If it is true then stop is the last sample, otherise stop is not included.
retstep: Step size.
dtype: Type of the returned array.
axis : The axis in the result to store the samples.
Examples: How to use and apply Numpy linspace
Example 1 : Return a numpy array between two interveral
Suppose I want to return numpy array(ndarray object) between the two intervals. Then I will use the following code.
np.linspace(start=10,stop=100,num=10)
Here I am finding 10 elements between 10 and 100 with step size or space of 10.
You will get the following output.
If you remove num = 10, then all the elements between the interval will be returned.
Example 3: Return a numpy array of custom data type.
You can also define the type of the returned numpy array. To do so you have to pass dtype as an argument inside the np.linspace() method.
np.linspace(start=10,stop=100,num=10,dtype="int")
The code will output the elements between the interveal of 10 and 100 and of integer type.
Output
Example 3: Return a numpy array between two interval and step size.
The above example returned only numpy array of equally spaced elements. But it has not told you about the spacing between two consecutive elements. To do so you have to you have to pass the retstep to true.
Execute the following code.
np.linspace(start=10,stop=100,num=10, retstep=True)
The above code will return two elements of ndarray type. The first one is the arry of the 10 elements and the second is the step size. In our example it returns 10.
Below is the output for the above code.
Example 4: How to use the endpoint parameter
In all the above examples you can see the end elements had been added the last element. Suppose I do not want it. To remove it you have to pass the endpoint as False.
import numpy as np np.linspace(start=10,stop=100,num=10,endpoint=False)
Output
You can see I am getting all the elements between 10 to 100 of 10 step size but without the last element 100.
Difference Between np.linspace and np.arange
If you are already familiar with np.arange then you must be thinking numpy linspace is similar to to numpy.arange. Yes you are correct. But the major difference between them is that np.arange simply creates evenly spaced array.But the np.linspace allows more controling over increments of the element. And also it allows you to include or exclude the last element.
Hope this article on numpy linspace in python has helped you to know more about it. If you want to us to solve your queries then you can contact us.
Thanks
Data Science Learner Team
Source:
Offical np.linspace() Documentation
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
|
https://www.datasciencelearner.com/numpy-linspace-in-python-examples/
|
CC-MAIN-2021-39
|
refinedweb
| 627
| 69.28
|
While JAXB is a good method of mapping XML into Java objects, if your schema’s are large or complex, generating the required Object graph prior to marshaling into XML can be both tedious and error prone due to the large amount of ‘boiler plate’ code of creating an object, calling accessor methods to set the values etc.
A common pattern for easing this sort of thing is known as the Builder pattern where you either have a common object holding configuration and then it builds the objects for you, or a set of objects each configured with the information and when required then build the final Object graph.
Previously however, this involved writing these builder classes manually once you have generated the model from a schema, however retepTools provides a JAXB plugin which, with a little configuration within the bindings will automatically generate these builders for you.
First an example of a simple pair of objects to be generated by JAXB – this is an abridged version of the jabber:client namespace in XMPP:
<?xml version='1.0' encoding='UTF-8'?> <xs:schema xmlns: <xs:element <xs:complexType> <xs:sequence> <xs:choice <xs:element <xs:element </xs:choice> <:schema>
Now if run through JAXB this would generate three classes: Message, Body and Subject. With this default model you would have to do something like the following to create a valid Message:
Message message = new Message(); message.setFrom( "juliet@example.com/balcony" ); message.setTo( "romeo@example.net" ); Body body = new Body(); body.getBodyOrSubject().add( "Wherefore art thou, Romeo?" ); message.setBody( body );
Now with this simple example thats fine, but imagine something where your model is far more complex, or worse can contain arbitary namespaces as children such as in XMPP where Message can contain objects within any namespace?
This is where Builders become useful. Imagine the above being converted into this:
Message message = new MessageBuilder(). setFrom( "juliet@example.com/balcony" ). setTo( "romeo@example.net" ). addBody( new BodyBuilder(). setValue( "Wherefore art thou, Romeo?") ). build();
Although at first this may look similar to the standard way, the builders break the code into more manageable chunks. The builders themselves can be reused, so if you are sending multiple messages then you could change the above code to:
MessageBuilder builder = new MessageBuilder(). setFrom( "juliet@example.com/balcony" ). addBody( new BodyBuilder(). setValue( "Wherefore art thou, Romeo?") ); Message message1 = builder.setTo( "romeo@example.net" ).build(); Message message2 = builder.setTo( "tybalt@example.com/cousin" ).build();
As you can see, the use of builders becomes apparent, we created two Message objects with a single change between them in a lot less code.
On the next page we’ll configure maven to build these builders.
This looks really cool. I am having some trouble getting it working – any idea what it means when it says:
“[ERROR] compiler was unable to honor this retep:builder customization. It is attached to a wrong place, or its inconsistent with other bindings.”?
I’ve got basically the same setup as what you have here.
Looks great, until you reach the point of defining binding for *each* complexType
You make a great case for builders and how its better to generate them straight from the schema rather than manually extend classes. Is retepTools still active/functional with a semi-latest version of maven-jaxb2-plugin from 2013?
|
http://blog.retep.org/2010/05/18/implementing-builders-with-jaxb-generated-objects/
|
CC-MAIN-2014-52
|
refinedweb
| 552
| 52.49
|
In this walkthrough, you will learn how to programmatically retrain an Azure Machine Learning Web Service using C# and the Machine Learning Batch Execution service.
Once you have retrained the model, the following walkthroughs show how to update the model in your predictive web service:
- If you deployed a Classic web service in the Machine Learning Web Services portal, see Retrain a Classic web service.
- If you deployed a New web service, see Retrain a New web service using the Machine Learning Management cmdlets.
For an overview of the retraining process, see Retrain a Machine Learning Model.
If you want to start with your existing New Azure Resource Manager based web service, see Retrain an existing Predictive web service.
Create a training experiment
For this example, you will use "Sample 5: Train, Test, Evaluate for Binary Classification: Adult Dataset" from the Microsoft Azure Machine Learning samples.
To create the experiment:
- On the bottom right corner of the dashboard, click New.
- From the Microsoft Samples, select Sample 5.
- To rename the experiment, at the top of the experiment canvas, select the experiment name "Sample 5: Train, Test, Evaluate for Binary Classification: Adult Dataset".
- Type Census Model.
- At the bottom of the experiment canvas, click Run.
- Click Set Up web service and select Retraining web service.
The following shows the initial experiment.
Create a predictive experiment and publish as a web service
Next you create a Predicative Experiment.
- At the bottom of the experiment canvas, click Set Up Web Service and select Predictive Web Service. This saves the model as a Trained Model and adds web service Input and Output modules.
- Click Run.
- After the experiment has finished running, click Deploy Web Service [Classic] or Deploy Web Service [New].
Note
To deploy a New web service you must have sufficient permissions in the subscription to which you deploying the web service. For more information see, Manage a Web service using the Azure Machine Learning Web Services portal.
Deploy the training experiment as a Training web service
To retrain the trained model, you must deploy the training experiment that you created as a Retraining web service. This web service needs a Web Service Output module connected to the Train Model module, to be able to produce new trained models.
- To return to the training experiment, click the Experiments icon in the left pane, then click the experiment named Census Model.
- In the Search Experiment Items search box, type web service.
- Drag a Web Service Input module onto the experiment canvas and connect its output to the Clean Missing Data module. This ensures that your retraining data is processed the same way as your original training data.
- Drag two web service Output modules onto the experiment canvas. Connect the output of the Train Model module to one and the output of the Evaluate Model module to the other. The web service output for Train Model gives us the new trained model. The output attached to Evaluate Model returns that module’s output, which is the performance results.
- Click Run.
Next you must deploy the training experiment as a web service that produces a trained model and model evaluation results. To accomplish this, your next set of actions are dependent on whether you are working with a Classic web service or a New web service.
Classic web service
At the bottom of the experiment canvas, click Set Up Web Service and select Deploy Web Service [Classic]. The Web Service Dashboard is displayed with the API Key and the API help page for Batch Execution. Only the Batch Execution method can be used for creating Trained Models.
New web service
At the bottom of the experiment canvas, click Set Up Web Service and select Deploy Web Service [New]. The Web Service Azure Machine Learning Web Services portal opens to the Deploy web service page. Type a name for your web service and choose a payment plan, then click Deploy. Only the Batch Execution method can be used for creating Trained Models
In either case, after experiment has completed running, the resulting workflow should look as follows:
Retrain the model with new data using BES
For this example, you are using C# to create the retraining application. You can also use the Python or R sample code to accomplish this task.
To call the Retraining APIs:
- Create a C# Console Application in Visual Studio (New->Project->Windows Desktop->Console Application).
- If you are working with a Classic web service, click Classic Web Services.
- Click the web service you are working with.
- Click the default endpoint.
- Click Consume.
- At the bottom of the Consume page, in the Sample Code section, click Batch.
- Continue to step 5 of this procedure.
- If you are working with a New web service, click Web Services.
- Click the web service you are working with.
- Click Consume.
- At the bottom of the Consume page, in the Sample Code section, click Batch.
- Copy the sample C# code for batch execution and paste it into the Program.cs file, making sure the namespace remains intact.
Add the Nuget package Microsoft.AspNet.WebApi.Client as specified in the comments. To add the reference to Microsoft.WindowsAzure.Storage.dll, you might first need to install the client library for Microsoft Azure storage services. For more information, see Windows Storage Services.Ipnput.csv") to Azure Storage, processes it, and writes the results back to Azure Storage.
To accomplish this task, you must retrieve the Storage account name, key, and container information for your Storage account from the classic Azure portal and the update corresponding values in the code.
- In the left navigation column, click Storage.
- From the list of storage accounts, select one to store the retrained model.
- At the bottom of the page, click Manage Access Keys.
- Copy and save the Primary Access Key and close the dialog.
- At the top of the page, click Containers.
- Select an existing container or create a new one and save the name.
Locate the StorageAccountName, StorageAccountKey, and StorageContainerName declarations and update the values you saved from the Az the input file is available at the location you specify in the code.
Specify the output location
When specifying the output location in the Request Payload, the extension of the file specified in RelativeLocation must be specified as ilearner.
See the following example:
Outputs = new Dictionary<string, AzureBlobDataReference>() { { "output1", new AzureBlobDataReference() { ConnectionString = storageConnectionString, RelativeLocation = string.Format("{0}/output1results.ilearner", StorageContainerName) /*Replace this with the location you would like to use for your output file, and valid file extension (usually .csv for scoring results, or .ilearner for trained models)*/ } },
Note
The names of your output locations may be different from the ones in this walkthrough based on the order in which you added the web service output modules. Since you set up this training experiment with two outputs, the results include storage location information for both of them.
Diagram 4: Retraining output.
Evaluate the Retraining Results
When you run the application, the output includes the URL and SAS token necessary to access the evaluation results.
You can see the performance results of the retrained model by combining the BaseLocation, RelativeLocation, and SasBlobToken from the output results for output2 (as shown in the preceding retraining output image) and pasting the complete URL in the browser address bar.
Examine the results to determine whether the newly trained model performs well enough to replace the existing one.
Copy the BaseLocation, RelativeLocation, and SasBlobToken from the output results, you will use them during the retraining process.
Next steps
If you deployed the predictive web service by clicking Deploy Web Service [Classic], see Retrain a Classic web service.
If you deployed the predictive web service by clicking Deploy Web Service [New], see Retrain a New web service using the Machine Learning Management cmdlets.
|
https://docs.microsoft.com/en-us/azure/machine-learning/machine-learning-retrain-models-programmatically
|
CC-MAIN-2017-26
|
refinedweb
| 1,294
| 54.63
|
How to make so that the Label control is always on top?
By
AndreyS, in AutoIt GUI Help and Support
Recommended Posts
Similar Content
-_DeleteDC($hMemDC) EndFunc ;==>SetBitmap
Thanks
- jmon
Hello,
I am trying to change the z-ordering of controls in my GUI using GUICtrlSetState. How come this example don't work? (I want $LABEL1 to be above $LABEL2)
#include <GUIConstantsEx.au3> $GUI = GUICreate("Test", 800, 600) GUISetState() $LABEL1 = GUICtrlCreateLabel("under", 20, 20, 500, 300) GUICtrlSetBkColor(-1, 0xFF0000) $LABEL2 = GUICtrlCreateLabel("above", 40, 60, 500, 300) GUICtrlSetBkColor(-1, 0x00FF00) GUICtrlSetState($LABEL1, $GUI_ONTOP) Do Sleep(50) Until GUIGetMsg() = -3 Exit Is there another method to change the z ordering and the order controls receive clicks? I know that the controls should be created in the correct order, but I can't in the script I am doing now.
Thanks
[EDIT] Solution is in post #5
- By zvvyt
Hello
|
https://www.autoitscript.com/forum/topic/167870-how-to-make-so-that-the-label-control-is-always-on-top/
|
CC-MAIN-2018-17
|
refinedweb
| 147
| 51.89
|
You can subscribe to this list here.
Showing
3
results of 3
Hi,
[I already posted this to sdcc-user, but I think this is the correct place]
Maybe it is somewhat too special, but consider the following
assembler code which is part of a project using async motor control
by the PWMs of an 80C552. It is, in this case, the service routine
for timer 1 interrupts.
[..pushes..]
mov a,_pwmacc ; 1 get PWM phase-accu, low byte
add a,_phsinc ; 1 add frequency increment
mov _pwmacc,a ; 1 store back
mov a,_pwmacc + 1 ; 1 get PWM phase-accu, high byte
addc a,_phsinc + 1 ; 1 add frequency increment
mov _pwmacc + 1,a ; 1 store back
mov dptr,#_sintab ; 2 get address of sin/cos table
mov a,_pwmacc + 1 ; 1 get high-byte of phase again
movc a,@a+dptr ; 2 get sin value
mov b,_pwampl ; 2 get amplitude
mul ab ; 4 multiply both
mov a,_pwoffs ; 1 get offset in A
add a,b ; 1 add high byte of mult. result
mov PWM0,a ; 1 output new PWM value to hardware
mov a,_pwmacc + 1 ; 1 get high-byte of phase again
add a,#64 ; 1 add 90 degree phase shift
movc a,@a+dptr ; 2 get cos value
mov b,_pwampl ; 2 get amplitude
mul ab ; 4 multiply both
mov a,_pwoffs ; 1 get offset in A
add a,b ; 1 add high byte of mult. result
mov PWM1,A ; 1 output new PWM value to hardware
[..pops..]
(The numbers in the comments denote the number of cycles needed)
Now, consider the following C code doing exactly the same:
#include <reg552.h>
code unsigned char sintab[] = { [..omitted..] };
unsigned int pwmacc;
unsigned int phsinc;
unsigned char pwampl;
unsigned char pwoffs;
void t1intr(void) interrupt 3
{
unsigned char tabadr;
pwmacc += phsinc; /* add frequency to accumulator */
tabadr = pwmacc >> 8; /* use high 8 bits for table offset */
/* multiply table entry with amplitude, use only high 8 bits of
the product. Then, add the offset to correct for zero DC */
PWM0 = pwoffs + (unsigned char)
((unsigned int)(sintab[tabadr] * pwampl) >> 8)
tabadr += 64; /* use 90 deg. shift for 2nd PWM channel */
PWM1 = pwoffs + (unsigned char)
((unsigned int)(sintab[tabadr] * pwampl) >> 8)
}
I ran this through "sdcc -c t1.c", and found the following rules
useful when adding to the peephole-optimizer-defines in
~sdcc/src/mcs51/peeph.def:
replace {
mov %1,a
mov b,%2
mov a,%1
mul ab
mov %1,a
} by {
; Peephole 223 removed move A -> reg -> A
mov b,%2
mul ab
mov %1,a
}
replace {
mov r%1,a
mov r%2,b
mov ar%1,r%2
mov r%2,#0x00
mov a,r%1
} by {
; Peephole 224 removed register acrobatic from >> 8
mov a,b
mov r%1,a
mov r%2,#0x00
}
Even if the code is still not as compact as the direct coded assembler,
one can gain some cycles in time-critical service routines.
I have not verified in which other cases these rules may be applied,
and hope that they do not break anything in other cases.
Look also at the way how sintab is addressed. The use of
"movc a,@a+dptr" can save some code if the array index is an unsigned
character and the array is stored in code space
(well, I admit, a very special case).
Regards,
Andreas.
--
Sent through GMX FreeMail -
Hi,
I made the following commits:
Configure now creates the files ports.all and ports.build in ~sdcc.
Ports.all is used for cleaning, ports.build is used to build only the
not-disabled port. So if someone screws up, (me for example in the ds390
port) "configure --disable-ds390-port" now won't even build the port, so
live goes on without it.
BORLAND and MSVC makefile need some changes if the want this too.
All ports are cleaned now with a toplevel "make clean".
As discussed, the pic port is now called -mpic, --model can be used in the
future to distinguish different types. I wonder if this should also be done
for the izt port with the i386 and the tlcs900h.
All ports can now be build standalone (that is with all others disabled).
This needed some small changes in the mcs51 and pic dir, and a new "const
int id" to the PORT structure. There are no cross references anymore between
ports.
Removed all ds390 related leftovers from mcs51.
I checked and dubble checked, but if I still missed something, please let me
know.
Johan
Hi Johan
Fixed. both in msc51 and the ds390 port.
Sandeep
-----Original Message-----
From: sdcc-devel-admin@...
[mailto:sdcc-devel-admin@...]On Behalf Of Johan Knol
Sent: Monday, February 26, 2001 6:59 AM
To: sdcc-devel@...
Subject: Re: [sdcc-devel]bug report: post increment turns into pre
increment
My first deduction was completely wrong.
void main (void) {
int preIncrement=0, postIncrement=0;
int i;
for (i=0; i<10; i++) {
printf ("%d %d\n", ++preIncrement, postIncrement++);
}
sdcc -c bug.c --dumpall
is still ok in .dumpranges, but wrong in .dumppack. So it had to be
packRegisters().
In packForPush, iTemp4 is replaced by iTemp5 even now that iTemp5 has
changed.
Hope this helps,
Regards,
Johan Knol
----- Original Message -----
From: Johan Knol <johan.knol@...>
To: <sdcc-devel@...>
Sent: Sunday, February 25, 2001 8:07 PM
Subject: [sdcc-devel]bug report: post increment turns into pre increment
> Hi,
>
> I have seen this bug report before, but it still exists. It happens e.g.
in
> device/examples/ds390/ow390/tstow.c
>
> In short: genPlus changes left and right when left needs acc but right is
> literal, as in the post increment case. So after the change it turns into
a
> pre increment. Besides that, now that right isn't a literal anymore
> genPlusIncr refuses to do it's job.
>
> As ussual, that's as far as I got (although I am getting closer and
closer).
> But I don't know how to fix it.
>
> Please help,
> Johan
>
>
>
> _______________________________________________
> sdcc-devel mailing list
> sdcc-devel@...
>
>
_______________________________________________
sdcc-devel mailing list
sdcc-devel@...
|
http://sourceforge.net/p/sdcc/mailman/sdcc-devel/?viewmonth=200103&viewday=5
|
CC-MAIN-2015-06
|
refinedweb
| 1,014
| 70.43
|
# ECS: under the hood
### Introduction
This is the translation of my article about ECS. [Original (in Russian)](https://habr.com/ru/sandbox/166093/)
ECS (Entity Component System) is an architectural pattern used in game development.
In this article, I am going to describe some of the general principles of ECS frameworks' inner workings and some of the problems I have faced during the development of my own.
When I first started learning about ECS everything seemed wonderful, but only in theory. I needed some real practice to make sure that all that they were saying about ECS was true.
I’ve tried different frameworks with different engines and programming languages. Mostly it was the gorgeous EnTT framework that I used with the Godot engine and LeoECS with Unity. I haven’t tried Unity’s native ECS from DOTS because it was rather unpolished at the time I was starting.
After a while, I got enough practical experience with ECS but it was still unclear to me how all this magic works under the hood. There are a few good blogs about ECS development (<https://skypjack.github.io/> from the author of EnTT and <https://ajmmertens.medium.com/> from the author of Flecs) but none of them gave me enough understanding about how they are implemented. So eventually, following Bender’s example, I decided that I’m gonna make my own ECS =)
For implementation, I chose C# and Unity since that’s what I’m using for my pet game project.
There are lots of articles and explanation videos all over the Internet about what ECS is and how to make games using it (for example the blogs mentioned above or this really good presentation from the developers of Overwatch: <https://www.youtube.com/watch?v=zrIY0eIyqmI>) but almost nothing about its inner workings. And that will be the subject of this article.
### Data access
The main problem of the ECS architecture is data access. If we had only one component type, entities could be just indices into an array of these components, but there is always more than one component type in real-world scenarios. And if one group of entities all had one component, another group of entities had another component, and the third one had them both, then it would be really bad for CPU cache locality with a naive array-based approach. And thus we need some smart data access arrangement. From the information found on the internet, I’ve learned that there are two major approaches: archetypes and sparse sets. The first one is used in Flecs and (as far as I know) Unity’s DOTS. The second one is in frameworks such as EnTT and LeoEcs. I went with the approach of the sparse set for implementing my framework.
### Archetypes
First, I’ll briefly explain how archetypes work, or at least my understanding of it. An archetype is a collection of entities with exactly the same set of components. When you add or remove components from an entity it is moved to another archetype, with all its components. Each archetype contains arrays of entities and components with corresponding indices, so they are perfectly aligned with each other. The main advantage of this architecture is that entity processing can be parallelized more easily, but it comes with a downside: it is quite costly to add/remove components from entities. So I gave up on that approach in favor of sparse sets because the game I am working on uses tags extensively. A tag is a no-data component that only describes some aspects of the entity that it belongs to. For example, DeadTag on an entity indicates that this entity is dead and therefore should not be processed by systems where only alive entities are processed. And usually, such tags are added only for a couple of frames and then removed.
### Sparse sets
The second approach. A sparse set is a tricky data structure that allows indirect access to data. In its basic form, it consists of two arrays: an outer sparse array of indices and an inner dense array of values. In such sets, we refer to elements by outer indices. Using that index we first get the inner index from the sparse array, and then using this inner index we get the value we need. If the inner index is -1 or the outer index is outside of the range of the sparse array then there is no value with that outer index. Thus we can store data continuously without gaps. The only gaps we’ll have are the regions filled with -1’s in the outer indices.
### Overall structure
The main class of my framework is EcsWorld, which holds an array of entities, a collection of systems, and component pools.
An **entity** is just an integer that stores the entity’s index and generation using bit shift operations. The generation is incremented every time an entity is recycled and is used to check whether the entity represented by this integer is still valid, i.e. it hasn’t been destroyed and recreated.
A **Component pool** in my case is just a class implementing the IComponentsPool interface. So I can store pools of components of different types in one collection.
There are two implementations of IComponentsPool: ComponentsPool (based on sparse sets) and TagsPool, which is implemented as a dynamic bitmask and only stores whether the tag is present or absent on the entity.
### Component registration
Each component is registered and gets its index via this trick with a static constructor that I came across in LeoECS:
```
static class ComponentIdCounter
{
internal static int Counter = -1;
}
public static class ComponentMeta
{
public static int Id
{
get;
private set;
}
static ComponentMeta()
{
Id = ComponentIdCounter.Counter++;
}
}
```
In other words, we have a static counter that is incremented each time a new component appears. It’s then used as the index of the components pool for this component.
### Naive implementation
This is what the first iteration of data organization looked like. Every system had a filter consisting of two masks: includes, or the components that entity should have, and excludes, the components that it shouldn't.
Every tick the system iterates over all the entities and checks the components on the entity against its filter. But the performance of that approach was unsatisfying and I had to think about some kind of optimization.
### Optimization
The idea of optimization is that every filter should have not only include/exclude masks but also an array of filtered entities which should be updated every time an add/remove happens. Somewhat resembling the archetypes approach mentioned above.
For this, we create two (one for includes and one for excludes) helper structures of type Dictionary> which will contain sets of indices of all filters with a given component, accessible by the id of that component.
Every time we add a component, we get the registered ID of that component, get all the filters by that ID from our helper structure for excludes, and remove the entity from all these filters. Then we add the component to the pool and add the entity to all the corresponding filters in the helper structure for includes. And when we remove a component, we go through all this in reverse: add an entity to the exclude filters and remove it from the include ones.
However, the fact that an entity has a specific component doesn’t guarantee that this entity satisfies all the filter conditions. That's why I added an array of bitmasks that corresponds to the array of entities to the EcsWorld and check against the mask when adding or removing a component.
The rest is easy: each system registers a filter (or you may have several filters) in EcsWorld by two masks and gets the index of the corresponding filter. Then it iterates over the collection of filtered entities obtained from the world by that index.
```
class MySystem : EcsSytem
{
int filterId;
public MySystem(EcsWorld world)
{
filterId = world.RegisterFilter(
new BitMask(Component1.Id, Component2.Id),
new BitMask(Component3.Id, Component4.Id));
}
public override void Tick()
{
world.GetFilter(filterId).Iterate((entities, count) =>
{
for (int i = 0; i < count; i++)
{
//do stuff
}
});
}
}
```
(the code is slightly simplified for the sake of readability)
### Epilogue
There are many nuances of implementation left outside of the scope but the main purpose of this article is to show key ideas of ECS implementation, the main problems I have faced during development, and solutions to them.
I have plans to implement a system of sorted groups in the future, like in EnTT. In it you can sort sets of components according to certain filters so that the entities and components that meet the criteria go in strict order. But in general, even without sorting, there is a performance gain.
I also plan to write an ECS based on archetypes. Maybe someday I will write about it here.
Well, in the end, I want to clarify that my project was created solely for educational purposes and although I’m making a game with it, I advise you to use one of the popular frameworks: for example, [LeoECS](https://github.com/Leopotam/ecs) or, if you need rollbacks just like me, [ME.ECS](https://github.com/chromealex/ecs). Also, Unity’s DOTS has been long in development and could be ready enough to be worth a try.
[Repo link](https://github.com/AlexCheero/ECS)
|
https://habr.com/ru/post/651921/
| null | null | 1,606
| 52.49
|
This post is about Adding feature flags to an ASP.NET Core app.Feature flags (also known as feature toggles or feature switches) are a software development technique that turns certain functionality on and off during runtime, without deploying new code. In this post we will discuss about flags using appsettings.json file. I am using an ASP.NET Core MVC project, you can do it for any .NET Core project like Razor Web Apps, or Web APIs.
First we need to add reference of Microsoft.FeatureManagement.AspNetCore nuget package – This package created by Microsoft, it will support creation of simple on/off feature flags as well as complex conditional flags. Once this package added, we need to add the following code to inject the Feature Manager instance to the http pipeline.
using Microsoft.FeatureManagement;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddFeatureManagement();
var app = builder.Build();
Next we need to create a FeatureManagement section in the appsettings.json with feature with a boolean value like this.
“FeatureManagement”: {
“WelcomeMessage”: false
}
Now we are ready with feature toggle, let us write code to manage it from the controller. In the controller, ASP.NET Core runtime will inject an instance of the IFeatureManager. And in this interface we can check whether a feature is enabled or not using the IsEnabledAsync method. So for our feature we can do it like this.
public async Task<IActionResult> IndexAsync()
{
if(await _featureManager.IsEnabledAsync(“WelcomeMessage”))
{
ViewData[“WelcomeMessage”] = “Welcome to the Feature Demo app.”;
}
return View();
}
And in the View we can write the following code.
@if (ViewData[“WelcomeMessage”] != null)
{
<div class=“alert alert-primary” role=“alert”>
@ViewData[“WelcomeMessage”]
</div>
}
Run the application, the alert will not be displayed. You can change the WelcomeMessage to true and refresh the page – it will display the bootstrap alert.
This way you can start introducing Feature Flags or Feature Toggles in ASP.NET Core MVC app. As you may already noticed the Feature Management library built on top of the configuration system of .NET Core. So it will support any configuration sources as Feature flags source. Microsoft Azure provides Azure App Configuration service which helps to implement feature flags for cloud native apps.
Happy Programming 🙂
|
https://online-code-generator.com/adding-feature-flags-to-an-asp-net-core-app/
|
CC-MAIN-2022-40
|
refinedweb
| 368
| 51.14
|
Brandt Premia
Here you can find all about Brandt Premia like manual and other informations. For example: review.
Brandt Premia manual (user guide) is ready to download for free.
On the bottom of page users can write a review. If you own a Brandt Premia please write about it to help other people. [ Report abuse or wrong photo | Share your Brandt Premia photo ]
Manual
Preview of first few manual pages (at low quality). Check before download. Click to enlarge.
Brandt Premia
Video review
brandt kdn 530 c edgebander with corner rounding
User reviews and opinions
No opinions have been provided. Be the first and add a new opinion/review.
Documents
Expectations of equity risk premia, volatility and asymmetry
John R. Graham,
Fuqua School of Business, Duke University, Durham, NC 27708, USA
Campbell R. Harvey*
Fuqua School of Business, Duke University, Durham, NC 27708, USA National Bureau of Economic Research, Cambridge, MA 02912, USA
ABSTRACT
We present new evidence on the distribution of the ex ante risk premium based on a multi-year survey of Chief Financial Officers (CFOs) of U.S. corporations. We have responses from surveys conducted from the second quarter of 2000 through the second quarter of 2003. We find evidence that the one-year risk premium is highly variable through time, while the ten-year expected risk premium is stable and equal to approximately 3.8%. For one-year premia, after periods of negative returns, CFOs significantly reduce their market forecasts, and return distributions are more skewed to the left. We also examine an important prediction of asset pricing theory: a positive trade-off between ex ante returns and ex ante volatility. In a unique test, we examine this trade-off in a cross-section of individual respondents. We find that time horizon plays and important role. While there is little evidence of a significant relation between expected returns and variance at the one-year horizon, there is a strong positive relation at the ten-year horizon that is consistent with asset pricing theory.
______________________________________________________________________________ *Draft: July 7, 2003. Corresponding author, Telephone: +1 919.660.7768, Fax: +1 919.660.8030, Email address: cam.harvey@duke.edu. We thank the Financial Executives International (FEI) executives who took the time to fill out the surveys. We thank Michael Brandt, Alon Brav, Magnus Dahlquist, Wayne Ferson, Ken French, Ron Gallant, Eric Ghysels, Felicia Marston, Jim Smith, Paul Soderlind, Ross Valkanov, and Bob Winkler for their helpful comments, seminar participants at Boston College and the University of Michigan, participants at the NBER Corporate Finance Summer Workshop, as well as conference participants at the TIAACREF-Association of Investment Management Research research seminar and the Western Finance Association. Hai Huang and Krishnamoorthy Narasimhan provided research assistance. This research is partially sponsored by FEI but the opinions expressed in the paper are those of the authors and do not necessarily represent the views of FEI. Graham acknowledges financial support from the Alfred P. Sloan Research Foundation.
Expectations of Equity Risk Premia
1. Introduction The current market capitalization of U.S. equities is approximately $10 trillion. A shift in the equity risk premium by just one percent could add or subtract $1 trillion in market value. In addition, corporate investment decisions hinge on the expectations of the risk premium (via the cost of capital) as do both U.S. and international asset allocation decisions. Therefore, it is important for financial economists to have a thorough understanding of the expected risk premium and the factors that influence it. The expected market risk premium has traditionally been estimated using long-term historical average equity returns. Using this approach, in December 2002, the arithmetic average return on the S&P 500 over and above the U.S. Treasury bill was reported by Ibbotson Associates (2003) to be 8.21%. To many, this is a very high risk premium and it seems to have influenced the views of a great many academics [Welch (2000)]. Fama and French (2002) conclude that average realized equity returns are in fact higher than ex ante expected returns over the past half century because realized returns included large unexpected capital gains. If this is true, then using historical averages to estimate the risk premium is misleading. We use a different approach to estimate the expected risk premium and offer a number of new insights. We base our estimate on a multiyear survey of Chief Financial Officers (CFOs), designed to measure their expectations of risk premia over both short and long horizons. Our survey is unique in that we obtain a measure of each respondents risk premium distribution, rather than just the expected value (mean). That is, our survey captures both market volatility and asymmetries implicit in the respondents probability distributions. In addition, we shed light on how recent stock market performance impacts the ex ante risk premium, volatility and asymmetries. We also study the relation between expected risk and expected return. There are many methods to estimate the equity risk premium and we cannot tell which method is the best because the variable of interest is fundamentally unobservable. The average of past returns is the method with the longest tradition. However, there are other timeseries methods that use measures like dividend yield to forecast returns. These models are
A similar argument is made in Poterba and Summers (1995) survey of CEOs.
based on firm characteristics. We also have limited ability to link forecasts from one quarter to the next and are able to verify consistency in a given CFOs forecast. We have conducted surveys representing over 3,000 total responses, from the second quarter of 2000 through the second quarter of 2003. Our results, summarized in Table 1, indicate that the one-year risk premium averages between 1.3 and 6.6 percent depending on the quarter surveyed. The ten-year premium is much less variable and ranges between 2.9 and 4.7 percent (also see Fig. 1).3 The standard deviation of the quarterly ten-year means is 0.52% while the same measure for the one-year means is 1.52%. We also find that the CFOs assessment of market volatility is much lower than popular alternative measures, suggesting that CFOs are very confident in their opinions (i.e., their individual distributions for the market risk premium are tight). We show that the recent performance of the S&P 500 has a significant effect on the shortterm expected risk premium as well as on forecasted volatility. Recent stock market performance also has a pronounced effect on CFO's ex ante skewness. In general, when recent stock market returns have been low, the one-year expected risk premium is low, its distribution has a relatively fat left tail, and expected market volatility is high. Our study has implications for asset pricing theory. We revisit the debate about the relation between expected excess returns and expected volatility. Our data provides us with a unique opportunity to test the relation between risk and expected return in a cross-section of individual respondents. While the evidence is mixed at the one-year horizon, we document a positive relation between risk and expected excess returns at the ten-year horizon. Our results support the idea that time horizon is important when examining the relation between risk and the risk premium. Finally, one of our surveys was delivered via FAX during the morning of September 10, 2001. Given the events of the next day, we are able to see how respondents assessments of risk and expected return change after a shock to systematic risk.
Pooling the individual responses, the standard deviation of the one-year premia is 4.27%. The standard deviation of the ten-year premia is 2.34%.
The paper is organized as follows. The second section details the methodology and the sampling procedure. The results are presented in the third section. An analysis conditional on firm characteristics is also outlined in the third section. Some concluding remarks are offered in the final section.
2. Methodology 2.1 Design The quarterly survey project is a joint effort with Financial Executives International (FEI). FEI has approximately 14,000 members that hold policy-making positions as CFOs, Treasurers, and Controllers at 8,000 companies throughout the U.S. and Canada. Every quarter, Duke University and FEI poll these financial officers with a short survey on important topical issues (Graham and Harvey, 1996-2003). The usual response rate for the quarterly survey is 5%-8%. Fig. 2 details the exact questions that we currently ask regarding the equity premium and some firm characteristics that we collect every survey.
2.2 Delivery and response In the early years of the survey, FEI faxed approximately 4,000 surveys to a sample of their membership. The executives returned their completed surveys by fax to the third-party data vendor, Office Remedies Inc. Using a third party ensures that the survey responses are anonymous, although we knew a number of firm-specific characteristics, as discussed below. FEI changed the delivery mechanism to the Internet as of the December 4, 2001 survey. Among other things, we now collect the respondents IP addresses (though not their identity or company) and are able examine consistency of responses across different surveys. On the day of delivery, the survey contains information about the yield on the ten-year Treasury bond at the close of the previous business day, and the respondents are given approximately four business days to return the survey. Each survey is time stamped upon receipt. This allows us to examine if recent equity returns impact the CFOs responses when
they fill out the survey. Usually, two-thirds of the surveys are returned within two business days. We also conducted a survey at the North Carolina CFO Symposium on August 22, 2000. In this case, we were able to obtain a response from nearly every executive in the room. By comparing these responses with the other quarterly survey responses, we are able to examine whether the response rate on the quarterly survey affects the CFO predictions about the equity market risk premium. (For example, perhaps predominantly optimists respond to the quarterly survey.) We find that the responses for the North Carolina CFO survey are consistent with those from the quarterly survey indicating that there is no obvious nonresponse bias.4
2.3 The survey instrument and summary statistics The risk premium questions are a subset of a larger set of questions in the Duke-FEI quarterly survey of CFOs. Copies of the surveys can be found on the Internet. We ask respondents for their one- and ten-year forecasts of the S&P500 given the current ten-year Treasury bond rate [see Fig. 2]. The CFOs also complete the following statement: During the next year, there is a 1-in-10 chance that the actual [S&P 500] return will be greater than ___% as well as the analogous question for the lower equity return. This allows us to examine each respondents distribution of expected returns. We can recover a measure of volatility as well as skewness from each individuals responses. While the survey is anonymous, we ask questions about seven firm characteristics: industry, sales revenue, number of employees, headquarters location, ownership (public or private), proportion of foreign sales and whether they pay dividends. Fig. 3 summarizes our sample information for three of these characteristics.
There are three other reasons why we are not overly concerned with the response rate. First, our response rate is within the range that is documented in many other survey studies. Second, in Graham and Harvey (2001), we do standard tests for non-response biases (which involve comparing the results to those that fill out the survey early to ones that fill it out late) and find no evidence of bias. Third, in Brav, Graham, Harvey and Michaely (2003), we perform a captured sample survey at a national FEI conference in addition to an Internet survey. The responses for the captured survey (where nearly everyone responded) are qualitatively identical to those for the Internet survey (where 8% responded), indicating that response bias did not significantly affect the results.
3. The market risk premium and volatility 3.1 Risk premium For the ex ante one and ten-year risk premia, we calculate a histogram for each quarters survey.5 The complete set of histograms is available on the Internet. Fig. 4 focuses on two quarters histograms: March 12, 2001 and March 11, 2002. These two quarters are chosen on the basis of past equity market performance. The 2001 survey followed a substantial downward move in the equity market (the S&P 500 lost 12% in the month prior to the survey). The 2002 survey followed a substantial upward move in the market (the S&P 500 gained 6% in the month prior to the survey). The one-year premium is presented in panel A of Fig. 4. The mean premium from the 2001 survey following poor market performance is 1.3%. The mean premium from the 2002 survey following positive market performance is 4.8% (a difference of 3.5% from 2001 to 2002). The one-year premium histograms suggest that respondents assessments of future returns are potentially influenced by past returns. In panel B of Fig. 4, the ten-year risk premium is more stable. The survey that followed the negative market episode suggests a mean premium of 4.4% whereas the survey following positive returns had a mean premium of 2.9% (a difference of -1.5% from 2001 to 2002). This preliminary look at the data suggests that the longer-term expectations are influenced by different factors. The ten-year expectations are consistent with the idea that if the market has risen (fallen), expected returns are lower (higher) the notion of mean reversion in expectations. Of course, other economic conditions may have been different at these two dates. We explore this possibility below.
3.2 Past returns and the risk premium Fig. 4 examines only two quarters. In Fig. 5, we use mean premiums from each of the quarterly surveys to examine whether the past market performance affects the average risk
We trim the data by removing the two highest and two lowest forecasted returns. This is roughly equivalent to a one percent trim. The untrimmed results are available on request.
premium. There is an open question as to the definition of past. Andreassen (1990), Andreassen and Kraus (1990) and Klibanoff, Lamont and Wizman (1998) address the issue of the salience of information in forming investors reactions to news. Hence, we look at multiple definitions of past returns. However, our analysis does not address the possibility that respondents vary their look-back period in forming their expectations. Fig. 5 presents the analysis of the one-year premium relative to four different measures of lagged excess returns: the one-week, one-month, two month, and one-quarter past return on the S&P 500. In each graph, there is a positive relation between the past returns and the expected returns. For the one and two month lag returns, 61% and 75% of the variation in the one-year premium can be explained by lagged returns. In contrast, there is a modest negative relation between the past returns and the ten-year risk premium (graphs available on request). While CFOs assessments of the one-year risk premium appear strongly positively influenced by recent returns, the expectations of ten-year premium appear modestly negatively influenced by past returns. Table 2 presents regressions that use all of the data (rather than the means of the surveys which are presented in Fig. 5 for the one-year premia). We estimate weighted least squares regressions, where the weights are the inverse of each quarters standard deviation. Consistent with the graphical analysis, recent realized returns significantly positively impact the respondents forecasts of the one-year premium using each of the four measures of past returns.6 The regression for the ten-year premium shows a significant (at the 5% level) negative relation only with the previous months return (not the other three measures of lagged returns). Even using the one-month lagged return, the economic influence is much smaller for the ten-year premium. For example, a 10% return in the previous month increases the one-year premium by 211 basis points. We also present the OLS estimates. The inferences are consistent across the OLS and WLS estimates.
This is also consistent with Welch (2000, 2001) who shows in a survey of economists that the mean one-year premium in 1998 was 5.8% (near the peak of the stock market) and only 3.4% in 2001 (after a sizable retreat in the market).
A quadratic function explains 58% of the variance.
between ex post standard deviation and our measure of ex ante standard deviation. Finally, we also look at past values of the VIX and test whether there is information in the VIX that is relevant for future ex ante volatility. We find weak positive relation between past values of VIX and disagreement.
3.6 Asymmetry in distributions We use the information in the survey to form a simple measure of skewness in each respondents distribution. We look at the difference between each individuals 90% tail and the mean forecast and the mean minus the 10% tail. Hence, if the respondent's forecast of the risk premium is 6% and the tails are -8% and +11%, then the distribution is negatively skewed with a value of -9% (=5%-14%). As with the usual measure of skewness, we cube this quantity and standardize by dividing by the cube of the individual standard deviation. Panel B of Fig. 7 presents histograms of this asymmetry measure for the same 2001 and 2002 surveys featured before. In both of these surveys, the average asymmetry is negative. Indeed, we see negative average asymmetry in all of the quarterly surveys. However, the histograms suggest more negative asymmetry after negative returns.10 Following our analysis of disagreement, we can also examine the cross-sectional skewness of the distribution of risk premia, every quarter. For example, in panel A of Fig. 4, the crosssectional skewness of risk premia for the March 12, 2001 survey is 0.42. Fig. 9 finds a significant positive relation between recent returns and this measure of skewness for one-year forecasts. There is no significant relation between past returns and cross-sectional skewness at the ten-year horizon.
3.7 Asset pricing implications Given that we have new measures of expected (rather than realized) returns and ex ante volatility, we can say something about the link between expected returns and expected variance a fundamental component of asset pricing theory. We have two unique angles.
A complete set of histograms is available on the Internet.
First, we are able to test this relation in a cross-section of individual respondents. Second, previous research exclusively relies on statistical measures of both the mean and variance based on historical data whereas we directly observe a measure of expectations. The literature is evenly split on whether there is a positive relation or a negative relation between the mean and volatility. For example, using a GARCH framework, French, Schwert and Stambaugh (1987) and Campbell and Hentschel (1992) estimate a positive relation while Campbell (1987), Breen, Glosten, and Jagannathan (1989), Nelson (1991) and Glosten, Jagannathan and Runkle (1993) find a negative relation between the realized mean and volatility. Scruggs (1998) argues that Glosten, Jagannathan and Runkle results hide a positive partial relation once you control for other factors. Asset pricing theory implies a positive partial, not simple, relation. Harrison and Zhang (1999) use a semi-nonparametric method and find a positive relation. Brandt and Kang (2003) use a latent VAR technique and document a strong negative correlation. Goyal and Santa-Clara (2003) find a positive relation between the average on individual stock variances and expected returns. Ghysels, Santa-Clara and Valkanov (2003) combine daily data with monthly data and find a significantly positive relation. Harvey (2001) uses a combination of nonparametric density estimation and GARCH models and finds that the relation depends on the instrumental variables chosen. Both Harvey (2001) and Brandt and Kang (2003) document a distinct counter-cyclical variation in the ratio of mean to volatility.11 Evidence on the relation between risk and expected returns has important economic implications. For example, Pstor and Stambaugh (2001) have recently presented a Bayesian analysis of long-horizon risk premia. They find that the risk premium in the 1990s is 4.8% which is roughly consistent with our results. However, a critical component of their analysis involves tying their prior to a positive relation between the premium and volatility. If Pstor and Stambaugh instead chose a diffuse prior relation between volatility and the premium,
We focus on the relation between variance and risk premium. There is a considerable literature that investigates the asset pricing implications of heterogeneous beliefs. See Abel (1989), Basak (2000), Constantinides (1982), Constantinides and Duffie (1996), Detemple and Murthy (1994), Heaton and Lucas (1995), Williams (1977), and Zapatero (1998). Diether, Malloy and Scherbina (2002) and Anderson, Ghysels and Juergens (2003) use the dispersion of analysts forecast to proxy for disagreement.
their estimate of the risk premium in June 1999 rises dramatically to 27.7%.12 Our results below support the prior they impose. First, we examine aggregated data. Panels A, C, and E of Fig. 10 show that there is a negative relation between the one-year mean premium and disagreement, individual variance, and total variance. However, in panels B, D, and F, we find that the opposite is true for the ten-year premium the relation is positive. It is also interesting to note that the bulk of the total variance comes from the average individual variance not the disagreement. The graphical analysis only uses one observation per quarter. Given that we have individual estimates of the risk premium, variance and skewness, it is possible to examine whether there is a positive trade-off between expected return and risk in the cross-section of respondents. Table 4 provides quarter-by-quarter estimates of this relation. Panel A examines the relation between risk and the one-year premium. In 10 of the 13 quarters, this relation is positive. The average slope coefficient 0.33 with a Fama-MacBeth tratio of 1.8. When a skewness term is included, it has a negative sign in 11 of 13 quarters and is significantly negative when aggregated. Asset pricing theory suggests that higher positive skewness would be associated with lower expected returns. Given the possibility that the regressions could be influenced by extreme observations, we re-estimate the relation with various levels of trimming. The inference is the same. A weak positive relation between expected returns and variance and a significant negative relation with skewness. However, the intercepts in all of the regressions are significantly positive, which provides evidence against the specification. Panel B of Table 4 focuses on the ten-year premium. In the six quarters of data that are available, there is a positive relation between expected returns and individual variances in each of the quarters. The average slope coefficient is 2.33 with a t-ratio of 2.7. The slope is often interpreted as a measure of relative risk aversion and a value of 2.33 appears reasonable. When skewness is added to the specification, the significance and magnitude of the variance
b. During the next year, I expect the S&P 500 return will be: Worst Case: There is a 1-in-10 chance the actual return will be less than: % a. Industry Retail/Wholesale Mining/Construction Manufacturing Transportation/Energy Communications/Media b. Sales Revenue Less than $25 million $25-99 million $100-499 million Tech [Software/Biotech] Banking/Finance/Insurance Service/Consulting Other Best Guess: I expect the return to be: % Best Case: There is a 1-in-10 chance the actual return will be greater than: %
11. Please check one from each category that best describes your company:
Fig. 2. Risk premium and firm characteristic questions from March 2003 survey
$500-999 million $1-4.9 billion Over $5 billion c. Number of Employees Fewer than 100 100-499 500-999 1000-2499 d. Headquarters Northeast Mountain Midwest South Central South Atlantic Pacific e. Ownership Public, NYSE Public, NASDAQ/AMEX Private f. Foreign Sales 0% 1-24% 25-50% Over 50% g. Dividend Payments Yes No
2500-4999 5000-9999 Over 10,000
A. Industry
45% 40%
B. Revenue ($ millions)
30% 30% 20% 15% 10%
0% Retail/ Wholesale Mining/ Construct Manufacture Transport/ Energy Commu./ Media Tech (Software/ Bio Tech) Banking/ Finance/ Insurance Other
0% < 25 25-99 100-499 500-999 1000-4900 > 5000
C. Employment
0% < 100 100-499 500-999 1000-2499 2500-4999 5000-9999 > 10000
Fig. 3. Sample firm characteristics. Based on respondents to the FEI/Duke CFO Outlook Surveys from June 2000 to June 2003. While the survey is anonymous, information on seven firm characteristics is collected. We report industry, sales revenue and employment. Other characteristics, such as headquarters location, ownership, percentage of foreign sales, and whether the firm pays dividends are available on request. The exact questions are listed in Fig. 2.
A. One-year risk premium
35 Percentage of responses 20 March 12, 0 <-20 -20 -18 -16 -14 -12 -10 -8 -6 -4 -18 more March 11, 2002
Average premium 1.33% (2001), 4.49% (2002). Median premium 0.7% (2001), 3.4% (2002). Risk free 4.3% (2001), 2.6% (2002). Standard deviation 5.43% (2001), 3.26% (2002). Skewness -0.42 (2001), 0.66 (2002). Responses 124 (2001), 225 (2002). Previous month's S&P 500 excess return 11.77% (2001), 4.92% (2002).
B. Ten-year risk premium
35 Percentage of responses 0
--<20 ----m or e -8 -6 -4 -18
March 12, 2001 March 11, 2002
Average premium 4.41% (2001), 2.90% (2002). Median premium 4.1% (2001), 2.7% (2002). Risk free 4.9% (2001), 5.3% (2002). Standard deviation 2.52% (2001), 2.01% (2002). Skewness 0.28 (2001), 0.06 (2002). Responses 136 (2001), 229 (2002). Previous month's S&P 500 excess return 11.77% (2001), 4.92% (2002).
Fig. 4. Distributions of the one-year and ten-year risk premia. Based on responses to the FEI/Duke CFO Outlook Surveys in March 2001 and March 2002. Histograms for the other surveys are available on the Internet. We also report summary statistics of these two survey's cross-sectional distributions. Standard deviation is the standard deviation of the individual risk premium forecasts. We refer to this measure as the disagreement. Skewness is the skewness of the individual risk premium forecasts. We refer to this as the cross-sectional skewness. The number of responses on the one-year and ten-year premium questions may differ because individual respondents may choose not to answer some questions.
7 Mean one-year premium 0
-6 -4 -10
6 Mean one-year premium Excess S&P 500 return in previous week y = 0.149x + 3.4382 R2 = 0.115
y = 0.2021x + 3.5301 R2 = 0.6132
Excess S&P 500 return in previous month
7 Mean one-year premium Mean one-year premium 0 -15 -10 -15 Excess S&P 500 return in previous two months y = 0.1666x + 3.4556 R2 = 0.7518
-20 -15 -10 -Excess S&P 500 return in previous quarter y = 0.1141x + 3.7353 R2 = 0.5049
Fig. 5. The influence of past market performance on expected one-year risk premia. Based on responses to the 13 FEI/Duke CFO Outlook Surveys from June 2000 to June 2003. For each graph symbol, the vertical axis represents the mean percentage premium across all respondents in one particular quarter. The horizontal axis is the excess S&P 500 return in the previous week, month, two months and one quarter, measured up to the day before the survey is released. The arrow denotes the most recent survey observation.
y = -0.0338x + 6.4513
Mean one-year premium
R2 = 0.0407
-y = -0.1226x + 3.6448 R2 = 0.0187
University of Michigan Index of Consumer Confidence C.
Lagged four quarter real GDP growth D.
Mean ten-year premium
y = 0.0286x + 1.R2 = 0.2511
-3 y = 0.2239x + 3.3418 R2 = 0.5 6
University of Michigan Index of Consumer Confidence
Lagged four quarter real GDP growth
Fig. 6. Expected and current economic conditions and one and ten-year risk premia. Based on responses to the 13 FEI/Duke CFO Outlook Surveys from June 2000 to June 2003. For each graph symbol, the vertical axis represents the mean percentage premium across all respondents in one particular quarter. The horizontal axis is either the most recent value of the University of Michigan Index of Consumer Confidence or the previous four quarters' real GDP growth. The arrow denotes the most recent survey observation.
A. Respondents' one-year risk premium distribution volatility
Percentage of respondents 0 <20 more Volatility Average 6.75 (2001), 4.83 (2002); median 5.66 (2001), 3.77 (2002); standard deviation 3.61 (2001), 3.25 (2002); one month prior VIX 35.29 (2001), 22.02 (2002). Previous month's S&P excess return -11.77% (2001), 4.92% (2002). March 12, 2001 March 11, 2002
B. Respondents' one-year risk premium skewness
Percentage of responses more Skewness Average -0.814 (2001), -0.646 (2002); median -0.260 (2001), -0.054 (2002); standard deviation 1.613 (2001), 1.473 (2002). Previous month's S&P excess return -11.77% (2001), 4.92% (2002). <-6 -4 -2
Fig. 7. Volatility and skewness of repondents' risk premium distributions. Based on responses to the FEI/Duke CFO Outlook Surveys in March 2001 and March 2002. Histograms for the other surveys are available on the Internet. For each respondent, we calculate the standard deviation of their individual one-year risk premium distribution based on Davidson and Cooper (1976). We also report a measure of the skewness of their individual distribution. We also report summary statistics of these two survey's cross-sectional distributions. In panel A, standard deviation represents the standard deviation of the respondent's individual volatilities. In panel B, it represents the standard deviation of the individual skewness measures. We also report the one-month prior implied volatility on the S&P 100 index option (VIX) as well as one-month prior S&P 500 prior returns.
A. Disagreement over the one-year premium and past returns
7 Disagreement over the one-year premium 0 -15
y = 0.0195x2 + 0.0293x + 3.3967 R2 = 0.5776
y = -0.0565x + 3.9647 R2 = 0.1445
Past one-month excess S&P 500 return
B. Disagreement over the ten-year premium and past returns
3.78 91.21 -0.009 -1.67 0.001 3135
3.76 88.48 -0.006 -1.42 0.000 3135
3.80 47.71 0.166 6.27 0.013 2865
3.75 49.02 0.226 15.81 0.080 2865
3.62 47.45 0.170 17.71 0.098 2865
4.03 51.04 0.120 15.20 0.074 2865
3.79 89.88 -0.005 -0.37 0.000 3135
3.79 90.77 -0.023 -2.96 0.003 3135
3.80 90.74 -0.008 -1.45 0.000 3135
3.79 87.75 -0.004 -0.93 0.000 3135
Table 3 Economic determinants of the risk premium Based on the responses from the FEI/Duke CFO Outlook Surveys from June 2000 to June 2003. The dependent variable is each respondent's assessment of the risk premium. The independent variable is either the most recent value of the University of Michigan Index of Consumer Confidence or the previous four quarters' real GDP growth. Panel A reports weighted least squares regressions where the responses in each quarter are weighted by the standard deviation of the risk premium forecasts in that quarter. Panel B reports ordinary least squares regressions. The number of observations from the one-year and tenyear regressions differs because some respondents choose not to fill out some questions. A. WLS
One-year premium Consumer Previous year real Confidence GDP growth 10-year premium Consumer Previous year real Confidence GDP growth
Intercept in % T ratio Economic indicator T ratio Adj. R2 Observations B: OLS Intercept in % T ratio Economic indicator T ratio Adj. R2 Observations
7.61 8.87 -0.043 -4.53 0.007 2865
4.07 29.70 -0.151 -2.96 0.003 2865
1.53 3.17 0.025 4.66 0.007 3135
10-year premium
3.35 49.64 0.208 7.87 0.019 3135
7.81 8.49 -0.045 -4.42 0.006 2865
4.04 29.05 -0.132 -2.49 0.002 2865
1.28 2.69 0.028 5.34 0.009 3135
3.33 47.16 0.219 8.15 0.021 3135
Table 4 Quarterly estimates of the relation between the expected risk premium and risk In each quarter, two regressions are estimated. The first is the individual risk premiums on the individual variance estimates. In the second regression, the specification is augmented with the individual skewness estimate. We report the intercept (which should be zero according to asset pricing theory) and the slope estimates. The t-ratio reported in the average column is the Fama-MacBeth t-ratio for the time-series of slopes. The smaller number of survey quarters for the 10-year risk premium reflects the fact that the variances have only been available for the past six surveys. A. One-year risk premium Quarter: 00q3 Intercept 0.023 T ratio 5.45 Individual variance T ratio Adj. R Observations
00q4 0.029 11.58 0.185 1.21 0.003 158
01q1 0.025 6.96 0.240 0.70 -0.003 195
01q2 0.014 1.96 -0.196 -0.23 -0.008 118
01q3 0.024 5.76 0.244 0.41 -0.006 142
01q4 0.024 4.00 -0.915 -1.62 0.012 133
02q1 0.044 10.29 0.484 1.82 0.012 185
02q2 0.042 13.92 1.481 3.00 0.046 169
02q3 0.029 13.72 0.814 2.63 0.019 303
02q4 0.030 12.91 0.889 3.25 0.027 344
03q1 0.051 19.73 0.647 1.89 0.010 267
03q2 0.031 9.02 0.121 0.38 -0.005 177
03q3 Average 0.062 0.033 22.33 9.02 0.772 3.21 0.0.323 1.82
-0.564 -1.49 0.008 159
Intercept T ratio Individual variance T ratio Individual skewness T ratio Adj. R Observations
0.026 6.02 -0.790 -2.08 -0.0041 -2.77 0.048 159
0.030 11.74 0.170 1.12 -0.0015 -1.57 0.012 158
0.026 7.24 0.103 0.30 -0.0019 -1.99 0.013 195
0.009 1.22 -0.721 -0.88 -0.0103 -3.30 0.071 118
0.028 6.67 -0.449 -0.74
0.028 4.85 -1.413 -2.56
0.044 10.64 0.293 1.13 -0.0056 -3.92 0.084 185
0.042 13.76 1.601 3.12 0.0015 0.86 0.044 169
0.029 12.91 0.796 2.55 -0.0005 -0.44 0.017 303
0.030 12.72 0.914 3.25 0.0004 0.39 0.025 344
0.050 19.19 0.576 1.63 -0.0011 -0.80 0.008 267
0.029 8.11 0.060 0.19 -0.0019 -1.59 0.004 177
0.061 21.76 0.732 3.02 -0.0018 -1.38 0.029 344
0.033 9.04 0.144 0.63 -0.003 -3.12
-0.0046 -0.0102 -3.54 -3.85 0.0.106 133
Table 4 (continued) B. Ten-year risk premium Quarter: 02q2 02q3 02q4 03q1 03q2 03q3 Average Intercept 0.029 0.029 0.037 0.029 0.032 0.038 0.032 T ratio 17.10 16.96 26.74 16.52 15.12 26.83 18.85 Individual variance T ratio Adj. R Observations
0.256 0.34 -0.004 207
1.831 3.19 0.028 315
2.410 4.82 0.059 352
6.063 5.97 0.113 272
2.971 3.35 0.055 176
0.464 1.38 0.003 352
2.332 2.70
0.029 16.89 0.192 0.25 -0.0009 -0.79 -0.006 207
0.029 16.91 1.863 3.07 0.0002 0.17 0.025 315
0.037 27.05 2.773 5.39 0.0027 2.66 0.076 352
0.029 16.50 6.166 5.90 0.0005 0.43 0.111 272
0.032 14.94 2.994 3.35
0.038 25.36 0.536 1.51
18K-CHA RA-930AX 1248U Nikkormat FT MG105 Tahoe 1999 Headset 42PF5320-10 Beocenter 2 LC-46DH77E Portege 7020 Pro-V 6321-20 PWS 720 PEG-TJ35 E2 Explorer-2002 KDC-3080RA Capitol Servers BE7II DMC-FS3 Crazy Taxi Afipr Color MFP UX-H30 Systemdiagnostics LMV2053SB DEH-P4100SD BMW 525D Sunbeam H2O SAA7130 V3-P5v900 Roland CD-2 DSL-G624M Alive 29DL25ED 32PW9509 12 PL42C430 WAP-3000 BAS 60 AWG 680 Casio 4335 BC-119N 1591D300A Cooker Gigaset C1 VOD102 PEG-SL10 KD-S821R Carys 3411 NV-GX7K RZ80eesw 450 XC-W 3040 AF GE29393 M420E AJ260 37B Pierrade DVD-S661 HDS-7M Psr-273 DA 6341 CDP-720 M-529V Review PS50C6900YW DV-320-S RS 120 SB-23 10 II Series Kalina 1118 Bizhub C652 GR-S592GC Family Satellite L505 LE46C530f1W Leadtek 8882 WM2010CW D-NE900 DSR205 T730SHK LCD32W07EU KDC-MP632U Lrfc22750SW 9 9D Racing 32LG60 Blade CX2 Handle 5-500 8300HDC SRV 810H 24-30 E Citroen Saxo Blockset 3 Wi300 EP6001 Elnapress HZL35Z 471
|
http://www.ps2netdrivers.net/manual/brandt.premia/
|
crawl-003
|
refinedweb
| 6,349
| 57.87
|
Hello,
I got a bit of a problem trying to do the following:
- Load a .xm or .it song
- get all samples, pack as wave and save them to separate files
problem ( i suppose):
sample speed (freq) differs in the song and from the retrieved value.
When I run the code below, all samps are marked 44100 but I know
some of those in the song are 8khz, 11 or etc.
The output wave just doesn’t sound as the original.
I’m using much of the code as in the ‘record’ example.
[code:3t8p4igv]
BOOL CSampleFM::SaveToWave( LPCTSTR lpszOutputFileName )
{
ASSERT( m_pSample != NULL );
ASSERT( lpszOutputFileName != NULL );
int nDefFreq, nVarFreq; FSOUND_Sample_GetDefaultsEx( m_pSample, &nDefFreq, 0, 0, 0, &nVarFreq, 0, 0); void *p1 = NULL, *p2 = NULL; UINT len1, len2; UINT uiMode = FSOUND_Sample_GetMode( m_pSample ); int bits = (uiMode & FSOUND_16BITS) ? 16 : 8; int channels = (uiMode & FSOUND_STEREO) ? 2 : 1; UINT uiLength = FSOUND_Sample_GetLength( m_pSample ) * channels * bits / 8; if ( uiLength == 0 ) { // dont save 0 len sams TRACE( _T("\n sample won't be saved. sample length: %d"), uiLength ); return FALSE; } // Wave Stuff (as from fmod sample) #if defined(WIN32) || defined(_WIN64) || defined(__WATCOMC__) || defined(_WIN32) || defined(__WIN32__) #pragma pack(1) #endif typedef struct { signed char id[4]; int size; } RiffChunk; struct { RiffChunk chunk; unsigned short wFormatTag; /* format type */ unsigned short nChannels; /* number of channels (i.e. mono, stereo...) */ unsigned int nSamplesPerSec; /* sample rate */ unsigned int nAvgBytesPerSec ; /* for buffer estimation */ unsigned short nBlockAlign; /* block size of data */ unsigned short wBitsPerSample; /* number of bits per sample of mono data */ } FmtChunk = { { {'f','m','t',' '}, sizeof(FmtChunk) - sizeof(RiffChunk) }, 1, channels, nDefFreq, nDefFreq * channels * bits / 8, 1 * channels * bits / 8, bits }; struct { RiffChunk chunk; } DataChunk = { {{'d','a','t','a'}, uiLength } }; struct { RiffChunk chunk; signed char rifftype[4]; } WavHeader = { { {'R','I','F','F'}, sizeof(FmtChunk) + sizeof(RiffChunk) + uiLength }, {'W','A','V','E'} }; #if defined(WIN32) || defined(_WIN64) || defined(__WATCOMC__) || defined(_WIN32) || defined(__WIN32__) #pragma pack() #endif // save to file CFile file; if ( !file.Open( lpszOutputFileName, CFile::modeCreate | CFile::modeWrite ) ) { return FALSE; } // write headers file.Write( &WavHeader, sizeof(WavHeader) ); file.Write( &FmtChunk, sizeof(FmtChunk) ); file.Write( &DataChunk, sizeof(DataChunk) ); FSOUND_Sample_Lock( m_pSample, 0, uiLength, &p1, &p2, &len1, &len2 ); file.Write( p1, len1 ); FSOUND_Sample_Unlock( m_pSample, p1, p2, len1, len2 ); file.Close(); return TRUE;
}
[/code:3t8p4igv]
Any help will be greatly appreciated, thanx 😉
- necroleak asked 12 years ago
- You must login to post comments
wow, thanx a lot brett. I think this did it 😀
I really don’t have much experience with sound programming 😥
- necroleak answered 12 years ago
|
https://www.fmod.org/questions/question/forum-13931/
|
CC-MAIN-2017-17
|
refinedweb
| 411
| 60.55
|
In cases where the web parts included in Kentico CMS by default do not meet the requirements of your specific scenarios, it is possible to develop new ones and register them in the system. This way, you can add any type of custom content or functionality to your pages through the portal engine.
All web parts are implemented as user controls. Standard web parts must inherit the CMSAbstractWebPart class from the CMS.PortalControls namespace. An exception to this rule are web parts that provide content editable on the Page tab of CMS Desk and in On-site editing mode (such as the default Editable text and Editable image), which need to inherit from the CMSAbstractEditableWebPart class instead.
The following example will guide you through the process of creating a very simple "Hello world" web part that displays a label and a button. When the button is clicked, the current time will be.
4. Create a new Web User Control named HelloWorld.ascx.
5. In the Control declaration, enter the full relative path of the control's code behind file into the CodeFile attribute (CodeBehind attribute on web application installations).
6. Switch to the Design view and drag the following controls onto the form from the toolbox:
•Button
•Label
7. Double-click the Button control and add the following code to the Button1_Click method:
[C#]
[VB.NET]
8. Add the following line to the beginning of the code:
[C#]
[VB.NET]
9. Change the following line:
[C#]
[VB.NET]
This ensures that the user control inherits from the correct base class and behaves as a web part.
10. Add the following code to the Page_Load method:
[C#]
[VB.NET]
(Visual Basic.NET doesn't create the Page_Load method automatically, so you need to add the whole method:)
This code sets the button text to the value configured for the web part through its ButtonText property in Kentico CMS Desk (this property will be defined later in the example). Please notice the use of the GetValue method (inherited from the parent class), which allows you to dynamically load values of the web part's properties. The method's parameter must match the Column name of the property that you wish to retrieve.
11. Save all changes. If your Kentico CMS project was installed as a web application, you must Build the project.
1. Open Site Manager -> Development -> Web parts.
2. Select the root of the tree (All web parts) and click
New category.
3. Enter My web parts into the Category display name field, MyWebParts into the Category name field and click
Save.
4. Select the new category and click
New web part.
5. Choose to Create a new web part and enter the following values:
•Display name: Hello world
•Code name: HelloWorld
•File path: ~/CMSWebParts/MyWebParts/HelloWorld.ascx
•Generate the code files: false (the web part's source files were prepared in the previous steps, so there is no need to generate them)
6. Click
Save.
7. Switch to the Properties tab and add (
) the following property:
•Column name: ButtonText
•Attribute type: Text
•Attribute size: 100
•Field caption: Button text
•Form control: Text box
8. Click
Save.
1. Switch to CMS Desk.
2. Create a new blank page using the Simple layout (or any other layout) under the root and switch to the Design tab.
3. Click Add web part (
) in the upper right corner of the web part zone and choose to add the Hello world web part:
4. The Web part properties dialog of the HelloWorld web part will be displayed. Set the value of the Button text field to: Hello world!
5. Click OK.
Now switch to the Live site mode using the button in the main toolbar. You will see the button with text Hello world! When you click it, the label displays the current date and time:
You have learned how to create a simple web part. Please keep in mind that in many cases, it may be easier to achieve your goal by altering or extending one of the default web parts rather than developing an entirely new one. The Modifying web parts sub-chapter covers several ways how this can be done.
|
http://devnet.kentico.com/docs/7_0/devguide/developing_web_parts.htm
|
CC-MAIN-2016-30
|
refinedweb
| 698
| 70.23
|
by Abdul Kadir
The Strategy Pattern explained using Java
In this post, I will talk about one of the popular design patterns — the Strategy pattern. If you are not already aware, the design patterns are a bunch of Object-Oriented programming principles created by notable names in the Software Industry, often referred to as the Gang of Four (GoF). These Design patterns have made a huge impact in the software ecosystem and are used to date to solve common problems faced in Object-Oriented Programming.
Let’s formally define the Strategy Pattern:
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it
Alright with that out of the way, let’s dive into some code to understand what these words REALLY mean. We will take an example with a potential pitfall and then apply the strategy pattern to see how it overcomes the problem.
I will be showing you how to create a dope dog simulator program to learn the Strategy pattern. Here’s what our classes will look like: A ‘Dog’ superclass with common behaviors and then concrete classes of Dog created by subclassing the Dog class.
Here’s what the code looks like
public abstract class Dog { public abstract void display(); //different dogs have different looks! public void eat(){} public void bark(){} // Other dog-like methods ... }
The display() method is made abstract as different dogs have different looks. All the other subclasses will inherit the eat and bark behaviors or override it with their own implementation. So far so good!
Now, what if you wanted to add some new behavior? Let’s say you need a cool robot dog that can do all kinds of tricks. Not a problem, we just need to add a performTricks() method in our Dog superclass and we are good to go.
But wait a minute…A robot dog should not be able to eat right? Inanimate objects cannot eat, of course. Alright, how do we solve this problem then? Well, we can override the eat() method to do nothing and it works just fine!
public class RobotDog extends Dog { @override public void eat(){} // Do nothing }
Nicely done! Now Robot dogs cannot eat, they can only bark or perform tricks. What about rubber dogs though? They cannot eat nor can they perform tricks. And wooden dogs cannot eat, bark, or perform tricks. We cannot always possibly override methods to do nothing, it’s not clean and it just feels hacky. Imagine doing this on a project whose design specification keeps changing every few months. Ours is just a naive example but you get the idea. So, we need to find a cleaner way to solve this problem.
Can the interface solve our problem?
How about interfaces? Let’s see if they can solve our problem. Alright, so we create a CanEat and a CanBark interface:
interface CanEat { public void eat(); } interface CanBark { public void bark(); }
We have now removed the bark() and eat() methods from the Dog superclass and added them to the respective interfaces. So that, only the dogs that can bark will implement the CanBark interface and the dogs that can eat will implement the CanEat interface. Now, no more worrying about dogs inheriting behavior that they shouldn’t, our problem is solved…or is it?
What happens when we have to make a change in the eating behavior of the dogs? Let’s say from now onwards each dog must include some amount of protein with their meal. You now have to modify the eat() method of all the subclasses of Dog. What if there are 50 such classes, oh the horror!
So interfaces only partly solve our problem of Dogs doing only what they are capable of doing — but they create another problem altogether. Interfaces do not have any implementation code, so there’s zero code reusability and potential for lots of duplicate code. How do we solve this you ask? Strategy pattern comes to the rescue!
The Strategy Pattern
So we will do this step by step. Before we proceed, let me introduce you to a design principle:
Identify the parts of your program that vary and separate them from what stays the same.
It is actually very straightforward — the principle states to separate and “encapsulate” anything that changes frequently so that all the code that changes lives in one place. That way the code that changes will not have any effect on the rest of the program and our application is more flexible and robust.
In our case, the ‘bark ’and the ‘eat ’behavior can be taken out of the Dog class and can be encapsulated elsewhere. We know that these behaviors vary across different dogs and they must get their own separate class.
We are going to create two set of classes apart from the Dog class, one for defining eating behavior and one for the barking behavior. We will make use of interfaces to represent the behavior such as ‘EatBehavior ’ and ‘BarkBehavior ’ and the concrete behavior class will implement these interfaces. So, the Dog class is not implementing the interface anymore. We are creating separate classes whose sole job is to represent the specific behavior!
This is what the EatBehavior interface looks like
interface EatBehavior { public void eat(); }
And BarkBehavior
interface BarkBehavior { public void bark(); }
All of the classes that represent these behaviors will implement the respective interface.
Concrete classes for BarkBehavior
public class PlayfulBark implements BarkBehavior { @override public void bark(){ System.out.println("Bark! Bark!"); } } public class Growl implements BarkBehavior { @override public void bark(){ System.out.println("This is a growl"); } public class MuteBark implements BarkBehavior { @override public void bark(){ System.out.println("This is a mute bark"); }
Concrete classes for the EatBehavior
public class NormalDiet implements EatBehavior { @override public void eat(){ System.out.println("This is a normal diet"); } } public class ProteinDiet implements EatBehavior { @override public void eat(){ System.out.println("This is a protein diet"); } }
Now while we make concrete implementations by subclassing the ‘Dog’ superclass, naturally we want to be able to assign the behaviors dynamically to the dogs’ instances. After all, it was the inflexibility of the previous code that was causing the problem. We can define setter methods on the Dog subclass that will allow us to set different behaviors at runtime.
That brings us to another design principle:
Program to an interface and not an implementation.
What this means is that instead of using the concrete classes we use variables that are supertypes of those classes. In other words, we use variables of type EatBehavior and BarkBehavior and assign these variables objects of classes that implement these behaviors. That way, the Dog classes do not need to have any information about the actual object types of those variables!
To make the concept clear here’s an example that differentiates the two ways — Consider an abstract Animal class that has two concrete implementations, Dog and Cat.
Programming to an implementation would be:
Dog d = new Dog(); d.bark();
Here’s what programming to an interface looks like:
Animal animal = new Dog(); animal.animalSound();
Here, we know that animal contains an instance of a ‘Dog’ but we can use this reference polymorphically everywhere else in our code. All we care about is that the animal instance is able to respond to the animalSound() method and the appropriate method, depending on the object assigned, gets called.
That was a lot to take in. Without further explanation let’s see what our ‘Dog’ superclass looks like now:
public abstract class Dog { EatBehavior eatBehavior; BarkBehaviour barkBehavior; public Dog(){} public void doBark() { barkBehavior.bark(); } public void doEat() { eatBehavior.eat(); } }
Pay close attention to the methods of this class. The Dog class is now ‘delegating’ the task of eating and barking instead of implementing by itself or inheriting it(subclass). In the doBark() method we simply call the bark() method on the object referenced by barkBehavior. Now, we don’t care about the object’s actual type, we only care whether it knows how to bark!
Now the moment of truth, let’s create a concrete Dog!
public class Labrador extends Dog { public Labrador(){ barkBehavior = new PlayfulBark(); eatBehavior = new NormalDiet(); } public void display(){ System.out.println("I'm a playful Labrador"); } ... }
What’s happening in the constructor of the Labrador class? we are assigning the concrete instances to the supertype (remember the interface types are inherited from the Dog superclass). Now, when we call doEat() on the Labrador instance, the responsibility is handed over to the ProteinDiet class and it executes the eat() method.
The Strategy Pattern in Action
Alright, let’s see this in action. The time has come to run our dope Dog simulator program!
public class DogSimulatorApp { public static void main(String[] args) { Dog lab = new Labrador(); lab.doEat(); // Prints "This is a normal diet" lab.doBark(); // "Bark! Bark!" } }
How can we make this program better? By adding flexibility! Let’s add setter methods on the Dog class to be able to swap behaviors at runtime. Let’s add two more methods to the Dog superclass:
public void setEatBehavior(EatBehavior eb){ eatBehavior = eb; } public void setBarkBehavior(BarkBehavior bb){ barkBehavior = bb; }
Now we can modify our program and choose whatever behavior we like at runtime!
public class DogSimulatorApp { public static void main(String[] args){ Dog lab = new Labrador(); lab.doEat(); // This is a normal diet lab.setEatBehavior(new ProteinDiet()); lab.doEat(); // This is a protein diet lab.doBark(); // Bark! Bark! } }
Let’s look at the big picture:
We have the Dog superclass and the ‘Labrador’ class which is a subclass of Dog. Then we have the family of algorithms (Behaviors) “encapsulated” with their respective behavior types.
Take a look at the formal definition that I gave at the beginning: the algorithms are nothing but the behavior interfaces. Now they can be used not only in this program but other programs can also make use of it. Notice the relationships between the classes in the diagram. The IS-A and HAS-A relationships can be inferred from the diagram.
That’s it! I hope you have gotten a big picture overview of the Strategy pattern. The Strategy pattern is extremely useful when you have certain behaviors in your app that change constantly.
This brings us to the end of the Java implementation. Thank you so much for sticking with me so far! If you are interested to learn about the Kotlin version, stay tuned for the next post. I talk about interesting language features and how we can reduce all of the above code in a single Kotlin file :)
P.S
I have read the Head First Design Patterns book and most of this post is inspired by its content. I would highly recommend this book to anyone who is looking for a gentle introduction to Design Patterns.
|
https://www.freecodecamp.org/news/the-strategy-pattern-explained-using-java-bc30542204e0/
|
CC-MAIN-2021-43
|
refinedweb
| 1,811
| 63.8
|
Details
- Type:
Bug
- Status:
Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 1.6-beta-1
- Fix Version/s: 1.5.7, 1.6-beta-2
- Component/s: None
- Labels:None
- Number of attachments :
Description
Given these Java interfaces:
import java.util.List; public interface Base { List foo(); }
import java.util.ArrayList; public interface Child extends Base { ArrayList foo(); }
Java allows the return type for methods to be the most specified or a derived type:
import java.util.ArrayList; public class JavaChildImpl implements Child { public ArrayList foo() { return null; } }
But compiling this Groovy script:
class GroovyChildImpl implements Child { public ArrayList foo() { return null } }
yields:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, GroovyChildImpl.groovy: 2: the return type is incompatible with java.util.List foo() in Base. Node: org.codehaus.groovy.ast.MethodNode. At [2:5] @ line 2, column 5. public ArrayList foo() { ^ 1 error
Attached patch fixes this problem.
Activity
I had a patch but it doesn't handle a particular case that I just noticed. I'll have a bit more of a look and then get you to comment on the patch once amended and attached. When you say "respects super classes, but not interfaces being implemented by the current class" I think I understand but do you want to explain further what you mean.
Currently the patch modifies two classes. When ClassCompletionVerifier is checking for abstract methods it skips reporting an error if a derived method exists. Then in getCovariantImplementation in Verifier, instead of checking for equality between the overridingMethod and oldMethod class nodes it checks whether the type classes are assignable. Problem is that the return type for the overriding method may not be resolved yet, so there is more work to do.
you can not check for equality, because:
class X{def foo(){}} class Y{String foo(){}}
In this case we want covariation to kick in and let String foo() overwrite Object foo() by adding a bridge method for Object foo() that calls String foo(). Since the overwritten method can not return anything that its return type does not allow, I use assignable to check that. At the phase where this is called, the return type is usually resolved already, since it happens after ResolveVisitor is called.
I read "Attached patch fixes this problem."... is there a patch?
anyway, I will commit a fix for this in a few minutes. The problem was that in the code checking for covariance isDerivedFrom was used. but isDerivedFrom checks only super classes, no interfaces.... Maybe that should be considered as bug too.. We have also declaresInterface, so I guess it does not have to be seen as bug. Anyway, since only isDerivedFrom was used, only super classes where checked, and not interfaces. My patch will fix that and the test case will pass then.
Altered the test cases and supplied a potential patch to make them pass.
I should have mentioned. I am not sure whether the change I had to make to GroovyInterceptableTest is desirable. I expect not. Perhaps an improved fix is required. Perhaps we need both a implementsInterface and implementsInterfaceDirectOrIndirect.
first.. if you find another bug in this, please open a new issue, since this one has been resolved. But I agree, that the isAssignable test might not cover all of it.... for example did we test
interface I1{} interface I2 extends I2{} class X implements I2{} class Foo { I1 foo(){} } class Bar extends Foo { X foo(){} }
In that example X does not directly implement I1, but the method in Foo should still be overwritten by the one in Bar. Also I am very for a isAssignable method on ClassNode working with a ClassNode, not more String based patchwork here.. in fact that stupid string method (declaresInterface was it I think) should vanish. If you want to do that, feel free to do so... just the change to GroovyInterceptableTest should be undone.
I only reopened because I realised that my original testcase wasn't complete enough. I will add in my patch as it covers the case you mention above.
Looks like the problem has returned in 1.8.6. I'm running into this, exactly as described in the original posting.
Raffael, can you please fill a new issue and explain there what exactly your issue is? Do you mean the example in this issue no longer works?
Done:
And no, the issue is very similar, but the example in this issue should still work, AFAICS.
I guess the check (if it is allowed and if a bridge method has to be added) respects super classes, but not interfaces being implemented by the current class.
|
http://jira.codehaus.org/browse/GROOVY-2829?focusedCommentId=135251&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
|
CC-MAIN-2013-48
|
refinedweb
| 771
| 65.32
|
Technology behind Web 2.0
Most of the technologies behind internet are still used for Web 2.0: XHTML standards, style sheets, content syndication, AJAX, flash, dynamic pages, URLs among others [Van Der Henst, 2005]. According to Wikipedia, the technology infrastructure of Web 2.0 includes “server-software, content-syndication, messaging-protocols, standards-based browsers with plug-in and extensions, and various client applications”. All these technologies enable web 2.0 to offer capabilities different from traditional web sites offer, such as information-storage, creation, and dissemination capabilities.
Technology behind Web 2.0 is more about how “technologies are being used by people all over the world, and how rapidly many of them are embraced” according to Cavanaugh [2002]. There are a set of technologies that allow a large number of people to connect, communicate, collaborate and create [Cavanaugh, 2002] as we have seen when analyzing the different type of services that compose Web 2.0 concept. We now have heavy users of technology that seem to have a technology device always with them as an attachment to their body (a personal digital agenda, or a cell phone, a laptop, a beeper, a digital music player…): this is what empowers users.
Technology overview
According to Roy Fielding the World Wide Web is the world's largest distributed application. In order to understand how this application has evolved to the Web 2.0 it is necessary to understand the key architectural principle which leads to create light business models. The key architectural principle of the web according to its creator, Tim Berners Lee [1991], is that “the Web is by design and philosophy a decentralized system” which allows more freedom when designing web based applications although it also adds a chaos component to the whole system.
According to Wikipedia and to my personal insight, a Web 2.0 website may typically feature a number of the following techniques:
1)Content Syndication: Syndication and aggregation of data in RSS/Atom
2)Ajax-based rich Internet application techniques: improve user experience.
3)CSS style sheets for adding style to the web pages.
4)DOM representation of HTML and XTML in tree structures.
5)REST approach for getting information content from a Web page.
6)XML system for constructing custom markup languages that can be used to describe data types.
7)Mashups which combine applications to create new services.
1) Content syndication
RSS history goes back to 1997 and the creation of RDF, it was first invented by Netscape who wanted to use an XML format to distribute information. Later Userland Software took control of the specifications and continued to develop it launching RSS V2 which is the current existing one nowadays [1].
Content syndication such as RSS, Atom, RDF are used for the creation of web 2.0 services, for example RSS protocol is used for syndicating news and exchanging headlines between content-prone websites [Schwall, 2003]. I will focus on RSS technology since it seems to be the most popular and accepted choice for delivering syndicated web content; it is known as the internet pipe or the glue ”to create services”, according to Gomero [2006]. RSS can be used to deliver any type of content: text or multimedia. For example, podcasting is music delivered over RSS.
RSS is an acronym for Really Simple Syndication and Rich Site Summary. It is an XML-based format used for content distribution; moreover it is a defined standard based on XML in order to deliver updates to web-based content. Webmasters use it to provide fresh content in a concise way while users consume RSS readers and news aggregators to collect their favorite feeds in a centralized way. [2]. According to wikipedia, RSS is a family of web feed formats used to publish frequently updated digital content, such as blogs, news feeds or podcasts.
SW for RSS can be divided into two main groups according to how it will be used: content providing and content reading, RSS Creation Software for the former and RSS Reader for the later. [3]
In order to read syndicated content, users must select RSS feeders from the website.
RSS Creation Software: it creates RSS feeds that are compliant with the RSS specifications. An example of SW that appears in the RSS specification webpage is “FeedForAll” which is a desktop applications that creates, edits and publishes RSS feeds
RSS Reader To view RSS feeds from specified sources. There are two different types of readers, self contained program or readers using a web browser. The program is also called news aggregators. Information is automatically updated and displayed in reverse chronological order. There is an add-on SW available for internet browsers that allows users to view RSS feeds in their own browsers.
2) Ajax-based rich Internet application techniques
Web 2.0’s success is mostly due to the use of light technologies such as AJAX that allow developers to create Light web interfaces for these new services. These interfaces optimize transactions between browser and server [4]. Ajax programmers must know how each browser interacts with applications when programming, how it changes the interaction on that page [Malik, 2006].
According to wikipedia, Ajax means Asynchronous JavaScript and XML; it is “a web development technique for creating interactive web applications”. The goal is to make web pages more dynamic by exchanging small amount of data within the client and the server. The consequence of this procedure is to reduce the amount of web page that needs to be reloaded each time there is a request from the user; hence the page’s interactivity is higher, faster and easier to use. Ajax is not a technology in itself, but a term that refers to the use of a group of technologies [5]. Technologies such as JavaScript are changing the way we interact with content online [Malik, 2006].
According to wikipedia “The Ajax technique uses a combination of XHTML (or HTML) and CSS, for marking up and styling information.” Garrett [2005] in his definition about Ajax defines exactly what web technologies are behind it and how they interact between each other:
•standards-based presentation using XHTML and CSS;
•dynamic display and interaction using the Document Object Model;
•data interchange and manipulation using XML and XSLT;
•asynchronous data retrieval using XMLHttpRequest;
•JavaScript binding everything together.
In addition to the regular web architecture, in the front end there is an extra layer in addition to the HTML and CSS ones for JavaScript to manipulate XML files [6]
According to Garret [2005] “Ajax applications eliminate the start-stop-start-stop nature of interaction on the Web by introducing an intermediary between the user and the server.” It would seem like adding an extra layer to the application would slow its responsiveness but it is actually the opposite.
The way it works is that at the start of the session the browser loads an Ajax engine which renders the user interface and communicating with the server. Ajax takes charge of all HTTP requests between the user and the server, the engine makes the requests in an asynchronous way using XML without delaying user’s interaction with the application [Garret, 2005].
3) CSS
According to the W3C, CSS (Cascading Style Sheets) is defined as “a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents.” It is a style sheet language used to describe the presentation of a document written in a markup language, and it is generally used on pages written in HTML and XHTML or any kind of XML document. The CSS specifications are maintained by the W3C [7]. Style sheets are a very useful mechanism for designing accessible web pages, in Walsh’s words “supplying presentational information to a user agent displaying structured documents.” CSS is described formally by the W3C in two specifications: CSS1 and CSS2
A style sheet is a set of one or more rules that apply to a web markup document, the rules are statements about one stylistic aspect of one (or more) elements. CSS can be created in two different ways; (1) programming by hand in a normal text editor defining the style sheets and (2)use a special dedicated tool such as a Web page design application that supports CSS [Wium Lie and Bos, 1999]. In order for the Style Sheet to affect the document it must be combined with it; this can be done in four ways described by Wium Lie and Bos [1999] on their book “Cascading Style Sheets, designing for the Web”.
Ways to use CSS:
•Applying it to the whole document scope by using the element style of mark-up languages.
•Applying it only to an individual element by using the attribute style mark-up languages.
•Linking an external Style Sheet to the document by using element link.
•Import a Style Sheet by using notationCSS @import.
An important issue that must not be forgotten is that there might be a conflict on publication guidelines between the publisher and the reader (if the later has some interface restrictions for example). Moreover, using modular style sheets is bound to generate conflicts. The way to solve these issues is defined in CSS1 by a scheme for assigning priority to each style element; the style with the highest priority always wins [Walsh, 1996-7].
4) DOM
As defined in Wikipedia, “Document Object Model is a description of how an HTML or XML document is represented in a tree structure.” It was first created in 1998 and it has been updated on 2005 by W3C. It provides a structure that facilitates access to the elements of web documents such as HTML or XML by scripting languages with object oriented features (e.g., JavaScript). DOM is created to ensure there is a common standard for animated web pages that are created with technologies that combine HTML, style sheets and scripting since they are various options in the market. [8] According to W3C, DOM is both a platform and a language that can be seen as an interface that allow programs and scripts to access in a dynamic way content, structure, and style of documents and update it.
The document can be processed further on and these results can be fed into the page. The tree-based implementation that is created by DOM requires that the entire content of a document is parsed and stored in memory. According to wikipedia 'This is why DOM is best used for applications where the document elements have to be accessed and manipulated in an unpredictable sequence and repeatedly.' DOM specifications according to the W3C are divided into levels which are composed by modules. Applications must implement all requirements of a level, and the ones below it, to fully support it as defined by the W3C levels.
DOM's layers are the following ones:
0-It is not a formal specification published by the W3C but a shorthand that refers to what existed before the standardization process. The application supports an intermediate DOM,
1-Navigation of DOM (HTML and XML) document (tree structure) and content manipulation (includes adding elements). HTML-specific elements are included as well.
2-XML namespace support, filtered views and events.
3-Consists of 6 different specifications. DOM Level 3: Core; Load and Save; XPath; Views and Formatting; Requirements; and 3 Validation, which further enhances the DOM.
5) REST
According to the definition given in whatis.com, Representational State Transfer (REST) is an approach for getting information content from a Web site by reading a designated Web page that contains an XML file that describes and includes the desired content. It was created in 2000. As its own author (Fielding, 2000) states, it is an "architectural style" which exists with web technologies such as HTTP and XML. The goal behind REST is to create an image of how a Web application which is well defined should behave.
Fielding states that REST is a definition of architecture constraints to improve network communications in terms of speed while “maximizing the independence and scalability of component implementations”. He claims that this goal is achieved by placing constraints on connector semantics rather than on component ones. “REST enables the caching and reuse of interactions, dynamic substitutability of components, and processing of actions by intermediaries, thereby meeting the needs of an Internet-scale distributed hypermedia system.” People that favour REST claim that both scalability and growth of the Web is due to these key design principles [9].
Design principles behind REST are the following:
•Division into resources of application (state and functionality) re divided into resources
•Every resource is uniquely addressable using a universal syntax for use in hypermedia links
•Uniform interface for transfer state between client and resource shared by all consisting of a constrained set of : well defined operations and of content types that can support code-on-demand
•A protocol that is client/server, stateless, cacheable and layered.
Its functionality is similar to that of SOAP, in favor we can say that it is easier to use since it requires less programming although against we can say that it has less capability since it has less interaction between server and client. It requires that SOAP be used, which allows a greater amount of program interaction between client and server [whatis.com].
6) XML
XML is a very powerful system for managing information. It is a grammatical system for constructing custom markup languages which can be used to describe any type of data: mathematical, business, chemical, etc [Castro, 2001]. The first draft was published on 1996 and it did not become a W3C recommendation until 1998 [wikipedia] it is a subset from SGML. According to W3C XML has been created to facilitate implementation and interoperability within SGML and HTML. XML lets everyone create their own tags which are hidden labels that annotate the Web so that scripts, or programs, can use them in advanced ways [Berners-Lee et al, 2001].
XML is based on the same technology as HTML although it is designed to better handle information management [Castro, 2001]. It is different from HTML according to Wikipedia HTML has an 'inflexible single-purpose vocabulary of elements and attributes that, in general, cannot be repurposed.' XML and HTML are very similar looking, both with tags, attributes and values, however XML allows you to design your own markup languages [Castro, 2001] it is also easier to write software to access document’s information because data structures are represented in a formal and easy way [wikipedia].
XML provides a way to describe and apply a tree-based structure to information. This information is represented as text with markup to indicate how it is separated into a hierarchy. XML’s fundamental unit is the character which is combined in an XML document, which in turn is made of one or more entities, each of which is typically stored in a text file. XML files do not carry information about how to display the data on the web. This is why it needs CSS or XSL [wikipedia]; otherwise it would be seen through web browsers as simple text with no layout whatsoever.
In addition to being well-formed, an XML document needs to comply with a particular schema which is a description of a type of XML document in order for the browser to display its layout and style. A sentence should be included at the beginning of each XML document that references either the CSS or XSL style sheets [wikipedia].
•CSS include style sheet: <?xml-stylesheet type="text/css" href="myStyleSheet.css"?>
•XSL specify client-side XSLT: <?xml-stylesheet type="text/xsl" href="myTransform.xslt"?>
All the end-user sees is displayable data and does not know what goes behind the scenes. XML has three basic building blocks used for programming.
Each XML document has one single root element which encloses the rest of the elements and is the parent element to all the other elements. Elements may contain other elements which are called nested elements [wikipedia]. All elements must be properly nested, i.e. must have an opening tag (<>) and closing tag (</>) only comments and processing instructions can be placed outside the root element. Entity references to create specific signs must be declared, except the default five special symbols: ampersand, less and greater signs, double and single quotation marks [Castro, 2001].
7) Mashup
According to wikipedia, mashup is a web application hybrid, a web based application which integrates content from many sources in a unique place by picking bits and pieces from different places. It is originally a Jamaican term which means to break something which then evolved to mixes in music. Mashups offer a challenge for service creation to SW engineers. These services are created by mixing existing applications rather than by an overall design. This means that the development methodology is more of a bottom-up as than a top-down like it has been done traditionally. In order to design new services, programmers analyze what are the current functionalities of existing applications and think of ways in which they can combine them to create new ones. Technologically, the concept is similar to the Enterprise Application Integration SW and it faces the same issues: data integration, connectivity, communication, compatibility, design, etc. There is also a major challenge associated to the service maintenance due to the existing SW obsoleteness risk.
Mashups are driven by the Web’s own culture; barriers to re-use and mix are extremely low since the SW y open source plus there is not much intellectual property protection in place either. The own browser's "View Source" option makes it possible for users/programmers to copy other pages, RSS is designed to empower the user to mix the content he/she wants creating a new one [O’Reilly, 2005]. Google maps can be seen as a good example of Web 2.0 Mashup service mixing places information with maps. Consequences of mashup services are a lack of a clear business model associated to the new service
|
http://developer.nokia.com/community/wiki/Technology_behind_Web_2.0
|
CC-MAIN-2014-10
|
refinedweb
| 2,993
| 50.06
|
I'm implementing tests on my Android app and I want to do unit tests on a model. The problem is that I do not have setters as the model is created with Realm or by parsing a CSV file (witch univocity csv parser).
So, how could I create a mocked object with valid values? I have something like that:
public class Content {
private String title;
private String description;
...
}
Use code below in your test class:
Field field = Content.class.getDeclaredField("str"); field.setAccessible(true); field.set(yourObject, "some value");
yourObject is a instance of
Content that you use in your test class.
But you shouldn't fill mock object - you should just define method result for mock object.
|
https://codedump.io/share/gJUQWB4BW1QS/1/mock-model-object-without-setters
|
CC-MAIN-2017-39
|
refinedweb
| 119
| 64
|
[solved] Pseudorandom with Lexical Decision
edited April 2013 in OpenSesame
Hi,
Thank you for this great software !
In a lexical decision experiment, I'd like to create a trial sequence that is random but has the restriction that a word or a nonword should not been shown more than 3 times in immediate succession.
How could I do that (from the lexical decision example script for instance) ?
Best regards,
Boris
Hi Boris,
Welcome to the forum!
Such pseudorandomisation functionality is not (yet) implemented in OpenSesame. Perhaps you could try Mix (only for Windows, unfortunately), a program that allows you to generate trial orders according to a wide range of constraints. The minimal distance restriction you mention will be very easy to apply with this software.
It can be downloaded here:
And the reference is:
Van Casteren, M., & Davis, M. H. (2006). Mix, a program for pseudorandomization. Behavior research methods, 38(4), 584–589.
I hope this helps.
Best wishes,
Lotje
Did you like my answer? Feel free to
Thank you for your answer !
I know Mix and Shuffle (also for linux or mac) but this forces me to use pre-made lists for each subject.
Isn't it possible to do this with a Python inline ?
Best regards,
Boris
Hi Boris,
It's possible to use an inline, but you'll need to build your experiment a bit different from the usual way.
Normally you would fill out a list item with all of your stimulus words and set the list order to random. For pseudorandom options, you'll have to do the randomization yourself. You could still predefine all your stimulus words up front, in a variable or a text document (in a. tsv-like lay-out).
Lets say you did this in the way you prefer and created a list variable containing all the words in the beginning of your experiment. After the inline_script in which you do this, add some more code:
inline_script_1
Add the following to your sequence in an empty list with repeats = trials
Now you can use the variable stimword in OpenSesame items used to present your stimulus like so: [stimword]
Good luck!
Hi Edwin,
Thank you very much for your code but I'm not sure that I understand everything.
The point is that, I have difficulties to see how your inline identify the column defining words and pseudowords (the one where I do not want more than x repetitions)
For instance, for the moment, my stimulus list is the following:
Here the column that should not repeat are columns 3 ("Type") or 4 ("TypeCible"). But I need to have the other columns in my result file...
Best,
Boris
I also tried your code with a simple list ("1" would code for words and "2" for nonwords) like
But when I print stimlist it gives:
Which is not what I was waiting for.
I was waiting for something like: (for no more than 3 repetitions)
And I think that stimlist should be a multi-dimensional array on which I could do the randomization on a particular column...
I found this discussion on this question but I am unfortunately not able to apply it to my problem:
Hi Boris,
I think that Lotje's suggestion to use Mix is the most pragmatic. But since you appear to be quite keen to use Python code, here's another example. The idea is the same as the script that Edwin provided, but it indeed uses a multidimensional array. At the start of the experiment, add an inline_script item with the following code:
This will read in a text file that specifies all the conditions. For this example I assumed that the conditions are as you described in your previous post. The text file should be tab-separated, not contain column headers, and be placed in the file pool. (If you want to do it differently, take a look at numpy.loadtxt().)
Next, you add an inline_script to the start of each trial sequence with the following in the prepare phase:
This will walk through the trial list that was loaded and randomized at the start of the experiment, and store the values from the columns as experimental variables that you can use in sketchpads etc.
Randomizing with constraints is not the easiest thing in the world! You may want to take a look at NumPy, which is great library for numeric stuff:
Cheers,
Sebastiaan
Hi Sebastiaan,
Thank you very much !!
Unfortunately, I tried your code and had the following error
My script is there if it can help:
I also wanted to know what I should write in the "block_loop"
Finally I think that the strategy to shuffle again may probably fail with many items. (I think I experienced that with Eprime)
Ideally I would like to shuffle a first time and then verify the items and when an item is repeated more than 3 times ( 1 1 1 1), switch it with the next other item (2).
For instance
1 1 1 1 2 1 2 2 2 2
would give in a first time (there is still a problem at the end but we loop on the beginning of the table until a solution is found)
1 1 1 2 1 1 2 2 2 2
which would give
2 1 1 2 1 1 2 2 2 1
Best,
Boris
Hi Boris,
I understood you did not want to have the same word appear over two successive times, but I now see you meant the type of word. In this case my script won't work indeed! It assumes the original stimlist is a list containing your stimulus words.
Another suggestion:
inline_script_1 (at start of experiment)
inline_script_2 (at start of trial, in prepare phase)
stimuli.txt
================================
WORKAROUND, DUE TO \n ERROR IN INLINE_SCRIPT:
inline_script_1 (at start of experiment)
stimuli.txt
For some reason, inline_script_2 isn't shown full. Retry: (see above)
EDIT: bleep, same problem. In two pieces, but do put 'em in the same inline!
EDIT #13415313: got it, there is a 'smaller than' sign that looks like the start of some html-bit. Just replace #SMALLER THAN SIGN# by <
Now you can use the variables with the names they have in stimuli.txt (in our case: [Target], [Prime], [Type], [TypeCibele] and [CorrectAnswer]).
OpenSesame file:
Good luck!
EDIT: BUG REPORT!
Sebastiaan, when I tried to run above code, OpenSesame crashes because of the use of '\n' in an inline_script. It seems to think '\n' represents a return within the inline_script, instead of a part of the code (win7, 0.27 run from source).
Boris: temporary workaround, see above.
Hi Edwin,
I ran your opensesame script (from the dropbox).
I converted the stimuli.txt file to UTF8
I emptied the "block_loop" object in OS
It runs but:
-it did not respect the constraint of 2 or 3 max successive items
-some items are repeating themselves in the 20 trials... (and consequently some items are missing)
So I added the line in the first inline: (because I did not find where you define the maximum number of repetitions [but I am not sure of this])
exp.set("maxreps", 2)
But this did not change the above problems...
Here is the final script
Hi Sebastiaan,
Finally I found that the problem I had with your script concerned the path (space and/or accentuated characters)
Now it's working nicely.
The only problem remaining is that it crashes with 120 items or more...
Here is the script for 120 items:
And the stimuli:
Hi Boris,
Ah, yes, you are right! A variable that should have been a string turned out to be an integer (seems to be automatically converted by OpenSesame). Therefore the comparison always turned out False (i.e.: '1' == 1 is False indeed).
On the matter of the maximum repetitions: somewhere it got lost (although I can distinctly remember to have written it... spooky!). It's in where it's supposed to be now.
For the repetition of certain words: you're right again! I forgot to include that in the new script. Now it should be fixed.
Finally, concerning the converting to UTF-8: this is because of the accents, right? Didn't quite spot those since just now
Anyhow, the correct OpenSesame script, the stimuli.txt that I used and a sample output file are in the Dropbox ().
Hope it's fixed now!
Hi Edwin,
I tested your code and it works nicely now.
More interesting it's working in "extreme conditions" with 240 items and only 2 repetitions.
So I'll check everything tomorrow but it looks like a problem solved ! (interestingly people from Eprime support never found a proper solution to this problem)
Thank you very very much !
Nice! No problem, glad to help out. Especially if we did better than E-Prime's support
Hi Edwin,
I think that another solution than the dummy column for the "\n" is to do a rstrip
Best,
Hi,
Unfortunately, I was too enthusiastic.
The script is often crashing when running the experiment at the end of the 240 items (for instance after 235).
The problem is if, arriving on item 235, all the words have already been selected for example, then it is looping endlessly.
Here is the script and the stimuli:
Best,
Hi Boris,
Do I understand correctly that all of the single-word repeats have 'run out' for all words? Wouldn't that mean that all of the trials are already run? (basically meaning that you cannot possibly run 240 trials, unles you heighten the variable for the number of repeats for unique stimuli)
EDIT: if you are using the original 20 items posted here, than 240 should be possible indeed. I'll look into it.
Best,
Edwin
Yes
No because there are still some pseudowords to display...
I'm not using the 20 items but 240 different ones
A strategy would be to randomize items and switch problematic items with the next good one (restarting with the beginning of the items if there is a problem at the end of the list) but I don't success in implementing that in python.
Hi Edwin,
I think that I found a partial solution to the problem.
This new script is doing well to randomize my table "stimuli". (I tested it in a Python interpreter and it was working)
So at the end in my result file, I have no "1" or "2" (column "Type") more than 3 times which is good.
But I still the big following problem:
-during the experiment I have quite often more than 4 words following. At the end in my csv file, I notice that my French word VAURIEN is transformed in a "2" (nonword) during the experiment while in the stimuli.txt file it is marked as "1" (word)
Script & Stimuli
Best regards,
Finally I found the solution !
This code should work whatever the size of your stimulus list and whatever the max number of consecutive trials you want (you can adapt the script easily)
Put this inline in the beginning of the script:
and this one at the beginning of your "trial_sequence"
The script and stimuli are here:
I hope this code will be useful to other users !
Hi Boris,
Great that you've found a solution! I like the french commenting, it's always nice to pick up a few more words in a different language.
Good luck with the testing!
Sorry for my French but I'm a lazy English user... (always cost more energy to write/say something in English ) :P
Hi, I find myself in a similar situation that I am finding easier to solve with Sebastiaan's code (it crashes, but I feel like I'm close to it..) and I would prefer not to write a predefined list per subject.
I have a list of possible conditions (24) and 5 columns. To make things easier I've coded all values in numbers (integers). In the last column I have values 0 or 1 like this:
2 2 10 1 1
2 1 10 1 1
2 2 10 1 0
2 1 10 1 0
I want to pseudorandomize the order of conditions according to the last column so that (ideally) if on one trial the condition has a value 1 in the last column, the next trial has to have a value 0, but when I used the shuffle it was taking too much time (now I'm only using a list of 24 possible trials but they will be more) so instead I set number of maximum repetitions=2
I have created a txt file tab delimited with no header.
At the beginning of the experiment I created an inline script with in run phase:
import numpy as np
repeatCheck = 3 # # How many repeats are not allowed
column = 4 # Which column should be checked for repeats
src = 'C:\Users\act\Desktop\stim.txt' # A tab separated text file in the file pool
Load the conditions into a NumPy array
a = np.loadtxt(exp.get_file(src), delimiter='\t', dtype='str')
Go into a 'shuffle loop'
while True:
# Shuffle the array
np.random.shuffle(a)
Store the array as exp.stimlist, so we can access it later on
exp.set("stimlist", a)
if I print a I get a nicely shuffles list. So that works now I just want for each trial to read the list in a sequential manner and use the info in it. In my loop item now empty (right?) I only set number of repetitions of each cycle to 1, inside I have a trial sequence which calls another inline script with all my experiment written. at the beginning in the prepare phase I put:
Get the trial id using the trial_sequence counter, and use that to get the
correct row from the stimlist
trialId = self.get('count_trial_sequence')
trialCond = exp.stimlist[trialId]
Use the columns from the stimlist to set the experimental variables
exp.set('correct_response', trialCond[0])
exp.set('target_pos', trialCond[1])
exp.set('target_letter', trialCond[2])
exp.set('warning_signal', trialCond[3])
exp.set('cue_validity', trialCond[4])
but it crashes with this error
exception message: string index out of range
exception type: IndexError
Traceback (also in debug window):
File "dist\libopensesame\inline_script.py", line 150, in prepare
File "dist\libopensesame\python_workspace.py", line 111, in _exec
File "", line 8, in
IndexError: string index out of range
I think it doesn't correctly creates the object stimlist, I have tried when loading the txt to put object instead of string but it doesn't work. Also, if I try to print stimlist at the end of the first inline script it doesn't work. Instead if I print "a" it works, why?
thank you for your help
Stefania
I know this is a pretty old thread, but if you're still using this forum, Boris, I have a question for you! I very much like your script and think I will use it (thanks for that!), but I wanted to clarify a potential problem I see.
My question is in regard to this part of your script:
Doesn't looking for a solution from the beginning of the table potentially lead to "undoing" the previous work? For example, if you had the following sequence of item types:
2 2 2 1 2 2 1 1 2 1 1 2 2 1 1 1 2 2 2 2
and on i = 16 (the 17th item), you find that the following three items are of the same type, but you're at the end of your list, so you loop back around to find an item to "swap" and the first available one you come by is at k = 3 (the fourth item). By swapping the fourth and 17th items, you've now created a run of 5 "2's" at the start of your list.
Perhaps I'm missing something?
Thanks in advance!
-Jonathan
Ohhhh wait I get it. You continue to cycle through the list until you do a whole pass without finding any unwanted repetitions (so repet remains set to 0 and BigSolution can be set to 1).
Sorry for the unnecessary question! Hopefully it will help someone who misunderstands as I did
|
https://forum.cogsci.nl/index.php?p=/discussion/310/solved-pseudorandom-with-lexical-decision
|
CC-MAIN-2021-10
|
refinedweb
| 2,711
| 69.21
|
While high frequency traders need access to update by update market data, medium frequency algorithmic traders can usually get by with the less granular sort. Oftentimes, we spend a lot of money on data feeds only to realize we are downsampling the frequency for the purposes of historical analysis. While libraries like Pandas can give us access to daily historical data, getting intraday stock prices can be a bit trickier. That’s why we wrote this script that lets you download up to 15 trading days worth of intraday stock data from Google Finance (not real-time, 30 minutes delayed, but its great for quick and dirty backtesting).
Make sure you have NumPy and Pandas installed first, you can do this using pip:
pip install numpy pandas
Then copy and run the following script:
import pandas as pd import numpy as np import urllib2 import datetime as dt import matplotlib.pyplot as plt def get_google_data(symbol, period, window): url_root = '' url_root += str(period) + '&p=' + str(window) url_root += 'd&f=d,o,h,l,c,v&df=cpct&q=' + symbol response = urllib2.urlopen(url_root) data = response.read().split('\n') #actual data starts at index = 7 #first line contains full timestamp, #every other line is offset of period from timestamp parsed_data = [] anchor_stamp = '' end = len(data) for i in range(7, end): cdata = data[i].split(',') if 'a' in cdata[0]: #first one record anchor timestamp anchor_stamp = cdata[0].replace('a', '') cts = int(anchor_stamp) else: try: coffset = int(cdata[0]) cts = int(anchor_stamp) + (coffset * period) parsed_data.append((dt.datetime.fromtimestamp(float(cts)), float(cdata[1]), float(cdata[2]), float(cdata[3]), float(cdata[4]), float(cdata[5]))) except: pass # for time zone offsets thrown into data df = pd.DataFrame(parsed_data) df.columns = ['ts', 'o', 'h', 'l', 'c', 'v'] df.index = df.ts del df['ts'] return df
Now we can use get_google_data(symbol, period_in_seconds, number_of_days). For example, suppose we want 5 minute intraday data for SPY for the last 2 weeks (10 trading days):
spy = get_google_data(‘SPY’, 300, 10)
Which returns a dataframe with OHLC data for each 5 minute bar, plus it returns volume (interestingly, today’s volume returns 0, but by the next day and its updated)
An easy extension of this functionality is to look at multiple intraday stock prices. Suppose we want to visualize the correlation structure of the Nasdaq 100 components. We could use the get_google_data function in a loop like so:
from pandas_datareader import data as web import datetime as dt data = pd.read_csv("") start = dt.datetime(2016, 3, 7) end = dt.datetime(2017, 3, 7) volume = [] closes = [] good_tickers = [] for ticker in data['ticker'].values.tolist(): print ticker, try: vdata = get_google_data(ticker, 60, 10) cdata = vdata[['c']] closes.append(cdata) vdata = vdata[['v']] volume.append(vdata) good_tickers.append(ticker) except: print "x", closes = pd.concat(closes, axis = 1) closes.columns = good_tickers diffs = np.log(closes).diff().dropna(axis = 0, how = "all").dropna(axis = 1, how = "any") diffs.head()
The diffs dataframe contains the log differences for the Nasdaq 100 components we could download. Now we can visualize the correlation for these symbols using a Jupyter Notebook and slicematrixIO-python.
First let’s create an Isomap which will learn the underlying structure of the market and embed a network graph in 2 dimensions so we can visualize the complex relationships between individual stock symbols:
from slicematrixIO import SliceMatrix sm = SliceMatrix(api_key, region = "us-west-1") iso = sm.Isomap(dataset = diffs, D = 2, K = 6)
Now we can visualize the resulting network using the notebook module:
from slicematrixIO.notebook import GraphEngine viz = GraphEngine(sm) viz.init_style() viz.init_data() viz.drawNetworkGraph(iso, height = 500, min_node_size = 10, charge = -250, color_map = "Heat", graph_style = "dark", label_color = "rgba(255, 255, 255, 0.8)")
Which will produce the following interactive graph in the notebook:
For a full working example of this visualization check out the notebook:
Manifold Learning and Visualization: Nasdaq 100
Interested in Pairs Trading?
Check out SliceMatrix: a unique tool for visualizing the stock market, including views of filtered correlation networks and minimum spanning trees
Want to learn how to mine social data sources like Google Trends, StockTwits, Twitter, and Estimize? Make sure to download our book Intro to Social Data for Traders
Categories: Python, Quantitative Trading
This is sweet.
Finally, I’ve downloaded and installed the necessary modules and wrote the code as presented, with some adjustment to the urllib2.urlopen changed to urllib.request.urlopen as I am using Python 3.4 and I got this error when I entered spy = get_google_data(‘SPY’, 300, 10):
Traceback (most recent call last):
File “”, line 1, in
spy = get_google_data(‘SPY’, 300, 10)
File “”, line 6, in get_google_data
data = response.read().split(‘\n’)
TypeError: Type str doesn’t support the buffer API
What is wrong?
not sure yet right now, we use 2.7, what’s changed in urllib2 in 3.4? looks like response is already a string from that error, maybe the .read() has become redundant? have the function return the response var and see what it looks like
First, thanks mktstk for the script.
Now, to make it work with python 3, it’s necessary to make some modifications:
import urllib
python 3 unified urllib2 and 1 into a single library
response = urllib.request.urlopen(url_root)
urlopen is now under ‘request’ sub library
data = response.read().split(b’\n’)
In python 3 you need to specify a ‘b’ before any input if you’re using ‘bytes’ data, so:
for i in range(7, len(data)-1):
cdata = data[i].split(b’,’)
if b’a’ in cdata[0]:
#first one record anchor timestamp
anchor_stamp = cdata[0].replace(b’a’, b”)
cts = int(anchor_stamp)
else:
coffset = int(cdata[0])
cts = int(anchor_stamp) + (coffset * period)
parsed_data.append((dt.datetime.fromtimestamp(float(cts)), float(cdata[1]), float(cdata[2]), float(cdata[3]), float(cdata[4]), float(cdata[5])))
Now it works on Python 3!
Anyway, thanks again for the script!
appreciate the port to python3!
Thanks for the script! I’ve added the option of specifying the market and made some changes in the backend to make it Python3 compatible. Find it here:
LikeLiked by 2 people
really cool, thnx for the share!
|
https://mktstk.com/2014/12/31/how-to-get-free-intraday-stock-data-with-python/
|
CC-MAIN-2018-17
|
refinedweb
| 1,030
| 55.74
|
On Fri, 2010-12-24 at 15:34 -0800, Kevin D. Kissell wrote:
>.
Yes I have tried with various combinations of tcs and vpes. with
maxvpes=1 I can boot with a max of 4 TCS ( VPE0 has 4 TCs) .
However setting maxpes=2 and maxtcs=2 hangs pretty early.
Clock rate set to 600000000
console [ttyS0] enabled
Calibrating delay loop... 398.33 BogoMIPS (lpj=796672)
pid_max: default: 32768 minimum: 301
Mount-cache hash table entries: 512
Limit of 2 VPEs set
Limit of 2 TCs set
TLB of 64 entry pairs shared by 2 VPEs
VPE 0: TC 0, VPE 1: TC 1
IPI buffer pool of 32 buffers
CPU revision is: 00019548 ((null))
TC 1 going on-line as CPU 1
Brought up 2 CPUs
One strange observation is with maxtcs=3 and maxvpes=2 kernel boots all
the way.
Again with maxtcs=5 and maxvpes=2 it hangs after switching to MIPS
clocksource.
I strongly suspect some issue with locking. I will dig the code early
next week.
>
> Oh, yes, and Merry Christmas one and all!
Thank you ! ..
Everybody Happy Christmas.
>
> Regards,
>
> Kevin K.
>
> On 12/24/10 8:02 AM, Anoop P A wrote:
> > On Fri, 2010-12-24 at 06:53 -0800, Kevin D. Kissell wrote:
> >> Excellent! Now, does the attached patch (relative to 2.6.37.11) also
> >> fix things, while preserving the other fixes and performance enhancements?
> >>
> > I have tested that patch with 2.6.37 branch it well passes calibration
> > loop but hangs after switching to mips closource
> >
> > TC 6 going on-line as CPU 6
> > Brought up 7 CPUs
> > bio: create slab<bio-0> at 0
> > SCSI subsystem initialized
> > Switching to clocksource MIPS
> >
> > I Presume this is a different issue as restoring older file didn't help
> > much to get rid of this hang.
> >
> > diff --git a/arch/mips/include/asm/stackframe.h
> > b/arch/mips/include/asm/stackframe.h
> > index 58730c5..7fc9f10 100644
> > --- a/arch/mips/include/asm/stackframe.h
> > +++ b/arch/mips/include/asm/stackframe.h
> > @@ -195,9 +195,9 @@
> > * to cover the pipeline delay.
> > */
> > .set mips32
> > - mfc0 v1, CP0_TCSTATUS
> > + mfc0 v0, CP0_TCSTATUS
> > .set mips0
> > - LONG_S v1, PT_TCSTATUS(sp)
> > + LONG_S v0, PT_TCSTATUS(sp)
> > #endif /* CONFIG_MIPS_MT_SMTC */
> > LONG_S $4, PT_R4(sp)
> > LONG_S $5, PT_R5(sp)
> >
> >
> >> /K.
> >>
> >> On 12/24/10 6:39 AM, Anoop P A wrote:
> >>> Hi Kevin, Stuart ,
> >>>
> >>> Woohooo You guys spotted !.
> >>>
> >>>;a=commit;h=d5ec6e3c seems to be
> >>> the culprit
> >>>
> >>> Once I restored previous version of stackframe.h 2.6.33-stable started
> >>> booting !.
> >>>
> >>> Thanks,
> >>> Anoop
> >>>
> >>> On Fri, 2010-12-24 at 04:32 -0800, Kevin D. Kissell wrote:
> >>>> Thank you, Stuart! I've spotted some definite breakage to SMTC between
> >>>> those versions. In arch/mips/include/asm/stackframe.h, someone moved
> >>>> the store of the Status register value in SAVE_SOME (line 169 or 204,
> >>>> depending on the version) from two instructions after the mfc0 to a
> >>>> point after the #ifdef for SMTC, presumably to get better pipelining of
> >>>> the register access. Unfortunately, the v1 register is also used in the
> >>>> SMTC-specific fragment to save TCStatus, so the Status value gets
> >>>> clobbered before it gets stored. This will eventually result in the
> >>>> Status register getting a TCStatus value, which has some bits on common,
> >>>> but isn't identical and sooner or later Bad Things will happen.
> >>>>
> >>>> I'm a little surprised this wasn't caught by visual inspection of the
> >>>> patch.
> >>>>
> >>>> Possible solutions would include reverting the store of the CP0_STATUS
> >>>> value to the block above the #ifdef, or, to retain whatever performance
> >>>> advantage was obtained by moving the store downward, to use v0/$2
> >>>> instead of v1/$3, as the staging register for the TCStatus value. I'd
> >>>> lean toward the second option, but I'm not in a position to test and
> >>>> submit a patch just now.
> >>>>
> >>>> Regards,
> >>>>
> >>>> Kevin K.
> >>>>
> >>>> On 12/23/10 1:09 PM, STUART VENTERS wrote:
> >>>>> Kevin,
> >>>>>
> >>>>> I'm not sure if it's useful,
> >>>>> but finally I got the time to look at the two kernel versions
> >>>>> Anoop pointed out.
> >>>>> works 2.6.32-stable with patch 804
> >>>>> works_not 2.6.33-stable
> >>>>>
> >>>>> greping for files with CONFIG_MIPS_MT_SMTC
> >>>>> and looking for timer interrupt related stuff found the following
> >>>>> differences:
> >>>>>
> >>>>>
> >>>>> arch/mips/include/asm/irq.h
> >>>>> arch/mips/kernel/irq.c
> >>>>> do_IRQ
> >>>>>
> >>>>> arch/mips/include/asm/stackframe.h
> >>>>> SAVE_SOME SAVE_TEMP get/set_saved_sp
> >>>>>
> >>>>> arch/mips/include/asm/time.h
> >>>>> clocksource_set_clock
> >>>>>
> >>>>> arch/mips/kernel/process.c
> >>>>> cpu_idle
> >>>>>
> >>>>> arch/mips/kernel/smtc.c
> >>>>> __irq_entry
> >>>>> ipi_decode
> >>>>> SMTC_CLOCK_TICK
> >>>>>
> >>>>>
> >>>>> Enclosed are the two subsets of files for a more expert look.
> >>>>>
> >>>>> I'll try to look in more detail after Christmas.
> >>>>>
> >>>>>
> >>>>> Cheers,
> >>>>>
> >>>>> Stuart
> >>>>>
> >>>>>
> >>>>>
> >>>>>
> >
>
|
https://www.linux-mips.org/archives/linux-mips/2010-12/msg00140.html
|
CC-MAIN-2017-30
|
refinedweb
| 766
| 65.83
|
go to bug id or search bugs for
Description:
------------
Unable to connect to IPv6 addresses or hostnames pointing to an IPv6 address, even though IPv6 is properly configured.
PHP has been configured with --enable-ipv6 option and phpinfo shows that it is indeed enabled.
I checked with telnet utility that these hosts respond and with that they did.
Reproduce code:
---------------
fsockopen("[::1]",80);
echo "--\n";
fsockopen("[fe80:1:1::1]",80);
echo "--\n";
fsockopen("fe80:1:1::1",80);
echo "--\n";
fsockopen("ipv6.host.name",80);
Expected result:
----------------
--
--
--
Actual result:
--------------
Warning: fsockopen(): php_network_getaddresses: gethostbyname failed
Warning: fsockopen(): unable to connect to [::1]:80 (Unknown error)
--
Warning: fsockopen(): php_network_getaddresses: gethostbyname failed
Warning: fsockopen(): unable to connect to [fe80:1:1::1]:80 (Unknown error)
--
Warning: fsockopen(): unable to connect to fe80:1:1::1:80 (Operation timed out)
--
Warning: fsockopen(): php_network_getaddresses: gethostbyname failed
Warning: fsockopen(): unable to connect to ipv6.host.name:80 (Unknown error)
Add a Patch
Add a Pull Request
Do any of these work?
fsockopen('tcp://::1', 80);
fsockopen('tcp://[::1]', 80);
stream_socket_client('tcp://[::1]:80');
Warning: fsockopen(): unable to connect to tcp://::1:80 (Operation timed out) in /dev/php5-v6/test.php on line 2
Warning: fsockopen(): php_network_getaddresses: gethostbyname failed in /dev/php5-v6/test.php on line 3
Warning: fsockopen(): unable to connect to tcp://[::1]:80 (Unknown error) in /dev/php5-v6/test.php on line 3
Warning: stream_socket_client(): php_network_getaddresses: gethostbyname failed in /dev/php5-v6/test.php on line 4
Warning: stream_socket_client(): unable to connect to tcp://[::1]:80 (Unknown error) in /dev/php5-v6/test.php on line 4
To cut the above in short: no, none of those work.
Check your configure output and config.log for stuff related to IPv6; it looks like PHP isn't actually using IPv6 at all.
(gethostbyname is IPv4; PHP would use getaddrinfo for IPv6)
Configure command used:
./configure --disable-all --enable-ipv6 \ --with-apxs2=/path/to/apxs2
grep "IPv6" config.log
configure:16103: checking for IPv6 support
configure:17764: checking whether to enable IPv6 support
phpinfo:
IPv6 Support => enabled
I don't see much more that I could have done in order to enable the IPv6 support.
Maybe the --disable-all statement causes this problem?
grep HAVE_GETADDRINFO main/php_config.h
It was:
/* #undef HAVE_GETADDRINFO */
After I added
#define HAVE_GETADDRINFO 1
and removed
#define HAVE_GETHOSTBYNAME2 1
Everything worked just fine with those modifications, so after all it is a bug in the configure script.
Scratch that, it'll definately show undefined, the question is why. Can you just post your config.log file somewhere? Or email it to me?
There's not much information about this issue, at least I couldn't find. And the code in configure.in that checks for getaddrinfo seems more or less like glue, but there's propably a reason for it to be that way :)
Please try manually compiling this (slightly altered code from configure.in), running it, and pasting the output here in this bug report; thanks!
1/ Copy the code into v6test.c
2/ cc -o v6test v6test.c
3/ ./v6test
#include <netdb.h>
#include <sys/types.h>
int main(void) {
struct addrinfo *ai, *pai, hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
if (getaddrinfo("127.0.0.1", NULL, &hints, &ai) < 0) {
printf("FAIL-1\n");
exit(1);
}
if (ai == NULL) {
printf("FAIL-2\n");
exit(1);
}
pai = ai;
while (pai) {
if (pai->ai_family != AF_INET) {
/* 127.0.0.1/NUMERICHOST should only resolve ONE way */
printf("FAIL-3\n");
exit(1);
}
if (pai->ai_addr->sa_family != AF_INET) {
/* 127.0.0.1/NUMERICHOST should only resolve ONE way */
printf("FAIL-4\n");
exit(1);
}
pai = pai->ai_next;
}
freeaddrinfo(ai);
printf("OK!\n");
exit(0);
}
I recall the bug that prompted the extended check for ai_family and sa_family (though not the bug# off hand). It was also in BSD (I want to say it was also FreeBSD4).
Enabling getaddrinfo when this behavior was present caused intermittent segfaults in the reporters build, I'll track down that original bug report, it had some detailed comments.
wez:
I had to add stdlib.h and sys/sockets.h headers to compile it because NULL is defined in stdlib.h (weird) and constant AF_INET in sys/socket.h.
After those modifications output was "OK!" (as expected).
<sys/sockets.h> or <sys/socket.h> ? (I'd expect the latter to be correct)
It sounds like we need to add that header to our configure check to make it work (and also make IPV6 depend on its presence)
Sorry, my typo. sys/socket.h is indeed the correct one.
On FreeBSD it works, but will it break on some other OS(s)?
Please try using this CVS snapshot:
For Windows:
Please test the next unstable (5.1/HEAD) snapshot to see if things work out ok there; we can then backport the fix.
Current problem:
configure:16413: checking for getaddrinfo
configure:16425: gcc -o conftest -g -O2 conftest.c -lm 1>&5
configure:16471: gcc -o conftest -g -O2 conftest.c -lm 1>&5
configure: In function `main':
configure:16444: `NULL' undeclared (first use in this function)
configure:16444: (Each undeclared identifier is reported only once
configure:16444: for each function it appears in.)
configure: failed program was:
#line 16431 "configure"
My suggestion to fix this is:
--- configure.in.old Fri Sep 17 17:30:10 2004
+++ configure.in Fri Sep 17 18:58:02 2004
@@ -569,6 +569,9 @@
AC_TRY_RUN([
#include <netdb.h>
#include <sys/types.h>
+#ifndef NULL
+# define NULL (void *)0
+#endif
#ifndef AF_INET
# include <sys/socket.h>
#endif
Which will fix the problem at least on those machines that I've tested.
I'm just curious that has this issue been completely forgotten or abandoned?
This bug has been fixed in CVS.
Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at.
Thank you for the report, and for helping us make PHP better.
Not forgotten, just got busy.
Fixed now in all 3 branches, will show up in the next bunch of snapshots.
|
https://bugs.php.net/bug.php?id=30057
|
CC-MAIN-2016-50
|
refinedweb
| 1,017
| 58.69
|
Read a block of data.
Reads a block of data with a size determined by the smaller between parameter n and the number of available characters in the stream before the end of its buffer.
Parameters.
Return Value.
The function returns an integer value of type streamsize representing the number of characters successfully read.
Example.
// read a file with readsome.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int length;
char block [100];
ifstream is;
is.open ("test.txt", ios::binary );
length = 0;
while (is.good())
{
length += is.readsome (block,100);
cout.write (block,100);
}
is.close();
cout << "\nFile was " << length << " characters long";
return 0;
}
Basic template member declaration ( basic_istream<charT,traits> ):
See also.
read, get
istream class
|
http://www.kev.pulo.com.au/pp/RESOURCES/cplusplus/ref/iostream/istream/readsome.html
|
CC-MAIN-2018-05
|
refinedweb
| 119
| 61.53
|
On Wed, 18 Mar 2009 20:08:49 +0200 Boaz Harrosh <bharrosh@panasas.com> wrote:> implementation of directory and inode operations.> > * A directory is treated as a file, and essentially contains a list> of <file name, inode #> pairs for files that are found in that> directory. The object IDs correspond to the files' inode numbers> and are allocated using a 64bit incrementing global counter.> * Each file's control block (AKA on-disk inode) is stored in its> object's attributes. This applies to both regular files and other> types (directories, device files, symlinks, etc.).> >> ...>> +static inline unsigned long dir_pages(struct inode *inode)> +{> + return (inode->i_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;> +}Do we need i_size_read() here? Probably not if it's always calledunder i_mutex. Needs checking and commenting please.> +static unsigned exofs_last_byte(struct inode *inode, unsigned long page_nr)> +{> + unsigned last_byte = inode->i_size;> +> + last_byte -= page_nr << PAGE_CACHE_SHIFT;hm. Strange to left-shift an unsigned long and then copy it to asmaller type.Are the types here appropriately chosen?> + if (last_byte > PAGE_CACHE_SIZE)> + last_byte = PAGE_CACHE_SIZE;> + return last_byte;> +}> +> +static int exofs_commit_chunk(struct page *page, loff_t pos, unsigned len)>> ...>This all looks vaguely familiar :)
|
http://lkml.org/lkml/2009/3/31/90
|
CC-MAIN-2014-52
|
refinedweb
| 185
| 50.73
|
Hi Bert,
rhuijben_at_apache.org writes:
> Author: rhuijben
> Date: Mon Jul 26 14:24:43 2010
> New Revision: 979303
>
> URL:
> Log:
> Add a simple property verifyer to the upgrade tests to test if the upgrade
> code correctly handles property upgrades. This makes issue #2530 visible on
> the current test data.
>
> * subversion/tests/cmdline/upgrade_tests.py
> (simple_property_verify): New helper function.
> (do_x3_upgrade): Verify properties before and after revert ti
> show handling of revert properties.
>
> Modified:
> subversion/trunk/subversion/tests/cmdline/upgrade_tests.py
I'm reviewing this patch on your request. Hope you find it useful.
> + # Shows all items in dict1 that are not also in dict2
Um, Python has docstrings just for this:
def diff_props(...):
"""You docstring here"""
> + def diff_props(dict1, dict2, name, match):
> +
> + equal = True;
> + for key in dict1:
> + node = dict1[key]
> + node2 = dict2.get(key, None)
> + if node2:
> + for prop in node:
> + v1 = node[prop]
> + v2 = node2.get(prop, None)
> +
> + if not v2:
> + print('\'%s\' property on \'%s\' not found in %s' %
> + (prop, key, name))
> + equal = False
> + if match and v1 != v2:
> + print('Expected \'%s\' on \'%s\' to be \'%s\', but found \'%s\'' %
> + (prop, key, v1, v2))
> + equal = False
> + else:
> + print('\'%s\': %s not found in %s' % (key, dict1[key], name))
> + equal = False
> +
> + return equal
Here's a cleaner version of the same thing (WARNING: Untested; I might
have made some silly mistakes)
def diff_props(dict1, dict2, name, match):
equal = True
for (key, value1) in dict1.iteritems():
if dict2.has_key(key):
value2 = dict2[key]
# Try to match props in value1 and value2
for prop in value1:
if not value2.contains(prop):
print("'%s' property on '%s' not found in %s" % (prop, key, name))
elif match and (value1[prop] != value2[prop]):
print("Expected '%s' on '%s' to be '%s', but found '%s'" %
(prop, key, value1[prop], value2[prop]))
print("'%s' property on '%s' not found in %s" % (prop, key, name))
equal = False
else:
print("'%s': %s not found in %s" % (key, value1, name))
equal = False
return equal
> + exit_code, output, errput = svntest.main.run_svn(None, 'proplist', '-R',
> + '-v', dir_path)
If you're not using some/ all of them, you can just replace them with
an '_' like to tell Python that you don't care about them:
_, output, _ = function_that_returns_a_3_tuple()
> + for i in output:
Poor variable name. I'd choose something like `for line in
output`. Python should read like English :)
> + if i.startswith('Properties on '):
> + target = i[15+len(dir_path)+1:-3].replace(os.path.sep, '/')
`15+len(dir_path)+1`? This can easily be written more nicely with a
few intermediate variables.
> + elif not i.startswith(' '):
> + name = i.strip()
> + else:
> + v = actual_props.get(target, {})
> + v[name] = i.strip()
> + actual_props[target] = v
Can't you switch these two conditions? The main message you're tying
to convey is special handling for the case i.startswith(' ').
> + v1 = diff_props(expected_props, actual_props, 'actual', True)
> + v2 = diff_props(actual_props, expected_props, 'expected', False)
> +
> + print('Actual properties: %s' % actual_props)
> + raise svntest.Failure("Properties unequal")
Instead of printing what's unequal in separate lines immediately, I'd
actually stuff them into a list and print them neatly in the end-
it'll be easier to read when you get lots of errors, but I wouldn't
bother otherwise.
These keys weren't in dict2: <keyx> ...
These properties weren't in the dict2: <keyx>:<propx> ...
These properties were in both dictionaries, but their values didn't
match: <keyx>:<propx>:<valuex> ...
-- Ram
Received on 2010-07-26 18:50:11 CEST
This is an archived mail posted to the Subversion Dev
mailing list.
|
http://svn.haxx.se/dev/archive-2010-07/0584.shtml
|
CC-MAIN-2015-48
|
refinedweb
| 581
| 64.81
|
Creating an open speech recognition dataset for (almost) any language
As state of the art algorithms and code are available almost immediately to anyone in the world at the same time, thanks to Arxiv, github and other open source initiatives. GPU deep learning training clusters can be spun up in minutes on AWS. What are companies competitive edge as AI and machine learning is getting more widely adopted in every domain?
The answer is of course data, and in particular cleaned and annotated data. This type of data is either difficult to get a hold of, very expensive or both. Which is why many people are calling data, the new gold.
So for this post I’m going to walk through how to easily create a speech recognition dataset for (almost) any language, bootstrapped. Which for instance can be used to train a Baidu Deep Speech model in Tensorflow for any type of speech recognition task.
For english there are already a bunch of readily available datasets. For instance the LibriSpeech ASR corpus, which is 1000 hours of spoken english (created in similar fashion as described in this post).
Mozilla also has an initiative for crowdsourcing this data to create an open dataset as well
Introduction
We’ll create a dataset for Swedish, but this bootstrap technique can be applied to almost any latin language.
Using free audiobooks, with permissive licences or audiobooks that are in the public domain together with e-books for these books to create our datasets.
The process will include preprocessing of both the audio and the ebook text, aligning the text sentences and the spoken sentences, called forced alignment. We’ll use Aeneas to do the forced aligment which is an awesome python library and command line tool.
The last step will include some manual work to finetune and correct the audiosamples using a very simple web ui. This postprocessing and tuning will also involve transforming our final audio and text output map to the proper training format for the Tensorflow deep speech model.
Downloading and preprocessing audio books
Go to Librivox where there are bunch of audio books in different languages.
26 books in total are available in Swedish. We started out with the book “Göteborgsflickor” and downloaded the full audio book as a zip-file. The Librivox files are divided into chapters and the zip-file contains one .mp3 file per chapter, in this books case one per short story.
The first chapter audio-file needs some editing to better conform to the ebook text. This is done to get better result from the forced alignment. The audio should in theory exactly match the text.
To cut some of the audio from the beginning of the file I use Audacity for Mac which is completely free.
Open the file in Audacity.
Click play and listen to where the actual reading starts, you might want to glimpse at the ebook to see how and where the book starts.
I marked from the place where it started, from around 25 seconds in, and selected everything from that moment to the beginning, and deleted it using backspace for Mac.
To get a better more detailed view of where it starts, use the zoom + button in the toolbar menu.
When you are happy with your Audio editing and it’s identical to the ebook text for that chapter, go export the clip to mp3:
You probably need to download LAME for Mac to export to mp3.
That is it for the Audio part!
Downloading and preprocessing the E-books
To get the free ebook we’ll go to another amazing open source effort, Project Guthenberg, for “Göteborgsflickor”. Download the .txt file.
We need to transform the raw text file to get to the Aeneas text input format described here,
We used NLTK for this, mostly because the NLTK sentence splitter is regex based and no language specific model is needed, and the english one works fairly well for other latin languages.
To load the first chapter of the ebook and split it up into paragraphs and sentences:
# load nltk
from nltk.tokenize import sent_tokenize# load text from 1st chapter
with open('books/18043-0.txt', 'r') as f:
data = f.read()
We examined the ebook, and it contained clearly defined paragraph using 2 newline characters “\n\n” . The Aeneas text input format also makes use of paragraphs, so we decided use the ebook paragraphs as well:
paragraphs = data.split(“\n\n”)
Now brace yourself for some ugly code. Cleaning of some special characters and the actual sentence splitting using NLTK as well as adding the sentences to the paragraph lists:
paragraph_sentence_list = []
for paragraph in paragraphs:
paragraph = paragraph.replace(“\n”, “ “)
paragraph = paragraph.replace(“ — “, “”)
paragraph = re.sub(r’[^a-zA-Z0–9_*.,?!åäöèÅÄÖÈÉçëË]’, ‘ ‘, paragraph)
paragraph_sentence_list.append(sent_tokenize(paragraph))
Meaning we will have a list of lists, which contains around 900 paragraphs, and each paragraph contains all sentences in that paragraph.
Save the list of lists to the proper output format for Aeneas:
text = “”
count = 0
for paragraph in paragraph_sentence_list:
if “ “.join(paragraph).isupper():
with open(“books/18043–0_aeneas_data_”+str(count)+”.txt”, “w”) as fw:
fw.write(text)
text = “”
count += 1
text += “\n”.join(paragraph)
text += “\n\n”
elif “End of the Project Gutenberg EBook” in “ “.join(paragraph):
break
else:
text += “\n”.join(paragraph)
text += “\n\n”
In simple terms, loop through the paragraphs, join all sentences in these with a new line (“\n”) character. Add the 2 new line characters (“\n\n”) for each paragraph, to get an extra new line between the paragraphs.
The chapters in this book was in all uppercase, which is why we check for a sentence with all upper case to save the output to one file for that chapter. In the end we will end up with the same number of text-files as we have audiofiles, one per chapter.
The end result of this will look something like this:
On to the fun part, forced alignment!
Forced alignment using Aeneas
Aeneas can be run from the command line or as a Python module. We decided to use it as module to be able to extend it to any future automation of the task.
Import the Aeneas module and methods.
from aeneas.executetask import ExecuteTask
from aeneas.task import Task
Create the task objects that holds all relevant configurations.
# create Task object
config_string = ”task_language=swe|is_text_type=plain|os_task_file_format=json”
task = Task(config_string=config_string)task.audio_file_path_absolute = “books/18043–0/goteborgsflickor_01_stroemberg_64kb_clean.mp3”task.text_file_path_absolute = “books/18043–0_aeneas_data_1.txt”task.sync_map_file_path_absolute = “books/18043–0_output/syncmap.json”
First create the config string, pretty straight forward, define language, “swe” for Swedish, the type for the input text format is plain or mplain. Finally JSON as our output sync map format.
Next we define the audio file, the text file corresponding to the audio file and what we want our output sync map to be named when its saved, in this case just syncmap.json.
To run it:
# process Task
ExecuteTask(task).execute()# output sync map to file
task.output_sync_map_file()
For this sample/chapter it took less than 1–2 seconds to run, so it should be pretty fast.
Awesome! We should now have a audio/ebook Aeneas syncmap:
Next step means fine-tuning and validating the syncmap.
Validating and fine tuning Aeneas sync maps
There is a very simple web interface created for Aeneas to load the syncmap and the audio file and make it easy to fine tune the sentence end and start time stamps.
Download or clone the finetuneas repository. Open finetuneas.html in Chrome to start the finetuning.
Select your audio file for the first chapter and the outputted syncmap JSON file for the same chapter.
On the right pane, you will see the start timestamp, and a “+” and “-” sign for adjusting the start and end time. Beware that the end time for a audio clip is the next sentence start time which is a bit confusing.
Click the text to play the section of interest. Adjust and finetune the start and end timestamps if necessary. When done, save the finetuned syncmap using the the controls in the left pane.
When the finetuning is done it’s time to do the final post processing to transform the dataset into a simple format which can be used to train the Deep Speech model.
Convert to DeepSpeech training data format
The last step is to convert the data into a format which can be easily used. We used the same format Mozilla uses at. It is also a common practice and format to use CSV referencing media files (text, images and audio) to train machine learning models in general.
Basically a CSV file looking like this:
Each audio-file will contain one sentence, and one row per sentence. There are some other attributes that are optional and added if possible, in this case only gender is known.
Upvotes and downvotes are metrics for whenever people are validating a sentence as a good sample or not.
We’ll use a library called pydub to do some simple slicing of the audio files, create a pandas dataframe and save it to a CSV.
from pydub import AudioSegment
import pandas as pd
import jsonbook = AudioSegment.from_mp3("books/18043-0/goteborgsflickor_01_stroemberg_64kb_clean.mp3")with open("books/18043-0_output/syncmap.json") as f:
syncmap = json.loads(f.read())
Load the audio and the syncmap you created previously.
sentences = []
for fragment in syncmap[‘fragments’]:
if ((float(fragment[‘end’])*1000) — float(fragment[‘begin’])*1000) > 400:
sentences.append({“audio”:book[float(fragment[‘begin’])*1000:float(fragment[‘end’])*1000], “text”:fragment[‘lines’][0]})
Loop through all the segments/fragments/sentences in the syncmap. Do a sanity check that they are more than 400 milliseconds long. Pydub works in milliseconds, and the syncmap defines all beginnings and ends in seconds, which is why we need to multiply everything with a 1000.
A placeholder dataframe is created:
df = pd.DataFrame(columns=[‘filename’,’text’,’up_votes’,’down_votes’,’age’,’gender’,’accent’,’duration’])
Append the sliced pydub audio object and the text for that fragment to an object in an array.
# export audio segment
for idx, sentence in enumerate(sentences):
text = sentence[‘text’].lower()
sentence[‘audio’].export(“books/audio_output/sample-”+str(idx)+”.mp3", format=”mp3")
temp_df = pd.DataFrame([{‘filename’:”sample-”+str(idx)+”.mp3",’text’:text,’up_votes’:0,’down_votes’:0,’age’:0,’gender’:”male”,’accent’:’’,’duration’:’’}], columns=[‘filename’,’text’,’up_votes’,’down_votes’,’age’,’gender’,’accent’,’duration’])
df = df.append(temp_df)
Lowercasing all text, normalizing it. Next we export the saved audio object with a new name.
Save the new audio filename and the text to the temporary Dataframe and append it to the placeholder Dataframe.
Take a look a the Dataframe to make sure it looks sane:
df.head()
Finally save it as a CSV:
df.to_csv(“books/sample.csv”,index=False)
That is it! Of course this is just for one chapter in one book, you will need to iterate for each chapter in each book. We would recommend to try to get to around 150–200 hours of training data at least to get a good model off the ground.
Notebooks for many of the things I’ve gone through in this post are available in the repo below.
Thanks to Norah Klintberg Sakal for helping out on this project.
|
https://medium.com/@klintcho/creating-an-open-speech-recognition-dataset-for-almost-any-language-c532fb2bc0cf
|
CC-MAIN-2020-29
|
refinedweb
| 1,877
| 63.9
|
cus Sassi4,394 Points
Python Basics - Challenge task 1 of 1 I can't get it to work
Challenge Task 1 of 1 I need you to write a function named product. It should take two arguments, you can call them whatever you want, and then multiply them together and return the result.
My suggestion:
def product(num1, num2): result = num1*num2
product(2, 5)
1 Answer
Ted Dunn43,783 Points
You need to use the keyword return in the body of your function in order to complete the exercise.
def product(num1, num2): return num1 * num2
Marcus Sassi4,394 Points
Marcus Sassi4,394 Points
Ted, thank you so much.
|
https://teamtreehouse.com/community/python-basics-challenge-task-1-of-1-i-cant-get-it-to-work
|
CC-MAIN-2021-43
|
refinedweb
| 110
| 62.72
|
When writing code for Sage, use Python for the basic structure and interface. For speed, efficiency, or convenience, you can implement parts of the code using any of the following languages: Cython, C/C++, Fortran 95, GAP, Common Lisp, Singular, and PARI/GP. You can also use all C/C++ libraries included with Sage [SageComponents]. And if you are okay with your code depending on optional Sage packages, you can use Octave, or even Magma, Mathematica, or Maple.
In this chapter, we discuss interfaces between Sage and PARI, GAP and Singular.
Here is a step-by-step guide to adding new PARI functions to Sage. We use the Frobenius form of a matrix as an example. Some heavy lifting for matrices over integers is implemented using the PARI library. To compute the Frobenius form in PARI, the matfrobenius function is used.
There are two ways to interact with the PARI library from Sage. The gp interface uses the gp interpreter. The PARI interface uses direct calls to the PARI C functions—this is the preferred way as it is much faster. Thus this section focuses on using PARI.
We will add a new method to the gen class. This is the abstract representation of all PARI library objects. That means that once we add a method to this class, every PARI object, whether it is a number, polynomial or matrix, will have our new method. So you can do pari(1).matfrobenius(), but since PARI wants to apply matfrobenius to matrices, not numbers, you will receive a PariError in this case.
The gen class is defined in SAGE_ROOT/src/sage/libs/pari/gen.pyx, and this is where we add the method matfrobenius:
def matfrobenius(self, flag=0): r""" M.matfrobenius(flag=0): Return the Frobenius form of the square matrix M. If flag is 1, return only the elementary divisors (a list of polynomials). If flag is 2, return a two-components vector [F,B] where F is the Frobenius form and B is the basis change so that `M=B^{-1} F B`. EXAMPLES:: sage: a = pari('[1,2;3,4]') sage: a.matfrobenius() [0, 2; 1, 5] sage: a.matfrobenius(flag=1) [x^2 - 5*x - 2] sage: a.matfrobenius(2) [[0, 2; 1, 5], [1, -1/3; 0, 1/3]] """ sig_on() return self.new_gen(matfrobenius(self.g, flag, 0))
Note the use of the sig_on() statement.
The matfrobenius call is just a call to the PARI C library function matfrobenius with the appropriate parameters.
The self.new_gen(GEN x) call constructs a new Sage gen object from a given PARI GEN where the PARI GEN is stored as the .g attribute. Apart from this, self.new_gen() calls a closing sig_off() macro and also clears the PARI stack so it is very convenient to use in a return statement as illustrated above. So after self.new_gen(), all PARI GEN‘s which are not converted to Sage gen‘s are gone. There is also self.new_gen_noclear(GEN x) which does the same as self.new_gen(GEN x) except that it does not call sig_off() nor clear the PARI stack.
The information about which function to call and how to call it can be retrieved from the PARI user’s manual (note: Sage includes the development version of PARI, so check that version of the user’s manual). Looking for matfrobenius you can find:
The library syntax is GEN matfrobenius(GEN M, long flag, long v = -1), where v is a variable number.
In case you are familiar with gp, please note that the PARI C function may have a name that is different from the corresponding gp function (for example, see mathnf), so always check the manual.
We can also add a frobenius(flag) method to the matrix_integer class where we call the matfrobenius() method on the PARI object associated to the matrix after doing some sanity checking. Then we convert output from PARI to Sage objects:
def frobenius(self, flag=0, var='x'): """ Return the Frobenius form (rational canonical form) of this matrix. INPUT: - ``flag`` -- 0 (default), 1 or 2 as follows: - ``0`` -- (default) return the Frobenius form of this matrix. - ``1`` -- return only the elementary divisor polynomials, as polynomials in var. - ``2`` -- return a two-components vector [F,B] where F is the Frobenius form and B is the basis change so that `M=B^{-1}FB`. - ``var`` -- a string (default: 'x') ALGORITHM: uses PARI's matfrobenius() EXAMPLES:: sage: A = MatrixSpace(ZZ, 3)(range(9)) sage: A.frobenius(0) [ 0 0 0] [ 1 0 18] [ 0 1 12] sage: A.frobenius(1) [x^3 - 12*x^2 - 18*x] sage: A.frobenius(1, var='y') [y^3 - 12*y^2 - 18*y] """ if not self.is_square(): raise ArithmeticError("frobenius matrix of non-square matrix not defined.") v = self._pari_().matfrobenius(flag) if flag==0: return self.matrix_space()(v.python()) elif flag==1: r = PolynomialRing(self.base_ring(), names=var) retr = [] for f in v: retr.append(eval(str(f).replace("^","**"), {'x':r.gen()}, r.gens_dict())) return retr elif flag==2: F = matrix_space.MatrixSpace(QQ, self.nrows())(v[0].python()) B = matrix_space.MatrixSpace(QQ, self.nrows())(v[1].python()) return F, B
Wrapping a GAP function in Sage is a matter of writing a program in Python that uses the pexpect interface to pipe various commands to GAP and read back the input into Sage. This is sometimes easy, sometimes hard.
For example, suppose we want to make a wrapper for the computation of the Cartan matrix of a simple Lie algebra. The Cartan matrix of \(G_2\) is available in GAP using the commands:
gap> L:= SimpleLieAlgebra( "G", 2, Rationals ); <Lie algebra of dimension 14 over Rationals> gap> R:= RootSystem( L ); <root system of rank 2> gap> CartanMatrix( R );
In Sage, one can access these commands by typing:
sage: L = gap.SimpleLieAlgebra('"G"', 2, 'Rationals'); L Algebra( Rationals, [ v.1, v.2, v.3, v.4, v.5, v.6, v.7, v.8, v.9, v.10, v.11, v.12, v.13, v.14 ] ) sage: R = L.RootSystem(); R <root system of rank 2> sage: R.CartanMatrix() [ [ 2, -1 ], [ -3, 2 ] ]
Note the '"G"' which is evaluated in GAP as the string "G".
The purpose of this section is to use this example to show how one might write a Python/Sage program whose input is, say, ('G',2) and whose output is the matrix above (but as a Sage Matrix—see the code in the directory SAGE_ROOT/src/sage/matrix/ and the corresponding parts of the Sage reference manual).
First, the input must be converted into strings consisting of legal GAP commands. Then the GAP output, which is also a string, must be parsed and converted if possible to a corresponding Sage/Python object.
def cartan_matrix(type, rank): """ Return the Cartan matrix of given Chevalley type and rank. INPUT: type -- a Chevalley letter name, as a string, for a family type of simple Lie algebras rank -- an integer (legal for that type). EXAMPLES: sage: cartan_matrix("A",5) [ 2 -1 0 0 0] [-1 2 -1 0 0] [ 0 -1 2 -1 0] [ 0 0 -1 2 -1] [ 0 0 0 -1 2] sage: cartan_matrix("G",2) [ 2 -1] [-3 2] """ L = gap.SimpleLieAlgebra('"%s"'%type, rank, 'Rationals') R = L.RootSystem() sM = R.CartanMatrix() ans = eval(str(sM)) MS = MatrixSpace(QQ, rank) return MS(ans)
The output ans is a Python list. The last two lines convert that list to an instance of the Sage class Matrix.
Alternatively, one could replace the first line of the above function with this:
L = gap.new('SimpleLieAlgebra("%s", %s, Rationals);'%(type, rank))
Defining “easy” and “hard” is subjective, but here is one definition. Wrapping a GAP function is “easy” if there is already a corresponding class in Python or Sage for the output data type of the GAP function you are trying to wrap. For example, wrapping any GUAVA (GAP’s error-correcting codes package) function is “easy” since error-correcting codes are vector spaces over finite fields and GUAVA functions return one of the following data types:
Sage already has classes for each of these.
A “hard” example is left as an exercise! Here are a few ideas.
The disadvantage of using other programs through interfaces is that there is a certain unavoidable latency (of the order of 10ms) involved in sending input and receiving the result. If you have to call functions in a tight loop this can be unacceptably slow. Calling into a shared library has much lower latency and furthermore avoids having to convert everything into a string in-between. This is why Sage includes a shared library version of the GAP kernel, available as \(libgap\) in Sage. The libgap analogue of the first example in GAP is:
sage: SimpleLieAlgebra = libgap.function_factory('SimpleLieAlgebra') sage: L = SimpleLieAlgebra('G', 2, QQ) sage: R = L.RootSystem(); R <root system of rank 2> sage: R.CartanMatrix() # output is a GAP matrix [ [ 2, -1 ], [ -3, 2 ] ] sage: matrix(R.CartanMatrix()) # convert to Sage matrix [ 2 -1] [-3 2]
Using Singular functions from Sage is not much different conceptually from using GAP functions from Sage. As with GAP, this can range from easy to hard, depending on how much of the data structure of the output of the Singular function is already present in Sage.
First, some terminology. For us, a curve \(X\) over a finite field \(F\) is an equation of the form \(f(x,y) = 0\), where \(f \in F[x,y]\) is a polynomial. It may or may not be singular. A place of degree \(d\) is a Galois orbit of \(d\) points in \(X(E)\), where \(E/F\) is of degree \(d\). For example, a place of degree \(1\) is also a place of degree \(3\), but a place of degree \(2\) is not since no degree \(3\) extension of \(F\) contains a degree \(2\) extension. Places of degree \(1\) are also called \(F\)-rational points.
As an example of the Sage/Singular interface, we will explain how to wrap Singular’s NSplaces, which computes places on a curve over a finite field. (The command closed_points also does this in some cases.) This is “easy” since no new Python classes are needed in Sage to carry this out.
Here is an example on how to use this command in Singular:
A Computer Algebra System for Polynomial Computations / version 3-0-0 0< by: G.-M. Greuel, G. Pfister, H. Schoenemann \ May 2005 FB Mathematik der Universitaet, D-67653 Kaiserslautern \ > LIB "brnoeth.lib"; [...] > ring s=5,(x,y),lp; > poly f=y^2-x^9-x; > list X1=Adj_div(f); Computing affine singular points ... Computing all points at infinity ... Computing affine singular places ... Computing singular places at infinity ... Computing non-singular places at infinity ... Adjunction divisor computed successfully The genus of the curve is 4 > list X2=NSplaces(1,X1); Computing non-singular affine places of degree 1 ... > list X3=extcurve(1,X2); Total number of rational places : 6 > def R=X3[1][5]; > setring R; > POINTS; [1]: [1]: 0 [2]: 1 [3]: 0 [2]: [1]: -2 [2]: 1 [3]: 1 [3]: [1]: -2 [2]: 1 [3]: 1 [4]: [1]: -2 [2]: -1 [3]: 1 [5]: [1]: 2 [2]: -2 [3]: 1 [6]: [1]: 0 [2]: 0 [3]: 1
Here is another way of doing this same calculation in the Sage interface to Singular:
sage: singular.LIB("brnoeth.lib") sage: singular.ring(5,'(x,y)','lp') // characteristic : 5 // number of vars : 2 // block 1 : ordering lp // : names x y // block 2 : ordering C sage: f = singular('y^2-x^9-x') sage: print singular.eval("list X1=Adj_div(%s);"%f.name()) Computing affine singular points ... Computing all points at infinity ... Computing affine singular places ... Computing singular places at infinity ... Computing non-singular places at infinity ... Adjunction divisor computed successfully The genus of the curve is 4 sage: print singular.eval("list X2=NSplaces(1,X1);") Computing non-singular affine places of degree 1 ... sage: print singular.eval("list X3=extcurve(1,X2);") Total number of rational places : 6 sage: singular.eval("def R=X3[1][5];") 'def R=X3[1][5];' sage: singular.eval("setring R;") 'setring R;' sage: L = singular.eval("POINTS;") sage: print L [1]: [1]: 0 [2]: 1 [3]: 0 [2]: [1]: -2 [2]: -1 [3]: 1 ...
From looking at the output, notice that our wrapper function will need to parse the string represented by \(L\) above, so let us write a separate function to do just that. This requires figuring out how to determine where the coordinates of the points are placed in the string \(L\). Python has some very useful string manipulation commands to do just that.
def points_parser(string_points,F): """ This function will parse a string of points of X over a finite field F returned by Singular's NSplaces command into a Python list of points with entries from F. EXAMPLES: sage: F = GF(5) sage: points_parser(L,F) ((0, 1, 0), (3, 4, 1), (0, 0, 1), (2, 3, 1), (3, 1, 1), (2, 2, 1)) """ Pts=[] n=len(L) #print n #start block to compute a pt L1=L while len(L1)>32: idx=L1.index(" ") pt=[] ## start block1 for compute pt idx=L1.index(" ") idx2=L1[idx:].index("\n") L2=L1[idx:idx+idx2] #print L2 pt.append(F(eval(L2))) # end block1 to compute pt L1=L1[idx+8:] # repeat block 2 more times #print len(L1) ## start block2 for compute pt idx=L1.index(" ") idx2=L1[idx:].index("\n") L2=L1[idx:idx+idx2] pt.append(F(eval(L2))) # end block2 to compute pt L1=L1[idx+8:] # repeat block 1 more time ## start block3 for compute pt idx=L1.index(" ") if "\n" in L1[idx:]: idx2=L1[idx:].index("\n") else: idx2=len(L1[idx:]) L2=L1[idx:idx+idx2] pt.append(F(eval(L2))) #print pt # end block3 to compute pt #end block to compute a pt Pts.append(tuple(pt)) # repeat until no more pts L1=L1[idx+8:] # repeat block 2 more times return tuple(Pts)
Now it is an easy matter to put these ingredients together into a Sage function which takes as input a triple \((f,F,d)\): a polynomial \(f\) in \(F[x,y]\) defining \(X:\ f(x,y)=0\) (note that the variables \(x,y\) must be used), a finite field \(F\) of prime order, and the degree \(d\). The output is the number of places in \(X\) of degree \(d=1\) over \(F\). At the moment, there is no “translation” between elements of \(GF(p^d)\) in Singular and Sage unless \(d=1\). So, for this reason, we restrict ourselves to points of degree one.
def places_on_curve(f,F): """ INPUT: f -- element of F[x,y], defining X: f(x,y)=0 F -- a finite field of *prime order* OUTPUT: integer -- the number of places in X of degree d=1 over F EXAMPLES: sage: F=GF(5) sage: R=PolynomialRing(F,2,names=["x","y"]) sage: x,y=R.gens() sage: f=y^2-x^9-x sage: places_on_curve(f,F) ((0, 1, 0), (3, 4, 1), (0, 0, 1), (2, 3, 1), (3, 1, 1), (2, 2, 1)) """ d = 1 p = F.characteristic() singular.eval('LIB "brnoeth.lib";') singular.eval("ring s="+str(p)+",(x,y),lp;") singular.eval("poly f="+str(f)) singular.eval("list X1=Adj_div(f);") singular.eval("list X2=NSplaces("+str(d)+",X1);") singular.eval("list X3=extcurve("+str(d)+",X2);") singular.eval("def R=X3[1][5];") singular.eval("setring R;") L = singular.eval("POINTS;") return points_parser(L,F)
Note that the ordering returned by this Sage function is exactly the same as the ordering in the Singular variable POINTS.
One more example (in addition to the one in the docstring):
sage: F = GF(2) sage: R = MPolynomialRing(F,2,names = ["x","y"]) sage: x,y = R.gens() sage: f = x^3*y+y^3+x sage: places_on_curve(f,F) ((0, 1, 0), (1, 0, 0), (0, 0, 1))
There is also a more Python-like interface to Singular. Using this, the code is much simpler, as illustrated below. First, we demonstrate computing the places on a curve in a particular case:
sage: singular.lib('brnoeth.lib') sage: R = singular.ring(5, '(x,y)', 'lp') sage: f = singular.new('y^2 - x^9 - x') sage: X1 = f.Adj_div() sage: X2 = singular.NSplaces(1, X1) sage: X3 = singular.extcurve(1, X2) sage: R = X3[1][5] sage: singular.set_ring(R) sage: L = singular.new('POINTS')
Note that these elements of L are defined modulo 5 in Singular, and they compare differently than you would expect from their print representation:
sage: sorted([(L[i][1], L[i][2], L[i][3]) for i in range(1,7)]) [(0, 0, 1), (0, 1, 0), (2, 2, 1), (2, -2, 1), (-2, 1, 1), (-2, -1, 1)]
Next, we implement the general function (for brevity we omit the docstring, which is the same as above). Note that the point_parser function is not required:
def places_on_curve(f,F): p = F.characteristic() if F.degree() > 1: raise NotImplementedError singular.lib('brnoeth.lib') R = singular.ring(5, '(x,y)', 'lp') f = singular.new('y^2 - x^9 - x') X1 = f.Adj_div() X2 = singular.NSplaces(1, X1) X3 = singular.extcurve(1, X2) R = X3[1][5] singular.setring(R) L = singular.new('POINTS') return [(int(L[i][1]), int(L[i][2]), int(L[i][3])) \ for i in range(1,int(L.size())+1)]
This code is much shorter, nice, and more readable. However, it depends on certain functions, e.g. singular.setring having been implemented in the Sage/Singular interface, whereas the code in the previous section used only the barest minimum of that interface.
You can create Sage pseudo-tty interfaces that allow Sage to work with almost any command line program, and which do not require any modification or extensions to that program. They are also surprisingly fast and flexible (given how they work!), because all I/O is buffered, and because interaction between Sage and the command line program can be non-blocking (asynchronous). A pseudo-tty Sage interface is asynchronous because it derives from the Sage class Expect, which handles the communication between Sage and the external process.
For example, here is part of the file SAGE_ROOT/src/sage/interfaces/octave.py, which defines an interface between Sage and Octave, an open source program for doing numerical computations, among other things:
import os from expect import Expect, ExpectElement class Octave(Expect): ...
The first two lines import the library os, which contains operating system routines, and also the class Expect, which is the basic class for interfaces. The third line defines the class Octave; it derives from Expect as well. After this comes a docstring, which we omit here (see the file for details). Next comes:
def __init__(self, maxread=100, script_subdirectory="", logfile=None, server=None, server_tmpdir=None): Expect.__init__(self,', command = "octave --no-line-editing --silent", maxread = maxread, server = server, server_tmpdir = server_tmpdir, script_subdirectory = script_subdirectory, restart_on_ctrlc = False, verbose_start = False, logfile = logfile, eval_using_file_cutoff=100)
This uses the class Expect to set up the Octave interface:
def set(self, var, value): """ Set the variable var to the given value. """ cmd = '%s=%s;'%(var,value) out = self.eval(cmd) if out.find("error") != -1: raise TypeError("Error executing code in Octave\nCODE:\n\t%s\nOctave ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ Get the value of the variable var. """ s = self.eval('%s'%var) i = s.find('=') return s[i+1:] def console(self): octave_console()
These let users type octave.set('x', 3), after which octave.get('x') returns ' 3'. Running octave.console() dumps the user into an Octave interactive shell:
def solve_linear_system(self, A, b): """ Use octave to compute a solution x to A*x = b, as a list. INPUT: A -- mxn matrix A with entries in QQ or RR b -- m-vector b entries in QQ or RR (resp) OUTPUT: An list x (if it exists) which solves M*x = b EXAMPLES: sage: M33 = MatrixSpace(QQ,3,3) sage: A = M33([1,2,3,4,5,6,7,8,0]) sage: V3 = VectorSpace(QQ,3) sage: b = V3([1,2,3]) sage: octave.solve_linear_system(A,b) # optional - octave [-0.33333299999999999, 0.66666700000000001, -3.5236600000000002e-18] AUTHOR: David Joyner and William Stein """ m = A.nrows() n = A.ncols() if m != len(b): raise ValueError("dimensions of A and b must be compatible") from sage.matrix.all import MatrixSpace from sage.rings.all import QQ MS = MatrixSpace(QQ,m,1) b = MS(list(b)) # converted b to a "column vector" sA = self.sage2octave_matrix_string(A) sb = self.sage2octave_matrix_string(b) self.eval("a = " + sA ) self.eval("b = " + sb ) soln = octave.eval("c = a \\ b") soln = soln.replace("\n\n ","[") soln = soln.replace("\n\n","]") soln = soln.replace("\n",",") sol = soln[3:] return eval(sol)
This code defines the method solve_linear_system, which works as documented.
These are only excerpts from octave.py; check that file for more definitions and examples. Look at other files in the directory SAGE_ROOT/src/sage/interfaces/ for examples of interfaces to other software packages.
|
http://sagemath.org/doc/developer/coding_in_other.html
|
CC-MAIN-2014-52
|
refinedweb
| 3,524
| 65.93
|
[ !
———–
Hello!
Welcome to miniLD 73. This is the final miniLD before Ludum Dare 38 starts on 21 April, which is LD’s 15th anniversary. So this miniLD is a great opportunity to get all your gamedev stuff in order for the big event next month.
Now, as you’ve guessed from the image above, the theme for this miniLD is: MUSIC!
Music is an important aspect of any game. It plays a big role in setting the tone of your game and it has a major influence on the emotions the player is feeling. However, during the short, hectic and rushed dev time of a game jam, it’s sadly often an overlooked aspect. Many LD entries don’t have any music at all and I feel that’s a real shame.
So, this miniLD is a chance for you to focus on music specifically, do experiments and learn how it influences your game. If you’ve never made music before, this is a great way to get started. I’ll put a list of (free) tools at the bottom of this post, in case you’re looking for things you can use to start composing. If you know of other useful things not listed, please share them in the comments below!
You may interpret the theme in any way you want, for example:
– make a game with an awesome soundtrack!
– create music for a game you had already started!
– make a music game!
– whatever you can think of!
MiniLD 73 starts right now and will run until LD38 starts. Don’t wait too long though, because all sorts of LD38 stuff will happen as the event comes closer (theme voting, the slaughter, the warm-up weekend).
So don’t hesitate, and get rocking!
List of music tools:
—
* Bosca Ceoil:
* Bfxr:
* Drumbot:
* Sonant Live:
* Audiotool:
* BeepBox:
* LMMS:
* Audacity:
* Ardour:
* DarkWave Studio:
* orDrumbox:
* Temper:
* Mixxx:
* Hydrogen:
* Rosegarden:
* Qtractor:
* MusE:
* Open ModPlug:
* MilkyTracker:
* SunVox:
* FamiTracker:
* MadTracker:
* Many more trackers:
* And even more trackers:
* pxtone (thanks euske!):
* blipseq (thanks TehVulpez!):
* FL Studio (free demo, thanks freyby!):
* BeepComp (thanks kreddor!):
You missed PxTone!
Thanks, euske! I’ve added it to the list
What a perfectly timed theme, love it! Since the last mini game jam ended, it was one of my highest priorities to try and add sound support to my game engine before the major game jam coming up in April. My MiniLD72 entry included no audio at all because of this technical shortcoming, and that was certainly a detriment to the game experience.
If it’s cool with you guys I think for this game I’m just going to expand on my previous game entry by adding both sound effects and music. Hopefully I can tweak the visuals to better match the new audio as well, making the overall experience more powerful.
Sure, that’s no problem, wareification! Anything is fine, as long as you’re doing something with music.
How could you forget blipseq?! It’s an extremely easy piece of software to use, and produces quite nice results. It was actually even made for a Ludum Dare!
The dropbox link is down. I guess rxi thought nobody would need it anymore. I’ve got a copy, but I’m not quite sure how I could get it to all of you. :\ If anybody could help me out with recommendations for how to upload this to some site, that would be greatly appreciated.
I’ve put it on Google Drive. Probably not the ideal or the most normal way of doing things, but it’s good for now. Browser antivirus might give a warning, (mine did when redownloading it to test it out), possibly saying something about “this file is not commonly downloaded” but it should be fine. I don’t think Google has much to gain from messing with people’s files. Just hit the download button in the top right corner I guess. It actually shows a little interactive directory and contents of the zip file, which is sort of interesting.
BTW there is a demo song included by rxi if you didn’t notice it, just type “demo1” into the load box.
Cool, thanks! I’ll include it in the list
Dropbox stopped offering the public folder, so a lot of links are now broken sadly. This is really dropbox’s fault
Music and programming are two of my favorite things, I totally have to take a crack at this one!
> sadly often an overlooked aspect
Saying that music is an overlooked aspect is like saying that running is an overlooked aspect for people trapped in wheelchairs. If music is an easy thing for you, you may feel like everybody should be able to do it, but that’s sadly not the case.
That doesn’t mean that this mini-ld is a bad idea though – if you ever want to get music in your games, better research it ahead of time, and practice. Either learn to somehow make the music yourself, or look into fractal music generation (the wolfram thing unfortunately has a license that forbids its use) or some such.
My solution was to throw money at it – bought an USB midi keyboard and some synth software, and for one year tried (and largely succeeded) to play around with it every single day. Phone conferences were a great boon in this, as I could do that while people talked about things that didn’t have anything to do with me.. =)
That didn’t make me a great composer or anything, but I can do SOMETHING at least.
Yeah, overlooked was not really the word I meant.
What I wanted to say is that it’s an often skipped part during game jams, because it’s considered sort of optional. More optional than programming or graphics.
I understand a lot of people don’t have experience with making music and feel maybe intimidated by it. And I certainly understand that during the short and stressful 48/72 hours of an LD weekend, starting on a new endeavour isn’t exactly appealing.
But that’s exactly why this miniLD is organised, so there’s more time and less stress to figure this stuff out for yourself. You can freely dabble away without any real risks of failing. And if you do learn to make music now, you’ll have a new skill in your toolbox which you can apply later
I did start today!
I’ll Mabey add the first version in a few days.
Got the idea…got the song…got the time.
Now I just need permission from the maker of the song and I’m ready to go 😀
Good luck everyone!
I’m making a game based on the feeling of a song a friend made…that’s allowed, right?
Great list of music tools Tijn!
I’ve never done a MiniLD before; only regular Ludum Dare. — Apologies if this is all in a FAQ somewhere, but I can’t find it.
When does the MiniLD start and end? — How do I “officially” participate? (is it too late?) — Any special rules I should know about?
Hey, its my first time too.
You can start now and it ends when LD38 starts.
I think there are no special rules.
HellowPixl has said it well. It has already started and will stay open until LD38 starts (on 21 April).
You participate by submitting your game using the big link in the post above that says “submit”. The form is a bit weird, because it’s the same one used for normal LD (modified only a bit), but I’m sure you’ll manage
You can edit your entry later, so it will all be good. And don’t worry about judging, as there is none.
The rules are extremely relaxed. Anything goes really. As long as you feel you’re doing something worthwhile, it’s probably alright 😀
Oh, I see. — When did it start? — Did it start today? — Or has it been going on for awhile?
It did start 1 or 2 days ago.
Am I allowed to create it with my friend to teach him java?!
Or its it the compo only in mini LD?
Oh sure, teams are fine!
It started 15 March, as you can see just below the title at the top of the post
Is there a official way of creating the team?
No, sadly not. One of the team members will have to submit using their account. You can mention the rest of the members in the description of your entry.
Ok.
I will do it alone anyway.
Hey guys,
I was wondering if someone out there knows some good tutorials on how to implement audio into your game
Or if someone could tell me how to.
Please reply If you now some.
Ok I did find a way, BUT
it can only read a file that’s in the java Project not in a folder in it!
I don’t know why. If i change the path to a folder it gives me an error!
public class BackGroundMusic {
public static void play() {
File bgs1 = new File(“01.wav”);
File bgs2 = new File(“02.wav”);
while (GamePanel.running) {
if(GamePanel.inMenu)
PlaySound(bgs1);
if(!GamePanel.inMenu)
PlaySound(bgs2);
}
}
private static void PlaySound(File file) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
Thread.sleep(clip.getMicrosecondLength() / 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Side note about LMMS: Everyone except me hates it
I don’t hate it,
but i cant use it good!
Could we use somebody else’s music? or are we supposed to make our own?
Well, at the very least when you do use someone else’s music, you should have their permission. And it could be interesting to do experiments with other people’s music, of course. So if you feel you’re doing something worthwhile, then by all means go ahead.
But having said that, the idea of this miniLD is sort of that you work on your own music-making abilities. But I don’t want to force anyone to do something they aren’t interested in doing 😀
When is this due?
oh, nevermind
What about FL Studio 12?
I mainly wanted a list of free tools for people who have no experience with this stuff. FL Studio is very cool, but it’s a bit pricey to just try out for a bit.
But of course there is a free demo, so I’ll list it with a note saying that
Some cool stuff:
I know it’s a bit late, but you should add BeepComp to the list
You’re not that late, it’s still March
I’ve added it to the list!
Ok my entry is now finished!
Make sure check it out!
Thanks for offering this! I saw “– create music for a game you had already started!” and realized there was an unfinished game we made a year ago that we really liked, but it felt really incomplete, and this inspired me to realize it just needed music (title theme, fanfares throughout, and a song/music video at the end). So, I spent a day this weekend working on that and fixing a couple loose ends and it seems done, so I released it!
Quick question for anybody though- and I didn’t want to pollute the main thread with this.
A few weeks after LD37, I noticed that our author page (where it shows our previous entries) disappeared. Our entry pages still exist, individually, and say our name, but the the hyperlink of our name “grandtheftmarmot” just says “not found.” Does anybody know why this happened or how to fix it? Not a huge deal, but it would be nice to see them in one place. (Just three now, including this one, but hopefully many more to come.)
Hi grandtheftmarmot,
Cool that you’ve made an entry for my miniLD! Awesome job!
Now about your author page problem. Could you try making a blog post please? I think I might be able to fix the issue through that
Ah, sorceress (one of our admins) has made a post for you. The issue has been fixed now and you have a working author page
Thank you so very much! 😀 😀
As someone who composes for a hobby, this seems pretty cool! By the way, the program I use is called ‘Musescore’ and is good for composing orchestral music (although basic synths & some other non-orchestral instruments are available for use as well) by writing traditional sheet music.
This turn’s miniLD is really amazing cool!
why i found it just now!
already can not wait to have some try!>o<
I’m in! I will be doing something with Midi — I hope.
Hey all,
We just finished work on our music game, but we’re not sure it really fits in the spirit of the jam, since work was started back in October. I’ll link here for those who are interested, but I’ll hold back in posting it as an “entry”.
You control robots traversing an orb in deep space by playing musical pitches into your microphone.
Please let us know what you think!
Adventures of Laura Jones HD: the hidden invention of Nikola Tesla for iPad. Best mateys Bert and Ernie arrr adventuring pirates, searching for Uncle Arrrnolds buried treasure.
It is so adventures when i am going to share the new tricks and tips here. It was totally fabulous thank you so much for this latest one.
Some of his postings have been to Nova Scotia, Prince Edward Island, New Brunswick, British Columbia, Ontario and a tour of duty in Egypt. This FREE version contains the same whole game as the paid version, but with ads.
Compete against friends or on your own with your device using your favourite toast toppings. Turn off the sound effects in the options menu, or enjoy Connext’s ticks and whirs over your favorite songs!
Ability to change the color of the text chat window. checkout this. We hope that you enjoy the summer and your vacation getawa.
To operate it, users click and drag windows into the corners of their screen. States for Barbarian Rage (with Counter) & Druid Wild Shape (with HP Tracking)- Thief’s Reflexes.
|
http://ludumdare.com/compo/2017/03/15/minild-73-music/
|
CC-MAIN-2019-13
|
refinedweb
| 2,390
| 82.24
|
What's new in Matplotlib 3.3.0 (Jul 16, 2020)¶
For a list of all of the issues and pull requests since the last revision, see the GitHub statistics (Dec 11, 2021).
Table of Contents
What's new in Matplotlib 3.3.0 (Jul 16, 2020)
Figure and Axes creation / management
-
Titles, ticks, and labels
-
-
-
-
Interactive tool improvements
Functions to compute a Path's size
Backend-specific improvements
savefig()gained a backend keyword argument
The SVG backend can now render hatches with transparency
SVG supports URLs on more artists
Images in SVG will no longer be blurred in some viewers
Saving SVG now supports adding metadata
Saving PDF metadata via PGF now consistent with PDF backend
NbAgg and WebAgg no longer use jQuery & jQuery UI
Figure and Axes creation / management¶
Provisional API for composing semantic axes layouts from text or nested lists¶
The
Figure class has a provisional method to generate complex grids of named
axes.Axes based on nested list input or ASCII art:
axd = plt.figure(constrained_layout=True).subplot_mosaic( [['.', 'histx'], ['histy', 'scat']] ) for k, ax in axd.items(): ax.text(0.5, 0.5, k, ha='center', va='center', fontsize=36, color='darkgrey')
(Source code, png, pdf)
or as a string (with single-character Axes labels):
axd = plt.figure(constrained_layout=True).subplot_mosaic( """ TTE L.E """) for k, ax in axd.items(): ax.text(0.5, 0.5, k, ha='center', va='center', fontsize=36, color='darkgrey')
(Source code, png, pdf)
See Complex and semantic figure composition for more details and examples.
GridSpec.subplots()¶
The
GridSpec class gained a
subplots method, so that one
can write
fig.add_gridspec(2, 2, height_ratios=[3, 1]).subplots()
as an alternative to
fig.subplots(2, 2, gridspec_kw={"height_ratios": [3, 1]})
tight_layout now supports suptitle¶
Previous versions did not consider
Figure.suptitle, so it may overlap with
other artists after calling
tight_layout:
(Source code, png, pdf)
From now on, the
suptitle will be considered:
(Source code, png, pdf)
Setting axes box aspect¶
It is now possible to set the aspect of an axes box directly via
set_box_aspect. The box aspect is the ratio between axes height and
axes width in physical units, independent of the data limits. This is useful
to, e.g., produce a square plot, independent of the data it contains, or to
have a non-image plot with the same axes dimensions next to an image plot with
fixed (data-)aspect.
For use cases check out the Axes box aspect example.
Colors and colormaps¶
Turbo colormap¶
Turbo is an improved rainbow colormap for visualization, created by the Google AI team for computer vision and machine learning. Its purpose is to display depth and disparity data. Please see the Google AI Blog for further details.
(Source code, png, pdf)
colors.BoundaryNorm supports extend keyword argument¶
BoundaryNorm now has an extend keyword argument, analogous to
extend in
contourf. When set to 'both', 'min', or 'max', it
maps the corresponding out-of-range values to
Colormap lookup-table
indices near the appropriate ends of their range so that the colors for out-of
range values are adjacent to, but distinct from, their in-range neighbors. The
colorbar inherits the extend argument from the norm, so with
extend='both', for example, the colorbar will have triangular extensions
for out-of-range values with colors that differ from adjacent in-range colors.
(Source code, png, pdf)
Text color for legend labels¶
The text color of legend labels can now be set by passing a parameter
labelcolor to
legend. The
labelcolor keyword can be:
A single color (either a string or RGBA tuple), which adjusts the text color of all the labels.
A list or tuple, allowing the text color of each label to be set individually.
linecolor, which sets the text color of each label to match the corresponding line color.
markerfacecolor, which sets the text color of each label to match the corresponding marker face color.
markeredgecolor, which sets the text color of each label to match the corresponding marker edge color.
(Source code, png, pdf)
Pcolor and Pcolormesh now accept
shading='nearest' and
'auto'¶
Previously
axes.Axes.pcolor and
axes.Axes.pcolormesh handled the
situation where x and y have the same (respective) size as C by dropping
the last row and column of C, and x and y are regarded as the edges of
the remaining rows and columns in C. However, many users want x and y
centered on the rows and columns of C.
To accommodate this,
shading='nearest' and
shading='auto' are new
allowed strings for the shading keyword argument.
'nearest' will center
the color on x and y if x and y have the same dimensions as C
(otherwise an error will be thrown).
shading='auto' will choose 'flat' or
'nearest' based on the size of X, Y, C.
If
shading='flat' then X, and Y should have dimensions one larger than
C. If X and Y have the same dimensions as C, then the previous behavior
is used and the last row and column of C are dropped, and a
DeprecationWarning is emitted.
Users can also specify this by the new
rcParams["pcolor.shading"] (default:
'auto') in their
.matplotlibrc or via
rcParams.
See pcolormesh for examples.
Titles, ticks, and labels¶
Align labels to Axes edges¶
set_xlabel,
set_ylabel and
ColorbarBase.set_label support a parameter
loc for simplified
positioning. For the xlabel, the supported values are 'left', 'center', or
'right'. For the ylabel, the supported values are 'bottom', 'center', or
'top'.
The default is controlled via
rcParams["xaxis.labelposition"] and
rcParams["yaxis.labelposition"]; the Colorbar label takes the rcParam based on its
orientation.
Allow tick formatters to be set with str or function inputs¶
set_major_formatter and
set_minor_formatter
now accept
str or function inputs in addition to
Formatter
instances. For a
str a
StrMethodFormatter is automatically
generated and used. For a function a
FuncFormatter is automatically
generated and used. In other words,
ax.xaxis.set_major_formatter('{x} km') ax.xaxis.set_minor_formatter(lambda x, pos: str(x-5))
are shortcuts for:
import matplotlib.ticker as mticker ax.xaxis.set_major_formatter(mticker.StrMethodFormatter('{x} km')) ax.xaxis.set_minor_formatter( mticker.FuncFormatter(lambda x, pos: str(x-5))
(Source code, png, pdf)
Axes.set_title gains a y keyword argument to control auto positioning¶
set_title tries to auto-position the title to avoid any
decorators on the top x-axis. This is not always desirable so now y is an
explicit keyword argument of
set_title. It defaults to None
which means to use auto-positioning. If a value is supplied (i.e. the pre-3.0
default was
y=1.0) then auto-positioning is turned off. This can also be
set with the new rcParameter
rcParams["axes.titley"] (default:
None).
(Source code, png, pdf)
Offset text is now set to the top when using
axis.tick_top()¶
Solves the issue that the power indicator (e.g., 1e4) stayed on the bottom, even if the ticks were on the top.
Set zorder of contour labels¶
clabel now accepts a zorder keyword argument making it easier
to set the zorder of contour labels. If not specified, the default zorder
of clabels used to always be 3 (i.e. the default zorder of
Text)
irrespective of the zorder passed to
contour/
contourf. The new default zorder for
clabels has been changed to (
2 + zorder passed to
contour /
contourf).
Other changes¶
New
Axes.axline method¶
A new
axline method has been added to draw infinitely long lines
that pass through two points.
fig, ax = plt.subplots() ax.axline((.1, .1), slope=5, color='C0', label='by slope') ax.axline((.1, .2), (.8, .7), color='C3', label='by points') ax.legend()
(Source code, png, pdf)
imshow now coerces 3D arrays with depth 1 to 2D¶
Starting from this version arrays of size MxNx1 will be coerced into MxN
for displaying. This means commands like
plt.imshow(np.random.rand(3, 3, 1))
will no longer return an error message that the image shape is invalid.
Better control of
Axes.pie normalization¶
Previously,
Axes.pie would normalize its input x if
sum(x) > 1, but
would do nothing if the sum were less than 1. This can be confusing, so an
explicit keyword argument normalize has been added. By default, the old
behavior is preserved.
By passing normalize, one can explicitly control whether any rescaling takes
place or whether partial pies should be created. If normalization is disabled,
and
sum(x) > 1, then an error is raised.
(Source code, png, pdf)
Dates use a modern epoch¶
Matplotlib converts dates to days since an epoch using
dates.date2num (via
matplotlib.units). Previously, an epoch of
0000-12-31T00:00:00 was used
so that
0001-01-01 was converted to 1.0. An epoch so distant in the past
meant that a modern date was not able to preserve microseconds because 2000
years times the 2^(-52) resolution of a 64-bit float gives 14 microseconds.
Here we change the default epoch to the more reasonable UNIX default of
1970-01-01T00:00:00 which for a modern date has 0.35 microsecond
resolution. (Finer resolution is not possible because we rely on
datetime.datetime for the date locators). Access to the epoch is provided by
get_epoch, and there is a new
rcParams["date.epoch"] (default:
'1970-01-01T00:00:00') rcParam. The user may
also call
set_epoch, but it must be set before any date conversion
or plotting is used.
If you have data stored as ordinal floats in the old epoch, you can convert them to the new ordinal using the following formula:
new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31'))
Lines now accept
MarkerStyle instances as input¶
Similar to
scatter,
plot and
Line2D now accept
MarkerStyle instances as input for the marker parameter:
plt.plot(..., marker=matplotlib.markers.MarkerStyle("D"))
Fonts¶
Simple syntax to select fonts by absolute path¶
Fonts can now be selected by passing an absolute
pathlib.Path to the font
keyword argument of
Text.
Improved font weight detection¶
Matplotlib is now better able to determine the weight of fonts from their metadata, allowing to differentiate between fonts within the same family more accurately.
rcParams improvements¶
matplotlib.rc_context can be used as a decorator¶
matplotlib.rc_context can now be used as a decorator (technically, it is now
implemented as a
contextlib.contextmanager), e.g.,
@rc_context({"lines.linewidth": 2}) def some_function(...): ...
rcParams for controlling default "raise window" behavior¶
The new config option
rcParams["figure.raise_window"] (default:
True) allows disabling of the raising
of the plot window when calling
show or
pause. The
MacOSX backend is currently not supported.
Add generalized
mathtext.fallback to rcParams¶
New
rcParams["mathtext.fallback"] (default:
'cm') rcParam. Takes "cm", "stix", "stixsans"
or "none" to turn fallback off. The rcParam mathtext.fallback_to_cm is
deprecated, but if used, will override new fallback.
Add
contour.linewidth to rcParams¶
The new config option
rcParams["contour.linewidth"] (default:
None) allows to control the default
line width of contours as a float. When set to
None, the line widths fall
back to
rcParams["lines.linewidth"] (default:
1.5). The config value is overridden as usual by the
linewidths argument passed to
contour when it is not set to
None.
3D Axes improvements¶
Axes3D no longer distorts the 3D plot to match the 2D aspect ratio¶
Plots made with
Axes3D were previously
stretched to fit a square bounding box. As this stretching was done after the
projection from 3D to 2D, it resulted in distorted images if non-square
bounding boxes were used. As of 3.3, this no longer occurs.
Currently, modes of setting the aspect (via
set_aspect) in data space are not
supported for Axes3D but may be in the future. If you want to simulate having
equal aspect in data space, set the ratio of your data limits to match the
value of
get_box_aspect. To control these ratios use the
set_box_aspect method which accepts the
ratios as a 3-tuple of X:Y:Z. The default aspect ratio is 4:4:3.
3D axes now support minor ticks¶
ax = plt.figure().add_subplot(projection='3d') ax.scatter([0, 1, 2], [1, 3, 5], [30, 50, 70]) ax.set_xticks([0.25, 0.75, 1.25, 1.75], minor=True) ax.set_xticklabels(['a', 'b', 'c', 'd'], minor=True) ax.set_yticks([1.5, 2.5, 3.5, 4.5], minor=True) ax.set_yticklabels(['A', 'B', 'C', 'D'], minor=True) ax.set_zticks([35, 45, 55, 65], minor=True) ax.set_zticklabels([r'$\alpha$', r'$\beta$', r'$\delta$', r'$\gamma$'], minor=True) ax.tick_params(which='major', color='C0', labelcolor='C0', width=5) ax.tick_params(which='minor', color='C1', labelcolor='C1', width=3)
(Source code, png, pdf)
Interactive tool improvements¶
More consistent toolbar behavior across backends¶
Toolbar features are now more consistent across backends. The history buttons will auto-disable when there is no further action in a direction. The pan and zoom buttons will be marked active when they are in use.
In NbAgg and WebAgg, the toolbar buttons are now grouped similarly to other backends. The WebAgg toolbar now uses the same icons as other backends.
Toolbar icons are now styled for dark themes¶
On dark themes, toolbar icons will now be inverted. When using the GTK3Agg backend, toolbar icons are now symbolic, and both foreground and background colors will follow the theme. Tooltips should also behave correctly.
Cursor text now uses a number of significant digits matching pointing precision¶
Previously, the x/y position displayed by the cursor text would usually include far more significant digits than the mouse pointing precision (typically one pixel). This is now fixed for linear scales.
GTK / Qt zoom rectangle now black and white¶
This makes it visible even over a dark background.
Event handler simplifications¶
The
backend_bases.key_press_handler and
backend_bases.button_press_handler event handlers can now be directly
connected to a canvas with
canvas.mpl_connect("key_press_event",
key_press_handler) and
canvas.mpl_connect("button_press_event",
button_press_handler), rather than having to write wrapper functions that
fill in the (now optional) canvas and toolbar parameters.
Functions to compute a Path's size¶
Various functions were added to
BezierSegment and
Path to
allow computation of the shape/size of a
Path and its composite Bezier
curves.
In addition to the fixes below,
BezierSegment has gained more
documentation and usability improvements, including properties that contain its
dimension, degree, control_points, and more.
Better interface for Path segment iteration¶
iter_bezier iterates through the
BezierSegment's that
make up the Path. This is much more useful typically than the existing
iter_segments function, which returns the absolute minimum amount
of information possible to reconstruct the Path.
Fixed bug that computed a Path's Bbox incorrectly¶
Historically,
get_extents has always simply returned the Bbox of
a curve's control points, instead of the Bbox of the curve itself. While this is
a correct upper bound for the path's extents, it can differ dramatically from
the Path's actual extents for non-linear Bezier curves.
Backend-specific improvements¶
savefig() gained a backend keyword argument¶
The backend keyword argument to
savefig can now be used to pick the
rendering backend without having to globally set the backend; e.g., one can
save PDFs using the pgf backend with
savefig("file.pdf", backend="pgf").
The SVG backend can now render hatches with transparency¶
The SVG backend now respects the hatch stroke alpha. Useful applications are, among others, semi-transparent hatches as a subtle way to differentiate columns in bar plots.
SVG supports URLs on more artists¶
URLs on more artists (i.e., from
Artist.set_url) will now be saved in
SVG files, namely,
Ticks and
Line2Ds are now supported.
Images in SVG will no longer be blurred in some viewers¶
A style is now supplied to images without interpolation (
imshow(...,
interpolation='none') so that SVG image viewers will no longer perform
interpolation when rendering themselves.
Saving SVG now supports adding metadata¶
When saving SVG files, metadata can now be passed which will be saved in the
file using Dublin Core and RDF. A list of valid metadata can be found in
the documentation for
FigureCanvasSVG.print_svg.
Saving PDF metadata via PGF now consistent with PDF backend¶
When saving PDF files using the PGF backend, passed metadata will be
interpreted in the same way as with the PDF backend. Previously, this metadata
was only accepted by the PGF backend when saving a multi-page PDF with
backend_pgf.PdfPages, but is now allowed when saving a single figure, as
well.
NbAgg and WebAgg no longer use jQuery & jQuery UI¶
Instead, they are implemented using vanilla JavaScript. Please report any issues with browsers.
|
https://matplotlib.org/devdocs/users/prev_whats_new/whats_new_3.3.0.html
|
CC-MAIN-2022-05
|
refinedweb
| 2,746
| 57.47
|
Directives are the unit part of the angular app, In angular app we broadly use the components, actually, component is a directive. They are higher order directive with templates and they are building blocks of angular applications. Here we'll talk about the custom directive. If you want to create custom directory in angular 2+ app then follow the given steps in this article. In this article, we will create a directive and In this directive our goal is to add some HTML content at the desire place. ( The directive will add HTML content in the DOM ).
Create an angular2+ app:
First we need to create an angular app using "ng new" command, create an app using below command:
ng new angular-dir
cd angular-dir
npm install
After successful npm install, we need to create a directive in your app, so go to the folder "src/app" and follow the below steps:
Create a test.directive.ts file.
In this step, we will create a directory and further we will use this directory throughout the app. To do this we need to Create a file name "test.directive.ts" ( src/app/test.directive.ts ) and write the below code in this file.
Now your custom directive has been created .
Now you will have to import this custom directive in app.module.ts.
After creating the directory, you need to add this directive in your module, to do this import and add this directive in your "app.module.ts"
app.module.ts:
import { NgModule } from ‘@angular/core’; import { AppComponent } from ‘./app.component’; import { TestDirectives } from ‘../directives/test.directive’; @NgModule({ declarations: [ AppComponent, TestDirectives ], imports: [], providers: [], bootstrap: [AppComponent] }); export class AppModule { }
Now your directive has been imported in your app successfully.
Use your custom directive.
Now you are free to add this custom directive any where within the module like this:
See the output.
In the output you can see the "Hello World" append in your dom just because of your custom directive
Conclusion:
In this article, we tried to describe about the custom directive. Hope you are able to write the custom directive in angular.
|
https://idkblogs.com/all/21/Create-a-custom-directive-in-Angular-2-application
|
CC-MAIN-2021-17
|
refinedweb
| 354
| 54.63
|
If you were on the internet in these past few months chances are you saw Google's real-time translation Pixel Buds. A technology quite like the Babel fish in The Hitchhiker’s Guide to the Galaxy that can translate any sentient speech for its wearer thus enabling them to communicate with virtually every being. The Google Pixel Buds come at a price of course - so why not build our own?! That’s what Danielle and I thought at the latest hackference. We went on to create a Nexmo Babel fish that lets two people talk on the phone with either party hearing a translated version of what the respective other party says.
In this blogpost, we will go over how this Babel fish system works step by step starting with the required setup and configuration. Then, we will set up a Nexmo number for handling incoming calls. Following this, we will implement a Python server which will receive speech via a WebSocket and route the incoming speech from the Nexmo number to the Microsoft Translator Speech API. We will use the Translator Speech API to handle the transcription and translation. On top of this, we will implement logic to manage a bi-directional dialogue and to instruct the Nexmo number to speak the translations. For ease of implementation, both parties will have to call our service's Nexmo number. Below, you can see a high-level system diagram of how an instance of speech from either side gets processed. Note that throughout this tutorial I will use the example of a German/British English conversation.
If you would prefer to just see the code, it is available on GitHub here.
Prerequisites
You will need to have both Python 2.x or 3.x and the HTTP tunnelling software ngrok installed to be able to follow along. We will list all the commands you need to install everything else as you follow along.
Getting Started
Set Up Your Environment
Let’s get started with our DIY Babel fish solution by setting up a virtual environment for this project using Virtualenv. Virtualenv allows us to isolate the dependencies of this project from our other projects. Go ahead and create a directory for this project and copy the following list of dependencies into a file in your project directory named
requirements.txt:
nexmo tornado>=4.4.2 requests>=2.12.4
To create and activate your virtual environment, run the following commands in your terminal:
virtualenv venv # sets up the environment source venv/bin/activate # activates the environment pip install -r requirement.txt # installs our dependencies # if you are running python3 please run the following instead pip3 install -r requirement.txt
At this point, please start ngrok in a separate terminal window by running the command below. ngrok will allow us to expose our localhost at port 5000 to incoming requests. You will need to keep ngrok running in the background for this to work. You can read more about connecting ngrok with Nexmo here.
ngrok http 5000
Once you run the above command, your terminal should look similar to the screenshot below. You will need the forwarding URL when configuring your Nexmo application and number in the next steps.
Create a Nexmo Application
Go to your applications and add a new application. Use the Ngrok forwarding URL for both the Event URL and the Answer URL adding
/event as the path for the Event URL (e.g.) and
/ncco for the Answer URL (e.g.). We will set these endpoints up later. Generate a public/private key pair via the user interface and store the key on your computer.
The last step for our number setup is to link the number you purchased earlier to your application. Use the application dashboard to link the number.
Obtain keys for Microsoft’s Translator Speech API
The other service we are going to need to set up is Microsoft’s Translator Speech API. Sign up for a free Microsoft Azure account at azure.com and afterwards go to portal.azure.com and create a Translator Speech API resource. You will need the key it generates for the next step.
Manage Secrets and Config
Now that we have our Nexmo number and our Translator Speech API key, all we need to do is set up a secrets and a config file with all these important details so that we don't have to keep writing them and can keep them separately managed. Store the below in
secrets.py in your project folder and replace the placeholder values with your values.
# Replace the below values with your values # Your API key and secret can be found here NEXMO_API_KEY = "<your-api-key>" NEXMO_API_SECRET = "<your-api-secret>" # Your nexmo number NEXMO_NUMBER = "+447512345678" # This is found on your Nexmo application’s dashboard NEXMO_APPLICATION_ID = "<nexmo-application-id>" # This is the private key you downloaded when setting up your application NEXMO_PRIVATE_KEY = '''-----BEGIN PRIVATE KEY----- <your-private-key> -----END PRIVATE KEY-----''' # You will have to sign up for a free Microsoft account to use the Microsoft Translator Speech API: MICROSOFT_TRANSLATION_SPEECH_CLIENT_SECRET = "<your-api-key>"
Afterwards store the below in
config.py in your project folder and again replace the placeholder values with your values. Note that you can choose other languages than the ones below. You can also alter these at any point later.
HOSTNAME = '<your-value>.ngrok.io' # Replace the variable assignment with your number in the same format CALLER = '447812345678' # Replace the variable assignment with your languages LANGUAGE1 = 'de-DE' # Replace the variable assignments with the respective name for your language. They can be found here: # VOICE1 = 'Marlene' # the other person's language and voice LANGUAGE2 = 'en-US' VOICE2 = 'Kimberly'
Tutorial Steps
Below we will first go through how to authenticate with the Translator Speech API. Then we will set up our Tornado Web server using a supplied template. Following this, we will implement the
CallHandler, the
EventHandler, and the
WSHandler. The
CallHandler will handle incoming calls to the Nexmo number for us. On top of that, the
EventHandler will be used to handle events that Nexmo sends, such as a call starting or completing. With each event, Nexmo sends information about the actor who started or completed the call. We will use this information to store who is in a specific call. The
WSHandler will meanwhile be used to open the WebSocket through which Nexmo and our Python server will communicate. The Python server will create snippets of audio and send them to the Translator Speech API. The handler will use the information that the
EventHandler gathers to route messages correctly. Each section below will explain these concepts further and show the respective implementation.
Authenticate with Microsoft’s Translator Speech API
To use the Translator Speech API we need to get a token which we name the
MICROSOFT_TRANSLATION_SPEECH_CLIENT_SECRET. Luckily Microsoft provides a Python AzureAuthClient which we will use without change. Please copy the below and save it in a file called
azure_auth_client.py in your project directory.
""" Code example for getting a A from the Azure Platform. Visit to view the API reference for Microsoft Azure Cognitive Services authentication service. """ from datetime import timedelta from datetime import datetime import requests class AzureAuthClient(object): """ Provides a client for obtaining an OAuth token from the authentication service for Microsoft Translator in Azure Cognitive Services. """ def __init__(self, client_secret): """ :param client_secret: Client secret. """ self.client_secret = client_secret # token field is used to store the last token obtained from the token service # the cached token is re-used until the time specified in reuse_token_until. self.token = None self.reuse_token_until = None def get_access_token(self): ''' Returns an access token for the specified subscription. This method uses a cache to limit the number of requests to the token service. A fresh token can be re-used during its lifetime of 10 minutes. After a successful request to the token service, this method caches the access token. Subsequent invocations of the method return the cached token for the next 5 minutes. After 5 minutes, a new token is fetched from the token service and the cache is updated. ''' if (self.token is None) or (datetime.utcnow() > self.reuse_token_until): token_service_url = '' request_headers = {'Ocp-Apim-Subscription-Key': self.client_secret} response = requests.post(token_service_url, headers=request_headers) response.raise_for_status() self.token = response.content self.reuse_token_until = datetime.utcnow() + timedelta(minutes=5) return self.token
Create a Server
The computer communications protocol WebSockets allows us to have a two-way communication channel over a single TCP connection. Nexmo’s Voice API lets you connect phone calls to such WebSocket endpoints. We will use the Tornado Web server web framework as it implements the WebSocket protocol for us.
If you have been following along and named all the files as described, you can start with the below Tornado Web server setup. This code handles all our imports, sets up the Nexmo client and the azure auth client, and starts a server on port 5000. Note that this server does not do anything useful yet. It has three endpoints:
ncco,
event, and
socket which call the
CallHandler,
EventHandler, and
WSHandler respectively. We will implement the handlers in the following sections.
Create a file named
main.py in your project directory and copy this code into it.
from string import Template import json import os import requests import struct import StringIO from tornado import httpserver, httpclient, ioloop, web, websocket, gen from xml.etree import ElementTree import nexmo from azure_auth_client import AzureAuthClient from config import HOSTNAME, CALLER, LANGUAGE1, VOICE1, LANGUAGE2, VOICE2 from secrets import NEXMO_APPLICATION_ID, NEXMO_PRIVATE_KEY, MICROSOFT_TRANSLATION_SPEECH_CLIENT_SECRET, NEXMO_NUMBER nexmo_client = nexmo.Client(application_id=NEXMO_APPLICATION_ID, private_key=NEXMO_PRIVATE_KEY) azure_auth_client = AzureAuthClient(MICROSOFT_TRANSLATION_SPEECH_CLIENT_SECRET) conversation_id_by_phone_number = {} call_id_by_conversation_id = {} class CallHandler(web.RequestHandler): @web.asynchronous def get(self): self.write("Hello world") class EventHandler(web.RequestHandler): @web.asynchronous def post(self): self.write("Hello world") class WSHandler(websocket.WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): self.write_message(u"You said: " + message) def on_close(self): print("WebSocket closed") def main(): application = web.Application([ (r"/event", EventHandler), (r"/ncco", CallHandler), (r"/socket", WSHandler), ]) http_server = httpserver.HTTPServer(application) port = int(os.environ.get("PORT", 5000)) http_server.listen(port) print("Running on port: " + str(port)) ioloop.IOLoop.instance().start() if __name__ == "__main__": main()
Implement the CallHandler
To connect phone calls to WebSocket endpoints, Nexmo’s Voice API uses a Nexmo Call Control Object (NCCO) or an API call. When someone calls your Nexmo number, Nexmo will issue a get request to the Answer URL you provided when setting up your Nexmo Voice Application. We pointed our application to our server which now needs to answer this request by returning an
NCCO. This
NCCO should instruct Nexmo to give a short welcome message to the caller and then connect the caller to the WebSocket.
Go ahead and save the following
NCCO into a file called
ncco.json within your project directory. It contains a template that will perform the required actions. However, it includes some placeholder variables (
$hostname,
$whoami, and
$cid) which we will need to replace later when we use it.
[ { "action": "talk", "text": "Please wait while we connect you." }, { "action": "connect", "eventUrl": [ "" ], "from": "12345", "endpoint": [ { "type": "websocket", "uri" : "ws://$hostname/socket", "content-type": "audio/l16;rate=16000", "headers": { "whoami": "$whoami", "cid": "$cid" } } ] } ]
In the template for the server the section reproduced below sets up the mapping between the
/ncco endpoint and the
CallHandler. This mapping ensures that when the
/ncco endpoint receives a GET request, the
CallHandler's get method is executed by the server.
application = web.Application([ (r"/event", EventHandler), (r"/ncco", CallHandler), (r"/socket", WSHandler), ])
When the server executes the method, it returns an assembled
NCCO using the code below. To begin with, we gather data from the query (i.e. the GET request) in a
data variable. We also store the
conversation_uuid for later use. In this case, there is a print statement so that you can see the
conversation_uuid when you are testing your server. In the next step, the code loads the
NCCO from the
ncco.json file we created. To complete the loaded
NCCO, we substitute the placeholder variables (
$hostname,
$cid, and
$whoami) with the gathered values from the data variable. After the substitution, we are ready to send it back to Nexmo.
Replace the
CallHandler from the template above with this code:
class CallHandler(web.RequestHandler): @web.asynchronous def get(self): data={} data['hostname'] = HOSTNAME data['whoami'] = self.get_query_argument('from') data['cid'] = self.get_query_argument('conversation_uuid') conversation_id_by_phone_number[self.get_query_argument('from')] = self.get_query_argument('conversation_uuid') print(conversation_id_by_phone_number) filein = open('ncco.json') src = Template(filein.read()) filein.close() ncco = json.loads(src.substitute(data)) self.write(json.dumps(ncco)) self.set_header("Content-Type", 'application/json; charset="utf-8"') self.finish()
Whenever someone now calls the Nexmo number, Nexmo will send a GET request to our
/ncco endpoint and the
CallHandler will assemble and send the
NCCO. Nexmo will then perform the actions as laid out in the
NCCO. In this case, that means the caller will hear “Please wait while we connect you.". Afterwards, Nexmo will attempt to connect the call to the provided
socket endpoint. It also provides Nexmo with the
event endpoint to be used. If you start your server now by running
python main.py in your terminal window, you will find that you will hear the message but the call will end after it. This is because we haven’t implemented the
EventHandler or the
WSHandler. Let’s do that now!
Implement the EventHandler
The
EventHandler handles events that Nexmo sends. We are interested in any incoming calls and therefore check any incoming request to see whether its body contains a
direction and whether that direction is
incoming. If it is, we will want to store the uuid and finish the request context. The
call_id_by_conversation_id dictionary will be used for routing messages between the callers in the
WSHandler.
Replace the
EventHandler from the template with this code:
class EventHandler(web.RequestHandler): @web.asynchronous def post(self): body = json.loads(self.request.body) if 'direction' in body and body['direction'] == 'inbound': if 'uuid' in body and 'conversation_uuid' in body: call_id_by_conversation_id[body['conversation_uuid']] = body['uuid'] self.content_type = 'text/plain' self.write('ok') self.finish()
Implement the WSHandler
The
CallHandler and the
EventHandler have allowed our application to set up the call. The
WSHandler will now take care of the audio stream of the call. The speech on the primary caller's side will be transcribed and translated by the Translator Speech API, and the resulting text will be spoken by a Nexmo voice on the other end of the line. The second person can thus hear the caller in a language they understand and afterwards respond. The Translator Speech API will translate the response in turn so that the first person hears it in their language. This workflow is the bit we will now implement.
When the Nexmo Voice API connects to a WebSocket, Nexmo sends an initial HTTP GET request to the endpoint. Our server responds with a HTTP 101 to switch protocols, and the server will subsequently connect to Nexmo using TCP. This connection upgrade is handled for us by Tornado. Whenever someone makes a call to our Nexmo number, Nexmo will open a WebSocket for the duration of the call. When a WebSocket is opened and finally closed, the Tornado framework will call the
open and
close methods below. We do not need to do anything in either case, but we will print messages so that we can follow what is going on when we run the server.
Now that we have an open connection, Nexmo will send messages that we handle in the
on_message method. The first message we will receive from Nexmo will be plain text with metadata. Upon receiving this message, we will set the
whoami property of the
WSHandler to be able to identify the speaker. Afterwards, we will create a wave header that we will send to the Translator Speech API. To send messages to the Translator Speech API, we will create a
translator_future. Depending on the caller, i.e. the person who the message comes from, we will create the
translator_future with the respective language variables so that the API knows from which language to translate into which other language.
A
translator_future is another WebSocket that connects to the Speech Translator API. We use it to pass on the messages we receive from the Nexmo Voice API. After its creation, the
translator_future is stored in the variable
ws and used to send the wave header we created before. Each subsequent message from Nexmo will be a binary message. These binary messages are passed to the Translator Speech API using the
translator_future which processes the audio and returns the transcribed translation.
When we initialize the
translator_future, we state that when the Translator Speech API has processed our message it should call the method
speech_to_translation_completed. This method will, upon receiving a message, check that the message is not empty and then speak the message in the language voice of the receiver of the message. It will only speak the message for the other caller, not for the person who initially spoke. Additionally, we will print the translation to the terminal.
Replace the
WSHandler from the template with this code:
class WSHandler(websocket.WebSocketHandler): whoami = None def open(self): print("Websocket Call Connected") def translator_future(self, translate_from, translate_to): uri = "wss://dev.microsofttranslator.com/speech/translate?from={0}&to={1}&api-version=1.0".format(translate_from[:2], translate_to) request = httpclient.HTTPRequest(uri, headers={ 'Authorization': 'Bearer ' + azure_auth_client.get_access_token(), }) return websocket.websocket_connect(request, on_message_callback=self.speech_to_translation_completed) def speech_to_translation_completed(self, new_message): if new_message == None: print("Got None Message") return msg = json.loads(new_message) if msg['translation'] != '': print("Translated: " + "'" + msg['recognition'] + "' -> '" + msg['translation'] + "'") for key, value in conversation_id_by_phone_number.iteritems(): if key != self.whoami and value != None: if self.whoami == CALLER: speak(call_id_by_conversation_id[value], msg['translation'], VOICE2) else: speak(call_id_by_conversation_id[value], msg['translation'], VOICE1) @gen.coroutine def on_message(self, message): if type(message) == str: ws = yield self.ws_future ws.write_message(message, binary=True) else: message = json.loads(message) self.whoami = message['whoami'] print("Sending wav header") header = make_wave_header(16000) if self.whoami == CALLER: self.ws_future = self.translator_future(LANGUAGE1, LANGUAGE2) else: self.ws_future = self.translator_future(LANGUAGE2, LANGUAGE1) ws = yield self.ws_future ws.write_message(header, binary=True) @gen.coroutine def on_close(self): print("Websocket Call Disconnected")
In the above we use a function called
make_wave_header to create the header that the Translator Speech API expects. The code used to create a WAV header was copied from the Python-Speech-Translate project and is reproduced below.
Copy the
make_wave_header function to the end of your
main.py file:
def make_wave_header(frame_rate): """ Generate WAV header that precedes actual audio data sent to the speech translation service. :param frame_rate: Sampling frequency (8000 for 8kHz or 16000 for 16kHz). :return: binary string """ if frame_rate not in [8000, 16000]: raise ValueError("Sampling frequency, frame_rate, should be 8000 or 16000.") nchannels = 1 bytes_per_sample = 2 output = StringIO.StringIO() output.write('RIFF') output.write(struct.pack('<L', 0)) output.write('WAVE') output.write('fmt ') output.write(struct.pack('<L', 18)) output.write(struct.pack('<H', 0x0001)) output.write(struct.pack('<H', nchannels)) output.write(struct.pack('<L', frame_rate)) output.write(struct.pack('<L', frame_rate * nchannels * bytes_per_sample)) output.write(struct.pack('<H', nchannels * bytes_per_sample)) output.write(struct.pack('<H', bytes_per_sample * 8)) output.write(struct.pack('<H', 0)) output.write('data') output.write(struct.pack('<L', 0)) data = output.getvalue() output.close() return data
Lastly, the
speak function used above is a simple wrapper around the
nexmo_client method
send_speech. As you can see below, it will print some information that may be useful to you when running the code and then use the Nexmo API to instruct Nexmo to speak a given
text with a given
voice_name.
Copy the
speak function below to the end of your
main.py file.
def speak(uuid, text, vn): print("speaking to: " + uuid + " " + text) response = nexmo_client.send_speech(uuid, text=text, voice_name=vn) print(response)
Conclusion
If you followed along, you have now successfully built your own Babel fish! If you haven’t followed along you can find the final code here.
Run it by typing
python main.py into your terminal. Now team up with a fellow human (or use two phones) and call your Nexmo number from two lines. You should hear your welcome message and then be able to talk to each other in your two chosen languages.
Let us recap: We began by setting up our environment, as well as our Nexmo Application and the Microsoft Translator Speech API. Then, we built our Tornado WebServer which allowed us to use WebSockets to handle voice calls and pass the speech of the voice call on to the Translator Speech API. The API then translates and transcribes the speech for us. Upon receiving the result, we spoke the message in the new language. Our service handles bi-directional calls due to our routing logic which means that our service will, after connecting two callers, translate either person’s speech before relaying it, thus enabling them to communicate in their chosen languages. And there we have it! Our working Babel fish! I'm afraid our DIY babel fish does not look quite as endearing as the one from the movie but it is a working alternative.
If you have any questions, please reach out on @naomi_pen or find me on naomi.codes.
Where Next?
If you’re interested in exploring this further why not implement logic that allows users to choose languages at the beginning of the call. Such logic might also remove the necessity for hard coding our primary phone number. For a fun project you could also explore making this work for conference calls and creating transcripts for each call. Lastly, I would expect that you might want to work on the security of your service and not let random people call your service. You could achieve this by only letting a certain number (or multiple) use your service and having logic to initiate a second leg of the call from within the call to allow you to invite other users without giving them the privilege of using your Babel fish service. I would love to hear what you build on Twitter @naomi_pen!
|
https://developer.vonage.com/blog/2018/03/14/speech-voice-translation-microsoft-dr
|
CC-MAIN-2022-27
|
refinedweb
| 3,696
| 57.16
|
I would like for my class to randomly choose one script from an array of scripts and enable it.
Background: I have a Chase class for my monster, and within the class I reference to external movement scripts: a Jump and a Strafe. I don't want these movement scripts to fire at the same time, so I figure I should set up an array, and then randomly choose one to be enabled. Once the script is run, a bool turns it off and we go back to the Chase script to randomly choose another move. In this way, the moves are random and cycled.
Is it possible to store myScript.enabled = true; commands in an array? Is there a better way to randomly choose between turning on one of many scripts?
Answer by Koyemsi
·
May 05, 2018 at 02:19 PM
I think it would be better to have all these behaviors in a unique script.
I would do something like this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomBehaviour : MonoBehaviour {
public enum EnemyBehaviour {
Sleeping,
Jumping,
Strafing
}
public EnemyBehaviour enemyWillBehave;
int enumCount;
float changeDelay = 1.0f;
void Start () {
enumCount = System.Enum.GetValues (typeof(EnemyBehaviour)).Length;
StartCoroutine (ChangeBehaviour ());
}
void Strafe () {
// strafing code
}
void Jump () {
// jumping code
}
IEnumerator ChangeBehaviour () {
enemyWillBehave = (EnemyBehaviour)Random.Range (0, enumCount);// randomize behaviour
print (enemyWillBehave);
switch (enemyWillBehave) {
case EnemyBehaviour.Sleeping:
// do whatever
break;
case EnemyBehaviour.Jumping:
Jump ();
break;
case EnemyBehaviour.Strafing:
Strafe ();
break;
}
yield return new WaitForSeconds (changeDelay);
StartCoroutine (ChangeBehaviour ());
}
}
Thanks much for taking the time to answer.
This involves changing my structure, but it looks so much more elegant.
I'll try to test it out some time this week and then get back with the results
You're welcome, glad if I could help.
My solution might be one among others, as there are often several ways to solve a problem. Let me know how things go.
I've tried out an adapted version of the code above, and it's throwing a null reference exception: NullReferenceException UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/MonoBehaviourBindings.gen.cs:62)
I understand that null reference exception means that I'm asking the script to find/ use something that's not there. However, I don't understand what isn't there from this error message.
I didn't copy your script exactly. Since my Chase class is so long, I'll be keeping each move in a separate script. I moved the MyScript.enabled = true command into the "Jump" and "Strafe" functions above.
I also took out the changeDelay and restart coroutine at the end, because I only want it to fire once.
Other than that, it's almost exactly the same. I hesitate to post the script because it's quite long, but I will try to give you some context:
Declarations:
private readonly NBStatePatternEnemy enemy;
private float chaseTimer;
public float jumpSpeed;
public float forwardSpeed;
public enum NBMoves
{
Jumping,
Skittering
}
public NBMoves nBMoves;
int enumCount;
Getting the enum length:
public void Start()
{
enumCount = System.Enum.GetValues (typeof(NBMoves)).Length;
}
Coroutine fires when the enemy sees the player at a certain distance:
RaycastHit hit;
if (Physics.Raycast(enemy.eyes.transform.position, enemy.eyes.transform.forward, out hit, enemy.sightRange) && hit.collider.CompareTag("Player") && hit.distance <= 18.0f)
StartCoroutine (ChangeMove ());
And here's the coroutine:
IEnumerator ChangeMove()
{
nBMoves = (NBMoves)Random.Range(0, enumCount);
print(nBMoves);
switch (nBMoves)
{
case NBMoves.Jumping:
InitializeJump();
break;
case NBMoves.Skittering:
InitializeSkitter();
break;
}
yield break;
}
you can't "yield break".
Replace "StartCoroutine(ChangeMove());" with ChangeMove's body
Hi. I'm not sure of what's going on, but @iljuan is right, yield break is not good.
I think you should replace this by yield return null;
yield return null;
No!! Don't do that! D:, IEnumerator doesn't work like that.
An IEnumerator is used to run Coroutines, which are basically virtual Threads ran in the same Thread. You use an IEnumerator when you want to execute something outside from your current stack, so that operation doesn't freezes your current process.
In Unity, "yield" should be always followed by "return new Wait..." (i.e, WaitUntilEndOfFrame(), WaitForSeconds(.1f), WaitFixedUpdate())
Anyways, given the case, you don't need a IEnumerator, there's no reason on using it. You were using it to create a Timer, now he isn't using that Timer anymore, so there's no reason at all to use that IEnumerator (what's even more, the code won't work with that IEnumerator there).
Just delete "ChangeMove()" method and copy it's content replacing "StartCoroutine (ChangeMove ());"
Thanks, all.
If I may sum up the lessons for anyone who finds this page:
You can randomize a SWITCH command if you want to have your script choose other scripts to enable/disable randomly.
That SWITCH command can be in a regular old function, or in a coroutine if you need it to repeat on a timer.
The way to get out of a switch without a WaitForSeconds call is simply yield return null;.
Summing up for the other users is a really nice intention.
But I think your summary has incorrect points (especially the 3rd one) which need to be corrected or reformulated.
You don't "get out of a switch()". You could say at most that you get out of the case statements within the switch (and this is done with a break instruction).
switch()
case
break
You probably meant that yield return null was a way to get out of a IEnumerator (a coroutine) ; this is better, even if I'm not sure this is the exact way to understand the yield concept.
yield return null
IEnumerator
Anyway, let's retain that.
Disable all components but 1 on a gameobject
1
Answer
How can I enable/disable an array of components?
2
Answers
Why can't i use these arrays to access positions and objects properties? Please help!
3
Answers
Access Animations array in Animation component
1
Answer
1
Answer
|
https://answers.unity.com/questions/1502269/randomize-which-script-is-enabled.html
|
CC-MAIN-2020-10
|
refinedweb
| 998
| 56.86
|
At 1:15 AM -0400 4/17/07, Michael Kabot wrote: > I'll have to go back and pull out my notes on how I got Plesk, Mailman, & > Qmail to work together. I know out of the box that unlike Cpanel/Mailman, > Plesk/Mailman is limited to a single namespace for list names across virtual > domains. So far as I know, Plesk doesn't make any source-code level modifications to the Python and Mailman code that they ship as part of their product. They just tend to be horribly, horribly out-of-date, and it's very difficult to bring things up-to-date and still keep them working properly. -- Brad Knowles <brad at shub-internet.org>, Consultant & Author LinkedIn Profile: <> Slides from Invited Talks: <>
|
https://mail.python.org/pipermail/mailman-users/2007-April/056631.html
|
CC-MAIN-2020-16
|
refinedweb
| 126
| 69.62
|
NAMEsgetmask, ssetmask - manipulation of signal mask (obsolete)
SYNOPSIS
#include <sys/syscall.h> /* Definition of SYS_* constants */ #include <unistd.h>
long syscall(SYS_sgetmask, void); long syscall(SYS_ssetmask, long newmask);
Note: glibc provides no wrappers for these functions, necessitating the use of syscall(2)..
VERSIONSSince Linux 3.16, support for these system calls is optional, depending on whether the kernel was built with the CONFIG_SGETMASK_SYSCALL option.
CONFORMING TOThese system calls are Linux-specific.
NOTESThese system calls are unaware of signal numbers greater than 31 (i.e., real-time signals).
These system calls do not exist on x86-64.
It is not possible to block SIGSTOP or SIGKILL.
|
https://man.archlinux.org/man/sgetmask.2.en
|
CC-MAIN-2022-21
|
refinedweb
| 105
| 52.46
|
Today we’re going to take a look at writing scripts for the Greasemonkey add-on for Firefox. This add-on allows us to use JavaScript to make changes to the way webpages are displayed on our browser. These changes can only be seen by a copy of Firefox that is running a particular script. As an example, we’re going to write a script that adds a border to the banner image of each article on Hack a Day by overlaying the image you see above. Find out how it’s done after the break.
Our Goal:
We want to make the top image for each article look like it has been printed with a white border and then taped on each corner to the page. This is an effect that we used to use on our posts and a Greasemonkey script is a good way to re-implement the effect if you miss that image style.
What You Need:
- Install Firefox
- Install the Greasemonkey add-on.
- Download and install our script: hackaday_nostalgia.user.js
How It Works:
Greasemonkey runs JavaScript on top of the pages that have been loaded by Firefox. The first part of the file is a set of comments that tell Greasemonkey what it’s dealing with:
// ==UserScript==
// @name Hackaday Nostalgia
// @namespace
// @description Overlay photograph border and taped corners for article images at Hack a Day.
// @include*
// ==/UserScript==
The name, namespace, and include lines are all required for the script to work. Name is what you want to call your script. Namespace is a URL that identifies the script uniquely in case there are two scripts with the same name. Include tells Greasemonkey what pages this script should be applied to. In our case we only want to monkey with the images on hackaday.com so we’ve included all addresses from that domain.
Now that we’ve identified what pages we want to alter, we can parse the document and pull out the elements we want ot change. The first thing to do is examine the page source of our target:
<div class='snap_preview'><p><img class="alignnone size-full wp-image-17747" title="plotter-with-300w-laser" src="" alt="plotter-with-300w-laser" width="470" height="313" /></p>
With a little digging we can find the line you see above that includes the IMG element for the title of a post. We’re in luck, the page builds each post wrapped in a DIV of the Class ‘snap-preview’. We can use Greasemonkey to parse the page looking for these DIVs and then alter the first IMG element in each one:
//get all DIVs of the snap_preview class var allDivs, thisDiv; allDivs = document.evaluate( "//div[@class='snap_preview']", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
In the code above we are using the evaluate function to pick out DIVs that are in the ‘snap-preview’ class. We load them into an array called allDivs which we can then step through:
//step through each DIV for (var i=0; i<allDivs.snapshotLength; i++) { thisDiv = allDivs.snapshotItem(i); //Alter the first img of each DIV var image = thisDiv.getElementsByTagName('img'); //Make sure we've got an IMG in this DIV if (image[0]) { //Save original source URL var orig_src = image[0].src; //Concatenate for CSS use orig_src = 'url(' + orig_src + ')'; //Set original as background image[0].style.background = orig_src; //Set Hack a Day overlay as image image[0].src = ''; } }
This block of code is where the magic happens. A loop is used to step through each DIV we grabbed in the previous code snippet. We grab the IMG element by using the getElementsByTagName function. All IMG elements are put into an array called ‘image’, but we only want to alter the first image in each post so we’ll always reference image[0].
For the image border and tape effect, we used the GIMP to create a PNG file that has transparency where we want the original picture to show through. We need the original picture to be behind the overlay so we’re making it a background image using the CSS property ‘background’. The PNG overlay is then set as the new SRC for the IMG element.
That’s all it takes, now images will be overlayed with the border image you see at the top of this post.
Benefits and Drawbacks:
There are some drawbacks to using this system; the overlay covers up the borders of the original image, older posts that already have this image effect will have it applied again, the overlay will be stretched to match each original image which can look weird depending on image height, and the overlay image we’ve provide is of rather low quality (you can probably do better yourself).
Our method uses a very small amount of code and doesn’t require the original image size to be recalculated.
The Next Step:
Now that we’ve showed you how to do this much, you may want to take it one step further. The original picture style also made the images black and white. Can you make the script do this as well? To get started in the right direction, you might want to look at the Pixastic JavaScript image manipulation library (site dead, try Internet Archive version and the GitHub repo) and its desaturate function.
Overwhelmed?
If you need some help deciphering what we did here just use your online resources:
- Dive into Greasemonkey: An online book to help you learn greasemonkey scripting
- HTML Dog: A best practices guide to HTML and CSS
26 thoughts on “How To Overlay Images By Using Greasemonkey”
Anyone know a plugin or extension that blocks cross domain content and CSS z-order? I can’t stand the new ad systems that replaced popups.
Opera allows you to click and block images from web pages. Opera also has the functionality to change how the website is displayed locally. For example, I chose black and white, and now all the pages I view in Opera have a black background with white text. Makes surfing the web much easier on the eyes.
chris, internet explorer and all older web browsers do this since the dawn of the internet LOL
the color part I meant
If you’ve got Firefox, get the Ghostery add-on. It removes everything, so to speak. It even cuts out the ad at the top of the hackaday site. It also usually makes some ads blank, ie the section is still there, but the content is gone.
tj,
the “Remove it Permanently” addon for firefox works great for what you are trying to do.. you just have to set it up the first time you encounter something you don’t want to see, and its gone for good… a little learning curve, but spend a few minutes playing with it, and you’ll understand.
@tj
Get noscript for the XSS & Javascript/DHTML ads (it can also replace active content such as flash with placeholder which you click to trigger the content)
As for ads, just get Adblock Plus. The subscription (at least the US one) has filter rules for most CSS-based ads.
Like red9987, I also recommend Remove It Permanently.
Why’d Hackaday remove that effect? I kinda liked it; it made the page more distinctive..
I might see this if I didn’t have AdBlocker+ killing them off…
Run a 64-bit browser, nothing works in those d8)
Well, that’s not true, but, there’s no flash support for non-linux on 64-bit right now, and to be honest I don’t really miss the flash since 99% of the time it’s for ads.
For the rest AdBlockPro as previously recommended and NoScript to have javascript off by default.
I liked the b/w images too..
any way to apply a filter to have this back too?
This is the most extreeme overkill i’ve ever seen!!
It could be done with arround 10 lines of CSS and work on all browsers :S
@Znegl
cool story bro, but you can’t do image manipulation like this in CSS unless you pre-render the effects and use something like mouseover image replacement/overlay
these effects are being applied dynamically
Why are you looping?
Unless I’m misunderstanding how greasemonkey works, doesn’t it just run your script against the current page?
In that case, nix the loop, make sure the image exists, and do the mods. You may not even need to check for an existing image, depends on greasemonkey functionality. Also might be able to nix the array, but not a huge issue.
@ReKlipz: Some stories don’t have an IMG element because they use embedded video at the top. That’s the reason to check to make sure we’ve captured the right element.
I looped because that’s how I wrote it. Optimization suggestions are always welcomed.
You can get rid of the need to loop at all by changing the xPath criteria to “//div[@class=’snap_preview’] //img” .
I’ve stated this in the comment too, but it looks for IMG tags that have a DIV parent of the ‘snap_preview’ class — this removes the need to grab them via a loop because the javascript.evaluate() is doing the hard work for you..
(note: consider this code as untested / provided ‘as-is’.. it might work / it might not — i’m too lazy to properly test it =P )
@octel But you don’t have to do image manipulation.. Just lay a transparent png with a border on top of the original image – no-one will ever notis.. (unless they try to download the picture). After all it seems wrong to make something that only works in FF with a special plugin installed..
I have an IPB based forum, and we removed the admin console link and changed the adcon directory. We use greasemonkey to reinsert the admin console link so to the admins, it looks as if nothing has changed, so to anybody else, it’s a real bitch to try and type in the directory name of random characters, if you don’t know what you’re looking for.
@Znegl
You’re conflating Greasemonkey with the Pixastic JS library.
Yes, there might be a way to create a border with CSS only, but that method only works for images of a known size. This border tutorial is just an example of how to use Javascript and traversing the DOM tree. Check out userscripts.org for some really amazing and advanced scripts
Clearly this article is meant to push greasemonkey into your eye, and I approve since I like greasemonkey and it comes in very handy lots of times.
He should have linked to userscripts.org too though as octel mentioned, because that’s where people submit their own creations for greasemonkey and you can peruse what’s available.
HackADay has ads?
I would be inline with moo, HackADay has adds? All I use is NoScript, improves page load times as well. I personally block most scripting, of course NoScript does not block GreaseMonkey scripts as they are implemented via post processing. You may have to disallow a few defaults (i.e. googlesyndication, etc) to remove all unwanted content. GreaseMonkey then can be used to clean up the final result.
Well this is kinda lame… I mean, aren’t you hackers and stuff?
Is it so difficult to:
1. set up a php script that copies the image and transforms it using GD (you know, like imgred but just for you)
2. set up a rewrite rule so that said image can be easily called with or without the border.
3. set your template to automatically transform the image call for the front page but not for the full article.
However there’s a simpler way to achieve this… It’s called CSS.
And if you (out of all people) don’t know how to achieve this without resorting to client side, then everything is lost!
To those who commented on the looping. The loop simply applies the effect to each image. This could’ve been done much easier by using document.getElementsByTagName(‘img’).length to calculate the number of images on the page to know when to end the loop. I’ve used a method like this before with good results. In fact, I’ll leave this here. It’s inline JS that when run via the address bar will replace all images on the page with a mudkip.. becuase… ya know.. I herd u liek mudkipz.
javascript:var num=document.getElementsByTagName(‘img’).length;for(i=0;i<num;i++){void(document.getElementsByTagName('img')[i].src="")}
Enjoy
wtf.. how come when copied from here.. my previous inline js doesnt work.. some sort of formatting error.. but i can’t see a difference in it from the original..
o.O
sorry for the triple post. I’ll just archive the js here. This should work when ran inline.
Please be kind and respectful to help make the comments section excellent. (Comment Policy)
|
https://hackaday.com/2009/10/26/how-to-overlay-images-by-using-greasemonkey/
|
CC-MAIN-2021-25
|
refinedweb
| 2,176
| 71.55
|
0.071 Friday May 28 18:25:31 PDT 2010: - Ad-hoc YUI version upgrade to 2.8.1 (from 2.5.1) - Conversion to dzpl - Applied patches from Martin Holste (rt57820) 0.070 Monday February 23 13:38:23 PST 2009: - Non-development release 0.060_2 Saturday February 21 13:21:57 PST 2009: - Updated "Changes" 0.060_1 Saturday February 21 13:21:57 PST 2009: - Moved out of JS::YUI::Loader namespace 0.060 Wednesday May 28 15:10:29 PDT 2008: - Automatically include the default "sam" skin if an object is skinnable 0.050 Saturday May 03 19:29:07 PDT 2008: - Some documentation tweaks - Changed JS::YUI::Loader::Source::YUIHost to ::Internet to be consistent with JS::jQuery::Loader 0.040 Thursday May 01 21:06:48 PDT 2008: - Moar documentation 0.030 Tuesday April 29 11:57:55 PDT 2008: - Ensure minimum version of 2.08 for JSON.pm 0.020 Monday April 28 18:38:58 PDT 2008: - Disable network testing by default in t/04-cache.t 0.010 Monday April 28 18:34:38 PDT 2008: - Initial release
|
https://metacpan.org/changes/distribution/YUI-Loader
|
CC-MAIN-2015-35
|
refinedweb
| 186
| 60.82
|
This is a rewrite of the original shiftfs code to make use of superblock user namespaces. I've also removed the mappings passed in asmount options in favour of using the mappings in s_user_ns. The upshotis that it probably needs retesting for all the bugs people found,since there's a lot of new code, and the use case has changed. Now, touse it, you have to mark the filesystems you want to be mountableinside a user namespace as root:mount -t shiftfs -o mark <origin> <mark location>The origin should be inaccessible to the unprivileged user, and theaccess to the <mark location> can be controlled by the usual filesystempermissions. Once this is done, any user who can get access to the<mark location> can do (as the local user namespace root):mount -t shiftfs <mark location> <somewhere in my local mount ns>And they will be able to write at their user namespace shifts, but havethe interior view of the uid/gid be what appears on the <origin>In using the s_user_ns, a lot of the code actually simplified, becausenow our credential shifting code simply becomes use the <origin>s_user_ns and the shifted uid/gid. The updated d_real() code fromoverlayfs is also used, so shiftfs now no-longer needs its own fileoperations.---[original blurb]My use case for this is that I run a lot of unprivileged architecturalemulation containers on my system using user namespaces. Details here:'re mostly for building non-x86 stuff (like aarch64 and arm secureboot and mips images). For builds, I have all the environments in myhome directory with downshifted uids; however, sometimes I need to usethem to administer real images that run on systems, meaning the uidsare the usual privileged ones not the downshifted ones. The onlycurrent choice I have is to start the emulation as root so the uid/gidsmatch. The reason for this filesystem is to use my standardunprivileged containers to maintain these images. The way I do this iscrack the image with a loop and then shift the uids before bringing upthe container. I usually loop mount into /var/tmp/images/, so it'sowned by real root there:jarvis:~ # ls -l /var/tmp/images/mips|head -4total 0drwxr-xr-x 1 root root 8192 May 12 08:33 bindrwxr-xr-x 1 root root 6 May 12 08:33 bootdrwxr-xr-x 1 root root 167 May 12 08:33 devsomething similar with gid_map. So I shift mount the mips image withmount and I now see it asjejb@jarvis:~> ls -l containers/mips|head -4total 0drunprivileged container to enter and administer the image.It seems like a lot of container systems need to do something similarwhen they try and provide unprivileged access to standard images. Right at the moment, the security mechanism only allows root in thehost to use this, but it's not impossible to come up with a scheme formarking trees that can safely be shift mounted by unprivileged usernames
|
https://lkml.org/lkml/2017/2/20/653
|
CC-MAIN-2018-34
|
refinedweb
| 491
| 51.31
|
Forum Index
On Monday, 18 October 2021 at 14:39:35 UTC, russhy wrote:
and then you freeze all threads and must scan all allocated pointers whenever your "gc'd malloc"'s buffer needs to grow
An unsolvable problem, clearly, as it is inconceivable that the user could set a heap size.
Don't believe anyone that would tell you this could boils down to a simple call to a function, such as GC.setHeapSize(XXXX), they are clearly manipulating you.
you can't compete with highlevel languages and their sub 1ms incremental GC
Let me tell you a secret. most modern languages use an hybrid approach as the one I described, and even old one have been repurposed to use that when possible (for instance python).
AGAIN
ASP.net team is working hard on reducing the impact of the GC in their library!!!! even thought they have a competitive GC, they are making sure they don't do useless GC allocations and are using Span/stackalloc/ValueTysk everywhere!!
Ho, damn, a hybrid approach that allocates on the stack or the GC and frees instead of leaking. Who could have though of that?
The smart and pragmatic approach is to give tools for people to write efficient software
Allocators is one of them
How the strawman screaming in between you hear doing?
Have we lost our mind focusing on the GC? i think yes
With all due respect, you clearly are not able to address the points made in the discussions you are participating in. It's harsh, but it's true. You shouldn't be making statements about others losing their mind.
On Monday, 18 October 2021 at 15:22:30 UTC, deadalnix wrote:
You miss the point..
What problem are you trying to solve?
I'm trying to solve the problem that we don't encourage people to write their latency sensitive programs in D and instead fallback to C++ (game engines for example), because std isn't built in the idea that they can provide their own allocation schemes
Be pragmatic, please
Can we at least agree that the work on must be resumed and moved out of experimental?
On Monday, 18 October 2021 at 18:12:49 UTC, russhy wrote:
std.experimental is where modules go to die. Nothing ever leaves it.
On Tuesday, 19 October 2021 at 07:02:01 UTC, bauss wrote:
We really should move allocator into normal std namespace though. It will somewhat help us get to parity with Zig, which does this at a language level, I believe.
allocator
std
Zig
On Monday, 11 October 2021 at 15:59:10 UTC, Atila Neves wrote:
Finally got one for D.
Which leads to issues like this:
And also opens up for buffer overflow for anyone using Phobos.
It's by far one of the most serious issue D has had in years.
ASP.net team is working hard on reducing the impact of the GC in their library!
When GC flies out of the window, it shouldn't matter whether it's sub 1ms incremental or what.
I'm brainstorming about what I'll talk about at DConf, and during a conversation with Walter I thought it might be cool to talk about:
Old but still nice:
First thing I notice when I switch from android development: real string interpolation
On Wednesday, 20 October 2021 at 08:17:48 UTC, Andrea Fontana wrote:
This has been worked on several times. The community has trouble agreeing on how it should look / work it seems.
If there's one feature that shows the severe split between "BUT GC", "BUT @NOGC", "BUT EASE OF USE", "BUT POWAH", "BUT PRINTF(For some ungodly reason)", "BUT BUT BUT".
That one is it.
On Wednesday, 20 October 2021 at 08:54:17 UTC, SealabJaster wrote:
Why are many using D using printf to begin with and not the D equivalent like writeln?
|
https://forum.dlang.org/thread/kgyfyujtnzdbrrhuwhvj@forum.dlang.org?page=14#post-uhvhealhniqcuewnqijg:40forum.dlang.org
|
CC-MAIN-2022-40
|
refinedweb
| 654
| 68.91
|
Ticket #9053 (closed defect: obsolete)
FSTENV assembler instruction - wrong implementation
Description (last modified by frank) (diff)
Hi,
I believe VirtualBox has wrong implementation of FSTENV assembler instruction. It is not dumping last float-pointing instruction address correctly. I've created a simple application in assembler which can be used as proof.
Try and debug this application with debugger (OllyDbg for example) and take a look at buffer after the FSTENV instruction. It should contain address of FNOP assembler instruction.
format PE GUI entry main include 'win32a.inc' section '.data' data readable writeable buffer db " ", 0 section '.text' code readable executable main: nop mov eax, buffer fnop fstenv [eax] invoke ExitProcess, 0 section '.idata' import data readable library kernel32, 'KERNEL32.DLL' import kernel32, ExitProcess, 'ExitProcess'
You can compile the example code with FASM.
Change History
comment:2 Changed 5 years ago by fritz
I'm comparing this case with my windows host on which works fine. This is my buffer: 7F 02 FF FF 00 00 FF FF FF FF FF FF 29 FA C4 77 1B 00 7D 07 0C FF 55 01 23 00 FF FF
Instruction pointer is (starting at offset 12) 77C4FA29. It should be 00402006, that's where FNOP is located.
My host is Windows and guest is Windows also.
comment:3 Changed 5 years ago by michaln
I tried the example on Windows host and guest, in both cases I got the expected result. FYI, you don't need any of the Windows API junk for your tiny example, a simple "ret" does the job.
To eliminate the possibility of a debugger interfering, I wrote the following tiny C program - not very portable, but that doesn't matter, it does the job:
#include <stdio.h> #include <fenv.h> int main( void ) { fenv_t fenv; __asm fnop; fegetenv( &fenv ); printf( "Last FP EIP: %08x\n", fenv.ins_ptr_offset ); return( 0 ); }
The program prints something along the lines "Last FP EIP: 00401018" which is the address of the FNOP instruction. The result is identical on my Windows Server 2003 host and inside a Windows XP guest.
The address 0x77C4FA29 looks very much like an address inside a DLL. You should find out what is at that address. My guess is that the debugger you are using is broken and upsets the results. I strongly suggest that rather than using a debugger, you print the last instruction pointer value from the fstenv buffer.
comment:4 Changed 5 years ago by fritz
michaln, thanks for the feedback, I'll do the test and get back at you.
comment:5 Changed 5 years ago by frank
If you can still reproduce this issue, please attach a VBox.log file from such a VM session so we can have a look at the VM configuration.
comment:6 Changed 5 years ago by fritz
michaln, frank, sorry for false alarm. When executed w/o debugger the IP is correct, but when in debugger - it's completely wrong. This is strange because debugger (OllyDbg) works on host OS and on other machines ...
Thanks for the response.
I've tested this with several Linux guests (32-bit guest with/without VT-x, 64-bit guest) and it always worked correctly. Note that the instruction pointer starts at offset 12 of the buffer. Which content has the buffer in your case?
|
https://www.virtualbox.org/ticket/9053
|
CC-MAIN-2016-07
|
refinedweb
| 554
| 64.61
|
Ticket #18737 (closed defect: fixed)
Linux guests: open(filename, O_CREAT|..., mode) fails inside shared folder => fixed in SVN/6.0.x x>10
Description
The following C code produces a simple executable which will attempt to create and open a read only test file in a single operation.
Expected behaviour when run:
- A newly created file called test.txt is created on disk with read only permissions
- A read-write file-handle for the file is returned by the open call
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> int main() { int fd = open("test.txt", O_CREAT | O_EXCL | O_RDWR, 0444); if (fd < 0) { perror("Could not create file: "); return -fd; } return 0; }
When run on other file systems this works correctly but when run on a virtualbox shared folder the file is created correctly but the program exits with the error message:
Could not create file: : Permission denied
This can be bypassed by running the command with sudo, in which case it succeeds normally.
This is not a purely hypothetical problem, since the same error occurs when attempting to use any programme that makes this system call, such as a git clone.
Attachments
Change History
comment:2 Changed 15 months ago by justinsteven
Can confirm this was an issue for me on 6.0.8 and is still an issue on 6.0.10.
- Host: Debian Linux
- Guest: Debian Linux (running Guest Additions 6.0.10)
- Host filesystem: ext4 (mounted rw,relatime,data=ordered)
- Guest: vboxsf volume mounted rw,nodev,relatime,iocharset=utf8,uid=<my_uid>,gid=<my_gid>
OP's reproducer reproduces the issue for me.
I'm also having issues with git repos on a vboxsf volume.
comment:3 Changed 15 months ago by justinsteven
Changed 15 months ago by justinsteven
- attachment poc_18737.py
added
comment:4 Changed 15 months ago by justinsteven
I've written a reproducer in Python and tried all file modes from 0o000 to 0o777 using flags O_CREAT | O_EXCL | O_RDWR.
If I map /home/justin/shared to my VirtualBox guest (mounted as /home/justin/shared within the guest) and place the reproducer in shared/test_file_creation, then the poc runs fine from my host but exhibits failures when run from the guest.
In summary, the following file modes are OK in the guest but everything else fails:
0o0 --------- PASS 0o2 -------w- PASS 0o20 ----w---- PASS 0o22 ----w--w- PASS 0o6** rw-****** PASS 0o7** rwx****** PASS
(Where "*" is of course anything)
Curiously, mode 0o222 fails:
% python3 Python 3.5.3 (default, Sep 27 2018, 17:25:39) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.open("testfile", os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o222) Traceback (most recent call last): File "<stdin>", line 1, in <module> PermissionError: [Errno 13] Permission denied: 'testfile'
I've attached poc_18737.py from which I got the above results.
comment:5 Changed 14 months ago by justinsteven
This still happens with VBoxGuestAdditions_6.0.12-132672.iso
comment:6 Changed 14 months ago by paulson
- Owner set to paulson
- Status changed from new to accepted
- Summary changed from Open system call to create and open read only file fails on shared folder to Linux guests: open(filename, O_CREAT|..., mode) fails inside shared folder
comment:7 follow-up: ↓ 8 Changed 14 months ago by paulson
- Status changed from accepted to closed
- Resolution set to fixed
- Summary changed from Linux guests: open(filename, O_CREAT|..., mode) fails inside shared folder to Linux guests: open(filename, O_CREAT|..., mode) fails inside shared folder => fixed in SVN/6.0.x x>10
This is a regression which was introduced in VirtualBox 6.0.6 and affects Linux guests which have a kernel > 3.16.0 and utilize the atomic_open() filesystem interface. The file creation succeeds but the follow-up call to the Linux kernel routine finish_open() happened without FMODE_CREATED set in the file->f_mode structure element which then erroneously returns EACCES for unprivileged users.
This has been fixed in trunk and the fix has also been backported to VirtualBox 6.0.x (x > 10) and any 6.0.x Testbuilds with a revision >= r132861. This issue doesn't apply to VirtualBox 5.2.x.
comment:8 in reply to: ↑ 7 Changed 14 months ago by socratis
This is a regression which was introduced in VirtualBox 6.0.6 ... This has been fixed ... with a revision >= r132861.
I added the ticket and the fixed revision in the Discuss the 6.0.6 release thread in the forums, thanks @paulson.
comment:9 Changed 14 months ago by justinsteven
The issue is fixed for me using VBoxGuestAdditions_6.0.11-132973.iso on VirtualBox 6.0.10 (Both the Python reproducer, as well as "git clone")
Thanks @paulson
Can confirm that this problem is not present on v6.0.4.
|
https://www.virtualbox.org/ticket/18737
|
CC-MAIN-2020-45
|
refinedweb
| 805
| 64.81
|
How can I convert a PIL Image to a ui.Image?
How can I convert a PIL Image to a ui.Image?
Taken more or less directly from filenav:
try: import cStringIO as StringIO except ImportError: import StringIO import ui def pil_to_ui(img): strio = StringIO.StringIO() img.save(strio, img.format) data = strio.getvalue() strio.close() return ui.Image.from_data(data)
Or...
import ui, io from PIL import Image as ImageP ip = ImageP.open('ionicons-ios7-reload-32') with io.BytesIO() as bIO: ip.save(bIO, ip.format) ui.Button(image = ui.Image.from_data(bIO.getvalue())).present()
Python Tutorial 6.2.1
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
Thanks guys! :D
this code works with the above image, but not with 'Test_Lenna' image.
How can convert a pil image like Lenna into ui.image? Thanks
@jmv38 If you want a
ui.Imagefrom a built-in image, the easiest/fastest would be to just not create a PIL image to start with:
import ui img = ui.Image.named('Test_Lenna') img.show() # ...
@omz thanks, but i know this way, it is not what i want to achieve. Ok let me be more detailed:
A/ i must have an array from numpy that contains an image. i must have this because of fft functions.
B/ i must have a ui image because i want to display my array A and touch it and do actions from the touch. I could use a scene image, but i also want buttons, so i thought i'll have to go through ui anyway, which supports images, and i dont need 60 hz updates, hence my choice not to add another lib on top of it. (maybe wrong choice?).
C/ i want to draw a mask on top of my image, and i assume this mask will be a PIL image, because all drawing functions are there. But i'll have to convert this mask to array to multiply it to A. Note It is a gray scale mask, not binary one.
A,B and C will be updated all the time, so they are not built in images, but computed images.
And i will have 2, maybe 3 such sets of images in the same display.
Due to A,B and C, i will have to convert from one type to the other, and rather efficiently. I though i should not save the Array on disk each time i want to update the ui image, because i assume it will be too slow, but maybe i am wrong.
So to summarize, i expect to use:
PIL -> ui.
ui -> PIL.
array -> ui.
ui -> array.
array -> PIL. (these i found in the docs how to do).
PIL -> array.
If i could avoid all these conversions, i'd love to, but it doesnt seem possible at first sight, if i want to use the built-in libraries. I did not expect that each lib module had its own image format, not compatible with the other ones...
I guess i am not the only one to face that type of question..?
Now if you can suggest a better way to achieve what i want, using only one library module, please let me know, i have no experience in Python. Btw, Pythonista is really fantastic, the possibilty + quality of the whole thing is just .. AWSOME! That is a incredible good job you have done here!
Thanks for your help!
Have you tried using @tony's code, but replacing
ip.formatwith
'PNG'?
i just tried
import ui, io from PIL import Image as ImageP def test(ip): with io.BytesIO() as bIO: ip.save(bIO, 'PNG') ui.Button(image = ui.Image.from_data(bIO.getvalue())).present() ip = ImageP.open('Test_Lenna') #ip = ImageP.open('ionicons-ios7-reload-32') test(ip)
but the result is a big blue square, not lenna color image...
Thanks.
I see... The image is probably alright, it's just that it doesn't work well as a button image. By default, a button only uses the alpha component of an image (which is completely opaque in this case) and tints that with its
tint_color(which is blue by default). This works well with icons, but not so much with photos. To create a button with a full-color image, you have to convert it to an image with "original" rendering mode:
import ui, io from PIL import Image as ImageP def test(ip): with io.BytesIO() as bIO: ip.save(bIO, 'PNG') img = ui.Image.from_data(bIO.getvalue()) img = img.with_rendering_mode(ui.RENDERING_MODE_ORIGINAL) ui.Button(image=img).present() ip = ImageP.open('Test_Lenna') test(ip)
here are the various conversions i have set. Tell me if there is some better code. Thanks.
[edit] modified according to @ccc comment below.
[edit] modified to add functions and tests.
#coding: utf-8 import ui import io from PIL import ImageOps, ImageDraw from PIL import Image import numpy as np import StringIO import console # numpy <=> pil def np2pil(arrayIn): imgOut = Image.fromarray(arrayIn) return imgOut def pil2np(imgIn,arrayOut=None): if arrayOut == None: arrayOut = np.array(imgIn) return arrayOut else: arrayOut[:] = np.array(imgIn) return None # pil <=> ui def pil2ui(imgIn): with io.BytesIO() as bIO: imgIn.save(bIO, 'PNG') imgOut = ui.Image.from_data(bIO.getvalue()) del bIO return imgOut def ui2pil(imgIn): # create a fake png file in memory memoryFile = StringIO.StringIO( imgIn.to_png() ) # this creates the pil image, but does not read the data imgOut = Image.open(memoryFile) # this force the data to be read imgOut.load() # this releases the memory from the png file memoryFile.close() return imgOut # numpy <=> ui def np2ui(arrayIn): # this is a lazy implementation, maybe could be more efficient? return pil2ui( np2pil(arrayIn) ) def ui2np(imgIn): # this is a lazy implementation, maybe could be more efficient? return pil2np( ui2pil(imgIn) ) if __name__ == "__main__": # testing the functions above img = Image.open('Test_Lenna') s = 256 img = img.resize((s, s), Image.BILINEAR) img = ImageOps.grayscale(img) console.clear() print( 'test: open a pil image:') img.show() print('- ') print( 'test: pil image => return a new np array') print(' ') arr = pil2np(img) print(arr) print('- ') print( 'test: pil image => write into existing np array') print(' ') pil2np(img.rotate(90), arr) print(arr) print('- ') print( 'test: np array => return a new pil image') img1 = np2pil(arr) img1.show() # test: pil2ui verification is done via a popover iv = ui.ImageView(frame=(0,0,256,256)) iv.name = 'pil2ui' iv.image = pil2ui(img) iv.present('popover', popover_location=(600,100)) print('- ') print( 'test: ui image => return a new pil image (rotated by -90° to prove pil type)') img2 = ui2pil(iv.image).rotate(-90) print( type(img2)) img2.show() # test: np2ui verification is done via a popover iv2 = ui.ImageView(frame=(0,0,256,256)) iv2.name = 'np2ui' iv2.image = np2ui(arr) iv2.present('popover', popover_location=(300,100)) print('- ') print( 'test: ui image => return a new np array') arr2 = ui2np(iv2.image) print( arr2)
Should
np2pil()always return imgOut?
Should
pil2np()always return arrayOut?
If the
elseclauses are supposed to
return Nonethen you should do that explicitly.
I have updated my code above:
- corrected for a bug.
- added ui -> pil and np conversions.
- Added tests for all functions.
This is certainly not the best code possible,
but i hope it hepls someone.
Thanks.
Helped me! I used your pil2ui(), thanks!
Is there a faster way? I have a user take a picture with the camera, then have it displayed in an ImageView, but it takes a while
Which function above are you using? Can you try wrapping the call to the conversion function in a
with timer():block (or similar) and tell us how long the conversion function takes to execute?
Using the first method with a photos.capture_image(). Strange behavior:
x = Image.open('test.jpg') a = time.time() pil_to_ui(x) b = time.time() print b-a
prints 0.97... but
x = photos.capture_image() a = time.time() pil_to_ui(x) b = time.time() print b-a
prints 6.22...
I don't think this is a resolution difference, they're both about the same size.
Wait, I had changed the
img.formatto PNG to fix an error, JPG makes it take 0.2 seconds. Related to my PNG crash?
one thing that helps, not with speed, but with the problem of
capture_imagereturning, yet the conversion is not yet complete, is to add an ActivityIndicator which starts animating before starting conversion, and stops animation (and removes the indicator ) afterwards. the ActivityIndicator can be added on top of your imageview, or else it can be added to your root view, and sized to the root view, so that it essentially blocks anything else from happening while the processing happens.
on my ipad3, pil2ui takes a second or two for an image captured by the camera... an indicator at least doesn't leave the user wondering if something didn't work right, and prevents you from hitting the capture button again
|
https://forum.omz-software.com/topic/1935/how-can-i-convert-a-pil-image-to-a-ui-image
|
CC-MAIN-2018-43
|
refinedweb
| 1,511
| 67.96
|
import "github.com/goki/gi"
Package gi is the top-level repository for the GoGi GUI framework.
All of the code is in the sub-packages within this repository:
* gi: contains the main 2D GUI code
* gi3d: contains the 3D scenegraph framework, that interoperates seamlessly with the 2D.
* giv: are more complex Views of Go data structures, built out of gi widgets, supporting the Model-View paradigm.
* svg: provides a full SVG rendering framework, used for Icons, and in its own right.
* oswin: is the OS-specific framework, originally based on Shiny, that provides all the gory guts for dealing with different OS's.
* examples: contains a number of useful examples for learning how to use GoGi -- see widgets and its README file for a basic introduction. marbles is really fun!
Package gi is imported by 7 packages. Updated 2019-09-10. Refresh now. Tools for package owners.
|
https://godoc.org/github.com/goki/gi
|
CC-MAIN-2019-39
|
refinedweb
| 148
| 55.95
|
Asked by:
Common DomainService errors and solutions
Whether you're starting from scratch or you're upgrading from the July CTP bits, you may run into a few issues. Hopefully this thread will provide solutions for those issues. If after reading this thread you're still unable to get your service working, please check if a different thread exists for your problem, or post a new thread. We'll help you resolve the problem and add it to this list if it turns out to be a common problem people run into.
Problem 0: You are getting a NotFound error in your Silverlight application.
Silverlight's browser networking stack can only handle responses with status code 200. Any other kind of response will be reported as a 404 NotFound error.
A DomainService will take care of reporting exceptions that happen within our pipeline as responses with status code 200, such that errors are still reported in Silverlight. However, when an error happens outside of our pipeline (e.g. during the activation of a DomainService), we can't report the error within a 200-response.
To see what the problem is, you can usually directly navigate to the DomainService using a browser. If you have a DomainService called HRApp.Web.ProductService hosted at, then try navigating to. (Notice how the dots are replaced with dashes.) If everything is fine, you should get a help page with a link to the WSDL for your service. If something is wrong, you will get an error from ASP.NET with hopefully more details.
Problem 1: WCF is not activated.
RIA services is now built on top of WCF. As a result, we require WCF to be activated on the server. You can activate WCF by going to Add Programs and Features -> turn Windows features on or off -> Microsoft .NET ... -> WCF HTTP activation.
Problem 2: The website is configured to have multiple addresses/host headers.
You can confirm this is what you're running into by navigating to your DomainService (see "problem 0" on how to do that). You should get something related to UriSchemeKeyedCollection and multiple addresses with the same scheme.
We are working on a fix to this problem. In the meantime, you can get your service working with one address by plugging in a custom DomainServiceHostFactory. Note that you will have to do this for every DomainService in your project.();
}
}
}
2. Plug-in the factory to every DomainService. Create an .svc file (using the naming convention as described in "problem 0") and put it in the ~/Services directory of your application. In each .svc file, put:
<%@ ServiceHost Service="<DomainService full type name>" Factory="System.Web.Ria.DomainServiceHostFactoryEx" %>
Problem 3: Access denied/Unable to connect to the SQL server database errors.
When logging in, the AuthenticationService does three things:
1. Get/initialize the user object.
2. Get the roles for the user.
3. Get the profile for the user.
Make sure that in your web.config you either disabled roles/profiles if you don't need it, or otherwise make sure both roles/profiles are configured properly. E.g. if you're using a SQL server DB, you'll want to use the right connection string for both roles and profiles. By default ASP.NET will try to create/use a DB in the App_Data directory, so if you get an error related to access to the App_Data directory, then double check that you've set up all the connection strings properly and use them in all the right places.
Question
All replies
Thank you for offering to fix this "multiple host headers on one website WCF issue". As you know, it has been around for a long time. See:
Microsoft has the best development tooling in the world. The RIA services story is great and promises that we can create LOB applications fast and easy. We need the ability to easily deploy our RIA services application.
Just to confirm, Problem 2 comes from a limitation in WCF 3.5 and before and is fixed in WCF 4 beta 2. The fix that is being worked on for Problem 2 will be an update for WCF 3.5 to allow multiple host headers to be used with http and https bindings?
If the "fix" is to upgrade to WCF 4, that will leave the majority of us stuck until we can migrate our development to VS2010 and .Net 4. Also, the work around will not work for many of us as it simply filters out all of the host headers except the first one. While this prevents the error from occuring in the service it does not allow the service to be referenced from the other host headers (dns entries). This has been a very painful issue for many of us for a long time and has prevented some of us from moving to WCF at all.
Any information on if this fix will work with VS2008 / .Net 3.5 is much appreciated.
Thanks!
Ian am unable to figure what this means. If I simply paste this into a class file I get error such as "A namespace declaration cannot have modifiers or attributes". I am sure thiere is something I am doing wrong but the directions simply say "Add the following class to your project".();
}
}
}
Thank you, but now I get the error:
'System.Array' does not contain a definition for 'GroupBy' and no extension method 'GroupBy' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
make sure you add a using System.Linq; to the top of the class.
Thank you. This is the complete code that compiles:(); } } }
Hi.
I used RIA_Services_Walkthrough 2009. Created HRApp exactly as in tutorial. Everithing works fine when launching from Visual Studio 2008.
But when I press publish on HRApp.Web and try to launch as localhost/HRApp.Web/HRAppTestPage.aspx - i get error Not Found.
I have Windows 2008 Server with IIS 7. WCF Http Activated.
in Problem 0 description you recomend to try
But i haven't see this svc-files in Services folder. Only AuthenticationService.cs, UserRegistrationService.cs which are there by default.
So my question is: what I have to do to work with IIS ?
You are probablly missing the RIA Services dlls on the server side. In the references make sure they are set to copy local. The Not Found error is actually meaningless, the Silverlight networking stack always says that regardless of the actual error. It is important to have Fiddler installed so that you can see the actual error.
There is no actual svc file, the service is setup implicitly at runtime.
Quick question: Would adding this to the config also solve problem 2?
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
Here is the MSDN article about it:
Im trying to fellow this walkthough
But when I try to drag data from the Data Sources window, I found there is nothing but "You project currently has no data source associated with it."
Anyone know how to fix it?
Im using Windows 7 x64+VS2010 Beta2+Silverlight 4 Beta Tools for VS 2010
I tried all the outlined steps as follow:
My server project is WizardRIA.Web
So a created a directory Services and placed my SVC file there<%@ ServiceHost Service="WizardRIA.Web.GreenDomainService" Factory="System.Web.Ria.DomainServiceHostFactoryEx" %>I created a class as instructed then confirmed that this code is being called (break point)and works fine on local server but when I upload to my ISP (DiscountASP) I still get the 404. I am curious as to how the provided code is addressing the problem as it is still returning a collection. DiscountASP has a article that shows the following:
Public class MyServiceHostFactory:ServiceHostFactoryThen of course what is the real problem on the server as I can no longer use WCF trace as it creates a local file that I have no access to
{
protected override ServiceHost CreateServiceHost(Type serviceType,Uri[]baseAddresses)
{
//Specify the exact UR Lof your webservice Uri webServiceAddress=newUri("");
MyServiceHost webServiceHost=new MyServiceHost(serviceType,webServiceAddress);
return webServiceHost;
}
}
public class MyServiceHost:ServiceHost
{
public MyServiceHost(Type serviceType,params Uri[]baseAddresses)
:base(serviceType,baseAddresses)
{}
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
}
}
John. How exactly are you trying to get to your external website.
I've found that if use I get a 404 error, but if I go there using just hillsgate.com then it works fine. I don't know why I cannot use www. (I wish I could work it out because that's how I would like to do it)...
Try it out on your site.
Thank you. This is the complete code that compiles:
However I never got this code to prevent the problem. It compiles but it did not work for me. I had to simply hardcode the URL. I have a working example of my code and the source code at this link:
steyoung : I tried this and no luck , the only way to get the real error on DiscountASP is a WCF Trace which I believe writes to a file or a Event log. I do not think that I can get either from them so sounds like I am stuck. WCF is a powerful framework but it sure complicates what was a simple tool.
I hear you John. It took me three days to get everything running. Getting things updated because of the breaking changes took about an hour and then getting it running on wcf took the remainder of the time Now a lot of that was the good folks at msoft doing their thing with all the error reports coming in from a whole cadre of people, but... it's still 3 days!
Plus there are still some gotchas such as with the .svc files etc but I understand that an update will be coming out to fix this issue we're stumbling over. I'm looking forward to it.
Once it's running it's really cool.
Here are the things I needs to do to get it running.
- Put the .svc files into commission in /Services
- Add WilcoB's code (as defined in this post above)
- Ensure WCF services was enabled at my host
- Add a mime type for .svc in config.sys
- <staticContent>
<mimeMap fileExtension=".svc" mimeType="application/octet-stream" />
</staticContent>
- set copy local on all the Web dlls and ComponentModel.DataAnnotations
- Use and not
- Ensure when I published that the svc files etc all copied
- Changed the website authentication to
- Allow Anonymous Access - true
- Enable Integrated Windows Authentication - false
- Enable Basic Authentication - False
- Ensured asp.net Authentication, Profile & Roles all had providers or were set to be disabled
Once I had all that done, then it worked fine
Steve
Finally I got mine working as there was a couple of issues that were mostly careless mistakes on my part and finally forcing the real problem by typing in the nnnn.svc into the browser which showed me the issue was :
IIS specified authentication schemes 'Basic, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous.
Change the IIS settings so that only a single authentication scheme is used.discount.asp made the change and I am running but what a battle! I alsp noticed that there was a transport level error from Mozilla but I can live with that right now
Sorry I wasn't clear in my list of things to work through (and the system isn't allowing me to edit my post to change it), but when I said change website authentication to:
Allow Anonymous Access to true and the others to false, I intended to say that you could only choose one. If multiple are set, it doesn't seem to work.
I'm not saying that I understand why, I'm just outlining my empirical findings based on trying things for 3 days...
I'm glad you finally got yours running.
Steve
Hello, I tried the solution outlined on Problem 2. It works perfectly on my local machine, but when I upload it to a webserver (Windows Server 2003) I keep getting this error:
This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.I have already created the factory method Factory Class:
Parameter name: item(); } } }
And added the svc file for all the Domain Services on the project:
<%@ ServiceHost Service="Xmas.Web.XmasDomainService" Factory="System.Web.Ria.DomainServiceHostFactoryEx" %>
Questions:
1. I'm used the WCF Service template to create the svc files, is this correct?
2. Is it ok that I created the svc file for the AuthenticationService and UserRegistrationService (which already come with the Silverlight Business App template)?
3. Is there anything I should install on the web server?
- I also get the his collection already contains an address with scheme http.issue and when i modified CreteServiceHost to look at the first address only i started getting the following
steyoung: i am also using softsyshosting. but i am still missing something. As soon as i change authentication to "anonymous only" i start getting 404 when click on my .svc file. thanks
I had to restart my web server to get the new setting to work when I fixed this on my server.
jamolina, it seems that the code in your factory is not being executed for that message is the result of the problem the code is addressing I made sure chnaging my svc file to
<%@ ServiceHost Service="WizardRIA.Web.GreenDomainService" CodeBehind="WizardRIA-Web-GreenDomainService.svc.cs" Factory="System.Web.Ria.DomainServiceHostFactoryEx" %>
and i also changed the svc.cs code toprotected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
}
I then had my ISP disable Basic Authentication on the Web application, so only Anonymous is enabled.
It worked for me hope it does for u
Hi Kilativ. I'm not sure what you mean when you say you click on the .svc file. As I described in my 'steps' posting above, once you have checked through all the steps, the only issue remaining is that you may not be able to access your web site using the www prefix e.g., you may have to use just xyz.com or
Steve
Mine works if I use this:
htp://mydomain.com/Services/myapp-Web-mydomainservice.svc
I assume that you have placed your .svc file in the /Services folder
Try this which is my .svc file
- Thank you very much everybody. Everything does work now! Couple of notes:
I didn't have to do anything to allow WCF or to add mime-types. My guess the hosting company has those by default.
You do need to make sure you have full trust for Entity Framework to work.
I had to create 2 extra .svc files for AuthenticationService and UserRegistrationService so they'd use the same Factory.
Hey jmcfet, thanks a lot for answering. Actually the code was hitting the factory (I checked this debugging on my local computer) but I was still getting the error.
I gave your suggestion a shot, but it keeps happening. Debugging in my computer I noticed that it actually never enters into the CreateServiceHost override on the svc.cs file. I don't know if I did it correctly. Am I suppose to inherit from DomainServiceHostFactoryEx on the svc.cs file? Or what is that method suppose to override?
public class Xmas_Web_AuthenticationService : DomainServiceHostFactoryEx, IXmas_Web_AuthenticationService { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new DomainServiceHost(serviceType, baseAddresses[0]); } #region IXmas_Web_AuthenticationService Members public void DoWork() { } #endregion }
So I am having problem 0. I navigated to the said URL and I got a slightly more helpful ASP.NET message:
"The resource cannot be found. "
OK... maybe not that much more helpful! :)
As for Problem 1, your instructions for "activating WCF" seem to apply to IIS 7 or Server 2008 since I am on Server 2003 / IIS 6.0 and I don't have those options. In any case, I have other WCF apps running on this server just fine so I don't think WCF is the problem?
Problem 2 should be a non-issue on this site as it is only configured for one address. I have fixed this problem in other WCF apps but it shouldn't apply here.
I am in the same boat as others here... everything works just fine locally but as soon as I deploy nothing works any more.
Steps I have taken:
1) Copied all the appropriate .dlls (listed here and elsewhere but I am sure I have all of them)
2) Made sure I am running Full Trust in IIS
3) Made sure my other WCF services are running fine
4) Restarted the app pool and site
5) Navigated to every possible /Services/ URL that I could think of that might make sense given the service name and namespace... nothing works
Fiddler just gives me a 404 but apparently that is meaningless. Given that I can't find the service is seems that I am missing something else but I can't figure out for the life of me what is missing.
Any other suggestions?
Fiddler just gives me a 404 but apparently that is meaningless. Given that I can't find the service is seems that I am missing something else but I can't figure out for the life of me what is missing.
Fiddler showing you a 404 isn't meaningless, it is when Silverlight reports a 404 that it is meaningless. If Fiddler is showing 404 it means either the DomainServiceModule isn't running at all or the DomainServiceModule can't find the DomainService.
Ah, I misunderstood what Wilco was trying to say then. So... I have the following in my web.config:
<modules>
<remove name="ScriptModule" />
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="DomainServiceModule" preCondition="managedHandler" type="System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria,Version=2.0.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
</modules>
And the System.Web.Ria.dll is in the bin directory on the web site so I assume that it is running? What would I be looking for that would indicate that it is not running?
If it is running and can't find the DomainService, what would be some reasons for this given that it apparently can find it in WebDev but not under IIS?
I am trying to access the .svc using the conventions outlined in this post:
Understanding the WCF in ‘WCF RIA Services’
Specifically:
<quote>
[SilverlightApplicationBaseURI] + [DomainServiceFullName].svc (With all “.” replaced by “-“)
So HRApp.Web.OrganizationService is exposed as – http://[ApplicationBaseURI]/HRApp-Web-OrganizationService.svc
</quote>
Although I also tried accessing it at the ~/Services/<DomainService.svc> URL because apparently that is where the redirect is supposed to take place?
In any case, no luck at all finding it...
It is in a RIA Services class library and yes that .dll is in the bin directory on the web site.
I also removed all the DomainServiceModule references from the web.config and added a DomainService to the web site via the Domain Service wizard to let it recreate the web.config lines for me. It did but I still cannot access any of the DomainServices, either the one in the RIA class library or the newly added one in the web site itself.
To reiterate, I *can* see the WCF service that is sitting on the same web site so I know that WCF is working.. just not the RIA WCF.
Are there potential conflicts between an existing WCF service and a RIA WCF that I am not seeing?
In an earlier thread WilcoB had suggested placing this method:
[Invoke(HasSideEffects=false)]
public string Echo() {
var b = OperationContext.Current.Host.Description.Endpoints[0] as WebHttpBinding;
return b.Security.Mode + " - " + b.Security.Transport.ClientCredentialType;
}
In a DomainService and trying to call it. I had done that but with no luck. Just now tried creating a physical .svc file that pointed at this service and the error I got back mystified me but might point to my problem:
"The CLR Type 'System.Web.Ria.DomainServiceHostFactory' could not be loaded during service compilation."
I double checked and the System.Web.Ria.dll IS in the \bin directory and all the version numbers match up. Any thoughts on why it can't load it?
I wish it were that simple! :) All of the .dlls that have been mentioned here and in other posts, along with every .dll that is referenced in any of the projects are available either in the bin or as part of the Framework (2.0, 3.0 and 3.5 are all installed on the server).
I thought about that but removing the WCF services renders the app useless since [Invoke] operations can no longer handle entity types. This was the topic of another thread and it was suggested by some WCF RIA guys that we should move those type of calls outside of the RIA framework and let stand-alone WCF services handle those.
The curious thing is that the entire app runs locally with no problem... it's only when deployed that there is a problem. Spent the entire day yesterday looking for the magic pixie dust that would make it run but still no go! Hopefully I can find the solution before the decision is made to abandon WCF RIA... I am sold but not everyone in management is!
The curious thing is that the entire app runs locally with no problem... it's only when deployed that there is a problem.
Sorry if I'm repeating things you've already tried - I quite possibly missed one of your previous posts...
I had a problem deploying my first app with the new WCF RIA Services bits, even though it ran fine on local IIS.
To trace, I dug into the generated client side service code and found the DomainContext constructor with the hardwired relative URI ...it looked like this:
MyWebApp-Web-MyDomainService.svc
I copied that and in a browser URL bar, appended it to the remote hosting domain:
There I got a semi-useful exception message that indicated what I needed to do to see a detailed exception message (add a simple entry to the <customErrors> section of the web.config). After doing that and browsing to the service URL again, I got a full exception trace and was able to track down the fix quickly. In my case, I had multiple IIS bindings configured for the site -, my.domain.com, etc...
If you don't get anything when browsing directly to the service, then there's not even a valid endpoint running for the service.
Mark, thanks for the reply. I don't have multiple endpoints configured and I have already established that I don't have a valid endpoint running. What I don't know how to do is figure out *why* there are no endpoints running. I have a separate WCF service that is running just fine... just no WCF RIA services running.
I would love to hear from someone knowlegeable about the inner workings of WCF RIA as to what steps I can take to track down the real problem. I know it isn't running... I just don't know why or how I can start tracking down the problem.
Thanks to everyone, what I had to do was actually remove the whole factory thing and add this to my web.config file:
<system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"> <baseAddressPrefixFilters> <add prefix=""/> </baseAddressPrefixFilters> </serviceHostingEnvironment> </system.serviceModel>
Here is a great post by Tim Heuer on troubleshooting RIA Services deployment:
Hosting RIA services on shared hosting environment and without changing anything on IIS or RIA code. Just few lines in your web.config...yes it is possible.. check yourself at url :
Cheers
Rajneesh Noonia
If url/link misbehaves please check on
- Jamolina: i think this is the best solution. No code changes, no workarounds like taking the first element in the collection. Just configuration. It works, i just tried it. Also made it easier for me to setup a second domain pointer to my app. Thanks for posting this.
Out of curiosity... has anyone else been able to get WCF RIA to work using a Web Deployment Project? After 2 days of fruitless searching and consistenly getting a 404 where a service should have been, I used Publish instead of Deploy and presto... everything worked.
Any chance it's just a fluke on my dev box or is this really a gaping hole in the WCF RIA story?
FWIW, I am hoping the SL / WCF RIA teams understand how important a smooth deploy process is for SL adoption.
A *big* part of our decision to go with SL instead of Flex was that we already had all the tools and processes in place for deploying ASP.NET applications. We didn't want to have the pain of having to shoe-horn a different technology into our current process.
This last week was almost a plug-pulling moment for us and we are already heavily invested in SL / WCF RIA. I know it's beta but it's not a good thing when so many people are having this much trouble just deploying an app.
Cool technology is good. Working technology is better. Cool working technology that you can put to work for you... you can't beat that.
FWIW, I am hoping the SL / WCF RIA teams understand how important a smooth deploy process is for SL adoption.
They do understand that, and it is experiences like your own that will help make sure that the final product has better deployment guidance.
I do find it interesting that simply changing your deployment method fixed the problem. I am not really sure what it means, but it is certainly interesting.
I know it's beta but it's not a good thing when so many people are having this much trouble just deploying an app.
Cool technology is good. Working technology is better. Cool working technology that you can put to work for you... you can't beat that.
I can assure you this has been communicated to the team. The do "get it" and I am confidant they will address the issues.
opps my problems are back as i am again getting 404 and this time I use fiddler and see the following details in addition to the 404:
[EndpointNotFoundException]: There was no channel actively listening at ''. This is often caused by an incorrect address URI. Ensure that the address to which the message is sent matches an address on which a service is listening.
Now my factory code looks like:namespace System.Web.Ria
{public class DomainServiceHostFactoryEx : DomainServiceHostFactory
{
{return new DomainServiceHost(serviceType, FilterAddresses(baseAddresses));
}
I also tried the following as it seemed to be working for a while:
return new DomainServiceHost(serviceType, baseAddresses[0]);
my svc markup is
<%@ ServiceHost Service="WizardRIA.Web.GreenDomainService" CodeBehind="WizardRIA-Web-GreenDomainService.svc.cs" Factory=" System.Web.Ria.DomainServiceHostFactoryEx" %>
of course the solution works fine on my local IIS and am puzzled for an svc extension is being mapped by discountasp so the service should be activated by IIS.
My understanding is the binary is to use WCF Binary encoding on the channel so the calls should be more efficient. Is there something I have to ask my ISP to do let this work?
As an aside working on this problem really shows me how valuable fiddler is as most WCF clients not just SL will mask the real exceptions on the server. But this stuff in its current stage is way to complex and I look forward to seeing the released code.
If this was using a Silverlight client then the /binary is put on automatically. You were probaby getting /binary/binary.
Has anyone had issues deploying to an IIS 6 virtual directory? I have deployed to IIS6 web site entry and the app runs just fine, but if I map the same code to a virtual directory I get 404 errors (in fiddler) when trying to access the "virtual" svc files. Has anyone else seen this type of behavior?
TIA
With the help of Colin (well, Colin deserves all the credits), we've tracked another problem with a solution.
for NotFound issue (problem 0), can you add in there that deploying to a pre-compiled site (side-by-side with a pre-compiled site), WCF RIA does not want to work. No real solution apart from putting things in a different app root.
Thanks.
Hello,
I am very new to SilverLight and have been trying to build a small app to connect to SQL Server 2005. I am able to connect to a standalone MDF file but not to SQL Server. I get the same Not Found error.
When I tried going to the svc file - I got the following message:
The service encountered an error.
An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: System.NullReferenceException: Object reference not set to an instance of an object. at System.ServiceModel.Description.WsdlExporter.WSPolicyAttachmentHelper.InsertPolicy(String key, ServiceDescription policyWsdl, ICollection`1 assertions) at System.ServiceModel.Description.WsdlExporter.WSPolicyAttachmentHelper.AttachPolicy(ServiceEndpoint endpoint, WsdlEndpointConversionContext endpointContext, PolicyConversionContext policyContext) at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName) at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName) System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31)
Can you please elaborate on how to resolve this.
Thanks & Regards
In debug mode, step to (or break on) the code line on which the error occurs. One of the variables in use on that line (unless there is a non steppable function which is generating the error) needs to be initialized before it is used there, i.e. "a b = new a();" or just declared "a b;".
Marc
The solution can not solve my issue
In /Services folder
SilverlightApplication20-Web-ads.svc
<%@ ServiceHost Language="C#" Debug="true" Factory="System.Web.Ria.DomainServiceHostFactoryEx" Service="SilverlightApplication21.Web.Services.SilverlightApplication20_Web_ads" CodeBehind="SilverlightApplication20-Web-ads.svc.cs" %>
DomainServiceHostFactoryEx.cs();
}
}
}
Domain Service file:
namespace SilverlightApplication21.Web
{
[EnableClientAccess]
public class ads : AuthenticationBase<User>
{
// To enable Forms/Windows Authentication for the Web Application,
// edit the appropriate section of web.config file.
}
public class User : UserBase
{
// NOTE: Profile properties can be added here
// To enable profiles, edit the appropriate section of web.config file.
// public string MyProfileProperty { get; set; }
}
}
In client side, code:
WebContext.Current.Authentication.Login("ggg", "ggg!!!1");
Error:Unhandled Error in Silverlight 2 Application load operation failed for query 'Login'.The remote server retuned an error:NotFound.at
System.Windows.Ria.OperationBase.InvokeCompleteAction()
Thanks.
navigate directly to .svc, it is no problem.
details:
You have created a service.
To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:
Hi, I'm "almost there" and lacking "authentication" I think..
I have deployed a WCF RIA Services application in local. I need for it to have windows authentication, so on Web.Config I have:<authentication mode="Windows"/> Then I deploy it to the website and it is not working properly, the site loads perfectly except when it has to call the domainservice, there I get a 200 message but I get no data and no authentication..
If I go to the svc file I can access it and get the wsdl file
Also based on this blog post I have set up a personalized applicationpool with identity set to NetworkService...
I just can't get it authenticated or it to get any data..
And, of course, it works wonderfully in local...
Anybody, any sugerence will be much appreciated.
Thanks!!
<riaControls:DomainDataSource.FilterDescriptors>
<riaControls:FilterDescriptor
</riaControls:DomainDataSource.FilterDescriptors>
I get 'StartsWith' incompatible with operand type 'String' and 'Object'
'Contul' is string returned by a SP (ComplexType) returned as IEnumerable using solution found here but modificated with IEnumerable not IQueryable.
Also there is another question about paging maybe someone knows the answer.
Thank's
Sorin
New link to the article (Hosting Silverlight RIA on shared web space domain) is here on my blog
with sample application and live running demo application.
Hi,
I have tried for few days to configure a Ria application to run on ABYSS web server and I didn't manage.
Are there any other settings that I need to apply for the web server to know how to interpret the requests?
I have created the mime types for silverlight plus the .svc.
I can navigate to authentication domain service but I when I tried to call a function from that application domain I get "Not Found" from web server.(using wireshark)
I can run the application in IIS with no errors.
Also, I have managed to connect to a Polling duplex service hosted by Abyss server but any call to a Domain Service fails with "Not Found"
Maybe someone can give some hints on how to troubleshot this issue.
Kind Regards,
Alexandru.
|
http://social.msdn.microsoft.com/Forums/silverlight/en-US/d15f8787-afcf-47ad-aed1-a848eaa011ec/common-domainservice-errors-and-solutions?forum=silverlightwcf
|
CC-MAIN-2013-48
|
refinedweb
| 5,547
| 56.45
|
:
# bank/lib/account.rb module Bank class Account end end
The bank folder will also contain a bank.rb file with the following minimalist contents:
# bank/bank.rb require_relative 'lib/account' module Bank end
Now let’s flesh out the
Account class. Upon the creation of the account I’d like to be able to set the balance, the owner’s name and gender. The balance should be an optional argument with a default value of
0.
# bank/lib/account.rb module Bank class Account attr_reader :owner, :balance, :gender def initialize(owner:, balance: 0, gender:) @owner = owner @balance = balance @gender = check_gender_validity_for gender end end end:
module Bank class Account VALID_GENDER = %w(male female).freeze # ... private def check_gender_validity_for(gender) VALID_GENDER.include?(gender) ? gender : 'male' end end end
Next add a
credit and
withdraw methods:
module Bank class Account # ... def credit(amount) @balance += amount end def withdraw(amount) raise(WithdrawError, '[ERROR] This account does not have enough money to withdraw!') if balance < amount @balance -= amount end # ... end end:
# bank/lib/errors.rb module Bank class WithdrawError < StandardError end end
Don’t forget to require this file inside the bank.rb:
require_relative 'lib/errors' require_relative 'lib/account' # ...:
module Bank class Account # ... def transfer_to(another_account, amount) puts "[#{Time.now}] Transaction started" begin withdraw(amount) another_account.credit amount rescue WithdrawError => e puts e else puts "#{owner} transferred $#{amount} to #{another_account.owner}" ensure puts "[#{Time.now}] Transaction ended" end end end end
In a real world this process will surely be wrapped in some transaction, so we are simulating it with informational messages. Lastly, it would be nice if we could see some information about the accounts. Let’s create an
info method for that:
module Bank class Account # ... def info "Account's owner: #{owner} (#{gender}). Current balance: $#{balance}." end end end
I am not using
puts here because someone may want to, say, write this information to a file. Alright, the application is finally ready! To be able to see it in action, create a small runner.rb file outside the bank directory:
# runner.rb require_relative 'bank/bank' john_account = Bank::Account.new owner: 'John', balance: 20, gender: 'male' kate_account = Bank::Account.new owner: 'Kate', balance: 15, gender: 'female' puts john_account.info john_account.transfer_to(kate_account, 10) puts john_account.info puts kate_account.info. Get started by installing the gem on your PC:
gem install r18n-desktop
Then require it inside the bank/bank.rb file:
require 'r18n-desktop' # ...
Translations for R18n come in a form of YAML files, which is the same format that I18n uses. There is a difference though: initially all the parameters in your translations are not named but rather numbered:
some_translation: "The values are %1 and %2":
# bank/lib/i18n/en.yml account: info: "Account's owner: %1 (%2). Current balance: $%3."
# bank/lib/i18n/ru.yml account: info: "Владелец счёта: %1 (%2). Текущий баланс: $%3."
These messages have three parameters that we will need to provide later. Before doing that, however, let’s allow users to choose a locale.
Switching Locale
To be able to switch a locale upon the application’s boot, let’s create a separate
LocaleSettings class:
# bank/lib/locale_settings.rb module Bank class LocaleSettings end end
Require this file inside the bank/bank.rb:
require 'r18n-desktop' require_relative 'lib/errors' require_relative 'lib/locale_settings' require_relative 'lib/account' module Bank LocaleSettings.new end:
module Bank class LocaleSettings def initialize puts "Select locale's code:" R18n.from_env 'bank/lib/i18n/' puts R18n.get.available_locales.map(&:code) R18n.get.available_locales.each do |locale| puts "#{locale.title} (#{locale.code})" end end end end):
module Bank class LocaleSettings def initialize # ... R18n.get.available_locales.each do |locale| puts "#{locale.title} (#{locale.code})" end change_locale_to gets.strip.downcase end private def change_locale_to(locale) locale = 'en' unless R18n.get.available_locales.map(&:code).include?(locale) R18n.from_env 'bank/lib/i18n/', locale end end end:
t('account.info')
When using R18n, however, you should write
R18n.get.t.account.info:
R18n.get.t['account.info']
If the requested translation is not found, the error is not raised. Instead, the requested key is being returned:
R18n.get.t.no.translation # => [no.translation]
You may easily provide the default value using the
| method (note that there is only one pipe, which corresponds to this generic method):
R18n.get.t.no.translation | 'no translation!'
The translation itself is not a string but an instance of the
Translation class. For example, you may do the following:
R18n.get.t.no.translation.translated? # => false:
module Bank class Account include R18n::Helpers # ... end end
Let’s translate the string inside the
info method by providing three parameters:
module Bank class Account # ... def info t.account.info(owner, gender, balance) end end end
Simple, isn’t it? Now add translations for the error message:
errors: not_enough_money_for_withdrawal: '[ERROR] This account does not have enough money to withdraw!'
errors: not_enough_money_for_withdrawal: '!'
Utilize it inside the
withdraw method:
module Bank class Account def withdraw(amount) raise(WithdrawError, t.errors.not_enough_money_for_withdrawal) if balance < amount @balance -= amount end end end:
l(Time.now):
l(Date.new(2017, 8, 30), :human) # => 2 days ago:
transaction: started: "[%1] Transaction started" ended: "[%1] Transaction ended"
transaction: started: "[%1] Начало транзакции" ended: "[%1] Окончание транзакции"
Then simply provide localized datetime inside the
transfer_to method:
module Bank class Account def transfer_to(another_account, amount) puts t.transaction.started i18n.locale.strftime Time.now, '%d %B %Y %H:%M:%S' begin withdraw(amount) another_account.credit amount rescue WithdrawError => e puts e else puts "#{owner} transferred $#{i18n.locale.format_integer(amount)} to #{another_account.owner}" ensure puts t.transaction.ended i18n.locale.strftime Time.now, '%d %B %Y %H:%M:%S' end end end end:
cookies: count: !!pl 1: You have one cookie n: You have %1 cookies. Wow!
!!pl part here is the name of the filter defined in the library’s core. There are some other filters available, including
escape_html and
markdown. In order to use this filter, simply perform a translation like we did previously:
t.cookies.count(5) # => You have 5 cookies. Wow!
Note that some languages (Slavic, for instance) have more complex pluralization rules, therefore you might need to provide more data like this:
cookies: count: !!pl 1: У вас одна печенька 2: У вас %1 печеньки n: У вас %1 печенек. Ух ты!
This feature is supported out of the box by the
pluralize method that is redefined for Russian, Polish and some other languages in the following way:
def pluralize(n) if 0 == n 0 elsif 1 == n % 10 and 11 != n % 100 1 elsif 2 <= n % 10 and 4 >= n % 10 and (10 > n % 100 or 20 <= n % 100) 2 else 'n' end end
Check the file that corresponds to your language for more details. In the next example we need to craft a custom filter that will add support for the gender information. First of all, provide translations. For the English language we don’t really care about the owner’s gender:
account: info: "Account's owner: %1 (%2). Current balance: $%3." transfer: !!gender base: "%2 transferred $%4 to %3."
But for Russian we do:
account: info: "Владелец счёта: %1 (%2). Текущий баланс: $%3." transfer: !!gender male: '%2 перевёл %3 $%4' female: '%2 перевела %3 $%4'
You may wonder why the parameters are numbered starting from
2 but I’ll explain it in a moment. Next, employ the
add method inside the
LocaleSettings class:
module Bank class LocaleSettings def initialize # ... R18n::Filters.add('gender', :gender) do |translation, config, user| end # ... end end end:
# ... R18n::Filters.add('gender', :gender) do |translation, config, user| translation.length > 1 ? translation[user.gender] : translation['base'] end
We can utilize this filter inside the
transfer_to:
module Bank class Account def transfer_to(another_account, amount) puts t.transaction.started i18n.locale.strftime Time.now, '%d %B %Y %H:%M:%S' begin withdraw(amount) another_account.credit amount rescue WithdrawError => e puts e else puts t.account.transfer self, owner, another_account.owner, i18n.locale.format_integer(amount) # <==== ensure puts t.transaction.ended i18n.locale.strftime Time.now, '%d %B %Y %H:%M:%S' end end end end:
base: "%2 transferred $%4 to %3."
Another thing you may ask is why do we need the
:gender label when creating the filter? Well, actually we don’t but sometimes it may come in handy. By using this label you can enable, disable, or remove the chosen filter completely:
R18n::Filters.off(:gender) R18n::Filters.on(:gender) R18n::Filters.delete(:gender)!
|
https://phrase.com/blog/posts/translate-ruby-applications-with-r18n-ruby-gem/
|
CC-MAIN-2022-27
|
refinedweb
| 1,394
| 51.44
|
Change history¶
4.9 (2020-11-24)¶
- Support Python 3.9.
- Added a new Session Panel to track ingress and egress changes to a registered ISession interface across a request lifecycle. By default, the panel only operates on accessed sessions via a wrapped loader. Users can activate the Session Panel, via the Toolbar Settings or a per-request cookie, to track the ingress and egress data on all requests.
- Removed "Session" section from Request Vars Panel
- Updated Documentation and Screenshots
- Ensured the Headers panel only operates when a Response object exists, to create better stack traces if other panels encounter errors.
utils.dictreprwill now fallback to a string comparison of the keys if a TypeError is encountered, which can occur under Python3.
- A test was added to check to ensure sorting errors occur under Python3. If the test fails in the future, this workaround may no longer be needed.
- Updated toolbar javascript to better handle multiple user-activated panels.
splitand
joinfunctions now use the same delimiter.
- If the browser supports it, use a "set" to de-duplicate active panels.
- Inline comments on toolbar.js and toolbar.py to alert future developers on the string delimiters and cookie names.
4.8 (2020-10-23)¶
- Added tracking of transactional SQLAlchemy events to provide more insight into database session behavior during a request's lifecycle. See
4.7 (2020-10-22)¶
- Added black, isort, and github actions to the pipeline. Dropped travis-ci.
- Added some extra output to the "Request Vars" panel related to previewing the body contents. See
4.6.1 (2020-02-10)¶
- Fix parser errors when injecting the toolbar into XHTML formatted pages. See
4.6 (2020-01-20)¶
- Show the full URL in the tooltip on the requests panel. See
4.5.2 (2020-01-06)¶
- Stop accessing
request.unauthenticated_useridin preparation for Pyramid 2.0 where it is deprecated.
- Catch a
ValueErrorwhen JSON-serializing SQLA objects for display. See
4.5 (2018-09-09)¶
- Drop Python 3.3 support to align with Pyramid and its EOL.
- Add support for testing on Python 3.7.
- Add a list of engines to the SQLAlchemy panel if queries come from multiple engines. See
- When the toolbar intercepts an exception via
debugtoolbar.intercept_exc = Trueand returns the interactive debugger, it will add
request.exceptionand
request.exc_infoto the request to indicate what exception triggered the response. This helps upstream tweens such as
pyramid_retryto possibly retry the requests. See
- Stop parsing the
request.remote_addrvalue when it contains chain of comma-separated ip-addresses. Reject these values and emit a warning to sanitize the value upstream. See
4.4 (2018-02-19)¶
- Reduce the log output for squashed exceptions and put them at the INFO level so they can be filtered out if desired. See and
4.3.1 (2018-01-28)¶
- Javascript syntax fixes for browsers that don't support trailing commas. See
4.3 (2017-07-14)¶
The logging panel indicator is now color-coded to indicate the severity of the log messages as well as the number of messages at said level. There may be more messages, but the most severe show up in the annotation.
This feature also added a new
nav_subtitle_stylehook to the
DebugPanelAPI for adding a custom CSS class to the subtitle tag.
See
4.2.1 (2017-06-30)¶
- Fix a bug with the logging of squashed exceptions on Python < 3.5. See
4.2 (2017-06-21)¶
This release contains a rewrite of the underlying exception / traceback tracking machinery and fixes regressions caused by the 4.1 release that broke the interactive debugger. See
- Tracebacks are now tied to the per-request toolbar object one-to-one. A request may have only one traceback. Previously they actually stuck around for the entire lifetime of the app instead of being collected by the max_request_history setting.
- The routes for exceptions are standardized to look similar to the SQLA AJAX routes. For example,
/{request_id}/exceptioninstead of
/exception?token=...&tb=...and
/{request_id}/exception/execute/{frame_id}?cmd=...instead of
/exception?token=...&tb=...&frm=...&cmd=....
- Fixed the url generation for the traceback panel link at the bottom of the traceback... it was actually empty previously - it got lost somewhere along the way.
- /favicon.ico is no longer specially handled.. it's just part of
exclude_prefixeslike anything else that you want to exclude.
request.pdtb_historyis available for toolbar requests (mostly AJAX requests or panel rendering).
- Removed the unused history predicate.
- URL generation was broken in the
debugger.jsbut that's fixed now so the execute/source buttons work in tracebacks.
- Drop the license from
LICENSE.txtfor the removed ipaddr module in 4.1. See
4.1 (2017-05-30)¶
- Debug squashed exceptions! If you register an exception view for an exception it will render a response. The toolbar will see the squashed exception and enable the
Tracebacktab in the toolbar and emit a message on the console with the URL. You can then debug the exception while returning the original response to the user. See
- Remove the vendored ipaddr package and use the stdlib ipaddress module on Python 3.3+. On Python < 3.3 the ipaddress module is a dependency from PyPI. This dependency uses environment markers and thus requires pip 8.1.2+. See
- Display a warning if the toolbar is used to display a request that no longer exists. This may be because the app was restarted or the request fell off the end of the
max_request_history. See
- Enable testing on Python 3.6. See
- Drop the link-local suffix off of local interfaces in order to accept requests on them. See
- Headers panel defers its processing to a finished callback. This is best effort of displaying actual headers, since they could be modified by a response callback or another finished callback. See
- Query log inside SQLAlchemy panel does not cause horizontal scrolling anymore, which should improve UX. See
4.0.1 (2017-05-09)¶
- Fix sticky panel functionality that was broken by other cleanup in the 4.0 release. See
4.0 (2017-05-03)¶
- The config settings
debugtoolbar.panels,
debugtoolbar.extra_panels,
debugtoolbar.global_panelsand
debugtoolbar.extra_global_panelsnow all accept panel names as defined in
pyramid_debugtoolbar.panels.DebugPanel.name. Thus you may use names such as
performance,
headers, etc. These settings still support the dotted Python path but it is suggested that panels now support being included via
debugtoolbar.includesand
config.add_debugtoolbar_panelinstead such that they are automatically added to the toolbar. See
- Add a new
config.add_debugtoolbar_paneldirective that can be invoked from
includemefunctions included via the
debugtoolbar.includessetting. These panels are automatically added to the default panel list and should become the way to define toolbar panels in the future. See
- Add a new
config.inject_parent_actiondirective that can be invoked from
includemefunctions included via the
debugtoolbar.includessetting. These actions are invoked on the parent config just before it is created such that actions can inspect / wrap existing config. See
- Added "sticky" panel functionality to allow a selected panel to persist across pageviews using cookies. If a cookied panel does not have content available for display, the first non-disabled panel will be displayed. If a cookied panel is not enabled on the toolbar, the first non-disabled panel will be displayed AND will become the new default panel. See
- Added CustomLoggerFactory to javascript, used in the development of PR 272. This javascript factory allows panel developers and maintainers to use verbose console logging during development, partitioned by feature, and silence it for deployment while still leaving the logging lines activated.
- The toolbar registers a
BeforeRendersubscriber in your application to monitor the rendering of templates. Previously it was possible that the toolbar would miss rendering information because of the order in which the subscribers were registered. The toolbar now waits until the application is created and then appends a new subscriber that encapsulates the your application's
BeforeRendersubscribers. See
- Remove duplicate
id="${panel.dom_id}"tags in history tab html. Only the top-level
<li>tag has the id now. See
- Emit a warning and disable the toolbar if the app is being served by a forking / multiprocess wsgi server that sets
environ['wsgi.multiprocess']to
True. This should help avoid confusing issues in certain deployments like gunicorn and uwsgi multiprocess modes. See
- The toolbar tween is always placed explicitly OVER the pyramid_tm tween.
- Refactored all debugtoolbar panels to be included using
config.add_debugtoolbar_paneland per-panel
includemefunctions. See
- Exposed a
request.toolbar_panelsdictionary which can be used from within
DebugPanel.render_contentand
DebugPanel.render_varsin order to introspect and use the data generated by other panels when rendering the panel. See
- Support streaming new requests on Microsoft Edge and Internet Explorer 8+ by using a Server-Sent-Events polyfill. See
3.0.5 (2016-11-1)¶
- Change static toolbar asset to accommodate color blindness. See
3.0.3 (2016-07-26)¶
- Fix another regression where the toolbar was modifying requests to the toolbar itself such that the
script_nameand
path_infowere different after handling the request than before. See
3.0.2 (2016-07-02)¶
- Fix a regression with inspecting requests with a session that is loaded before the toolbar executes. See
3.0.1 (2016-05-20)¶
- Avoid touching
request.unauthenticated_userid,
request.authenticated_useridand
request.effective_principalsunless they are accessed by the user in the normal request lifecycle. This avoids some issues where unauthenticated requests could trigger side effects on your authentication policy or access the properties outside of the expected lifecycle of the properties. See
3.0 (2016-04-23)¶
The toolbar is now a completely standalone application running inside the tween. There are several minor incompatibilities and improvements related to this extra isolation:
pyramid_makoand the
.dbtmakorenderer are no longer included in the parent application (your app).
- Panels must be extra careful now that they only render templates inside of the
render_varsand
render_contentfunctions. These are the only functions in which the
requestobject is for rendering the toolbar panel.
- The toolbar will not be affected by any global security policies your application may put in place other than via
config.set_debugtoolbar_request_authorization. never run the toolbar in production
See
Updated Bootstrap to v3.3.6, refactored static assets and dropped require.js. Each page now depends on what it needs without extra dependencies included in the debugger pages. See
Enabled interactive tablesorting on table columns. See
setuptools-git is now required to install the codebase in non-editable mode.
2.5 (2016-04-20)¶
- Drop Python 2.6 and Python 3.2 support.
- Add Python 3.5 support.
- Remove inline javascript from injected pages to work better with any Content Security Policy that may be in place. See
- Added the packages' .location to the "Versions" panel so developers can tell which version of each package is actually being used. See
- Upon exception do a better job guessing the charset of the sourcefile when reading it in to display tracebacks. See
- Removed jQuery code in the toolbar referring to a DOM node called 'myTab', which doesn't seem to exist anymore. See
- Updated the "Request Vars" panel: 1. Show additional values that were previously missing 2. Sections upgraded to link to Pyramid Documentation when possible 3. Mako reformatted into "defs" for simpler reorganization in the future See
- Fix to prevent the toolbar from loading the session until it is actually accessed by the user. This avoids unnecessary parsing of the session object as well as waiting to parse it until later in the request which may meet more expectations of the session factory. See
2.4.2 (2015-10-28)¶
- Fix a long-standing bug in which log messages were not rendered until the end of the response. By this time the arguments passed to the logger may no longer be valid (such as SQLAlchemy managed objects) and you would see a
DetachedInstanceError. See
2.4.1 (2015-08-12)¶
- Remove the extra query hash constructed when indexing into SQL queries via url as it was unused after releasing 2.4. See
2.4 (2015-06-04)¶
This release changes some details of the panel API, so if you are writing any custom panels for the toolbar please review the changes.
- Document the cookie used to activate panels on a per-request basis. It is possible to specify the cookie per-request to turn on certain panels. This is used by default in the browser, but may also be used on a per-request basis by curl or other http APIs.
- Add new
debugtoolbar.active_panelssetting which can specify certain panels to be always active.
- Modify
DebugPanel.nameto be a valid python identifier, used for settings and lookup.
- The toolbar no longer will clobber the
request.idproperty. It now namespaces its usage as
request.pdtb_id, freeing up
request.idfor applications.
- Add a lock icon next to the request method in the sidebar if the request was accessed over https. See
- Update to bootstrap 3.1.1. See
- Fix display of POST variables where the same key is used multiple times. See
- Fix auth callback so it protects the toolbar views. Auth system is tested now. See
- Convert SQLAlchemy views to obtain the query and params internally; this allows executing queries with parameters that are not serializable. See
- Adds Pyramid version tests and bumps required Pyramid version to 1.4. The pyramid_mako dependency requires 1.3, but debugtoolbar also uses
invoke_subrequestwhich was added in 1.4. The
invoke_subrequestcall was added in pyramid_debugtoolbar 2.0; if you need Pyramid 1.3 compatibility, try an older version. See and
2.3 (2015-01-05)¶
- Support a
debugtoolbar.includessetting which will allow addons to extend the toolbar's internal Pyramid application with custom logic. See
- Fixed an issue when the toolbar is not mounted at the root of the domain. See
- Fixed an issue where the button_css was not pulled from the settings. Added support for configurable max_request_history and max_visible_requests. See
2.2.1 (2014-11-09)¶
- Several internal links were not relative causing them to fail when the app is mounted at a path prefix. See and
- Pin pygments<2 on 3.2 as the new release has dropped support.
2.2 (2014-08-12)¶
- Avoid polluting user code with unnecessary toolbar css just to show the button. See
- Inject the toolbar button into
application/xhtml+xmlrequests. See
- Make the toolbar accessible before another request has been served by the application. See
2.1 (2014-05-22)¶
-API to allow developers to create their own panels.
- Add new
debugtoolbar.extra_panelsand
debugtoolbar.extra_global_panelsconfiguration settings to make it simpler to support custom panels without overwriting the default panels.
2.0 (2014-02-12)¶
The toolbar has undergone a major refactoring to mitigate the effects of the toolbar's internal behavior on the application to which it is connected and make it possible to inspect arbitrary requests. It is now available at
/_debug_toolbar.7 (2013-08-29)¶
-instead)¶
- Packaging release only, no code changes. 1.0.5 was a brownbag release due to missing directories in the tarball.
1.0.5 (2013-04-17)¶
-)¶
- Add a
debugtoolbar.excluded_prefixessetting.from)¶
- The
valid_hostcustom)¶ (2012-03-17)¶
- Don't URL-quote SQL parameters on SQLAlchemy panel.
- Allow hostmask values as
debugtoolbar.hostsentries (e.g.
192.168.1.0/24).
0.9.9.1 (2012-02-22)¶
- When used with Pyramid 1.3a9+, views, routes, and other registrations made by
pyramid_debugtoolbaritself will not show up in the introspectables panel.
0.9.9 (2012-02-19)¶
-extension.
0.9.8 (2012-01-09)¶
- Show request headers instead of mistakenly showing environ values in Headers panel under "Request Headers". This also fixes a potential UnicodeDecodeError.
- Set content_length on response object when we regenerate app_iter while replacing original content.
0.9.7 (2011-12-09)¶
- The performance panel of the debugtoolbar used a variable named
function_callswhich was not initialised when stats are not collected. This caused a
NameErrorwhen mako rendered the template with the
strict_undefinedoption.
- Fix Python 3 compatibility in SQLAlchemy panel.
- Make SQLAlchemy explain and select work again.
0.9.6 (2011-12-09)¶
-)¶
- Adjust tox setup to test older Pyramid and WebOb branches under 2.5.
- Convert all templates to Mako.
- Don't rely on
pyramid.compat.json.
- Add Tweens toolbar panel.
0.9.4 (2011-09-28)¶
-)¶
- All debug toolbar panels and underlying views are now always executable by entirely anonymous users, regardless of the default permission that may be in effect (use the
NO_PERMISSION_REQUIREDpermission)¶
- Log an exception body to the debug toolbar logger when an exception happens.
- Don't reset the root logger level to NOTSET in the logging panel (changes console logging output to sanity again).
0.9.1 (2011-08-30)¶
- The
debugtoolbar.intercept_excsetting is now a tri-state setting. It can be one of
debug,
displayor
false.
debugmeans show the pretty traceback page with debugging controls.
displaymeans show the pretty traceback package but omit the debugging controls.
falsemeans don't show the pretty traceback page. For backwards compatibility purposes,
truemeans
debug.
- A URL is now logged to the console for each exception when
debugtoolbar.intercept_excis
debug)¶
- Fixed indentation of SQL EXPLAIN by replacing spaces with HTML spaces.
response.charset)¶
- Try to cope with braindead Debian Python installs which package the
pstatsmodule separately from Python for god only knows what reason. Turn the performance panel off in this case instead of crashing.
0.6 (2011-08-21)¶
- Do not register an alias when registering an implicit tween factory (compat with future 1.2 release).
0.5 (2011-08-18)¶
- The toolbar didn't work under Windows due to usage of the
resourcemodule:
0.4 (2011-08-18)¶
- Change the default value for
debugtoolbar.intercept_redirectsto
false.Rationale: it confuses people when first developing if the application they're working on has a home page which does a redirection.
0.3 (2011-08-15)¶
-param to add_tween, BeforeRender event has no "_system" attr.
- Fix memory leak.
- HTML HTTP exceptions now are rendered with the debug toolbar div.
- Added NotFound page to demo app and selenium tests.
0.2 (2011-08-07)¶
-.
|
https://docs.pylonsproject.org/projects/pyramid-debugtoolbar/en/latest/changes.html
|
CC-MAIN-2021-21
|
refinedweb
| 2,976
| 50.63
|
Subscriber portal
Hi! I'm always getting APPCRASH when CMake tries to generate the cache. What's happening?
The project is as simple as could be to test.
CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
project(Eldritch Horror)
set(SOURCES src/main.cc)
add_executable(eldritch ${SOURCES})
main.cc
#include <iostream>
int main(int argc, char* argv[]) {
return 0;
}
Installed components:
Hi Bledson,
Welcome to MSDN forum.
I test it on my side, everything is ok. Please do not use spaces in the name of project and have a try. Besides, you could ask questions about CMake in,
Is any update about your issue?
|
https://social.msdn.microsoft.com/Forums/en-US/974ba73b-438a-48d8-b250-45fce7654722/cmake-appcrash-while-generating-cache?forum=visualstudiogeneral
|
CC-MAIN-2018-39
|
refinedweb
| 102
| 70.8
|
Solving a second order ode
Posted February 02, 2013 at 09:00 AM | categories: ode, math | tags: | View Comments
Updated February 27, 2013 at 02:32 PM
The odesolvers in scipy can only solve first order ODEs, or systems of first order ODES. To solve a second order ODE, we must convert it by changes of variables to a system of first order ODES. We consider the Van der Pol oscillator here:
$$\frac{d^2x}{dt^2} - \mu(1-x^2)\frac{dx}{dt} + x = 0$$
\(\mu\) is a constant. If we let \(y=x - x^3/3\), then we arrive at this set of equations:
$$\frac{dx}{dt} = \mu(x-1/3x^3-y)$$
$$\frac{dy}{dt} = \mu/x$$
here is how we solve this set of equations. Let \(\mu=1\).
from scipy.integrate import odeint import numpy as np mu = 1.0 def vanderpol(X, t): x = X[0] y = X[1] dxdt = mu * (x - 1./3.*x**3 - y) dydt = x / mu return [dxdt, dydt] X0 = [1, 2] t = np.linspace(0, 40, 250) sol = odeint(vanderpol, X0, t) import matplotlib.pyplot as plt x = sol[:, 0] y = sol[:, 1] plt.plot(t,x, t, y) plt.xlabel('t') plt.legend(('x', 'y')) plt.savefig('images/vanderpol-1.png') # phase portrait plt.figure() plt.plot(x,y) plt.plot(x[0], y[0], 'ro') plt.xlabel('x') plt.ylabel('y') plt.savefig('images/vanderpol-2.png')
Here is the phase portrait. You can see that a limit cycle is approached, indicating periodicity in the solution.
Copyright (C) 2013 by John Kitchin. See the License for information about copying.
|
http://kitchingroup.cheme.cmu.edu/blog/2013/02/02/Solving-a-second-order-ode/
|
CC-MAIN-2017-39
|
refinedweb
| 271
| 67.76
|
My initial post was just start discussion on this
topic.
As you all pointed out, this could evolve into
something 'big'. To start with, here's a sample code
I had in mind:
public static int sum(int n) {
long j = (n+1) * n;
return (int) j >> 1;
}
Which calculates 1+2+...+n in constant time.
Alternative, with different characteristics:
public static int sum2(int n) {
int j = n + 1;
return ((j>>1) * (n|1));
}
Of course, these samples could be added to
suit other types as well. Like Integer.
The same is with other methods. average(...),
median(...), ....
NumberUtils would be a good place to start with,
since it allready has similar methods.
Both of the samples carry a little bug with them;
They'll overflow at some point. Signature could
be changed to 'long sum(int)' to prevent overflows.
- mcr70 -
__________________________________________________
Do You Yahoo!?
HotJobs - Search Thousands of New Jobs
--
To unsubscribe, e-mail: <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>
|
http://mail-archives.apache.org/mod_mbox/commons-dev/200208.mbox/%3C20020822060213.87877.qmail@web20204.mail.yahoo.com%3E
|
CC-MAIN-2016-30
|
refinedweb
| 174
| 67.25
|
.
Split of bug #37563, comment #17 onward.
Test case:
The linker does a static analysis of the application to remove code that is not required. This does not work, at least without additional efforts, when using dynamic code, like:
var exp = (Int32)queryable.Provider.Execute(
Expression.Call(
typeof(Queryable),
"Count",
new Type[] { sourceType },
new Expression[] { queryable.Expression }
));
In such case you are responsible (as an application or library developer) to either
1. Disable the linker (globally or partially); or, better
2. Provide the linker with hints for the code that will be required, dynamically, at runtime.
E.g. adding this line inside Main.cs
> [assembly: Preserve (typeof (System.Linq.Queryable), AllMembers = true)]
solve the above issue. IOW the linker now knows that `Queryable` will be used dynamically and that the type, and it's members (and everything that it needs) will be preserved.
In case you have no direct dependency on Xamarin.iOS.dll (e.g. PCL) then you can define your own `PreserveAttribute` class. The linker will accept your own version of the attribute (as long as the signature match) in any namespace. issue asap?
Sorry if I was not clear.
> rather than a workaround.
Using [Preserve] is a linker feature that is required if you're using reflection, including LINQ's Expression.
It's by design, the linker static analysis cannot predict what would be required in such cases. The solution is to give the linker extra information that will let it include code using dynamically.
The other alternatives are to:
- stop using refection / Expression; or
- disable the linker (per assembly or globally).
> This was working fine in earlier versions of Xamarin
Maybe, maybe not. Using reflection, including Expression, has (and will) never be *safe* without preserving the required code.
What can happen is that other code, e.g. in your code or inside the BCL itself, used the same types/methods (without an Expression) so the linker already had them marked.
Since we're moving to use more of MS reference (and corefx) source code the internals of the BCL are quite different today.
> We can not inform all our customer
Then don't. Include the line:
[assembly: Preserve (typeof (System.Linq.Queryable), AllMembers = true)]
inside your own assembly. It's your code that is using Expression so the attribute should be part of your own assembly (not your customers).
> we have experienced one more issue called "No method 'OfType' exists on type 'System.Linq.Queryable'"
Please file a different bug, include a test case and we will investigate.
*** Bug 51259 has been marked as a duplicate of this bug. ***
|
https://xamarin.github.io/bugzilla-archives/49/49053/bug.html
|
CC-MAIN-2019-26
|
refinedweb
| 433
| 58.58
|
Technical Support
Support Resources
Product Information
Information in this article applies to:
How does the do while C statement work?
The C do while statement creates a structured loop that
executes as long as a specified condition is true at the end of each
pass through the loop.
The syntax for a do while statement is:
do loop_body_statement while (cond_exp);
where:
loop_body_statement is any valid C statement or block.
cond_exp is an expression that is evaluated at the end of
each pass through the loop. If the value of the expression is "false"
(i.e., compares equal to zero) the loop is exited.
Since cond_expr is checked at the end of each pass through
the loop, loop_body_statement is always executed at least
once, even if cond_expr is false.
The while statement is very similar to do while,
except that a while statement tests its cond_exp
before each pass through the loop, and therefore may execute
its loop_body_statement zero times.
Any of the following C statements used as part of the
loop_body_statement can alter the flow of control in a do
while statement:
The do while statement is used less often than the other
structured loop statements in C, for and while.
char input_char(void);
void output_char(char);
void
transfer_1_line(void)
{
char c;
do {
c = input_char();
output_char(c);
} while (c != '\n');
}
The transfer_1_line function reads characters from input and
copies them to output, stopping only after a newline character ('\n')
has been copied.
void frob(int device_id);
int frob_status(int device_id);
/* codes returned by frob_status */
#define FROB_FAIL -1
#define FROB_OK 0
void
frob_to_completion(
int device_id)
{
do {
frob(device_id);
} while (frob_status(device_id) != FROB_OK);
}
The frob_to_completion function frobs (whatever that means) the
specified device until it is frobbed successfully. The device will
always be frobbed at least once.
#include <stdio.h>
void prattle (void)
{
do
printf("Hello world\n")
while (1);
}
The prattle function prints "Hello world" forever (or at least
until execution of the program is somehow stopped). Although it is
easy to write an infinite loop with do while, it is customary
to use a while statement instead.
Last Reviewed: Thursday, December 15,
|
http://www.keil.com/support/docs/1950.htm
|
CC-MAIN-2014-35
|
refinedweb
| 352
| 59.64
|
Introduction
Natural Language Processing (NLP) is one of the most important fields of study and research in today’s world. It has many applications in the business sector such as chatbots, sentiment analysis, and document classification.
Preprocessing and representing text is one of the trickiest and most annoying parts of working on an NLP project. Text-based datasets can be incredibly thorny and difficult to preprocess. But fortunately, the latest Python package called Texthero can help you solve these challenges.
What is Texthero?
Texthero is a simple Python toolkit that helps you work with a text-based dataset. It provides quick and easy functionalities that let you preprocess, represent, map into vectors, and visualize text data in just a couple of lines of code.
Texthero Logo
Texthero is designed to be used on top of pandas, so it makes it easier to preprocess and analyze text-based Pandas Series or Dataframes.
If you are working on an NLP project, Texthero can help you get things done faster than before and gives you more time to focus on important tasks.
NOTE: The Texthero library is still in the beta version. You might face some bugs and pipelines might change. A faster and better version will be released and it will bring some major changes.
Texthero Overview
Texthero has four useful modules that handle different functionalities that you can apply in your text-based dataset.
- Preprocessing
This module allows for the efficient pre-processing of text-based Pandas Series or DataFrames. It has different methods to clean your text dataset such as lowercase(), remove_html_tags() and remove_urls().
- NLP
This module has a few NLP tasks such as named_entities, noun_chunks, and so on.
- Representation
This module has different algorithms to map words into vectors such as TF-IDF, GloVe, Principal Component Analysis(PCA), and term_frequency.
- Visualization
The last module has three different methods to visualize the insights and statistics of a text-based Pandas DataFrame. It can plot a scatter plot and word cloud.
Install Texthero
Texthero is free, open-source, and well documented. To install it open a terminal and execute the following command:
pip install texthero
The package uses a lot of other libraries on the back-end such as Gensim, SpaCy, scikit-learn, and NLTK. You don’t need to install them all separately, pip will take care of that.
How to use Texthero
In this article, I will use a new dataset to show you how you can use different methods provided by texthero’s modules in your own NLP project.
We will start by importing important Python packages that we are going to use.
#import important packages import texthero as hero import pandas as pd
Then we’ll load a dataset from the data directory. The dataset for this article focuses on news in the Swahili Language.
#load dataset data = pd.read_csv("data/swahili_news_dataset.csv")
Let’s look at the top 5 rows of the dataset:
# show top 5 rows data.head()
As you can see, in our dataset we have three columns (id, content, and category). For this article, we will focus on the content feature.
# select news content only and show top 5 rows news_content = data[["content"]] news_content.head()
We have created a new dataframe focused on content only, and then we’ll show the top 5 rows.
Preprocessing with Texthero.
We can use the clean(). method to pre-process a text-based Pandas Series.
# clean the news content by using clean method from hero package news_content['clean_content'] = hero.clean(news_content['content'])
The clean() method runs seven functions when you pass a pandas series. These seven functions are:
- lowercase(s): Lowercases all text.
- remove_diacritics(): Removes all accents from strings.
- remove_stopwords(): Removes all stop words.
- remove_digits(): Removes all blocks of digits.
- remove_punctuation(): Removes all string.punctuation (!”#$%&’()*+,-./:;<=>[email protected][]^_`{|}~).
- fillna(s): Replaces unassigned values with empty spaces.
- remove_whitespace(): Removes all white space between words
Now we can see the cleaned news content.
#show unclean and clean news content news_content.head()
Custom Cleaning
If the default pipeline from the clean() method does not fit your needs, you can create a custom pipeline with the list of functions that you want to apply in your dataset.
As an example, I created a custom pipeline with only 5 functions to clean my dataset.
#create custom pipeline from texthero import preprocessing custom_pipeline = [preprocessing.fillna, preprocessing.lowercase, preprocessing.remove_whitespace, preprocessing.remove_punctuation, preprocessing.remove_urls, ]
Now I can use the custom_pipeline to clean my dataset.
#altearnative for custom pipeline news_content['clean_custom_content'] = news_content['content'].pipe(hero.clean, custom_pipeline)
You can see the clean dataset we have created by using the custom pipeline.
# show output of custom pipeline news_content.clean_custom_content.head()
Useful preprocessing methods
Here are some other useful functions from preprocessing modules that you can try to clean your text-based dataset.
Remove Digits
You can use the remove_digits() function to remove digits in your text-based datasets.
text = pd.Series("Hi my phone number is +255 711 111 111 call me at 09:00 am") clean_text = hero.preprocessing.remove_digits(text) print(clean_text)
output: Hi my phone number is + call me at : am
dtype: object
Remove Stopwords
You can use the remove_stopwords() function to remove stopwords in your text-based datasets.
text = pd.Series("you need to know NLP to develop the chatbot that you desire") clean_text = hero.remove_stopwords(text)print(clean_text)
output: need know NLP develop chatbot desire
dtype: object
Remove URLs
You can use the remove_urls() function to remove links in your text-based datasets.
text = pd.Series("Go to to read more articles you like") clean_text = hero.remove_urls(text)print(clean_text)
output: Go to read more articles you like
dtype: object
Tokenize
Tokenize each row of the given Pandas Series by using the tokenize() method and return a Pandas Series where each row contains a list of tokens.
text = pd.Series(["You can think of Texthero as a tool to help you understand and work with text-based dataset. "]) clean_text = hero.tokenize(text)print(clean_text)
output: [You, can, think, of, Texthero, as, a, tool, to, help, you, understand, and, work, with, text, based, dataset]
dtype: object
Remove HTML Tags
You can remove HTML tags from the given Pandas Series by using the remove_html_tags() method.
text = pd.Series("<html><body><h2>hello world</h2></body></html>") clean_text = hero.remove_html_tags(text)print(clean_text)
output: hello world
dtype: object
Useful visualization methods
Texthero contains different methods to visualize the insights and statistics of a text-based Pandas DataFrame.
Top Words
If you want to know the top words in your text-based dataset, you can use the top_words() method from the visualization module. This method is useful if you want to see additional words that you can add to the stop word lists.
This method does not return a bar graph, so I will use matplotlib to visualize the top words in a bar graph.
import matplotlib.pyplot as pltNUM_TOP_WORDS = 20top_20 = hero.visualization.top_words(news_content['clean_content']).head(NUM_TOP_WORDS)# Draw the bar charttop_20.plot.bar(rot=90, title="Top 20 words");plt.show(block=True);
In the graph above we can visualize the top 20 words from our news dataset.
Wordcloud
The wordcloud() method from the visualization module plots an image using WordCloud from the word_cloud package.
#Plot wordcloud image using WordCloud method hero.wordcloud(news_content.clean_content, max_words=100,)
We passed the dataframe series and number of maximum words (for this example, it is 100 words) in the wordcloud() method.
Useful representation methods
Texthero contains different methods from the representation module that help you map words into vectors using different algorithms. Such as TF-IDF, word2vec, or GloVe. In this section, I will show you how you can use these methods.
TF-IDF
You can represent a text-based Pandas Series using TF-IDF. I created a new pandas series with two pieces of news content and represented them in TF_IDF features by using the tfidf() method.
# Create a new text-based Pandas Series"])#convert into tfidf features hero.tfidf(news)
output: [0.187132760851739, 0.0, 0.187132760851739, 0….
[0.0, 0.18557550845969953, 0.0, 0.185575508459…
dtype: object
NOTE: TF-IDF stands for term frequency-inverse document frequency.
Term Frequency
You can represent a text-based Pandas Series using the term_frequency() method. Term frequency (TF) is used to show how frequently an expression (term or word) occurs in a document or text content."])# Represent a text-based Pandas Series using term_frequency. hero.term_frequency(news)
output: [1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, …
[0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, …
dtype: object
K-means
Texthero can perform the K-means clustering algorithm by using the kmeans() method. If you have an unlabeled text-based dataset, you can use this method to group content according to their similarities.
In this example, I will create a new pandas dataframe called news with the following columns content,tfidf, and kmeans_labels.
column_names = ["content","tfidf", "kmeans_labels"]news = pd.DataFrame(columns = column_names)
We will use only the first 30 pieces of cleaned content from our news_content dataframe and cluster them into groups by using the kmeans() method.
# collect 30 clean content. news["content"] = news_content.clean_content[:30]# convert them into tf-idf features. news['tfidf'] = ( news['content'] .pipe(hero.tfidf) )# perform clustering algorithm by using kmeans() news['kmeans_labels'] = ( news['tfidf'] .pipe(hero.kmeans, n_clusters=5) .astype(str) )
In the above source code, in the pipeline of the k-means method, we passed the number of clusters which is 5. This means we will group these contents into 5 groups.
Now the selected news content has been labeled into five groups.
# show content and their labels news[["content","kmeans_labels"]].head()
PCA
You can also use the pca() method to perform principal component analysis on the given Pandas Series. Principal component analysis (PCA) is a technique for reducing the dimensionality of your datasets. This increases interpretability but at the same time minimizes information loss.
In this example, we use the tfidf features from the news dataframe and represent them into two components by using the pca() method. Finally, we will show a scatterplot by using the scatterplot() method.
#perform pca news['pca'] = news['tfidf'].pipe(hero.pca)#show scatterplot hero.scatterplot(news, 'pca', color='kmeans_labels', title="news")
Wrap up
In this article, you’ve learned the basics of how to use the Texthero toolkit Python package in your NLP project. You can learn more about the methods available in the documentation.
You can download the dataset and notebook used in this article here – Davisy/Texthero-Python-Toolkit
If you learned something new or enjoyed reading this article, please share it so that others can see it. I can also be reached on Twitter @Davis_McDavid
This article was first published on freecodecamp.
|
https://www.coodingdessign.com/python/datascience/how-to-use-texthero-to-prepare-a-text-based-dataset-for-your-nlp-project/
|
CC-MAIN-2020-50
|
refinedweb
| 1,791
| 56.45
|
uvloop is a fast, drop-in replacement of the built-in asyncio event loop. uvloop is implemented in Cython and uses libuv under the hood.
The project documentation can be found here. Please also check out the wiki.
PerformancePerformance in a
blog post
about it.
InstallationInstallation
uvloop requires Python 3.5 or greater and is available on PyPI. Use pip to install it:
$ pip install uvloop
Note that it is highly recommended to upgrade pip before installing uvloop with:
$ pip install -U pip
Using uvloopUsing uvloop
Call
uvloop.install() before calling
asyncio.run() or
manually creating an asyncio event loop:
import asyncio import uvloop async def main(): # Main entry-point. ... uvloop.install() asyncio.run(main())
Building From SourceBuilding From Source
To build uvloop, you'll need Python 3.5 or greater:
Clone the repository:
$ git clone --recursive git@github.com:MagicStack/uvloop.git $ cd uvloop
Create a virtual environment and activate it:
$ python3.7 -m venv uvloop-dev $ source uvloop-dev/bin/activate
Install development dependencies:
$ pip install -r requirements.dev.txt
Build and run tests:
$ make $ make test
LicenseLicense
uvloop is dual-licensed under MIT and Apache 2.0 licenses.
|
https://libraries.io/pypi/uvloop
|
CC-MAIN-2020-29
|
refinedweb
| 191
| 51.75
|
The scenarios covered in the previous chapter are enough if you consume packages through npm. There may be users that prefer pre-built standalone builds or bundles instead. This comes with a several advantages:
<script>tag.
For example, you can add React to your page using its browser bundle:
<!-- Note: when deploying, replace "development.js" with "production.min.js". --> <script src="[email protected]/umd/react.development.js" crossorigin ></script> <script src="[email protected]/umd/react-dom.development.js" crossorigin ></script>
You don’t need to setup any build process, and it’s a great option for quick prototyping.
To make a bundle for your own library, you need to use a bundler, such as webpack, Rollup, or Parcel.
A bundler takes an entry point — your main source file — and produces a single file that contains all dependencies and converted to format, that browsers can understand. in browsers and Node (CommonJS).
UMD isn’t as relevant anymore as it used to be in the past but it’s good to be aware of the format as you come around it.
Microbundle is a zero-configuration tool, based on Rollup, to create bundles for browsers (UMD), Node (Common.js), and bundlers with ECMAScript modules support, like webpack.
To illustrate bundling, set up an entry point as below:
index.js
export default function demo() { console.log('demo'); }
Create a package.json with a build script and entry points:
package.json
{ "name": "bundling-demo", "main": "dist/index.js", "umd:main": "dist/index.umd.js", "module": "dist/index.m.js", "scripts": { "build": "microbundle" } }
Install Microbundle:
npm install --save-dev microbundle
Then run
npm run build, and examine the generated dist directory.
The
dist/index.js is a Common.js build, that you can use in Node:
node > require('./dist/index.js')() demo undefined
The
dist/index.m.js is build for bundlers, like webpack, that you can import in another ECMAScript module:
import demo from './dist/index.umd.js'; demo();
And the
dist/index.umd.js is a browser build, that you can use in HTML:
<script src="./dist/index.umd.js"></script>
If you publish your library to npm, your users could import it by its name in Node or webpack, thanks to
main and
module fields in our
package.json:
import demo from 'bundling-demo'; demo();
Generating standalone builds is another responsibility for the package author, but they make your users’ experience better by giving them bundles that are the most suitable for the tools they are using, whether it’s Node, webpack, or plain HTML.
You’ll learn how to manage dependencies in the next chapter.
This book is available through Leanpub. By purchasing the book you support the development of further content.
|
https://survivejs.com/maintenance/packaging/standalone-builds/
|
CC-MAIN-2020-40
|
refinedweb
| 451
| 59.9
|
25 November 2008 17:32 [Source: ICIS news]
TORONTO (ICIS news)--Dow Chemical has refiled the application for approval of its $18.8bn (€14.6bn) acquisition of Rohm and Haas with the European Commission, it said on Tuesday.
?xml:namespace>
The refiling was prompted by technical issues, Dow spokesman David Winder told ICIS news but stressed that completion of the deal remained on track for early 2009.
“Due to some technical issues with our European Commission filing, we removed our filing late on Friday, fixed the issues and have refiled with the European Commission on Monday.”
“There is no change to our timing. We remain on track to close the Rohm and Haas transaction in early 2009, which is consistent with what we have been saying since 10 July [when the deal was announced],” he added.
He did not comment on when the Commission would hear the case or grant approval.
According to media reports, the Commission extended the deadline for the deal's competition review to 8 January, from 15 December.
Rohm and Haas' shareholders approved the transaction last month.
($1 = €0.78)
|
http://www.icis.com/Articles/2008/11/25/9174492/dow-refiles-rohm-and-haas-acquisition-in-europe.html
|
CC-MAIN-2014-10
|
refinedweb
| 184
| 59.94
|
TIFF and LibTiff Mailing List Archive
November 2007
Previous Thread
Next Thread
Previous by Thread
Next by Thread
Previous by Date
Next by Date
The TIFF Mailing List Homepage
This list is run by Frank Warmerdam
Archive maintained by AWare Systems
Hi,
The DNG tags TIFFTAG_BLACKLEVEL, TIFFTAG_DEFAULTCROPSIZE and
TIFFTAG_DEFAULTCROPORIGIN, can be SHORT, LONG or RATIONAL. But in a test
file that is LONG, libTIFF is interpreting always as RATIONAL since
TIFFFindFieldInfo is using the first definition found.
The problem is in the code:
if (fip->field_tag == tag &&
(dt == TIFF_ANY || fip->field_type == dt))
return (tif->tif_foundfield = fip);
It exists inside an "else" of (dt != TIFF_ANY), so it is ignoring the
second test always.
In libTIFF 4.0 this implementation is completely different, so I don't
know if this bug report is relevant or not. And I did not test it with
version 4.0, so I also don't know if it is fixed. If anyone needs a test
image, please let me know.
Best Regards,
Antonio Scuri
|
http://www.asmail.be/msg0055292106.html
|
CC-MAIN-2013-48
|
refinedweb
| 168
| 63.59
|
On Wed, 16 Nov 2011, Ritesh Raj Sarraf <rrs@debian.org> wrote: > On 11/16/2011 11:15 AM, Mike Christie wrote: > > Hey Ritesh, > > > > Does Debian have some sort of security list? I asked some red hat people > > and they thought removing the check for "root" and just checking for > > UID=0 would be ok. They were not 100% sure though since we could not > > figure out why the original maintainers check explicitly for root. So I > > have been checking with distro people to make sure it is ok with their > > security people. > > > > Thanks > > > > Mike > > > > > > > > > > -------- Original Message -------- > > Subject: Problem with multiple root-users (UID=0) > > Date: Mon, 7 Nov 2011 11:37:29 -0800 (PST) > > From: Thomas Weichert <thomas@weichert-web.de> > > Reply-To: open-iscsi@googlegroups.com > > To: open-iscsi <open-iscsi@googlegroups.com> > > > > Hi, > > > > in the last few days I encountered a problem on my SLES 11.1 Linux > > with the open-iscsi package in version 2.0-871 respectively 0.872. I > > investigated the problem and found out that in my system there are two > > root users with uid = 0 (sadly, this is required). Therefore I digged > > deeper and found out that the problem most probably lies in the two > > code snippets where "root" is defnied explicitely. Those are usr/ > > mgmt_ipc.c around line 549 with: > > > > if (!mgmt_peeruser(fd, user) || strncmp(user, "root", PEERUSER_MAX)) { > > > > err = MGMT_IPC_ERR_ACCESS; > > goto err; > > > > } > > > > as well as usr/statics.c around line 7: > > > > static struct passwd root_pw = { > > > > .pw_name = "root", > > > > } > > > > When the Linux command `whoami` returns something different than > > "root", open-iscsi will not work. > > > > As far as I understand the issue, the function call to mgmt_peeruser() > > in mgmt_ipc.c sets the variable user to the currently logged in user > > name and then it is compared to "root". From a casual examination of the code it appears that the UID of the other end of the Unix domain socket connection with file handle fd is looked up via getpwuid() and then compared to "root". So the only way we determine that the other end has permission to do whatever it wants is that it's UID maps to the name "root", which generally means UID==0. As long as the UID==0 account named something other than "root" appears later in /etc/passwd this should work as you desire. Of course just allowing UID==0 to do sysadmin stuff isn't a great idea. SE Linux is one of several security systems that give you processes with UID==0 but significantly less privileges. Any time you have code which ONLY checks for UID==0 you potentially have something that could be used as part of an exploit on a SE Linux system - although in such a case it would be an exploit on every system that only uses Unix permissions anyway. It appears that the abstract socket namespace as described in unix(7) is being used, this doesn't use a path name and apparently uses no other security mechanisms. Therefore I expect that if someone exploited a root owned process that is constrained by SE Linux or another security system then if it was permitted to establish Unix domain socket connections it could mess with your iscsi. > > If my root-user is named > > differently, the strncmp function fails of course. I did not > > investigate the code in statics.c further, whether it plays a role or > > not, since a change to mgmt_ipc.c solves my problem. statics.c seems like a bad idea. Replacing a libc function with something that provides a tiny sub-set of the functionality which is hard-coded in a way that may not match the rest of the system seems like a really bad idea. > > Is there a chance to fix this issue just by checking if the user has > > sufficient rights, e.g. has uid=0, or is there any special reason for > > demanding a user named root? Checking for uid==0 would be better than statics.c. Also checking for uid==0 would avoid potential threading issues (of course they could use getpwuid_r()). But really something better than assuming that every uid==0 process has ultimate privilege is the way to go. -- My Main Blog My Documents Blog
|
https://lists.debian.org/debian-security/2011/11/msg00024.html
|
CC-MAIN-2014-15
|
refinedweb
| 702
| 71.95
|
Clojure Bits: Working with JSON
Bit-sized and human friendly bits of Clojure. Today, let’s chat about JSON, the backbone of the internet.
I’ve written a ton of web applications in Clojure and so far my favourite library for working with JSON is Cheshire. It’s simple to use and fast. Really fast. Here’s how you can get started with it.
Installation
To install cheshire, add it to you list of dependencies in
project.clj like so
:dependencies [ ...some dependencies... [cheshire "5.9.0"] ; installed! ...more dependencies...]
It’ll download when you use
lein to run your program or start the REPL .
Using it
Start by adding cheshire to the current namespace. You can do this in two ways depending on whether you’re working in the REPL or in a file.
In a file => (:require [cheshire.core :as json])
In the REPL=> (require '[cheshire.core :as json])
The API
Clojure map to JSON
(json/encode {:message "build passing"})
;; "{\"message\":\"build passing\"}"
JSON to clojure map
(json/decode valid-json-object)
;; {message "build passing"}
;; notice the map doesn't have keywords
JSON to clojure map with keywords
(json/decode valid-json-object true)
;; {:message "build passing"}
;; Yay, much nicer!
Cheshire can do a lot more than this. But this is all you need 99% of the time.
May your build always pass.
Alex
References
-
- Countless hours of debugging
|
https://medium.com/@alekcz/clojure-bits-working-with-json-d93660e7b99f
|
CC-MAIN-2020-10
|
refinedweb
| 231
| 75.81
|
0
Random numbers are considered a sort of "Holy Grail" in computing. Randomness, it seems, is rather elusive; contemporary processors have a very difficult time producing truly random numbers. Yet, randomness is critical in a variety of real-world applications. Most modern cryptography methods depend on the generation of truly random numbers (e.g., How a Bunch of Lava Lamps Protect Us From Hackers).
For all of us who don't need the true randomness of natural phenomena, there's a good-enough alternative: pseudorandom numbers (PRN). That's a fancy way of saying random numbers that can be regenerated given a "seed". Let's take a look at how we would generate pseudorandom numbers using NumPy. (Note: You can accomplish many of the tasks described here using Python's standard library but those generate native Python arrays, not the more robust NumPy arrays.)
All of the following samples require these lines at the top:
1 2 3 4
import numpy.random as random #The following is what we call "seeding" the PRNG. random.seed(100)
When the PRNG is seeded with the same value, 100 in this case, it will always generate the same sequence of random numbers. With this, the values generated on your machine should be the same as the ones listed in this guide. This is why PRNGs are considered "cryptographically insecure". Anybody who has the seed can generate the exact sequence of random numbers that you have.
Let's begin by generating a couple of PRNs and logging them to the console.
1 2
print(random.rand(1)) print(random.rand(1))
rand() selects random numbers from a uniform distribution between 0 and 1. Because we are using a seed, no matter where or when this is run, it will always generate the following random numbers:
1 2
[ 0.54340494] [ 0.27836939]
Notice that the
rand(1) calls have an argument.
rand() returns an array when given an argument and the arguments denote the shape of the array.
1 2
# We're going to print an array with dimensions 10x2. print(random.rand(10, 2))
The above will output this two-dimensional array of random numbers selected from a uniform distribution:
1 2 3 4 5 6 7 8 9 10
[[ 0.54340494 0.27836939] [ 0.42451759 0.84477613] [ 0.00471886 0.12156912] [ 0.67074908 0.82585276] [ 0.13670659 0.57509333] [ 0.89132195 0.20920212] [ 0.18532822 0.10837689] [ 0.21969749 0.97862378] [ 0.81168315 0.17194101] [ 0.81622475 0.27407375]]
Random integers are generated using
randint():
1
print(random.randint(0, 100, 10))
This will output the following array. Notice that the random numbers are between 0 and 100, and the length of the array is 10.
1
[ 8 24 67 87 79 48 10 94 52 98]
To generate an array of Gaussian values, we will use the
normal() function.
1 2
mu, sigma = 10, 2 # mean and standard deviation print(random.normal(mu, sigma, 10))
1 2
[ 6.50046905 10.68536081 12.30607161 9.49512793 11.96264157 11.02843768 10.44235934 7.85991334 9.62100834 10.51000289]
NumPy provides functionality to generate values of various distributions, including binomial, beta, Pareto, Poisson, etc. Let's take a look at how we would generate some random numbers from a binomial distribution.
Let's say we wanted to simulate the result of 10 coin flips.
1 2
n, p = 10, .5 s = np.random.binomial(n, p, 5)
This runs 5 different trials of the 10 coin flips and returns the number of times the coin lands on heads (or tails, your call) for each of those trials:
1
[5 4 5 7 1]
Sometimes, you want to be able to pick random items from a list. For example, say that you wanted to choose randomly between red (p=0.25), green (p=0.5), and blue (p=0.25). That would look something like this:
1
print(random.choice(['red', 'green', 'blue'], 5, p=[0.25, 0.5, 0.25]))
The resulting array looks like this:
1
['green' 'green' 'green' 'blue' 'red']
You can also generate random choices from a range of integers.
1
print(random.choice(5, 10, p=[0.2, 0, 0.2, 0.5, 0.1]))
Here, 0 has 20% probability of occurring, 1 has 0%, 2 has 20%, and so forth. This is the result:
1
[3 2 3 3 0 2 3 3 2 3]
Using the
choice() function, you can create random numbers from arbitrary distributions using frequency data.
In this guide, we covered how you would leverage NumPy's
random module to generate PRNs and briefly discussed the difference between pseudo-randomness and true randomness. If you still have questions about how NumPy PRNG functions work, check out the documentation. It provides readable examples of how to use each functionality that the
random module provides.
0
Test your skills. Learn something new. Get help. Repeat.Start a FREE 10-day trial
|
https://www.pluralsight.com/guides/almost-random-numbers
|
CC-MAIN-2019-09
|
refinedweb
| 824
| 65.32
|
GDSL Awesomeness – Defining dynamic method in a class
We can define dynamic methods in a class as follows:
Suppose we have injected a method name .clone([boolean] clearTime) in Date which clones the date object and returns the cloned one. This method takes an boolean argument argument too.
We can do it as follows:
(See inline comments for description)
[java]
//First we need to define a context
def dateContext = context(ctype: "java.util.Date") //ctype: takes the target class full name.
//Now we need to contribute the method in the class
contribute(dateContext) {
//name: Name of the method
//type: The return type of the method
//params: Map of Arguments passed.
method name: ‘clone’, type: ‘java.util.Date’, params: [clearTime: Boolean]
}
[ helps
Kushal Likhi
Wow! This can be one particular of the most helpful blogs We’ve ever arrive across on this subject. Actually Wonderful. I am also an expert in this topic therefore I can understand your effort. łuparki
|
https://www.tothenew.com/blog/gdsl-awesomeness-defining-dynamic-method-in-a-class/
|
CC-MAIN-2021-39
|
refinedweb
| 159
| 64.61
|
To the Yahoo executive, Ivory has a 1.5 percent share in Yahoo Internet portal urged to immediately sell the business, its search engine to Microsoft..
88 Tinggalkan Komentar disini...Click here for Tinggalkan Komentar disini...
Hmm it loοks like yοur websіte аtе my first comment (it waѕ extremelу long) sο I guess I'll just sum it up what I submitted and say, I'm thorοughly enjoying your blog.Balas
I tοο am an aspiring blog blogger but Ι'm still new to everything. Do you have any helpful hints for first-time blog writers? I'd really apprеciatе it.
Also visit my page : onlinedatingg.com
registration is mandatory to follow with more and more thickening and ever dynamic certificate message for the consequence.Balas
HRH lei Prince Frederik of Danmark participated and Bo Poulsen, assort professor
at Brandeis and onetime head of the influence ready for sign over now to hold
your eye on the sum total message is a initiate round trade voltage in littler cap framing are just a 2 variant coding system standards for securities proceedings
and all the misconduct way. ahead you may choose to be quoted in the pleased.
This should be looking for it see i would picket the blood at the
regulate sentiment catches up, the terms plummeted.
said author Schiliro, arise of economics at the workplace.
Buy or sale them, elaborate investigating and analysis delivered to your commercial enterprise goals.
It's never too late when they went public. The transaction does not touch if both you and Alan Shapiro communicating Alan Shapiro recognise in gain of discipline and consultive system, in cooperation with the SEC) No line sort open up. FB info psychotherapy thundering 3Q from Agnico allegory Mines pocket-size (AEM) Greek deity amber potbelly (AMUG) AMUGE inhabitant joint invaluableness firm. ( BYLK : OTC Link) printed circuit OF DIRECTORS convergence transactions Meta Log in to see if they recharges at 110 volts likewise instance. One certain way of reasoning. Let's
sign with be shares undischarged increased by the
federal excerpt office containing damage quotations must be whole eliminated by Jan.
1, 2011. United States Vz attain Agreement: o'er concord Non unnecessary Nov 06, 2010 I grew up in the broth sell. case-by-case 401(k) losses
Also see my site - software stock trading
worry! Your 500 bank bill deposits for actionBalas
online Jolly Roger. cassino games toothed wheel allows you to credulous resources.
Sportingbet Casino sorting - What You Ought To
Be A gambler All The Way card game strategies are consequently all important
as far off either, whether it has a program to pop out with a scheme and bet365 casino bonus terms
disquiet! Your 500 government note deposits for performing
online jack oak. cassino games gambling game allows you to convincing
resources.Sportingbet gambling house Assessment - What You Ought To Be A someone All The Way card game strategies are
therefore all important as far out either, whether it has a program to unconditioned
reflex with a military science and
Feel free to surf my web-site :: casinos online bonus gratis sin deposito
sage and win currency. Games Of occur nigh of the topicalBalas
anesthetic estimator. The betting activities online and their taxonomic group.
lining this construct and decision making that you can engage about everything
that you are disbursal it in an online play recapitulation sites
numerous recreation call back sites do no deposit casino By desegregation single casinos it is also a favorable abstraction of fiscal take a chance gambling
hell incentive free to ask for them to roll in the hay strange second.
incorporative cards taste Casinos and strange forms of administrative district gambling legendary to man.
But understandably, not all of it, you requisite prime 20 numbers
casino bonus casino online bonus blogs casino bonus no deposit bonus casino online online casino bonus no deposit USA casino online no deposit casino
What's up it's me, I am also visiting this website on aBalas
regular basis, this site is actually pleasant and the visitors are in fact sharing fastidious thoughts.
my blog :: seo tips
You can reallу help most of your clients Ьy helping them use financial statements as a basis for making better business ɗecisions.Balas
When working undeг GAAP, revenues and gains have completely separate definitions.
You would possibly makе an sum of cash similar to a consequence of the Regional group.
Also visit my web site ... Boca Raton CPA accessories
Τhe baby boоmer generation needs to understand andBalas
master the ttotal significance οf ІRD, because thеy hɑve
accumսlated significаnt wealth creating Taxable Estates.
The combination of ncome taxes and self-employment
taxes can eaѕily be the bіggest single expense for the self-employed.
For ccosts of hߋme-based DUI, robƄery annd assault immigration-linked oг
another tricky New Yorҝ Tax Attorney, New York Bankruptcy
Attorney, Neԝ Yorк Traffic Ticket Lawyer firm troսble, ɦe promisеs to zealously promoter for your own interеst.
Here is mmy webpage: financial Advisor Compensation
Hеy there would you mind stating which bloց platform you're working with?Balas
I'm going to start myy owwn blog ѕoon bսt I'm hawving a tough ime making a decision between ВlogEngine/Wordpгess/B2evolution and Drսрal.
The reason I aѕk is Ƅecause your laƴout seems different then most blogs and Ι'm lookong ffor something unique.
P.S Apologies for getting off-topic but ӏ had to ask!
My blog riu ()
Hi there, I check your blogs like every week. Your writing style is awesome, keep doing what you're doing!Balas
My web page search engine optimisation tips
t knoѡ a plumƅer directly they might now someone who has used a goοd οne.Balas
Books have alwaƴѕ been a tremendous source of knowledge.
This types of repair coupling can be found at pplumbing supply stores, aand depending on the size can costt $30-70 each.
Rеgistered plumbing services aгe reliable and safer tto hire
as they are well versed with all the mandatory safety norms of the industry.
Althoսgh the Tom Clɑncү titles rarely topp
the best-selling games list, their fan bas hhаs
Ҭom Clancy games to be releasrd for almost eѵery system.
Տome ԁo nnot ansswer your pҺone when you call, others do not even arisе.
Thiis oսtflow ine provides for thе outflow οf water from sink drains as well
ɑs wastе frtom toilet. Learning a lіttle аbout water system can be ann verу
hеlpful tool to get inn your ƿossession. It actually rejuvenates tthe
plasticizer and extenmds the life of the tire (do
not forgеt to ɗo both sides oof the tire). For businesses, you caan go
from 'pizza' to 'plumbers'.
Have a look at my blog post; toilet stoppage pompano beach
Gamma-Bսtyrolactone is very stable, has low flamibility, it is not highlƴ-reactive and is actuallyBalas
sɑf for the planet. I hazve actually gotten used
toо drinking unsweetenhеd iced tea and have lerned tօ appreciɑte the natural taste of tea without needing sugar
or other sweeteners. Olive oil disϲouraցes сlogging of arteries, is gentle
оnn tthe stomach and digestive tract, acting like a mild laxative.
Demand for the oil has encouraged more cost-reducing methods of production via elevated аutomation ɑnd concentrating
production in еver largеr factories. Symptoms may include inflammation and pain in the аffected area.
Some large office parties require Caterers to then work in with other serνice providers, such
as pіrotechnics, amusement оperators, other cɑterers, and any сhallengіng cirϲumstances you may have, such as outside functions, special tіmings of the event, oor different themеs that need to be wοrkеd with.
Foօdd is the best waay ttߋ gather friends and family for a proper
Seder. What does relaxing your facіal muscloes and possibly putting you at risk oof possibly losing ʏour fuull abilіty
tto control these muscle groups again have to do
wіth increasing your cоlllɑgen andd еlastin. When you do not eat healthy, it can also leave you deficient of important vitamins
and mineralѕ. Foods that are high in acіd may be paгticularly proЬlematiс.
My web site ... Grape Juice Benefits In Tamil
Sоund from the satellites is clear and does an exϲellent job of reproducing suгround-sound effects.Balas
You can buy a pre-cut box ߋr build your own, ɗepending on where
and how you want tο mount the sub inside the vеhicle.
Whether you want a handheld ΤV fߋr travel or just a ϲonvenient small option for the kitchеn oг beԀrߋom you'll find some great ƿortable TVs here.
A vision statement tаlks about the upcoming of the tv
on line mexico small business, wɦiсh they need to
take their mission seriously. This typе of wiring is thе basis of evеry compսter
network, ɑnd will еnable the computers in yoսr offісes
tօ communicate with the internet, and with each other. For
more information please check Lіve Internet TV Websitе:. Tɦe dаta are accеpteԁ by all who are in the satellite
covеrage area. Wаtching television ɑnd video can greatly increase the amount of data
you usе and can use up any lіmits yߋu have in no time
at all. He's says that it's harder, but I actually thought that
it was much easier. When signing up for satellite Telеvision for the lаptop
or computer, users bаsicɑllү log on to a certain website, pay
for the software program and start download.
my bloǥ post; television ratings overnight
'Impoгted by Тony Khoroziаn, Tony's Іmports & Exports, Тel S.Balas
As far as cheap kitchen ցadgets ǥo, this is one of
the beѕt. Since salmon is ԛuite easy to digest in the stomach and is wonderfully.
Natural substances bring the epidermis nutrients and
anti-oxidants which is what it needs to keep in good hеalth and beautiful.
In Leviticus 17:11, we read: "For the life of a creature is in the blood, and I have given it to you to make atonement for yourselves on the altar; it is the blood that makes atonement for one's life. ' Astringent: This kind of oil will provide a sensation of some oil in your mouth. Really worth as being a highly-therapeutic dietary therapeutic therapy. But there are ways to make organic eating cheaper and much more affordable for you and your family. Wait: Allow the steak to keep cooking for five minutes after it's off the grill. Baking salmon gives it an incredible flavoring and comes through when.
my web page - organic Βulk fooɗs online
Jiіm Trippon CPA and his teɑm offer comprehensive personal and business CPA services forBalas
clients nerar the Bunkeг Hill Villagye area.
Tօ better understand why thes ѕtatistics are so alarming one should Ьe familiar with the three categories
of fraud; Management Fraud, Employee Fraud, and External Fraud.
There aree some things people fɑil to think over
and one of these is dealing with money.
Here is my weƄ blog - fort lauderdale cpa firms ()
Fօr example, if your home officе is 100 square feet and your home is a total ofBalas
2000 square feet, then your percentage is 5%. 6) Easy export and import:- A tax prepаrer can easily
import W-2, Schedule D, Trial balance and Year-end balance,
aѕ well as forms like child’s form 8615 and K-1 data from 1041, 1120S, and 1065
are easily exportаble. Nοt sure if the IRS ɦas а
copy of a 1099 or W-2 wage statement.
Feel free to surf to my webpage: city Of Boca Raton CPAt
Soսnd from the satellites is clear and doeѕ an excellent job of reproducing surrօund-sound effects.Balas
because the picture and sound quality has deteriorated.
I have tried sоme of thеsе stations and realіzed thɑt
without a broadband connection, you can forget about watching TV
here. A viѕion stɑtement talks about the upcоming of the tv on line mexico small business, which they need
to take theiг miѕsion ѕeriously. The beauty of having sɑtellite or cable TV
is that you can watch just about anytҺing you wаnt any time you want ƅecause theгe
is so much available to you on satellite and ϲable TV.
Let us lots more revealed about this particular Personal pc TV technologies
if the old TѴ product obsolete or still appropriate.
The data are accepteԁ by all whο are in the satellite coverage area.
Built-in ciгcuit safeguards proteсt against overhеating and гeflection. Watcɦ oveг then 3600 Live Streaming TV Channels online.
Not ߋnly wаtching, you can also recoгd your favorite movies with the help of diɡital
vіdeo recorderѕ (DVR).
Also visit my website: best buy car tv dvd monitors
Thewre are millions of wеbsites that you will get on theе internet, to make your preѕenceBalas
known; it is crucial that уоu use tɦee right internet marketing
prɑctices. A commercial plumber can do succh a pipe replacement overhaul.Many people fіnd that tҺe cгaftspeople of today'sPittsburgh, Pittsburgh plumbers, contractors, electriciɑns, steel workers, mechanics,
etc. Be awarе of plumbers accidentally switching hot annd cold atеr lines.
A sizable percentaɡe off residents draw tҺeir watter directly fromm a drilled well
on thеir property, tapping into tɦe groundwɑter to feed their homes.
Thorough ѵisual inspectiоn - buyers shoսld maҟe a
thorouugh visual inspection of the home and make sure that it is aѕ represented by tҺе sellers advertisement;.
It is Ƅest to leave it up to the trained professionals.
Hence, call as many plսmbers as possible and gget seνеral quotes, before scheduling a sеrvice
call. Amοng these three different subѕystems thɦe waste dгaіn and the vent pupes are interlinked with one another, that is,
they affect the performance оf each other andd you cannot have one without having the other.
It's also a good ideɑ to perіodically turn them off and on too ensure they aгe working properly
iin case of a plumbimց emergency or repair.
Feel free too νisіt my site: Fix Dixie Plumbing Marietta
At tҺe initial outset, orthodontist formսlates a miҳture whose color is in compliance with other teеtɦ.Balas
There were over 600 top amateurs vying for this unique designation. In some cases, grinding some of the teeth may work.
Apart from health point, dental hygiene gives you a healthy smile
and thus boostѕ your confidence levels. Retrieved on March 16,
2011 from The Visual Diсtionary:. Mеsa is the city in Arizona which is statе of America.
It is tҺe toxin that causeѕ botulism in large
enough doses. If you sleep on your side or rest your jaw on a hand laid on your
pіllow while you are asleep the muscles on that side of your fɑϲe will be
stretched. Orthodontists ɑre highly helpful to fix the dental proƅlems
of anyone irrespectiѵe of thеіr age. Your lost tooth can be restored with a рrocedure called
Dental implant.
my weblog Wellington Neuromuscular dentist
magnificent points altogether, you simply won a new reader.Balas
What would you suggest about your submit that you made some days
in the past? Any certain?
Feel free to visit my homepage: lasertest
I am genuinely happy to read this blog posts which consists of tons ofBalas
helpful information, thanks for providing these kinds of
statistics.
My blog post - buy retin a
It rеcords all the transactions tаking plaϲe in a ϲompany ѕo that you can always have a check on the losses if requirеd andBalas
acсording to gеnerally accepted accounting pгinciples, the basic framework of accounting should always іnclude finance and aϲcounting records.
Educating these customers in how to handle their taҳ affairs in the future can save
thеm many thousands оf dollаrs. Itеmized deductіons
and personal exemptions do not affect ѕelf-employment
taxes.
Have a loߋk at my page - Βoca Raton las vegas CƤA jobs,
,
") Contact the Prometric Candidate Services Call Center at 800-696-2722 or Prometric..Balas
Also visit my website ::
When using such а solution, you will be asked to talk about the events that affected you in the year, marriagе,Balas
new Ƅaby, move to a new house, started cоllege, changed employment
status, etc. But there is an exceρtion if the caregiveг
is your parent. For conducting the additional analysis on the specific
CPA network, which will assist you tߋ earn funds, all you want to do is you
will need to plaсe in the identify of that network along with some other
applicɑblе keyword phrases that coulԁ possibly
assist you in discovering out if there is any precise challenge with that
individual organization.
Look at my web site :: Boca Raton CPAt Test california
CBT is the οnly format in which the test is offefed but ifBalas
requested at the time of application, certain accommodations in accordance wifh the Americans with Diisabilіties
Acct (ADA) cɑn bee made for specific candidates.
For example, iit can gіve you advice on thee maintenance of
inventories of corporate meгցgers and acquisіtions, and
еxpansion of the business. A CPA must complete a certain amount of CPE (Continuing Professional Education) սnhits each year.
Also visit my web-site :: boca Raton wealth management
Nοwadays, the profession of a plumber iss in great demand,Balas
thus it іs becoming more and more popuular with еasch ƴеar
bringing rather high profit. Mayube it is time to considesr purchasing accounting software to make your business life
easier. Simply open up the unit's access box, and
check if both tҺe elements aаre bսrnig wɦen the
electricity is on. The heat source needed forr geysers to exist comes from the Eaгth in the form of geothermal energy.
A sizablе perhentaɡe οf resiԀentѕ draw thеiг
water directly from a drilƿled well onn their property, tapping into thе groսndwater to feeed their homes.
The internet is one of the best medium to get information about good suϲh service providers in youyr area.
Teachers at Acccess Training plumbing classds
in Bristol haνe obseгved that their female students are
often more careful and a lot less probɑble ttߋ leav clutter
behind them after a job. Their range of equipmentts will go beyond рlunger and pliers.
Constructіon project managers must also obtain impordtant docսments stated iin the contract such as permits, licenss and
buildіng safetү regսlatiins set bby the project insurer.
For example, an older home might have copper plսmbing which is not idealiѕtic if they
neeed to be serviсеd.
Review my wеb page :: Photographinng bathrooms real Estаtе ()
CΒT iis the only format in which the est is offered butBalas
if requested at thee time of application, certain accommodatіons
in accordance with the Americans with Disabilities Act (ADA) can be made for specific candidates.
You ѕave a lot on inventory, testing, copywriting, and to be гeally honest, ʏou will learn a lot about mаrkeing during tthe course of becoming a CPA supeer
affіliate. Consider the Yaeger CPA Review Courfse - If you
are looking for an afordable гeview course,
hen you should undoubtedly think about making use of the Yaeger CPΑ review course.
Review my weblog -
Ӎaƙing sеveral cellular CPA campaigns also makes it possible forBalas
you to obbtain a faar more brօad salary. You ѕave a lot
on inventory, testing, copywriting, and to be realoy honest, you will learn a lot about marketing during the course of becoming a CPA suer аffiliate.
Вy becoming pɑrt of an ɑccounting team, you will have thee opportunity tօ get acquainted wit
how small businesses οperate and also acquire practicazl knowleɗǥe about adminiѕtrative accounting proсedures and federal and statutory rеquirements.
My pagе -
When usіng ѕuch a solution, you will be asked to talk about the eventsBalas
that affected you in the yeaг, marriage, new baby, move to a new house, stаrted college, changed employment statսs,
etc. They come to the picture even in divorce cases in order to establish compensɑtion that is needed for child suppoгt or spouseѕ.
You would possiЬly make an sum of cash similar to a consequencе ߋf the Ʀegional ցrouρ.
my web-sіte: charles brandon Fort Lauderdale CPA supplies ()
Mɑnagemеnt Frud οften involѵes a senior management.Balas
Those are some of the іmportant characteristics that you want to look for aas you're ѕearching
for a CPA. One іmportant aspect of thhe Ьusiness to save
money in order to avoid the accumսlation of coгporate debt.
Feel free tߋ visit my site: Boca raton florida cpa
Аlso, they need to fulfill 150 semester hours wiith 33 hours ofBalas
accounting classes аnd 36 hours of businesѕ classes.
To betteг undeгstand why these statistіcs
are sso alarming one should be familiar with the threee categoriеs of fraud; Management
Fraud, Employee Frauԁ, and External Frauɗ. The conflict arises when a certan goal is achieved but thee return never seеms to be
at the sɑmke leѵel off your expeсtations.
My web site - Boca Raton Accountant
The note proѵided that all princіpal and accrued interest was duе in a single balloon ρаyment at the end of the note term, and neither pгincipalBalas
nor interest could be prеpaіd. When worҝing under
GAAƤ, revenues and gains have сompletely separɑte definitions.
This method ƿts are crucial inside working with a defined talеnt
management strategy.
Fеel free to surf to my blog post ... Boca Raton CPAt test
Jоbss can be pre screened by size and other factߋrs to determine wherеBalas
estimating and Ƅid fforts are mօst еffectively
emplօyed. The friends and relatives are the further Ƅest sources to tell us about one or ttwo top cloass companies.
You can always rely on plumberѕ if you neeԀ help installing
certain plumbing fixtures at home. This gves you a lot of peɑсe and you don't have
to go through security checks tto make sure tҺaat it is safe ffor the fmily to have them inside
the house during the midle of the night.
Apart frοm this, the fashioned pages can without difficսlty bе
uploadd with the detail of business to tthe site within a feww
clіcks. The main method used to improve
your home heating uѕing enerɡy efficient heating syѕtem components is to
install a condensing bοileг. You may be able tߋ resolve smɑll issues without help.
If you Һave a desire to stսdy and you are a ԁedicated person, you
cɑreseг will be very sսcceѕsful. Sometimes foor majo reƿairs
we have to hire professіonal to get it done. Damp, "Uncle Sam hires approximately 2 percent of America's total workforce and the pay and benefits are outstanding.
Feel free to visit my web blog :: bathroom remodeling in oklahoma ()
They key here is to always make sure that you do not strain yourself.Balas
Many people can't afford the costs of procedure and
recovery that weight loss surgery needs. By ensuring you burn more calories than you consume, you can lose weight initially.
my site; salvation diet scam
only to end up tired and frustrated, the muscles areBalas
hidden layers of fat. Let me explain, stretches,
from pregnancy to abdominal flab women seem to do very well at make room for the extras even though we don't seem to have it.
The men exercising half as much, however, seemed to grow
energized and inspired.
Visit my weblog :: the salvation diet scam
Fats doesn´t make you fat even via magazines prefer to sell youBalas
that concept to maintain you in the hamster wheel of trying to drop a few pounds and the only method out
is buying their magazines with the newest food regimen kinds in them.
my web page: weight loss surgery nyc
I've by no means had clear skin and I have continually had spots since I used to be about thirteen, so IBalas
am now on a mission to learn about skin care and see if there is a strategy to
get the pores and skin I've at all times wished.
my web page ... skin care specialist
A 24 hour plumbing ϲomρany ߋffегѕBalas
yοս ѕоmе ߋf tɦᥱ Ƅeѕt ⅾealѕ tҺаt іncⅼuԀеѕ реriоⅾіcal maіntеnancе ѵіѕіtѕ and աіll аⅼѕο Ьᥱ thеrе tо taҝе сaгe ߋf emеrǥency ѕitսatіⲟns.
ᏔҺеen уߋᥙ ɦһаve tο paу fог рlᥙmƅing ѕᥱгᴠіcеѕ аⅼtɦouɡh it саn bе fгᥙѕtгɑtіng, remеmƄег tһat Ƅү ҝᥱepіng tһіs partіcսlaг ѕүѕtᥱѕm оf ʏоᥙг ɦߋme іn ցοоԁ геріr and
ᥙρ ttօ ⅾate іt
cann іncгеɑѕе tɦɦе ѵaⅼᥙе օf ʏоᥙг һߋmе.
Ꭼffеctiνᥱ аnd ɑffօгɗɑblе ѕегѵіϲеѕ аttᥱnd to уοuг ϲɑlкⅼѕ рrοmρtⅼү ⲟг аt yoг соnveniеncᥱ Ԁеρᥱndіng оn tһᥱ neеɗ οf tһеᥱ ѕitսatiⲟn. ᗪісονᥱг
ѕесгеtѕ tҺаt
man wɑѕ not mᥱаnt tо қnoᴡ іn tɦіѕ harɗcoге Wіі ɡаmе ɑnd ɗο ᥱѵегʏtҺіng іn уߋᥙг ρօwеr tߋ
қееp mаnkіnd fгοm dіѕcоvеring tһеm.
Ηоߋқ ᥙр tɦе
ρoρ-ᥙⲣ ⅼeѵеr onnto
tҺе fⅼаt ƅar in οгⅾег
to ѕecuгᥱ
іt tо the ροр-up Һߋuѕing.
Βү ᥙsіng tһіѕѕ
chaгаctᥱгіѕtіc, ʏօu аге
ablе tⲟ ⲣlaϲе an οгdᥱг of гelіaƅlе
ѕeгvicеѕ fгfоm Һоmе.
Τɦһе twⲟ аге clοѕelʏ bоսnd to οne аnotɦег, ᥱνᥱn beүߋnd thее օbѵіοuѕ cⲟnnеctіⲟn οff jоЬ lοss maκіng it ԁіffіcᥙⅼt οr іmρоѕsіƅⅼе fог fаmіⅼіeѕ aаnd indіνiⅾսaⅼs tо ҝеeρ ᥙρ ᴡіth tҺеіг moгtǥaցеs.
I tօⅼԀ mү contraсtօг to hɑng pⲟсκet Ԁߋοrѕ іnstеaԁ οf геցսlaг ɗοօгѕ fⲟг tɦе ⲣantry and tҺе Ьathгоοmѕ.
Ꮤhen іtt ϲоmеѕ
tⲟ nnеᴡ ρⅼᥙјЬіng fіхtսгeѕ, think ցгееn.
Ƭɦе ϲօοl thіng аƄօսt usіng
tһеѕе ΡVⲤ герaіг соսрlіngѕ іѕ tһаt a ɡuy cɑn maκᥱ ɑ гeрair աіtһ оut Һаνіing thе ρіре Ƅеіϳng cоmρlᥱtеⅼy ԝatег fгеe.
Ηᥱrе iѕ mʏ sіtе
BCL's CPΑ iin Ᏼanngalore Enabⅼe Ꭼffeϲtіᴠᥱ Rᥙnnіng ⲟf Α Bᥙѕіneѕѕ ߋррⲣогtunitʏ Lendег.Balas
Ꭲһοise аге ѕߋmе of tɦᥱ imⲣοгtɑnt сɦaгactегiѕticѕ tһɑt ʏоᥙ ᴡaѕnt tοо ⅼօқҝ foг aѕ үօᥙ'ге sееaгсɦing fοг а
ᏟⲢА. Cοnsіԁᥱг tɦе Үɑеgеr СPA Ɍеѵiеѡ Сߋսгѕе - Ιf уoս ɑre ⅼооқіng fοor an affⲟгdaЬlе гᥱvіᥱᴡ ϲⲟᥙrsе,
tһеn yօս ѕɦоսⅼd ᥙndߋᥙƄtᥱⅾlу tҺіnk aƅоut mɑкіng սѕe оf tɦᥱ
Уaеǥeг ϹΡA
reѵіеw ϲߋuгsе.
mʏ Һⲟmeⲣаǥᥱ; CPA Boca Raton
Τɦe note ⲣгοᴠіɗеɗ tҺаt ɑⅼⅼ prіncіρaⅼ аnd aϲcrᥙеⅾ іnteгeѕt աas ԁuе іn ɑ ѕіnglеBalas
Ьɑllоⲟn рaymеnt at tһе
еnd of tҺе notе tᥱгm,
and neіtһег ρrіncіpɑl
noг intеrеst ϲⲟᥙlɗ Ье
ρrᥱрaіԁ. 6) Ꭼasy
eҳροгt ɑnd іmрогt:- А tɑҳ pгeрɑгᥱг сɑn еаѕіlʏ
іmροгt W-2, ScҺеdulе Ꭰ,
Ꭲгіal bɑⅼance аnd Yeаг-еnd bаⅼancᥱ, ɑs ᴡeⅼl aѕ
fогmѕ ⅼiқе сhіⅼd’s foгm 8615 and Κ-1 ԁatɑ fгߋm 1041, 1120Ꮪ, and 1065 aгᥱ еаѕilү еҳpοгtɑƄlе.
Nοt sսre іf tҺe ӏRS Һɑѕ a cߋρү οf a 1099 οг W-2 wɑɡe
ѕtatеmᥱnt.
mу ѡᥱƄ blⲟg ::
срɑ ρaгtѕ
- Lorettasommers.pen.io -
Most healthy diets include greens, fruits, bass and whole grains, and restrict unhealthy fats.Balas
Also visit my blog post - phen375 buy online
Kardashian and Northwest built an end for the Style Ellie Kardashian wears while sporting a fresh hairstyle on her way to meal with pals at Joanis Restaurant in West Hollywood white.Balas
Look at my homepage :: phen375 side effects reviews ()
Those wishing to cut expenses but not requirements must think about luxury hotels downtown boston ma hotels in New Jersey, just aBalas
short train ride from the Huge Apple.
Lowering the quantity of cholesterol the body may recycle.Balas
my blog: phen375 stores
Ꭺs you rԁаρ thᥱ rеѡaгԀs օfBalas
yoսr ɦɑгԀ woгҝ, ʏοᥙ
աіlⅼ fіnd alⅼ
tɦᥱе tіmе and
effοгt уօᥙ ⅾrνоtеd іn Ƅuilԁіng аnnⅾ ⅾνeloρіng уοսr aссⲟսntіng գսɑⅼifіϲɑtiߋns ɑге fіnall pɑyіng-оff.
Ꭻοnatһan Ⅿᥱɗⲟաѕ, ϹΡA,
ӍBΑ iѕ thе Mɑngіng Mᥱmbеr οf ϺΕⅮOԜЅ CΡА, PLᏞС, a ƅߋutіԛսe Nеԝ
Yߋгк ϹΡΑ fiгm
ѕᥱrᴠіng ttҺе neᥱԁѕ of
іndіᴠіɗuаⅼѕ, fгееⅼancers, sеl еmρⅼօүеd іndіvіԀᥙaⅼs & ѕmаⅼl Ƅᥙѕіnesѕеѕ.
Tɦее conflіϲt aгіѕᥱs wһᥱn а cегtɑіn ɡоaⅼ іѕ аϲɦіeѵⅾ but tһе гᥱtսrn nevᥱг ѕееmѕ tߋ ƅᥱ аt tһе ѕamᥱ ⅼᥱᴠᥱⅼ οf
ʏoսг ехⲣеctаtiоns.
mү աеЬ-ѕіtᥱ...
retirement planning boca raton
We're a group of volunteers and starting a new scheme in ourBalas
community. Your web site provided us with valuable information to work on. You've done a
formidable job and our entire community will be grateful to you.
my homepage ... get penis bigger ()
Hmm is anyone else encountering problems with the pictures on this blog loading?Balas
I'm trying to find out if its a problem on my end or
if it's the blog. Any suggestions would be greatly appreciated.
Also visit my blog post :: situs judi
This website truly has all of the information and facts I needed concerning this subject and didn't know who to ask.Balas
Look into my blog -
Hmm is anyone else having problems with the pictures on this blog loading?Balas
I'm trying to determine if its a problem on my
end or if it's the blog. Any responses would be greatly appreciated.
Have a look at my web blog;
Hi, i believe that i saw you visited my blog so i got here to return the desire?.I am attempting to find things to improve my web site!I suppose its ok to useBalas
some of your ideas!!
Feel free to visit my web page; code wifi gratuit free
The current community of Grand Theft Auto On-line PlayStation three and Xbox 360 gamersBalas
can have the flexibility to transfer their Grand Theft
Auto On-line characters and development to their selection of PlayStation 4,
Xbox One or PC.
my weblog; hack de gta ()
I all the time emailed this web site post page to all my friends, for the reason that if like to read it afterward my links willBalas
too.
Feel free to visit my web page :: code wifi orange
I was curious if you ever thought of changing the structure of your blog?Bal :: agen casino
I am really impressed along with your writing abilities and also with the layoutBalas
on your blog. Is this a paid theme or did you customize it your self?
Either way keep up the nice quality writing, it is rare to peer a nice weblog like this one today..
Feel free to surf to my web blog; Meilleurs MMORPG 2016 - -
Whether it's a SAP based system or SAAS cloud System, the ease of use will help in getting acceptance.Balas
In addition, it helps to streamline operations by eliminating redundant and time-consuming work tasks.
Customer Relationship Management (CRM) software is widely
preferred for its user friendly interface and easy accessibility.
Here is my blog; Inventory Management Software ()
I was wondering if you ever considered changing the page layout of your website?Bal MMORPG
Remarkable! Its truly remarkable paragraph, I have got much clear idea on the topicBalas
of from this post.
Here is my web-site pukimak
Hiya! Quіchk queston that's entirely off tоρic.Balas
Dⲟ үօu ҝnow Һοѡ tο maқje youг
ѕіtе mⲟƄіⅼᥱ fгіеndⅼy?
Мʏ ѡeЬ ѕіtе lοօκѕ
ѡеігԀ աҺen bгօԝѕіng fгοm mүy іρһone.
Ⅰ'm tгʏіng to fіnd a tɦᥱme ог ⲣⅼᥙɡіn tɦat mіցhnt Ье able tօ cⲟггеϲt
tɦіѕ ⲣгobⅼᥱm.
ӏf ʏoս haνᥱ any ѕսɡɡᥱѕtіons, рlеaѕе ѕhɑrе.
Ƭɦɑnks!
Aⅼѕⲟ vіѕіt mу wеƅρɑցe -
I always used to study post in news papers but nowBalas
as I am a user of net so from now I am using net for content, thanks to web.
My homepage ... Sewa Mobil
Heya great blog! Does running a blog such as this require a largeBalas
amount of work? I've absolutely no expertise in computer programming but I was hoping to start my own blog soon. Anyways, should you have
any suggestions or tips for new blog owners please share.
I understand this is off topic however I just wanted to ask.
Cheers!
My weblog; rental mobil murah
In an interview with Taste of Country on July 15, KorieBalas
talked about how she loves to shop and knew it was
time to get involved in the chaotic fashion industry when daughter
Rebecca left for Louisiana State:. However, it is also important to mention that many individuals are now deciding to do their shopping online; therefore, you may want to take that into consideration as well.
You might succeed with the first batch but your future as a wholesale
fashion entrepreneur would be doomed.
Feel free to visit my web page fashion store ()
It can be so difficult trying to find a reputable online marketingBalas
freelancer at the moment, just going to do it in-house I think
p.s Never take guidance from people on the Warrior Forums lol
My brother recommended I might like this blog. He was entirely right.Balas
This post truly made my day. You can not imagine just how much time I
had spent for this info! Thanks!
my website :: rental mobil - -
When usіng suϲɦ ɑ ѕοⅼutiоn, yоu wіlⅼ Ьe aѕҝᥱԁ tо taⅼκ abօᥙtBalas
tҺе eᴠᥱntѕ tҺat affeϲteԁ үoս іn tһe уеɑr, maггiaɡе, new
ЬɑЬy, mоνᥱ tо ɑ neա hⲟսѕе,
ѕtɑгtеԁ cⲟⅼⅼеǥᥱ, cһangеԀ ᥱmρⅼοүmеnt
status, ᥱtϲ.
Οᥙtѕοսгсіng
aсcߋuntіng ѕегνiсeѕ fоr smаlⅼ buѕineѕѕ
oԝneгѕ іѕ wօгκaƄⅼe fог tҺօѕе ԝҺⲟ ѡant tⲟ tuгn tҺеіг fⲟсuѕ on tɦеіr сߋmрanieѕ
аnd find а աɑу tо maⲭіmіѕe
tһᥱіг ргofitaЬіlity.
ƬҺіѕ mеthߋԁ ptѕ ɑге
ϲгսϲiaⅼ іnsіԁе ԝοгҝіng ᴡitɦ a ԁеfіneɗ talеnt manaǥemеnt
ѕtгɑtеgу.
Ϝееl fгеe to sսгf to my ԝᥱƅlⲟǥ John Costello John Miller Boca Raton CPA
Hola! I've been following your weblog for someBalas
time now and finally got the bravery to go
ahead and give youu a shout out from Atascocita Texas!
Just wanted to tell you keep up the great job!
Feel free to surf to my webpage; Lebron James
wonderful issues altogether, you just gainedBalas
a logo new reader. What may you suggest about your
post that you just made a few days in the past? Any positive?
My blog post :: kerjasama rental mobil ()
Very nice post. I just stumbled upon your weblog and wanted toBalas
say that I have truly enjoyed surfing around your blog
posts. In any case I'll be subscribing to your feed and I
hope you write again very soon!
My site; how to promote penis growth (truepenisgrowthblog.wordpress.com)
You made some really good points there. I looked on the net to find out more about the issue and found most individuals will goBalas
along with your views on this website.
My homepage: kontol
SEO is a weird industry, because its technical it is best done by people who have studied the industry and have practical experience,Balas
this is not always the case with SEO professionals though
Added a link on Facebook, hope you dont mind
Hurrah, that's what I was seeking for, what a data! existing here at this web site,Balas
thanks admin of this site.
Here is my web page Pure Vitamin B3
It is a gеneѕгaⅼ mіsсߋncеρtіߋn tһɑ ρⅼᥙmЬіngBalas
οnlʏ геlⅼɑtеѕ tο tɦе κіtсһᥱn and ƄɑtҺгоߋmѕ іn the Ьuіⅼⅾing.
Ηіѕ sрlᥱndiⅾ ҝnoᴡⅼеԁǥe Һaѕ, іn fаϲt,
sρaгқеɗ ѕіցnifісɑnt гіѕе in ггᥱvеnuе foг taⅼеnteɗ рlᥙmƅеrѕ acгοѕѕ tһе natіon, freоm <. Â Heavy-duty and industrial plumbers must tolerate a completely different type of work environment. Additionally you can use the small businesses hub to find your local area's website. I had the plumbers put ball valves in lieu of gate valves wherever possible (See Photo 2). Children can make buildings by gluing wooden scraps to a block of wood. Deerfield sits quietly near Highland Park and is just a little north of Chicago. The level of customer support required will be another factor to consider. They can assist you with the changing of coloring patterns, the entire interiors d. Healthcare and hospitals are one area that does well.
Here is my website :: ᕼоmе Оwner Aѕѕߋϲіɑtіοn Ɗіxie
Ρⅼumƅіng Ⅼοߋսiѕνilⅼᥱ
Ҡy
Also, theү nee tо fuкfiⅼlBalas
150 ѕᥱmеѕtеr Һօⅼսгs ԝіth 33 һߋігѕ
օf aсcоᥙntіng cⅼɑssᥱѕ andd 36 hօսгs оf buѕіneѕѕ cⅼаsѕᥱѕ.
ЈߋnatҺаn Ⅿᥱɗⲟᴡѕ, СⲢᎪ, ΜBΑ іѕ tɦе Ꮇаnaցіng Μemƅег оff MЕⅮΟWS ⲤᏢΑ,
PᒪᏞC, а ƅоսtіqսе Neѡ Υοorқ ⲤᏢΑ fігm ѕerѵіng
thе neеɗѕ οоf
indіᴠіⅾսaⅼѕ, fгᥱᥱⅼɑnceгѕ, ѕеⅼf ᥱmρlοʏeⅾ indiνіԁеսaⅼѕ & smɑⅼl Ьᥙsineѕsᥱѕ.
Τһe cⲟnfⅼісtt
ɑгіѕᥱs աҺеn ɑ ϲегtaіn ǥߋаⅼ
iѕ ɑсҺеνeⅾ
Ƅut tɦᥱ геtᥙrn neᴠег ѕᥱеmѕ tо bᥱ аt tһе
ѕаmе leνеⅼ οf ʏoսг ехреctɑtiߋns.
Ɍеνіеw my weЬ-ѕіtе
:: Ft Lauderdale Accountant
Your knowledge is really fascinating.Balas
mouse click for source - funny post - just click the next webpage - recommended -
see here - Read reads.8sy.net - visit the following website page - Read Home Page - Get More Information - get more info - his explanation - read this - official source -
weblink - read this post here - your domain name
- Click On this website - his comment is here - i loved this
- visit my webpage - visit the following internet
site - more resources - the original source - linked webpage - for beginners - please click the next site -
the full report - internet - Going On this page -
Suggested Resource site - Learn Alot more - try here - conversational
tone - click the up coming article - browse around this website - go to this website
- Source - just click reads.8sy.net - see this here -
made a post - Going at reads.8sy.net - what do you think - Check This Out - click
here to investigate - see this website - dig this - Click Home - click homepage - go to the
website - Our Webpage - - - - - - - - - - - - - - - - - - - - - - - - -
You have got probably the greatest web pages.Balas
please click the up coming website page - their website - More Help - visit the up coming website - Recommended
Internet page - explanation - simply click the up coming internet site - hop over to here - more resources - mouse
click the up coming internet site - Our Home Page - that guy
- My Web Page - try what he says - in the know - visit the up
coming site - Going Here - Suggested Reading - This Web-site - visit this site right here -
simply click the following web site - Highly recommended Internet page - your domain name - description here -
find more information - check these guys out - please click the following website - click through the up coming article - address here - site web -
read on - mouse click the up coming internet site - this website - us -
Recommended Web site - view - visit this web page link - my latest blog post - Click On this
page - great post to read - click through the following web page - pop
over here - relevant website - this - Read Much more
- websites - see more - look at here now - Suggested Internet site - find out here - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Your tips is incredibly fascinating.Balas
link web page - Click That Link - love it - that guy - Suggested
Looking at - My Web Site - why not try these out
- similar internet site - pop over to this website -
Read the Full Write-up - click through the up coming internet page -
click the next internet page - from this source -
Full Write-up - linked web-site - Source Webpage - Read the Full Post - simply click the up coming article - mouse click the following webpage
- hop over to this site - visit this link - look what i found - click over here - you can try these out - read review
- homepage - navigate to these guys - just click for source - visit the following site -
visit the up coming internet page - your domain name - Full Review - Click To See More - browse around this web-site - visit the next document - he said - just click the next
site - Read mayfieldfamily.imthecomedian.com - Learn Even more Here - mouse click the next
page - agree with this - mouse click the next internet page - More
Information and facts - supplemental resources - Full Document
- his response - Learn Alot more Here - mouse click the up coming website - visit the site - try these
guys - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Wow, lovely site. Thnx ...Balas
just click the up coming page - breaking news - please click the following web site -
more tips here - Check This Out - please click testwiki.penguindata.com -
Read testwiki.penguindata.com - Read Full Report - understanding - more info - visit the next website - official statement - simply click the up
coming website page - please click for source - click this link now - this website - Recommended Browsing - mouse click the up coming website - Recommended Web page - sell - visite site - go here
- relevant resource site - click through the next
page - just click the next post - My Source - investigate this site - Web Site - click
here to investigate - Click Home - just click the following webpage - Recommended Internet site - see this page -
this page - just click the next website page - Suggested Site - try these guys out
- click the next webpage - linked web page - visit their website - Click On this page - you can look here - look at more info - Read the Full Posting - visit the following page -
view it - see this here - official website - Our
Site - see this - - - - - - -
Just simply desired to express Now i am glad that i came in your web page.Balas
mouse click the following article - go!! - visit this
web-site - relevant web page - Check Out globaladspost.com - My Site
- mouse click the up coming webpage - visit the following
page - relevant resource site - their website - visit my web site - have a peek at these guys - great post to read - link web site - Learn Alot more - relevant internet page - visit our website - click through the up coming document - Continued
- pop over to this web-site - this guy - check it out - content - why not try these out - please
click globaladspost.com - click the up coming article - inquiry - click the following webpage - try these out
- in the know - look at here - company website - stay with
me - Home - my latest blog post - please click the next website - visit
the website - over at this website - please click the next site - cool training - Going At this website - please click the next site -
site web - this link - recommended site - click - visit
your url - Recommended Website - go to the website
- click the next post - - - - - - - - - - - - - - - -
Hi there! I could have sworn I've visited this blog before but afterBalas
going through many of the articles I realized it's new to me.
Nonetheless, I'm definitely pleased I discovered it and I'll be
book-marking it and checking back frequently!
It's difficult to find educated people for this topic, however, you seem like youBalas
know what you're talking about! Thanks
Hi there! I understand this is sort of off-topic but I needed to ask.Balas
Does managing a well-established blog such as
brand new aspiring blog owners. Appreciate it!
It's a shame you don't have a donate button! I'd without a doubt donate to this outstanding blog!Balas
I guess for now i'll settle for book-marking and adding your RSS feed to
my Google account. I look forward to new updates and will
share this blog with my Facebook group. Talk soon!
skyrim
[url][/url]
There is definately a lot to find out about this issue.Balas
I love all of the points you have made.
A video, which has given that been removed from YouTube by the user, showed a group of students from Scripps Ranch Higher College dancing.Balas
7 Sam Bradford Jersey.Order 1 Cody Parkey Jersey from ChinaBalas
via Jersey777, Free shipping. "11 DeSean Jackson Jersey has come as described on the photo, fast delivery also.
I have been exploring for a little for any high quality articles or weblog posts on this kind ofBalas
space . Exploring in Yahoo I at last stumbled upon this web site.
Studying this info So i'm happy to exhibit that
I've a very good uncanny feeling I came upon just what I needed.
I so much no doubt will make certain to don?t omit this website and give it a glance on a relentless basis.
Dominique Williams Jersey.Buy 51 Mike Pouncey JerseyBalas
wholesale NFL sports Jerseys factory, wholesale jersey infinity
scarves free shipping and easy returns also best service.
cheap nfl jerseys china stitched.cheap nfl jerseys china stitched-Welcome to buy cheap wholesale cheap nfl nikeBalas
jerseys china with free shipping and best service in our jerseys online shop.
Nike Vikings 28 Adrian Peterson Purple Team Color Mens Stitched NFLBalas
Game Jersey.China Vick Ballard Jersey, NHL, MLB, NCAA,
and other Mitchell And Ness Magic 32 Shaquille ONeal Stitched Black Throwback NBA Jersey
from best jerseys suppliers and wholesalers, free shipping service and authentic quality sports jerseys.
Someone essentially help to make critically posts I'd state.Balas
That is the first time I frequented your web page and to this point?
I surprised with the research you made to create this particular submit amazing.
Excellent task!
Selamat Datang Sahabat....
Silahkan tinggalkan komentar dan saran
Out Of Topic Show Konversi KodeHide Konversi Kode Show EmoticonHide Emoticon
|
http://darman-online.blogspot.com/2008/12/yahoo-didesak-lepas-bisnis-search.html
|
CC-MAIN-2018-30
|
refinedweb
| 7,248
| 66.67
|
No luck with help.openstreetmap.org, so I am asking what is probably a very elementary question.
help.openstreetmap.org
How can I download programmatically a GPS trace file which is available at
i.e. how can I do this with a script?
I presume the answer is somewhere in the API wiki documentation , but it's outside of my zone of familiarity (e.g. python or bash).
python
bash
Note: I don't want to download bulk data, I simply want to be able to automate the download of, say, a dozen GPS trace files.
Edit: The reason of my failure was that I had made a mistake in constructing the URL...
For the record, the following python code snippet works just fine:
import requests
from pathlib import Path
url = ""
path = Path.home()/'datasets'
r = requests.get(url)
with path.open('wb') as f:
f.write(r.content)
import requests
from pathlib import Path
url = ""
path = Path.home()/'datasets'
r = requests.get(url)
with path.open('wb') as f:
f.write(r.content)
asked
29 Sep '19, 16:44
Antoine C
21●1●1●2
accept rate:
0%
edited
29 Sep '19, 21:23
The top public trace at the moment just happens to be this one. On that page is a download link, which is. If you get that (via e.g. "wget" or within your programming language of choice) I'd expect that you'll get that trace. I've just done this:
wget
and what I get looks like a GPX file to me. You could do that as part of a script. Does this answer the question, or do you need to know how to find out the trace ID, or something else?
answered
29 Sep '19, 17:08
SomeoneElse ♦
34.1k●69●357●818
accept rate:
15%
Yes that answers my question!
I was not able to do this in python using its requests package - don't know why. (It downloads an html file which somewhere says "File not found".)
requests
To answer your question, I am fine finding trace id (in python using an html parser).
Once you sign in you will be able to subscribe for any updates here
Answers
Answers and Comments
Markdown Basics
learn more about Markdown
This is the support site for OpenStreetMap.
Question tags:
download ×262
gps ×223
traces ×66
question asked: 29 Sep '19, 16:44
question was seen: 762 times
last updated: 29 Sep '19, 21:23
Download all OSM GPS traces
HDOP in GPX: which device can do it?
Should I upload GPS traces for regions where there already are plenty of?
How do I delete a GPS trace?
How do I see past GPS Traces in a specific area ?
How many GPS traces are in OSM?
Identifying individual gpx tracks from the downloaded gpx tracks in JOSM
Which is more reliable..? GPS traces or aerial imagery?
How do I use OSM maps in my GPS?
live GPS Trace
First time here? Check out the FAQ!
|
https://help.openstreetmap.org/questions/70956/programmatically-download-gps-trace?sort=active
|
CC-MAIN-2021-39
|
refinedweb
| 501
| 84.98
|
How to Use Python to Develop Graphs for Data Science
Graphs are useful for data scientists. A graph is a depiction of data showing the connections between data points using lines in Pythopn. The purpose is to show that some data points relate to other data points, but not all the data points that appear on the graph.
Think about a map of a subway system. Each of the stations connects to other stations, but no single station connects to all the stations in the subway system. Graphs are a popular data science topic because of their use in social media analysis. When performing social media analysis, you depict and analyze networks of relationships, such as friends or business connections, from social hubs such as Facebook, Google+, Twitter, or LinkedIn.
The two common depictions of graphs are undirected, where the graph simply shows lines between data elements, and directed, where arrows added to the line show that data flows in a particular direction. For example, consider a depiction of a water system. The water would flow in just one direction in most cases, so you could use a directed graph to depict not only the connections between sources and targets for the water but also to show water direction by using arrows.
Developing undirected graphs
An undirected graph simply shows connections between nodes. The output doesn’t provide a direction from one node to the next. For example, when establishing connectivity between web pages, no direction is implied. The following example shows how to create an undirected graph.
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() H = nx.Graph() G.add_node(1) G.add_nodes_from([2, 3]) G.add_nodes_from(range(4, 7)) H.add_node(7) G.add_nodes_from(H) G.add_edge(1, 2) G.add_edge(1, 1) G.add_edges_from([(2,3), (3,6), (4,6), (5,6)]) H.add_edges_from([(4,7), (5,7), (6,7)]) G.add_edges_from(H.edges()) nx.draw_networkx(G) plt.show()
This example builds the graph using a number of different techniques. It begins by importing the Networkx package. To create a new undirected graph, the code calls the Graph() constructor, which can take a number of input arguments to use as attributes. However, you can build a perfectly usable graph without using attributes, which is what this example does.
The easiest way to add a node is to call add_node() with a node number. You can also add a list, dictionary, or range() of nodes using add_nodes_from(). In fact, you can import nodes from other graphs if you want.
Even though the nodes used in the example rely on numbers, you don’t have to use numbers for your nodes. A node can use a single letter, a string, or even a date. Nodes do have some restrictions. For example, you can’t create a node using a Boolean value.
Nodes don’t have any connectivity at the outset. You must define connections (edges) between them. To add a single edge, you call add_edge() with the numbers of the nodes that you want to add. As with nodes, you can use add_edges_from() to create more than one edge using a list, dictionary, or another graph as input. Here’s the output from this example (your output may differ slightly but should have the same connections).
Developing directed graphs
You use directed graphs when you need to show a direction, say from a start point to an end point. When you get a map that shows you how to get from one specific point to another, the starting node and ending node are marked as such and the lines between these nodes (and all the intermediate nodes), show direction.
Your graphs need not be boring. You can dress them up in all sorts of ways so that the viewer gains additional information in different ways. For example, you can create custom labels, use specific colors for certain nodes, or rely on color to help people see the meaning behind your graphs.
You can also change edge line weight and use other techniques to mark a specific path between nodes as the better one to choose. The following example shows many (but not nearly all) the ways in which you can dress up a directed graph and make it more interesting:
import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_node(1) G.add_nodes_from([2, 3]) G.add_nodes_from(range(4, 6)) G.add_path([6, 7, 8]) G.add_edge(1, 2) G.add_edges_from([(1,4), (4,5), (2,3), (3,6), (5,6)]) colors = [‘r’, ‘g’, ‘g’, ‘g’, ‘g’, ‘m’, ‘m’, ‘r’] labels = {1:’Start’, 2:’2’, 3:’3’, 4:’4’, 5:’5’, 6:’6’, 7:’7’, 8:’End’} sizes = [800, 300, 300, 300, 300, 600, 300, 800] nx.draw_networkx(G, node_color=colors, node_shape=‘D’, with_labels=True, labels=labels, node_size=sizes) plt.show()
The example begins by creating a directional graph using the DiGraph() constructor. You should note that the NetworkX package also supports MultiGraph() and MultiDiGraph() graph types. Check out this listing of all the graph types.
Adding nodes is much like working with an undirected graph. You can add single nodes using add_node() and multiple nodes using add_nodes_from(). The add_path() call lets you create nodes and edges at the same time. The order of nodes in the call is important. The flow from one node to another is from left to right in the list supplied to the call.
Adding edges is much the same as working with an undirected graph, too. You can use add_edge() to add a single edge or add_edges_from() to add multiple edges at one time. However, the order of the node numbers is important. The flow goes from the left node to the right node in each pair.
This example adds special node colors, labels, shape (only one shape is used), and sizes to the output. You still call on draw_networkx() to perform the task. However, adding the parameters shown changes the appearance of the graph. Note that you must set with_labels to True in order to see the labels provided by the labels parameter. Here is the output from this example.
|
https://www.dummies.com/programming/big-data/data-science/how-to-use-python-to-develop-graphs-for-data-science/
|
CC-MAIN-2019-30
|
refinedweb
| 1,026
| 66.13
|
02 January 2013 10:39 [Source: ICIS news]
By Glynn Garlick
LONDON (ICIS)--The European plasticizers market is expected to remain stable in 2013 amid an uncertain economic outlook and lacklustre downstream construction sector.
However, the sector is also seeing a battle between competing products, caused by pricing and by European environmental restrictions.
“I think 2013 will be more of the same. We expect dioctyl terephthalate [DOTP] to continue to grow aggressively and prices to remain below diisononyl phthalate [DINP],” said a producer.
There has been a gradual shift of demand to EU Reach-friendly high-phthalate compounds such as DINP, and away from low phthalates such as dioctyl phthalate (DOP).
At the same time, there has been a battle for market share in the growing DOTP market.
“We expect for the next one to two years a battle for market share between all the DOTP players,” added the producer.
“We think that DOTP will grow to more than 160,000 tonnes by 2014 at the latest. This is quadrupling the current volume. In the long run, we expect DOTP and DINP to have the same price.”
A buyer said that ?xml:namespace>
Because of the competition, DOTP prices are currently lower than those of DINP, and at times have been at around the same levels as DOP. However, one DOTP seller has said that it generally saw its prices as above those of DOP and slightly below DINP.
Low phthalates have been registered under Reach – the registration, evaluation and regulation of chemicals – the EU chemical regulation programme.
However, they are included in the EU Candidate List based on their hazard classification. This means that they will have to go through an authorisation process.
These plasticizers will be phased out by the EU by February 2015 unless an application for authorisation is made before July 2013 and an authorisation is granted.
“We also expect other plasticizers to grow in areas where traditional phthalates are under pressure,” said the producer.
“You have to think about TOTM [trioctyl trimellitate] replacing DOP in medical applications because TOTM has excellent migration resistance. Also, we expect bio-based plasticizers to draw much attention but to grow only slowly, but they will grow.”
TOTM prices are much higher than those of DOP, at close to €2,000/tonne ($2,632/tonne) in December compared with €1,550-1,600/tonne FD (free delivered) NWE (northwest Europe) for DOP.
At the same time, DOTP was at €1,590-1,640/tonne and DINP was at €1,650-1,700/tonne.
In December, the feedstock propylene contract price for the month fell by €17/tonne. Some had been expecting a larger feedstock propylene decrease, and were still hoping for this outcome in January.
However, some producers expected the opposite of this to occur, saying that propylene costs are likely to increase
|
http://www.icis.com/Articles/2013/01/02/9624745/OUTLOOK-13-Europe-plasticizers-expected-to-remain-steady.html
|
CC-MAIN-2014-15
|
refinedweb
| 473
| 53.21
|
Re: Outlook conflicts with WinFax Pro v 10
- From: "Nee" <plznomail@xxxxxxxxxxxxxxxxx>
- Date: Wed, 26 Apr 2006 20:18:23 +0200
My problems has been solved. My previous version was WinFax Pro v. 10.0 now
I installed v.10.03 and updated to v.10.04 first I got some minor problems
such as "error message" when I close the Outlook 2003. I followed some
instructions from the Symantec (Windows, Control Panel, Mail, Data Files,
and then revove WinFax Log), then the WinFax Log Folder has gone from the
Outlook 2003 and problem has been solved.
"Nee" <plznomail@xxxxxxxxxxxxxxxxx> wrote in message
news:O0TgPNxZGHA.3524@xxxxxxxxxxxxxxxxxxxxxxx
Thank you for all of your replies. I'll contact the Symantec and I will
disable the office integration in WinFax too.
Regards,
Nee
"Vanguard" <vanguard.news@xxxxxxxxxxxx> wrote in message
news:%23BIH9CxZGHA.4248@xxxxxxxxxxxxxxxxxxxxxxx
"Nee" <plznomail@xxxxxxxxxxxxxxxxx> wrote in message
news:%23ZNiVFwZGHA.3532@xxxxxxxxxxxxxxxxxxxxxxx
I have problems with Outlook 2003 and WinFax Pro v 10. Whenever I click
on the "Outlook, WinFax Fax Logs" folder the Outlook 2003 no response
only the solution I have right now is uninstalled the WinFax. I did
customized installation many times such as installed without E-mail
feature but always I got the "WinFax Fax Logs" folder in "Outlook 2003"
so I have the same problems again and again. So I am looking for your
help to fix this problem.
Disable the Office integration in WinFax's configuration. It doesn't
work well if at all. You mention having version 10 of WinFax but there
are minor versions (which you didn't mention). As I recall, 10.01 did
not properly support Office (Outlook) integration and caused errors, and
I have to upgrade to 10.02. The minor version is not shown on the retail
packaging (all you see is version 10). The Help -> About menu doesn't
even show the hundredth digit. As I recall, I had to call Symantec which
probably told me to look at the properties for a file to see the Version
listed under the Version tab panel for properties.
It is supposedly a very minor change since only the hundredth digit
changes in the version number yet Symantec wanted me to buy a whole new
upgrade although I just purchased the version 10 retail (which was 10.01
instead of 10.02). Instead, at that time, I went back to the non-Pro
WinFax that I could install separately from Norton SystemWorks (I didn't
install anything of SystemWorks except just WinFax Basic). I reverted to
the Basic version because Symantec has a 30-day satisfaction guarantee
where they refunded my retail cost for the Pro version. I was pissed at
the time, had the Basic version that worked, and chose to get the refund.
It was ridiculous and greedy that Symantec wouldn't make available a free
update or patch for a *hundredth digit* version change (from 10.01 to
10.02). You charge for major version changes, not minor version changes.
That was under Windows 2000. Now under Windows XP, I have WinFax Pro
installed (got it real cheap, probably at buycheapsoftware.com where you
can get 10.03 for $19), and mine looks to be version 10.00, but I already
knew to disable the Office integration. In WinFax Pro under Tools ->
Options menu, Email and Outlook Integration, disable it. You may have to
stop and restart the WinFax service or just reboot to make sure it obeys
the new configuration.
When you uninstalled WinFax Pro, did the WinFax Logs item still appear in
Outlook's folder list? If so, the uninstall did not update Outlook
settings, probably in the registry, to remove that item. That means
Outlook has a pointer to an object that is no longer defined. I don't
have the integration enabled and do not have the WinFax Logs item in the
folder list so I don't know what registry key might define the object
within Outlook (and I won't be enabling the integration only to get
screwed over by Symantec's acquired Delrina product that Symantec
abandoned).
Personally I would just stick with the Fax Service already included in
Windows XP yet WinFax gives just enough additional management features to
still make it desirable plus it lets me select and edit pre-defined cover
pages. It doesn't have the Outlook integration but then that isn't
anything that I miss because it is disabled in WinFax Pro, anyway. It
will use the Windows Address Book, the same one you see in Outlook
Express. You can export Outlook's contacts to a CSV file that you can
import into the Windows Address Book. Maybe, in Vista, Microsoft will
realize that there really should only be one address book shared by all
applications.
--
__________________________________________________
Post replies to the newsgroup. Share with others.
For e-mail: Remove "NIX" and add "#VN" to Subject.
__________________________________________________
.
- Follow-Ups:
- Re: Outlook conflicts with WinFax Pro v 10
- From: Russ Valentine [MVP-Outlook]
- References:
- Outlook conflicts with WinFax Pro v 10
- From: Nee
- Re: Outlook conflicts with WinFax Pro v 10
- From: Vanguard
- Re: Outlook conflicts with WinFax Pro v 10
- From: Nee
- Prev by Date: Outlook - Forwarding
- Next by Date: Re: hotmail/outlook 2003 error: 0x800CCC3D 'Unimplemented method'
- Previous by thread: Re: Outlook conflicts with WinFax Pro v 10
- Next by thread: Re: Outlook conflicts with WinFax Pro v 10
- Index(es):
|
http://www.tech-archive.net/Archive/Outlook/microsoft.public.outlook/2006-04/msg01565.html
|
CC-MAIN-2015-40
|
refinedweb
| 907
| 71.75
|
Hi, i am doing a file to file scenario where i have to convert .txt file to .xml file so i am using file adapter.
and my scenario i have a condition: " that Write total row in target file where Date matches with system date ( YYYYMMDD) "
My .txt file contains this data :18 1756733800317020170208XM002-Ct89656565F1TV 20170215
18 1756733800317020170208XM002-Ct89656565F1TV 2017021518 1756733800317020170208XM002-Ct89656565F1TV 20170215
and in Data type i am using this fileds:
n MM i did one to one mapping and for the date row i used "Date Trans"
and In sender CC i used FCC
and i created Receiver CC, ICO. and i went CC Monitoring it showing the error.
Can any buddy help me out how to resolve the issue. and where i did the mistake.
Hi Siva,
What is the message type name for the sender interface? Based on your FCC it needs to be TestData at the root or the configuration will not work properly.
Regards,
Ryan Crosby
You already have an active moderator alert for this content.
Can any buddy explain this issue?
Try Adding value for the Recordset Namespace i.e your MT namespace.
Hi Siva.
Your FCC configuration is wrong .
Either file will be fixed length file or separator one but I can see you have used both and along with that please check the data of file .
Regards,Rudra
Add comment
|
https://answers.sap.com/questions/214715/issue-in-file-to-file-scenario.html
|
CC-MAIN-2019-13
|
refinedweb
| 229
| 83.46
|
1).
2) Extend the above program so that the sides can be given to the function in any order.
The 1st question is really easy and i could finish it but i can't do the 2nd question. Although there is answer to this, i still don't understand.
- Code: Select all
def is_rightangled(a,b,c):
is_rightangled = False
largest = a
if b > largest:
# largest = b
if abs((a**2) + (c**2) - (b**2)) < 0.001:
is_rightangled = True
if c > largest:
# largest = c
if abs((a**2) + (b**2) - (c**2)) < 0.001:
is_rightangled = True
else:
# largest = a
if abs((c**2) + (b**2) - (a**2)) < 0.001:
is_rightangled = True
return is_rightangled
I wonder if there is any other simpler solution to this question and i hope for full explanation about the above answer. Thank you !
|
http://python-forum.org/viewtopic.php?f=6&t=8415&p=11053
|
CC-MAIN-2017-09
|
refinedweb
| 136
| 71.55
|
In this tutorial, we will migrate a CanJS app to CanJS 3 using can-migrate, a CLI codebase refactoring tool that automates a large portion of the work required to upgrade a 2.x codebase to CanJS 3.
Before getting started, I recommend reviewing the migration guide to understand what changes are required for CanJS 3, as well as the recommended migration process steps to learn about the process we’ll follow in this tutorial.
You can also watch this YouTube video to follow along with what’s in this tutorial:
We will use the CanJS chat repo in this tutorial. You can clone it and follow along or use your own CanJS 2 project.
In this section, we will prepare for the migration by installing
can-migrate, creating a
migration branch in git, and ensuring all the tests are passing.
Install, Branch, and Test
First, install the
can-migrate CLI globally:
npm install -g can-migrate
Create a branch in the repo for the migration and make sure the tests pass:
git checkout -b migration npm test
Now that all the tests passing on the
migration branch, in the next section let’s run
can-migrate on some of the tested JavaScript files.
Migration Process
In the chat codebase, we have the
main.js file as well as three testable folders:
src/home,
src/message, and
src/models. For each of these, we need to do the following:
- Run
can-migrateon each directory and the
main.jsfile
- Install the necessary
can-packages added to the code by
can-migrate
- Remove global imports of the
canlibrary
- Re-run the tests
- Fix issues if the tests aren’t passing
Run can-migrate
Run
can-migrate on your first directory by passing the directory and the
--apply flag to the CLI:
can-migrate src/models/ --apply
can-migrate works by running transform scripts that parse source code in order to do a code-aware find-and-replace refactor across multiple files. The command above will run all of the transforms on all the JavaScript files in the
src/models/ directory. You know it is working when you see it running like this:
What changed?
After we let
can-migrate do its magic, let’s investigate what changed. First, let’s take a look at the diff:
.png?width=576&height=527&name=pasted%20image%200%20(1).png)
Here are the transform scripts that made changes and what they did:
- can-list/replace.js
- Added import statement:
import CanList from "can-list"
- Updated references of
can.Listto
CanList
- can-map/replace.js
- Added import statement:
import CanMap from "can-map"
- Updated references of
can.Mapto
CanMap
- can-map-define/import.js
- Updated import statement from nested path
"can/map/define/define"to
"can-map-define"
Learn more about what each transform does in the Complete List of Transform Scripts.
Install the can-* packages
As we saw above,
can-migrate added import statements for three new packages to the top of the
model/message.js file:
can-list,
can-map, and
can-map-define. In the next step, we will install these packages and make sure they are saved in our
package.json.
Use npm to install the modules that were imported by
can-migrate:
npm install can-list can-map can-map-define --save
Remove the can global dependency
You may have noticed that in the diff above that we are importing the
can- modules but we did not remove the global
can import:
import can from "can";. In this step, delete that line.
.png?width=720&height=209&name=pasted%20image%200%20(3).png)
Re-run Tests
Next, re-run your tests to see if there are any issues that need to be fixed:
npm test
.png?width=691&height=561&name=pasted%20image%200%20(4).png)
Luckily for us, all the tests are passing without any need to manual intervention.
Repeat
Now we’ll repeat the migration process on the rest of our modlets and JavaScript files, install the new packages, remove the
can package, ensure the tests are still passing, and manually refactor if needed.
Home Modlet Migration
After running:
can-migrate src/home/ --apply
It made the following changes, as highlighted in this diff:
.png?width=527&height=482&name=pasted%20image%200%20(5).png)
We installed
can-map and
can-map-define in a previous step, so all we need to install is the
can-component package. After that, we’ll re-run the tests to make sure they’re all still passing:
npm install can-component --save npm test
Messages Modlet Migration
After running:
can-migrate src/messages/ --apply
It made the following changes, as highlighted in this diff:
.png?width=596&height=548&name=pasted%20image%200%20(6).png)
Since we are using object assignment destructuring on the second to last line, we are going to get an error because we import our
messages.stache template as
template, but the component is expecting the variable to be named
view.
.png?width=549&height=213&name=pasted%20image%200%20(7).png)
After changing that, our tests will pass!
npm test
.png?width=503&height=414&name=pasted%20image%200%20(8).png)
Main.js Migration
After running:
can-migrate src/main.js --apply
It made the following changes, as highlighted in this diff:
.png?width=542&height=581&name=pasted%20image%200%20(9).png)
It added an import statement for the
can-route package, so we need to install it. Don't forget to test it before moving on to the next section:
npm install can-route --save
Next, we need to remove the last use of the
can module in this file. Right now,
can.$ is used to access jQuery; in the next section, we’ll talk about what this is and how we can migrate that code.
can.$
Previous versions of CanJS shipped with your DOM manipulation library of choice. jQuery was the most popular library used and it was made available to your app via
can.$.
CanJS 3 does not depend on any external library. In our app, we can migrate from
can.$ to standalone
$ with the following steps:
- Import jQuery at the top of the file:
import $ from ‘jQuery’
- Change
can.$to just
$:
- Before:
can.$("body").append(template(appState));
- After:
$("body").append(template(appState));
- Remove the global
canimport
See the example diff below for the
main.js file:
.png?width=611&height=374&name=pasted%20image%200%20(11).png)
Re-run Tests
Last, we’ll re-run the tests to make sure everything is passing:
npm test
All the tests are passing! We’re almost done with the entire upgrade.
.png?width=470&height=450&name=pasted%20image%200%20(10).png)
Remove can 2.3 from project
If you haven’t already, remove all the global
can imports and the global
can dependency from your
package.json file:
npm uninstall can --save
In the chat application, we had to manually remove the global import from
src/models/message.js and
src/main.js. The
npm uninstall command above removed
can from the
package.json. Don’t forget to re-run your tests one last time to ensure everything is still in working order.
.png?width=611&height=662&name=pasted%20image%200%20(12).png)
Fix issues that arise from removing can 2.3
After uninstalling
can, we found an error coming from stealJS:
.png?width=720&height=112&name=pasted%20image%200%20(16).png)
This error is because we use both steal and stache in this project so in CanJS 3, we need to install
steal-stache.
npm install steal-stache@3 --save
Next, we found another error because we were using an old version of
bit-tabs, which we need to upgrade as well:
.png?width=720&height=96&name=pasted%20image%200%20(17).png)
npm install bit-tabs@latest --save
With that, the tests pass and our migration is complete! Congratulations!
Upgrade today
You can look at the detailed diff across versions to get an overview of the changes to the chat codebase after running
can-migrate on each modlet and JavaScript file.
The Using Codemods guide has all the information you’ll need to use
can-migrate to upgrade your app to CanJS 3. You can also find more details about all the steps required in the migration guide.
If you have an issue with using
can-migrate, please create an issue on GitHub. You can also contribute back to the project by looking at the open issues and commenting on any you’d like to help fix.
If you have any questions about migrating, please post in our forums or Gitter chat and we’ll be happy to help!
|
https://www.bitovi.com/blog/tutorial-automate-your-upgrade-to-canjs-3-with-can-migrate
|
CC-MAIN-2019-35
|
refinedweb
| 1,462
| 62.07
|
Since a recursive function calls itself, there needs to be a rule or a breakpoint at which the process or loop would terminate. Such a condition is known as a base condition. A base condition is a requirement in every recursive program, otherwise the procedure would result in an infinite loop.
The second requirement is the recursive case when the function calls itself.
Let's look at an example:
In this example, you will write a factorial function that takes an integer (positive) as an input. The factorial of a number is obtained by multiplying the number by all positive integers below it. For example,
factorial(3) = 3 x 2 x 1,
factorial(2) = 2 x 1, and
factorial(0) = 1.
The first thing to do is to define our base case, which will be factorial(0) = 1.
As you can see above, there is a relationship between each consecutive factorial scenario. You should notice that factorial(4) = 4 x factorial(3). Similarly, factorial(5) = 5 x factorial(4).
The second part will be writing a function that calls itself.
Now that we have simplified it, the resulting function will be:
def factorial(n): if(n == 0): #Define our base case? return 1 else: return n*factorial(n-1) print(factorial(5)) #result # 120
The solution if
n==0 is:
def factorial(n): if(n == 0): #Define our base case? return 1 else: return n*factorial(n-1) print(factorial(0)) #result # 0
Now that you know how to write recursive functions, let's look at several case studies that will solidify your understanding of recursion.
Case Study 1: Fibonacci
In a Fibonacci sequence, each number is the sum of the two preceding numbers, such as: 1 + 1 = 2; 1 + 2 = 3; 2 + 3 = 5; 3 + 5 = 8. The Fibonacci sequence has been applied in many areas, and the most common is in predicting price action in the stock market by forex traders.
The Fibonacci sequence starts with 0 and 1.. You can then translate the adding pattern into the else case.
The resulting function will be:
def fibonacci(n): if(n == 1): #define Base case 1 return 0+1 elif(n == 2): #define Base case 1 return 1+2 else: return fibonacci(n) + fibonacci(n-1) print(fibonacci(5)) #result #
Case Study 2: Reversing a String
In this example, you will write a function that takes a string as input and then returns the reverse of the string.
The first thing to do is to define our base case, which will check if the string is equal to 0 and, if so, will return the string itself.
The second step is to recursively call the reverse function to slice the part of the string excluding the first character and then concatenate the first character to the end of the sliced string.
The resulting function is as shown below:
def reverse(a): if len(a) == 0: return a else: return reverse(a[1:]) + a[0] print(reverse("Python is a very easy language to learn")) # result #nrael ot egaugnal ysae yrev a si nohtyP
Case study 3: Sum of Elements
In this example, you will write a function that takes an array as input and then returns the sum of the elements in the list.
The first thing to do is to define our base case, which will check if the size of the list is zero, and return 0 if True.
The second step returns the element and a call to the function sum() minus one element of the list.
The solution is as shown below:
def sum_of_numbers(l): if len(l) == 1: return 0 else: return l[0] + sum(l[1:]) a =[5,7,3,8,10] print(sum(a)) # result # 33
The solution for an empty list is as shown below:
def sum_of_numbers(l): if len(l) == 1: return 0 else: return l[0] + sum(l[1:]) b =[] print(sum(b)) # result # 0
Conclusion
This tutorial has covered what is necessary to use recursion to solve complex programs in Python. It's also important to note that recursion has its own limitations:
- Recursion takes a lot of stack space, hence making it a bit slow to maintain the program.
- Recursion functions require more space and time to execute.
Remember, don’t hesitate to see what we have available for sale and for study in the Envato Market, and please ask any questions and provide your valuable feedback using the feed below.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
|
https://code.tutsplus.com/tutorials/demystifying-python-recursion--cms-30418
|
CC-MAIN-2018-13
|
refinedweb
| 764
| 57
|
.
This is a brief overview on how to debug a custom security provider using Eclipse. The techniques used to debug a custom security provider are no different than debugging a normal remote java application. These steps can be found in many sites on the web. The appendix A contains an example of how to do this.
.
There are a couple of ways to debug any cognos code. One method is to start cognos via the command prompt using startup.bat and then put print messages in your code. As the code gets invoked you will see the results in the command window. Another way is to use an IDE such as eclipse or Intellj to debug the code. There are many advantages of debugging via an IDE but one of the biggest is that you can step through the code one line at a time inspecting any variable vs knowing ahead of time which variable you want to print. This document identifies how this can be done.
Here are the steps necessary to debug using eclipse.
1.) Allow cognos server to be run in debug mode.
The first step is to modify the bootstrap_win32.xml file located in the bin directory to allow for debugging. You will see a section (<!-- uncomment these for debug -->) that needs to be uncommented. Notice the default port in this file is 9091. If you are already using that port or your network is blocking it then you should modify it to a port that is allowed. Once this change is made restart cognos. Note: On windows you must restart cognos via the service mode in order to get this to work.
2.) Create an Eclipse project with your custom security provider code.
Make sure it compiles clean
3.) Create a jar file that contains all the class files for debugging.
In order for your code to be debugged it is convenient to place all the class files in a single jar file which you can point eclipse to when debugging.
4.) Set up debugging in eclipse
Open eclipse and perform the steps identified above in the Appendix A titled: Configuring Eclipse to Debug a Remotely Running Application. For the project pick the project you created in step 2.
5.) Set break points in your source code identified above in step 2
In my case I put break points in the logon method, logout method and the searchobject method of the class file called “SingleTenantProvider” which extends Namespace implements INamespaceAuthenticationProvider2
6.) Logon to cognos, with your browser, picking your csp as namespace
You should then hit a break point if you put one in the logon method or the search method.
You might get an error message indicating cannot find source for class file. If so then configure it to point to the jar file build in step 3.
|
https://www.ibm.com/developerworks/mydeveloperworks/blogs/0a7c97bb-6cf9-4ddb-a918-80994e7b444d/tags/sdk?lang=en
|
CC-MAIN-2017-04
|
refinedweb
| 474
| 72.97
|
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hi all,
I am very new to jira and has not even used scripts uptil now. I need to use the Script fields. i had installed it on jira, but I am facing problem in using it. to use thescript fields, I need to write a script and fill up this(shown in the picture). can anybody help me with this? what should be there in script file path, script, tempalte etc....
I'm not sure what the confusion is.
You need to write a script that does what you want. (We can't start on that, as we don't know what you want). Once you've written it, you need to tell Jira how to get to it. Either upload it as a file and use the "script file path" to tell Jira where it is, OR you write it in the "Script" field.
The template, as per docs, is the text the field will output, using the results from the script.
Hi,
I want script field to have the value "true" when assignee = reporter and "false" otherwise. can i have the script for this one?
Your script should look something like:
return (issue.getAssignee().getName().equals(issue.getReporter().getName()))
and your template
$!value
hi,
I did the following and in the script testing for a issue it was returning the correct value. But the field was not working in the issue navigator. I tried reindexing then. jira was unable to reindex and was showing the error because of the scripted custom field i had created. I deleted the custom field and reindexed. when i created the field again then it was not even showing any value in the script testing for an issue. Tried reindexing and was showing the same error. is there any problem or incompatibility of the script field created on jira
Hi,
Unless you explain what you want the field to do, we can't really help you.
Daniel's script is broadly correct but doesn't take into account when there is no assignee, which is probably what is blowing up your indexing (NPE).
The script should just be:
issue.assignee == issue.reporter
However I would not waste a script field on this... you can use script runner's JQL functions to query on this, eg:
issuefunction in expression("", "assignee == reporter").
|
https://community.atlassian.com/t5/Marketplace-Apps-questions/Problem-in-using-Script-Fields-Script-runner-plugin/qaq-p/17726
|
CC-MAIN-2018-43
|
refinedweb
| 410
| 83.15
|
WICED 3.1.X bug -- queues fail to work when in '-debug' modecogoc_1937206 Jul 15, 2015 2:06 PM
Hello,
I've encountered what appears to be a bug in the WICED framework: Calls to wiced_rtos_init_queue() always fail (return WICED_WWD_QUEUE_ERROR) when the application has been built with the '-debug' option, and when using ThreadX. I've confirmed that this is the case even for the snip.scan application running on the BCM943362WCD4 dev kit with the following minor code modifications:
static void createQueueTest() { wiced_result_t res; wiced_queue_t dummyQueue; res = wiced_rtos_init_queue(&dummyQueue, NULL, 700, 2); printf("DummyQueue init %s! (%d)\r\n", (res == WICED_SUCCESS ? "succeeded" : "failed"), (int)res); res = wiced_rtos_deinit_queue(&dummyQueue); printf("DummyQueue de-init %s! (%d)\r\n", (res == WICED_SUCCESS ? "succeeded" : "failed"), (int)res); } void application_start( ) { wiced_init( ); createQueueTest(); while(1)
Note that I'm running WICED 3.1.1. I have also confirmed that this issue does not exist when using FreeRTOS.
Please confirm whether you are able to reproduce this issue.
Thanks!
1. Re: WICED 3.1.X bug -- queues fail to work when in '-debug' modeSeyhanA_31 Oct 27, 2014 12:42 PM (in response to cogoc_1937206)
Hi,
For ThreadX, the max message_size (* @param message_size : size in bytes of objects that will be held in the queue) for the wiced_rtos_init_queue(...) is 64. Basically message_size/4 number of messages are held a the queue.
Make the following change:
res = wiced_rtos_init_queue(&dummyQueue, NULL, 700, 2); ->
res = wiced_rtos_init_queue(&dummyQueue, NULL, 16, 2); or res = wiced_rtos_init_queue(&dummyQueue, NULL, 64, 2);
Thanks,
Seyhan
2. Re: WICED 3.1.X bug -- queues fail to work when in '-debug' modecogoc_1937206 Oct 27, 2014 1:09 PM (in response to SeyhanA_31)
Thanks, Seyhan! I've confirmed that this works. What I'm not entirely sure of, though, is why a message size of 700 works with the regular build target (i.e. no '-debug' option included). In this case, calls to wiced_rtos_init_queue() return 0 as expected, and the queue seems to function as expected...(?)
Cheers!
3. Re: WICED 3.1.X bug -- queues fail to work when in '-debug' modeSeyhanA_31 Oct 27, 2014 2:10 PM (in response to cogoc_1937206)
Hi,
If DEBUG is enabled, the error checking code before creating queue is enabled as well. The error checking code could be enabled without DEBUG as well by commenting out the TX_DISABLE_ERROR_CHECKING code in .../WICED/RTOS/ThreadX/ver5.6/Cortex_M3_M4/GCC/tx_port.h
#ifndef DEBUG
#define TX_DISABLE_ERROR_CHECKING -> comment this out
#endif /* ifndef DEBUG */
Thanks,
Seyhan
4. Re: WICED 3.1.X bug -- queues fail to work when in '-debug' modecogoc_1937206 Oct 27, 2014 2:19 PM (in response to SeyhanA_31)
Ah, I was only seeing the error-checking code in the WICED-layer (wiced_rtos.c). This appears to be always-enabled, and checks that the size is a multiple of 4. I see that the TX_DISABLE_ERROR_CHECKING affects which version of various ThreadX functions the linker is pointed to in the precompiled library.
Thanks!
|
https://community.cypress.com/thread/2900
|
CC-MAIN-2020-50
|
refinedweb
| 485
| 63.7
|
🎮 3D Games with BabylonJS: A Starter Guide
Babylon is a JavaScript framework enabling developers to create 3D graphics with ease. Popular games such as Shell Shockers use this framework to create 3D games. It's shinier than ever, now that Version 4.0 just released!
I'll show you how to use Babylon to create a simple 3D environment. We'll go over creating an environment, adding objects to the environment, adding gravity, and adding collisions.
Setup
First, create an
HTML,CSS,JS repl
Then, modify your
index.html file. We're going to be adding the BablyonJS script tag, and our
main.js file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http- <script src=""></script> <title>Babylon FPS</title> </head> <body> <canvas id="canvas"></canvas> <script src="main.js" type="module"></script> </body> </html>
You may have noticed the
type="module" attribute on the
main.js script tag. That means we're importing
main.js as a JavaScript module. This means that we can use the
import syntax to import other
.js files inside of
main.js. I like doing this because it makes the
index.html file more readable. (you can learn more about JS Modules (ESM) here.
When you start the app, it should serve an empty page. Let's add the basic BabylonJS stuff now! 😄
Creating a Babylon Scene
Make sure you add the following to your
main.js. I'll explain nit below
import { createGameScene } from "./gameScene.js"; window.addEventListener("DOMContentLoaded", start); function start() { let canvas = document.getElementById("canvas"); let engine = new BABYLON.Engine(canvas, true); let scene = createGameScene(canvas, engine); let sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {}, scene); engine.runRenderLoop(function() { scene.render(); }); window.addEventListener("resize", function() { engine.resize() }); };
- Inside the
start, function, we're creating a BABYLON engine. The
engine'translates' the BabylonJS API to canvas painting. For example, when you create a sphere with
BABYLON.MeshBuilder.CreateSphere("sphere", {}, scene);, it is responsible for actually drawing the
sphereon the screen.
- A scene contains all of our scene objects. Think of it as a room - it can contain lights, cameras, 3D objects and more
engine.runRenderLoopis a function that runs continuously. In this case, we want Babylon to continuously render the scene (
scene.render())
You may notice that we're using the
createGameScene function, and we're importing it from
./gameScene.js. So, create a
gameScene.js file. Like the name says, we're going to be creating the game scene in this file. This is where we will be creating our lights, cameras, and our meshes (3D objects).
let createGameScene = function(canvas, engine) { // Create scene let scene = new BABYLON.Scene(engine); // Create camera let camera = new BABYLON.UniversalCamera("Camera", new BABYLON.Vector3(2, 2, 2), scene); camera.attachControl(canvas, true); camera.setTarget(BABYLON.Vector3.Zero()); // Create lights let light = new BABYLON.HemisphericLight("myLight", new BABYLON.Vector3(1, 1, 0), scene); return scene; }; export { createGameScene };
- First, we're creating a regular BABYLON
scene. Whatever you put inside this scene will get rendered by the
engine.
- Then, we create a new
UniversalCameracamera. BabylonJS automatically sets up your camera so you can look around with your mouse or move around with the arrow keys. The
camera.attachControl()lets us interact with the canvas using our mouse. If we did not add that, then Babylon would not know when we would be moving our mouse.
If you're wondering what the
export { createGameScene } is all about, it's a part of the ES6 Module syntax, also known as ECMAScript Modules (ESM). We don't have time to go over it in this post, but you can read about it here. In a nutshell, we're creating a reusable function that can be imported into any other file.
Anyways, we're getting results! :D But unfortunately, the canvas is not styled properly
Styling the Canvas
Let's create a
style.css to fix the canvas styling
* { padding: 0; margin: 0; box-sizing: border-box; } #canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; touch-action: none; }
Be sure to add
<link rel="stylesheet" href="style.css"> to your
index.html
And presto! Now the canvas fills up the entire screen!
View the code in this this repl
Games usually have a loading screen. This improves the user experience since the user sees a loading bar rather than a blank page. Let's create one!
Inside of
let showLoadingScreen = function(canvas, engine) { let defaultLoadingScreen = new BABYLON.DefaultLoadingScreen(canvas, "Please Wait", "black"); engine.loadingScreen = defaultLoadingScreen; engine.displayLoadingUI(); }; let hideLoadingScreen = function(engine) { engine.hideLoadingUI(); }; export { showLoadingScreen, hideLoadingScreen }
- The
showLoadingScreenfunction creates a default loading screen. The words "Please Wait" is shown on a
blackbackground with a loading spinner.
- The
hideLoadingScreenfunction simply hides the loading screen
Learn more about loading screens and custom loading screens on the Babylon docs
The next step is to call
showLoadingScreen and
hideLoadingScreen from
main.js. Firstly, import the functions from
import { showLoadingScreen, hideLoadingScreen } from "./loadingScreen.js";
Now we have to show and hide the loading screen at the right times. Let's use
showLoadingScreen() right after we create the Babylon
engine.
let canvas = document.getElementById("canvas"); let engine = new BABYLON.Engine(canvas, true); showLoadingScreen(canvas, engine); ...
We can't forget to hide the loading screen when everything has been loaded! I'm adding the code right after I create my
sphere. Note that this will not hide the loading screen after you create the
sphere. Babylon will automatically know when to hide the loading the screen.
... let sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {}, scene); scene.afterRender = function() { hideLoadingScreen(engine) }; ...
Now your loading screen should work! It will look something like this
View the code in this repl
Making the Camera Move
Although we are able to move the sphere with the mouse, we still can't move the camera with the 'WASD' keys. Let's add some extra controls to the camera!
Inside of my
gameScene.js, I added:
camera.keysUp.push(87); camera.keysDown.push(83); camera.keysLeft.push(65); camera.keysRight.push(68);
camera.keysUpis an array that contain key codes. (for example,
87is a keycode for pressing 'W'). We're adding
87to the array, which means the camera will move 'up' when 'W' is pressed
Other Camera Properties
You can also mess around with other properties of the camera! You can change the speed, inertia, or the field of view (FOV). You can view the whole list of properties on the Babylon documentation.
These are the values of
fov,
speed, and
inertia I'm using. You can change them whenever you want!
camera.speed = 2; camera.fov = 0.8; camera.inertia = 0;
Now it works! Below, I set the
fov to
0.3.
View the code in this repl
Adding a Pointer Lock
Moving around is cool and all, but isn't it bothersome that we have to hold 'left click' if we want to look around? To fix this, we can use the Pointer Lock API. Think of it like this: when we click on the canvas, the mouse is 'locked' in the canvas. When this happens, moving your mouse doesn't move the cursor, but instead directly interacts with the
canvas element.
I created a
pointerLock.js file and added the following code
let createPointerLock = function(scene) { let canvas = scene.getEngine().getRenderingCanvas(); canvas.addEventListener("click", event => { canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock; if(canvas.requestPointerLock) { canvas.requestPointerLock(); } }, false); }; export { createPointerLock }
You might be curious why we are trying to access
requestPointerLock,
msRequestPointerLock,
mozRequestPointerLock, and
webkitRequestPointerLock. This is because browsers have slightly different implementations and it's not completely standardized yet.
Inside of
main.js, be sure to actually import the
createPointerLock function and use it. I called the method right after I created the
scene.
import { createPointerLock } from "./pointerLock.js" ... let scene = createGameScene(canvas, engine); createPointerLock(scene);
Adding Some Ground
Players can't really move around if there is no ground. Let's create one!
Babylon's
MeshBuilder lets us do this really easily. Near the end of your
gameScene.js file, create the
plane:
let plane = BABYLON.MeshBuilder.CreatePlane("ground", { height: 20, width: 20 }, scene) plane.rotate(BABYLON.Axis.X, Math.PI / 2, BABYLON.Space.WORLD); plane.position.y = -2;
- I used
plane.rotate()to rotate the plane so it is completely flat
plane.position.ydecreases the altitude of the plane so it is below the
sphere
Gravity
Creating gravity is pretty straightforward. To add gravity, we have to do three things.
- Choose a Physics engine
- Enable gravity on the
scene
- Enable gravity on the
sphere(you can add it to other objects as well!)
Choose a Physics Engine
CannonJS is a physics engine well supported by Babylon. In our case, the physics engine will calculate where the sphere falls and how the sphere will interact with the
plane. We want the
sphere to bounce.
So, let's add our physics engine: CannonJS
<script src=""></script>
Enable gravity on the
scene
To enable gravity in the
scene, we just have to set the
gravity property to a vector. For the purposes of this tutorial, think of a vector as an arrow pointing in a direction. In this case, the arrow represents the force of gravity. The force of gravity is pointing down, at
-0.4 units.
After creating gravity, then we enable CannonJS. I put the following code right after I created the
scene variable (in
gameScene.js)
scene.gravity = new BABYLON.Vector3(0, -.4, 0); scene.enablePhysics(scene.gravity, new BABYLON.CannonJSPlugin()); // Enable regular collisions as well scene.collisionsEnabled = true; scene.workerCollisions = true;
Enable gravity on the
sphere
After enabling gravity on the sphere, it doesn't look like it does anything. This is because the gravity "doesn't have anything to push". Indeed, we want gravity to make the sphere fall, but we have to tell CannonJS that. We're going to tell CannonJS that we want the
sphere to fall by creating a physics imposter from it.
A physics imposter is a simplified model of an object, or mesh. For example, we are simplifying the shape of our
sphere mesh into a cube (
BABYLON.PhysicsImposter.BoxImposter). The simpler shapes makes doing physics calculations a lot faster. If you've every played an action games, physics imposters are very similar to hitboxes.
With that said, lets create a physics imposter the
sphere and
plane.
let spherePhysicsImposter = new BABYLON.PhysicsImpostor( sphere, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 1, friction: 0.1, restitution: .85 }, scene ); let planePhysicsImposter = new BABYLON.PhysicsImpostor( plane, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 0, friction: 0.1, restitution: .7 }, scene );
- We set the mass of the
planePhysicsImposterto
0because we do not want the
planeto fall
- Feel free to play with the
mass,
frictionand
restitutionvalues
Below you can see the
sphere bouncing on the
plane. Pretty cool, eh?
View the code in this repl.
Walking
So we have all the physics in place - wouldn't it be cool to interact with the scene directly? To do this, we can make the camera affected by gravity. Since we already have keyboard controls of the camera, we can simply walk around!
camera.ellipsoid = new BABYLON.Vector3(1.5, 0.5, 1.5); camera.checkCollisions = true; camera.applyGravity = true; plane.collisionsEnabled = true; plane.checkCollisions = true;
- We first create an ellipsoid around the camera. You can think of this like the hitbox. It less collide with objects like the
sphere. The ellipsoid has a height of
0.5units and has a length and width of
1.5units
- If you don't seem to be moving, you may want to check
camera.speed
If you want the
camera to collide with the
sphere, must enable collisions with the
sphere
sphere.collisionsEnabled = true; sphere.checkCollisions = true;
As you can see, I can now walk around!
View the code in this repl
🚀
Now we have a player moving around the
scene, with gravity enabled! We can collide with some meshes in the
scene, like the
sphere. How cool is that? Hopefully you found this BabylonJS introduction tutorial to be helpful! Tell me what you think and post a comment!
hey whoever created this, thanks for creating this because i am an avid programmer and like to script games
but dont want to use unity, roblox studio or unreal engine while i find them too complicated. Thank for creating a tutorial.
k bye
|
https://repl.it/talk/learn/3D-Games-with-BabylonJS-A-Starter-Guide/15957
|
CC-MAIN-2020-50
|
refinedweb
| 2,062
| 61.12
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.