text
stringlengths
171
82.6k
HTC's Vive Pro headset is available to pre-order for $799 We've seen plenty of Beats-focused KIRFs in our time, some better than others. Few, however, play quite so directly on the name as OrigAudio's Beets. For $25, adopters get a set of headphones that bear little direct resemblance to Dr. Dre's audio gear of choice, but are no doubt bound to impress friends -- at least, up until they see a root vegetable logo instead of a lower-case B. Thankfully, there's more to it than just amusing and confusing peers. Every purchase will lead to a donation of canned beets (what else?) to the Second Harvest Food Bank of Orange County. For us, that's reason enough to hope that Beats doesn't put the kibosh on OrigAudio's effort. Besides, we could use some accompaniment for our BeetBox.
Q: NullPointerException in getview of custom adapter I'm getting image from bitmap method and trying to populate the listview. But when i call the bitmap function inside getview the nullpointerException error occurs. please help me... here is my view Activity class: public class Viewactivity extends Activity{ TextView tv; ImageView im; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.views); ListView mListView = (ListView)findViewById(R.id.listView); //array houlds all images int Images[] = new int[]{ R.drawable.confidential, ... }; //array holds all strings to be drawn in the image CustomList adaptor = new CustomList(this , Images); mListView.setAdapter(adaptor); } public Bitmap ProcessingBitmap(int image) { // TODO Auto-generated method stub Bitmap bm1 = null; Bitmap newBitmap = null; final String data =getIntent().getExtras().getString("keys"); bm1 = ((BitmapDrawable) Viewactivity.this.getResources() .getDrawable(image)).getBitmap(); Config config = bm1.getConfig(); if(config == null){ config = Bitmap.Config.ARGB_8888; } newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(),config); Canvas newCanvas = new Canvas(newBitmap); newCanvas.drawBitmap(bm1, 0, 0, null); if(data != null){ Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG); paintText.setColor(Color.RED); paintText.setTextSize(300); // paintText.setTextAlign(Align.CENTER); paintText.setStyle(Style.FILL); paintText.setShadowLayer(10f, 10f, 10f, Color.BLACK); Rect rectText = new Rect(); paintText.getTextBounds(data, 0, data.length(), rectText); paintText.setTextScaleX(1.f); newCanvas.drawText(data, 0, rectText.height(), paintText); Toast.makeText(getApplicationContext(), "drawText: " + data, Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(), "caption empty!", Toast.LENGTH_LONG).show(); } return newBitmap; } } this is my adapter class: public class CustomList extends BaseAdapter{ Viewactivity act; int[] IMAGES; LayoutInflater inflator; Context sContext; //private String[] TEXTS; public CustomList(Context context, int[] images){ this.IMAGES = images; //this.TEXTS = texts; this.sContext = context; inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return IMAGES.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v = inflator.inflate(R.layout.row_list, parent, false); final ImageView imageView = (ImageView) v.findViewById(R.id.imageView); imageView.setImageBitmap(act.ProcessingBitmap(IMAGES[position]));// line no:52 return imageView; } } this is my logcat: 12-18 06:16:51.406: E/AndroidRuntime(1388): FATAL EXCEPTION: main 12-18 06:16:51.406: E/AndroidRuntime(1388): Process: com.emple.example, PID: 1388 12-18 06:16:51.406: E/AndroidRuntime(1388): java.lang.NullPointerException 12-18 06:16:51.406: E/AndroidRuntime(1388): at com.emple.example.CustomList.getView(CustomList.java:52) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.AbsListView.obtainView(AbsListView.java:2263) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.ListView.measureHeightOfChildren(ListView.java:1263) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.ListView.onMeasure(ListView.java:1175) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.View.measure(View.java:16497) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.View.measure(View.java:16497) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.View.measure(View.java:16497) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 12-18 06:16:51.406: E/AndroidRuntime(1388): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.View.measure(View.java:16497) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 12-18 06:16:51.406: E/AndroidRuntime(1388): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.View.measure(View.java:16497) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.Choreographer.doCallbacks(Choreographer.java:574) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.Choreographer.doFrame(Choreographer.java:544) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.os.Handler.handleCallback(Handler.java:733) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.os.Handler.dispatchMessage(Handler.java:95) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.os.Looper.loop(Looper.java:136) 12-18 06:16:51.406: E/AndroidRuntime(1388): at android.app.ActivityThread.main(ActivityThread.java:5017) 12-18 06:16:51.406: E/AndroidRuntime(1388): at java.lang.reflect.Method.invokeNative(Native Method) 12-18 06:16:51.406: E/AndroidRuntime(1388): at java.lang.reflect.Method.invoke(Method.java:515) 12-18 06:16:51.406: E/AndroidRuntime(1388): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 12-18 06:16:51.406: E/AndroidRuntime(1388): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 12-18 06:16:51.406: E/AndroidRuntime(1388): at dalvik.system.NativeStart.main(Native Method) 12-18 06:21:51.616: I/Process(1388): Sending signal. PID: 1388 SIG: 9 A: You haven't initialized your act variable. Init it in your adapter constructor. Something like: public CustomList(Viewactivitty act, int[] images){ this.act = act; this.IMAGES = images; //this.TEXTS = texts; this.sContext = act; inflator = (LayoutInflater)act.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }
Syringocystadenoma papilliferum of the cervix presenting as vulvar growth in an adolescent girl. Syringocystadenoma papilliferum (SCP) is a rare, benign, adnexal tumour of apocrine or eccrine differentiation. It is commonly located on head and neck region. We report the case of an 18-year-old woman who presented with a vulvar lobulated growth that was found to arise from the posterior lip of cervix. Histopathological examination revealed the diagnosis of SCP. To our knowledge, SCP arising from the cervix has never been reported previously in the literature, thus we believe this to be the first case of SCP arising from the posterior lip of the cervix.
The basic goal of the effective altruism movement is to create efficient philanthropic change by backing programs and innovations that are cost-effective so that each dollar given impacts as many people as possible. The underlying tenet is that donor dollars are a limited resource, but dollars are just one of the limiting factors. There’s still another major resource that needs to be accounted for: research time. There’s a learning curve for calculation-driven cause groups (and donors) to figure out what world-plaguing problems really are the most pressing, what solutions seem the most promising or neglected, and what else might need to be done. The problem is there hasn’t been a single resource for accessing all this information in one place. To change that, Rethink Priorities, an initiative of the effective altruism awareness and engagement building nonprofit Rethink Charity, has launched Priority Wiki, a publicly editable Wikipedia-like online encyclopedia for cause prioritization wonks. It collects and categorizes vetted research around pressing charitable causes and potential interventions. “This is a big problem because thousands of hours are going into this kind of research, and you don’t want people to forget it exists, or maybe try to duplicate efforts, or just not even remember it,” says Peter Hurford, who codeveloped the wiki alongside colleague Marcus Davis. “We’re trying to capture all relevant research under a wide variety of global issues so that everyone can have a go-to spot to get up to speed.” To do that, Wiki is organized into six broad types of causes. That includes “Existential/Catastrophic Future Risks,” “Improving Research,” “Decisions and Values,” “Improving Policy,” “Developing World Health and Economic Development,” “Developed World Health and Economic Development,” and “Specific Scientific Research.” Each entry is then comprised of related topics. Under the catastrophe heading, for instance, there’s biosecurity, nuclear security, climate change, and geomagnetic storms. As the developers explain in an open letter about their efforts, the wiki is currently populated with a collection of research by effective altruism research organizations including Open Philanthropy, GiveWell, 80,000 Hours, and Animal Charity Evaluators. Many of these are formatted in what’s commonly referred to as a “shallow review,” or high-level overview of each issue, and various important statistics and findings. “That gives you a lot of opportunities to dive into the problem and make a more structured way than dumping someone a 60-item reading list,” says Hurford. Contributors are already revising the content and sharing data about things the originators hadn’t considered. Two recent additions include information about psychedelics and drug reform, and how to prevent or reduce aging-related diseases to extend our natural lifespan.
Essays Philosophers who think everyday morality is objective should examine the evidence, argues Joshua Knobe. Imagine two people discussing a question in mathematics. One of them says “7,497 is a prime number,” while the other says, “7,497 is not a prime number.” In a case like this one, we would probably conclude that there can only be a single right answer. We might have a lot of respect for both participants in the conversation, we might agree that they are both very reasonable and conscientious, but all the same, one of them has got to be wrong. The question under discussion here, we might say, is perfectly objective. But now suppose we switch to a different topic. Two people are talking about food. One of them says “Don’t even think about eating caterpillars! They are totally disgusting and not tasty at all,” while the other says “Caterpillars are a special delicacy – one of the tastiest, most delectable foods a person can ever have occasion to eat.” In this second case, we might have a very different reaction. We might think that there isn’t any single right answer. Maybe caterpillars are just tasty for some people but not for others. This latter question, we might think, should be understood as relative. Now that we’ve got at least a basic sense for these two categories, we can turn to a more controversial case. Suppose that the two people are talking about morality. One of them says “That action is deeply morally wrong,” while the other is speaking about the very same action and says “That action is completely fine – not the slightest thing to worry about.” In a case like this, one might wonder what reaction would be most appropriate. Should we say that there is a single right answer and anyone who says the opposite must be mistaken, or should we say that different answers could be right for different people? In other words, should we say that morality is something objective or something relative? This is a tricky question, and it can be difficult to see how one might even begin to address it. Faced with an issue like this one, where exactly should we look for evidence? Though philosophers have pursued numerous approaches here, one of the most important and influential is to begin with certain facts about people’s ordinary moral practices. The idea is that we can start out with facts about people’s usual ways of thinking or talking and use these facts to get some insight into questions about the true nature of morality. Thinkers who take this approach usually start out with the assumption that ordinary thought and talk about morality has an objectivist character. For example, the philosopher Michael Smith claims that we seem to think moral questions have correct answers; that the correct answers are made correct by objective moral facts; that moral facts are wholly determined by circumstances and that, by engaging in moral conversation and argument, we can discover what these objective moral facts determined by the circumstances are. And Frank Jackson writes: I take it that it is part of current folk morality that convergence will or would occur. We have some kind of commitment to the idea that moral disagreements can be resolved by sufficient critical reflection – which is why we bother to engage in moral debate. To that extent, some sort of objectivism is part of current folk morality. Then, once one has in hand this claim about people’s ordinary understanding, the aim is to use it as part of a complex argument for a broader philosophical conclusion. It is here that philosophical work on these issues really shines, with rigorous attention to conceptual distinctions and some truly ingenious arguments, objections and replies. There is just one snag. The trouble is that no real evidence is ever offered for the original assumption that ordinary moral thought and talk has this objective character. Instead, philosophers tend simply to assert that people’s ordinary practice is objectivist and then begin arguing from there. If we really want to go after these issues in a rigorous way, it seems that we should adopt a different approach. The first step is to engage in systematic empirical research to figure out how the ordinary practice actually works. Then, once we have the relevant data in hand, we can begin looking more deeply into the philosophical implications – secure in the knowledge that we are not just engaging in a philosophical fiction but rather looking into the philosophical implications of people’s actual practices. Just in the past few years, experimental philosophers have been gathering a wealth of new data on these issues, and we now have at least the first glimmerings of a real empirical research program here. But a funny thing happened when people started taking these questions into the lab. Again and again, when researchers took up these questions experimentally, they did not end up confirming the traditional view. They did not find that people overwhelmingly favoured objectivism. Instead, the results consistently point to a more complex picture. There seems to be a striking degree of conflict even in the intuitions of ordinary folks, with some people under some circumstances offering objectivist answers, while other people under other circumstances offer more relativist views. And that is not all. The experimental results seem to be giving us an ever deeper understanding of why it is that people are drawn in these different directions, what it is that makes some people move toward objectivism and others toward more relativist views. For a nice example from recent research, consider a study by Adam Feltz and Edward Cokely. They were interested in the relationship between belief in moral relativism and the personality trait openness to experience. Accordingly, they conducted a study in which they measured both openness to experience and belief in moral relativism. To get at people’s degree of openness to experience, they used a standard measure designed by researchers in personality psychology. To get at people’s agreement with moral relativism, they told participants about two characters – John and Fred – who held opposite opinions about whether some given act was morally bad. Participants were then asked whether one of these two characters had to be wrong (the objectivist answer) or whether it could be that neither of them was wrong (the relativist answer). What they found was a quite surprising result. It just wasn’t the case that participants overwhelmingly favoured the objectivist answer. Instead, people’s answers were correlated with their personality traits. The higher a participant was in openness to experience, the more likely that participant was to give a relativist answer. Geoffrey Goodwin and John Darley pursued a similar approach, this time looking at the relationship between people’s belief in moral relativism and their tendency to approach questions by considering a whole variety of possibilities. They proceeded by giving participants mathematical puzzles that could only be solved by looking at multiple different possibilities. Thus, participants who considered all these possibilities would tend to get these problems right, whereas those who failed to consider all the possibilities would tend to get the problems wrong. Now comes the surprising result: those participants who got these problems right were significantly more inclined to offer relativist answers than were those participants who got the problems wrong. Taking a slightly different approach, Shaun Nichols and Tricia Folds-Bennett looked at how people’s moral conceptions develop as they grow older. Research in developmental psychology has shown that as children grow up, they develop different understandings of the physical world, of numbers, of other people’s minds. So what about morality? Do people have a different understanding of morality when they are twenty years old than they do when they are only four years old? What the results revealed was a systematic developmental difference. Young children show a strong preference for objectivism, but as they grow older, they become more inclined to adopt relativist views. In other words, there appears to be a developmental shift toward increasing relativism as children mature. (In an exciting new twist on this approach, James Beebe and David Sackris have shown that this pattern eventually reverses, with middle-aged people showing less inclination toward relativism than college students do.) So there we have it. People are more inclined to be relativists when they score highly in openness to experience, when they have an especially good ability to consider multiple possibilities, when they have matured past childhood (but not when they get to be middle-aged). Looking at these various effects, my collaborators and I thought that it might be possible to offer a single unifying account that explained them all. Specifically, our thought was that people might be drawn to relativism to the extent that they open their minds to alternative perspectives. There could be all sorts of different factors that lead people to open their minds in this way (personality traits, cognitive dispositions, age), but regardless of the instigating factor, researchers seemed always to be finding the same basic effect. The more people have a capacity to truly engage with other perspectives, the more they seem to turn toward moral relativism. To really put this hypothesis to the test, Hagop Sarkissian, Jennifer Wright, John Park, David Tien and I teamed up to run a series of new studies. Our aim was to actually manipulate the degree to which people considered alternative perspectives. That is, we wanted to randomly assign people to different conditions in which they would end up thinking in different ways, so that we could then examine the impact of these different conditions on their intuitions about moral relativism. Participants in one condition got more or less the same sort of question used in earlier studies. They were asked to imagine that someone in the United States commits an act of infanticide. Then they were told to suppose that one person from their own college thought that this act was morally bad, while another thought that it was morally permissible. The question then was whether they would agree or disagree with the following statement: Since your classmate and Sam have different judgments about this case, at least one of them must be wrong. Participants in the other conditions received questions aimed at moving their thinking in a different direction. Those who had been assigned to the “other culture” condition were told to imagine an Amazonian tribe, the Mamilons, which had a very different way of life from our own. They were given a brief description of this tribe’s rituals, values and modes of thought. Then they were told to imagine that one of their classmates thought that the act of infanticide was morally bad, while someone from this Amazonian tribe thought that the act was morally permissible. These participants were then asked whether they agreed or disagreed with the corresponding statement: Since your classmate and the Mamilon have different judgments about this case, at least one of them must be wrong. Finally, participants in the “extraterrestrial” condition were told about a culture that was just about as different from our own as can possibly be conceived. They were asked to imagine a race of extraterrestrial beings, the Pentars, who have no interest in friendship, love or happiness. Instead, the Pentars’ only goal is to maximise the total number of equilateral pentagons in the universe, and they move through space doing everything in their power to achieve this goal. (If a Pentar becomes too old to work, she is immediately killed and transformed into a pentagon herself.) As you might guess, these participants were then told to imagine a Pentar who thinks that the act of infanticide is morally permissible. Then came the usual statement: Since your classmate and the Pentar have different judgments about this case, at least one of them must be wrong. The results of the study showed a systematic difference between conditions. In particular, as we moved toward more distant cultures, we found a steady shift toward more relativist answers – with people in the first condition tending to agree with the statement that at least one of them had to be wrong, people in the second being pretty evenly split between the two answers, and people in the third tending to reject the statement quite decisively. Note that all participants in the study are considering judgments about the very same act. There is just a single person, living in the United States, who is performing an act of infanticide, and participants are being asked to consider different judgments one might make about that very same act. Yet, when participants are asked to consider individuals who come at the issue from wildly different perspectives, they end up concluding that these individuals could have opposite opinions without either of them being in any way wrong. This result seems strongly to suggest that people can be drawn under certain circumstances to a form of moral relativism. But now we face a new question. If we learn that people’s ordinary practice is not an objectivist one – that it actually varies depending on the degree to which people take other perspectives into account – how can we then use this information to address the deeper philosophical issues about the true nature of morality? The answer here is in one way very complex and in another very simple. It is complex in that one can answer such questions only by making use of very sophisticated and subtle philosophical methods. Yet, at the same time, it is simple in that such methods have already been developed and are being continually refined and elaborated within the literature in analytic philosophy. The trick now is just to take these methods and apply them to working out the implications of an ordinary practice that actually exists. Share This Joshua Knobe is an associate professor at Yale University, affiliated both with the Program in Cognitive Science and the Department of Philosophy.
Getting the DID number from a CallCentric SIP trunk for FreePBX I’ve got a few DDI numbers from CallCentric all around the world (UK, US, Australia) and couldn’t figure our how to setup an ‘Inbound Route’ in FreePBX that used the number that had been dialled to route the call. It turns out that you need to extract the number from the ‘SIP header’ information and there’s no setting in FreePBX to do this so it means hacking at the Asterisk config files just a little. There are a few methods for doing this but these instructions should work for FreePBX/Asterisk – When setting up your ‘SIP trunk’ in FreePBX under ‘PEER DETAILS’ you want to put the line – “context=custom-get-did-from-sip” then you need to edit the file /etc/asterisk/extensions_custom.conf and add the following lines –
Introduction ============ Blood-borne pathogens first encounter the adaptive immune system in the marginal zone region of the spleen where the convergence of innate and adaptive immune mechanisms insures an early and effective response to pathogen antigens ([@bib1], [@bib2]). Both thymic-independent and -dependent responses are elicited in response to infection ([@bib1], [@bib3]). The thymic-independent response involves the targeting and activation of marginal zone B cells (MZBs)[\*](#fn1){ref-type="fn"}through their interaction with the repetitive antigenic determinants of pathogens with complement and B cell antigen receptors ([@bib4], [@bib5]). In contrast, the thymic-dependent Ab response is driven by the interaction and reciprocal stimulation of APCs, T lymphocytes, and B cells. The organization of the splenic white pulp nodule into discrete zones enriched for either B cells, T cells, or APCs provide a spatial microenvironment that facilitates an efficient interaction of pathogens with the various cellular populations required for insuring an efficient immune response ([@bib6]--[@bib8]). Antigen presentation and stimulation of T and B cells ultimately results in the formation of germinal centers, high affinity neutralizing Abs, and memory cells. Recent reports have begun to define the cellular components and molecular signals that are necessary to establish the marginal zone. B cell intrinsic pathways have been described involving specific chemokines and their receptors, molecules involved in B cell activation, as well as adhesion molecules and their ligands ([@bib9], [@bib10]). Apart from the MZB, the other predominant cell of the marginal zone is the marginal zone macrophage (MZMO), which is distinct from the metallophilic macrophage, defined by the marker MOMA-1, located at the border of the marginal and follicular zone ([@bib11]). The MZMO is defined by its location, interspersed in several layers within the marginal zone, and by its expression of the markers MARCO and ER-TR9 ([@bib12], [@bib13]). The former molecule is a scavenger receptor belonging structurally to the class A receptor family whereas the latter is identical to the C-type lectin SIGN-RI ([@bib14]--[@bib17]). MARCO has been shown to bind a range of microbial Ags including *Staphylococcus aureus* and *Escherichia coli* whereas SIGN-RI is the predominant receptor for uptake of polysaccharide dextran by MZMOs. Even though both MZBs and MZMOs are implicated in both thymus-dependent and -independent immune responses, the exact roles of the two cell types in initiation of the response to blood-borne pathogens is not known. We now define a unique role for the MZMO in regulation of MZB retention and activation and show that movement of this subset of macrophages to the red pulp of the spleen involves signaling via SH2-containing inositol-5-phosphatase 1 (SHIP) and Bruton\'s tyrosine kinase (Btk). In addition, we show a direct interaction between MZMOs and MZBs via the MARCO receptor on MZMOs and a ligand on MZBs. Materials and Methods ===================== Mice. ----- C57BL/6 mice obtained from The Jackson Laboratory were used as WT mice and controls unless otherwise stated. Founders of SHIP-deficient mice were provided by G. Krystal (Terry Fox Laboratory, BC Cancer Agency, Vancouver, Canada; reference [@bib18]) and Btk-deficient mice were purchased from The Jackson Laboratory. Op/op mice were provided by J. Pollard (Albert Einstein College of Medicine, New York, NY) and LysMCre transgenic mice ([@bib19]) were provided by I. Forster (Technical University of Munich, Germany). Abs and bacteria was injected i.v. in the tail vein and all experiments involving mice were performed in accordance with National Institutes of Health (NIH) guidelines. All mice were maintained under specific pathogen-free conditions at The Rockefeller University. Antibodies and Reagents. ------------------------ For histological examination 6-μM frozen sections were stained, and for FACS^®^ analysis erythrocyte-depleted spleen cells were used. Macrophages were detected using MOMA-1, MARCO Abs from Serotec, and ER-TR9 from Accurate Chemical & Scientific Corp. Abs to CD1d, B220, CD19, CD21/CD35 (CRI/II), CD23, MAC-1, anti--rat alkaline phosphatase, and anti--rabbit horseradish peroxidase were from BD Biosciences. Secondary Abs for immunohistochemistry, anti-biotin, anti-FITC F(ab′) horseradish peroxidase, or alkaline phosphatase were from DakoCytomation and rabbit anti--SHIP used for Western blot was from Upstate Biotechnology. Vector Blue Alkaline Phosphatase Substrate from Vector Laboratories and DAB peroxidase substrate from Sigma-Aldrich were used for development of immunohistochemistry stains. Soluble MARCO receptor was provided by T. Pikkarainen (The Karolinska Institute, Stockholm, Sweden; reference [@bib20]) and was biotinylated using the EZ-Link™ kit from Pierce Chemical Co. The biotinylated soluble MARCO was detected using Streptavidin-CyChrome™ from BD Biosciences. *S. aureus* fluorescent bioparticles were purchased from Molecular Probes, Inc. and MACS anti-FITC and anti-biotin beads were from Miltenyi Biotec. Cl~2~MDP (or clodronate) and PBS liposomes were provided by Roche Diagnostics. Conditional Targeting of SHIP. ------------------------------ Floxed SHIP mice were created by insertion of loxP sites flanking the 10th and 11th exons (see [Fig. 2](#fig2){ref-type="fig"} a) of the SHIP gene. The targeting vector was introduced into embryonic stem (ES) cells by electroporation and clones were selected with neomycin and ganciclovir and verified by Southern blot and PCR. Properly integrated ES clones were transiently transfected with a Cre-expressing plasmid. Clones were subsequently selected for a conditional floxed allele (SHIP^flox^) or null allele (SHIP^null^) using Southern blot and PCR. Appropriate ES clones were then injected into blastocysts to generate chimeric mice. The chimeric mice were then bred with C57BL/6 mice to achieve germline transmission. These mice were subsequently crossed with mice expressing Cre in the myeloid compartment (LysMcre; reference [@bib19]) to generate Cre^+^/null/flox mice. Mice were screened for respective genotype by PCR and SHIP protein expression using Western blot ([@bib21]) on equal numbers of spleen cells purified by MACS (Miltenyi Biotec) sorting according to protocol from the manufacturer. Relative expression of SHIP in macrophage and B cell populations (comparing wt/null with flox/null/cre) were estimated using Alpha imager software from Alpha Innotech Corp. Results and Discussion ====================== Mice deficient in the inhibitory signaling molecule SHIP display pleiotropic defects in macrophages, NK cells, and lymphocytes ([@bib18], [@bib22]). A prominent feature of these mice is their splenomegaly resulting from dysregulation of myeloid proliferation. As seen in [Fig. 1](#fig1){ref-type="fig"} Figure 1.SHIP-deficient mice lack MZBs and MZMOs are displaced to the red pulp. (a) FACS^®^ profiles of single cell suspensions from the spleen of SHIP-heterozygous (SHIP^+/−^) and -deficient (SHIP^−/−^) mice. MZBs were measured as the CD19^+^, CRI^high^, and CD23^low^ population. The numbers shown represent percent of CD19^+^ cells for the depicted gates as an average of five mice. Numbers for the follicular B cells are shown for comparison. (b) Representative immunohistochemical analysis of above listed mice. At least four serial sections from each mouse were stained for MOMA-1^+^ (blue, top) metallophilic macrophages or MARCO^+^ MZMOs (blue, bottom). Sections were also stained for B220 (brown) to show the positioning of the follicle. ×10. , SHIP-deficient mice also display a specific defect in the organization of the splenic follicle with the loss of MZBs measured as the CD21^high^/CD23^low^ population in FACS^®^ and in sections as the B220^+^ cells localizing peripherally to the MOMA-1^+^ cells ([Fig. 1](#fig1){ref-type="fig"}, a and b). In the SHIP-deficient mice the MARCO^+^ MZMO cells are no longer organized within the marginal zone and adjacent to the MOMA-1 macrophages but are redistributed to the red pulp, whereas MOMA-1^+^ metallophils remain unaffected ([Fig. 1](#fig1){ref-type="fig"} b). Because SHIP is expressed in most hematopoietic cells, including lymphoid and myeloid subsets, we determined if this marginal zone phenotype in SHIP-deficient mice was the result of primary macrophage dysregulation. A conditional disruption of SHIP was generated in which macrophages displayed an approximate \>90% reduction in SHIP expression whereas B cell expression was reduced by \<10% ([Fig. 2](#fig2){ref-type="fig"} Figure 2.Conditional targeting of SHIP in macrophages results in MZMO displacement and reduced numbers of MZBs. (a) A targeting construct covering exons 10 to 13 of SHIP, from EcoRI (E) to HindIII (H), was made. Boxes represent exons and triangles represent loxP sites flanking exons 10 to 11 and a neomycin resistance gene (neo). Properly integrated ES cell clones were transiently transfected with Cre recombinase to create conditional floxed (SHIP^flox^) or null (SHIP^null^) clones. These cells were subsequently used to create floxed (flox) and null mice, which were crossed to mice expressing Cre from a macrophage-specific lysosomal promoter (cre). (b) Western blot analysis of MAC1^+^ and CD19^+^ spleen cells (SPC) from WT, WT/null, null/null, LysM floxed (flox/null/cre), and relative spleen size of 6-wk-old WT/null and flox/null/cre SHIP mice. (c) FACS^®^ and histological profiles of single cell suspensions from the spleen of the conditionally targeted SHIP KO mice. MZBs were measured as the CD19^+^, CRI^high^, and CD23^low^ population. The numbers shown represent percent of CD19^+^ cells for the depicted gates as an average of five mice and the numbers for the follicular B cells are shown for comparison. For representative immunohistochemical analysis, at least four serial sections were stained for MOMA-1^+^ (blue, top) metallophilic macrophages or MARCO^+^ MZMOs (blue, bottom). Sections were also stained for B220 (brown) to show the positioning of the follicle. Refer to [Fig. 1](#fig1){ref-type="fig"} for SHIP^+/−^ and SHIP^−/−^ profiles. ×10. , a and b). This is consistent with the expression patterns of Cre recombinase, driven by the lysosyme promoter used ([@bib19]). The mice developed a splenomegaly at ∼5 wk of age ([Fig. 2](#fig2){ref-type="fig"} b), similar to that of complete SHIP deletion, thus implicating a primary macrophage defect as the cause for splenomegaly in SHIP^−/−^ mice ([@bib18]). In addition, the mice displayed essentially the same marginal zone phenotype with significantly reduced MZBs as defined by flow cytometry and reorganization of the MZMOs as observed by histological staining ([Fig. 2](#fig2){ref-type="fig"} c). To confirm that the SHIP phenotype is B cell nonautonomous and that SHIP-deficient B cells can give rise to MZB populations when WT MZMOs are available, we produced BM chimeras using SHIP-deficient BM combined with WT BM and injected these cells into irradiated WT recipients. In the resulting chimeric mice the SHIP-deficient and WT BMs contributed equally to the MZB population (unpublished data). In B cell lines it has been shown that SHIP functions as a negative regulator of cellular activation by regulating the association of the positive signaling kinase Btk with the membrane, thus raising the threshold required for stimulation ([@bib23]). It does so by hydrolyzing PIP~3~, the substrate for Btk association with the membrane, thereby reducing the ability of Btk to become membrane associated and activated ([@bib24]). Because both SHIP and Btk are expressed in macrophages and a link between these molecules had been suggested, we reasoned that the myeloid proliferation and MZMO phenotype leading to the loss of MZBs might be the result of inappropriate activation of Btk in macrophages of SHIP-deficient animals ([@bib25], [@bib26]). Disruption of Btk in macrophages may thus be sufficient to restore normal signaling thresholds in SHIP-deficient mice. Combining the SHIP deficiency with a Btk deficiency resulted in the restoration of both the normal marginal zone structure ([Fig. 3](#fig3){ref-type="fig"} Figure 3.SHIP and Btk interact in myeloid proliferation and activation. (a) FACS^®^ and histological profiles of single cell suspensions from the spleen of SHIP and Btk double KO mice (SHIP^−/−^/Btk^−^). MZBs were measured as the CD19^+^, CRI^high^, and CD23^low^ population. The numbers shown represent percent of CD19^+^ cells for the depicted gates as an average of four mice and the numbers for the follicular B cells are shown for comparison. For representative immunohistochemical analysis, at least four serial sections from were stained for MOMA-1^+^ (blue, top) metallophilic macrophages or MARCO^+^ MZMOs (blue, bottom). Sections were also stained for B220 (brown) to show the positioning of the follicle. ×10. (b) Relative spleen size of 5-wk-old heterozygous KO or double KO mice. a) and spleen size ([Fig. 3](#fig3){ref-type="fig"} b) indicating that Btk is an important target of SHIP in myeloid cells in vivo. Similarly, Btk deficiency counteracted the over responsiveness of myeloid progenitors to GM-CSF and M-CSF in SHIP-deficient mice (unpublished data). Both the dysregulation of myeloid proliferation and follicular architecture likely result from enhanced signaling through the Btk pathway in myeloid cells. Reversion of the MZB and myeloid phenotypes in SHIP^−/−^ mice by deletion of Btk suggests that Btk is the dominant Tec family member regulated by SHIP in these cells. The observation that other members of the family are expressed in macrophages and have been shown to be able to substitute for Btk both in vivo and in KO mice indicates a surprising degree of specificity to the SHIP inhibitory pathway ([@bib27]--[@bib29]). These results suggested that MZMOs might be critical to the organization of the white pulp nodule and localization of MZBs in this structure. To test this directly we exploited the observation that MZMOs can be ablated by their preferential ingestion of macrophage-depleting liposomes ([@bib30]). At a low concentration of these liposomes we could see preferential depletion of MARCO^+^ MZMOs as opposed to the adjacent MOMA-1 macrophages ([Fig. 4](#fig4){ref-type="fig"}) Figure 4.MARCO^+^ MZMOs are required for retention of MZBs. Representative immunohistochemical analysis and FACS^®^ profiles of spleens from at least four WT mice treated with liposomes or untreated op/op mice. WT mice were injected i.v. with 100 μl PBS containing liposomes or with liposomes containing clodronate at a 1:24 dilution where MZMOs were preferentially depleted. 48 h later serial spleen sections were stained for MOMA-1^+^ (blue, top) metallophilic macrophages or MARCO^+^ (blue, middle) MZMOs. The sections were also stained for B220 (brown) to see the positioning of these populations in relation to the B cell follicle. ×10. Spleen cells were analyzed by FACS^®^ analysis for detection of MZBs as measured by the CD19^+^, CRI^high^, and CD23^low^ population. Numbers shown are the average percent-positive cells of four mice. Similar profiles are shown for untreated *op/op* mice (right). Data shown are representative of three independent experiments. . Other phagocytic cells in the spleen, such as red pulp macrophages and dendritic cells were largely unaffected by this treatment (not depicted). When MZMOs were depleted in this fashion, we observe a specific reduction in the MZBs by both flow cytometry and histological staining. In contrast, MOMA-1 macrophages are specifically absent in the CSF-1--deficient strain *op/op* but these mice retain MARCO^+^/ER-TR9^−^ MZMOs ([@bib31], [@bib32]). The absence of the MOMA-1^+^ cells and the ER-TR9 marker did not result in reduction in MZBs, but rather, an expansion of these cells is observed, indicating that the macrophage population that is required for MZB retention are the MARCO^+^ MZMOs. The identity of the retention signal expressed by MARCO^+^ MZMO cells was next determined by investigating the role of specific surface receptors on the MZMO in maintaining the marginal zone structure. The MARCO receptor, in addition to binding to bacteria ([@bib33]), contains an SRCR domain that has been implicated in binding to CD19^+^ lymphocytes ([@bib34], [@bib35]). To determine if MARCO itself is capable of binding to MZBs, we expressed the extracellular domains of MARCO as a soluble molecule ([@bib20]) and used it to stain splenic populations ([Fig. 5](#fig5){ref-type="fig"}) Figure 5.Soluble MARCO receptor (sMARCO) binds preferentially to MZBs. Representative FACS^®^ analysis of spleen cells from WT mice stained with CRI, CD23, and biotinylated sMARCO. Binding of sMARCO to different spleen cell populations was based on gates set on the CRI versus CD23 stain. red, MZBs; blue, follicular B cells; black, non-B cells. The histogram (bottom) shows the mean fluorescence index (MFI) and SD (*n* = 5) for the different populations as well as the avidin (Av) control and block using the MARCO-specific ED31 Ab. Data shown are representative of three independent experiments. . Three populations of cells were distinguished by flow cytometry when stained with CD21 and CD23. Maximal binding to soluble MARCO was observed for the MZBs (CD21^hi^ CD23^low^), whereas the follicular B cells (CD21^low^ CD23^hi^) displayed reduced binding. None of the other splenic populations (T cells, macrophages, or dendritic cells) were capable of binding to soluble MARCO. This binding was specific for the MARCO SRCR domain, as determined by the ability of a monoclonal Ab to this domain (ED31; reference [@bib33]) to block the binding of soluble MARCO to MZBs. When the MARCO-specific Ab was injected i.v. to WT mice it resulted in disruption of the marginal zone structure in which MZBs, identified by CD1d staining, were found in the follicular region whereas MZMOs, identified by ER-TR9 staining, were retained in the marginal zone ([Fig. 6](#fig6){ref-type="fig"}) Figure 6.In vivo disruption of MARCO and MZB interactions leads to MZB migration to the follicle. WT mice were given 100 μg control rat IgG or anti-MARCO (ED31) IgG i.v. 3 h later the mice were killed and the spleens were stained for macrophage and B cell populations. Representative stains of serial sections from at least four different mice are shown. MZMOs were detected with anti-MARCO (blue, top) or ER-TR9 (blue, middle) antibodies whereas metallophilic macrophages were stained with MOMA-1 (brown, bottom). B220^+^ B cells (brown) were stained for positioning of the follicle and MZBs as the CD1^high^ (blue, bottom) population. ×10. Part of the spleen was used for flow cytometric analysis to determine the CD19^+^, CRI^high^, and CD23^low^ populations. Numbers shown are the average of four mice. The percent of CD19^+^ cells for either MZBs or follicular B cells is shown for comparison. Data shown are representative of two independent experiments. . These results suggest that a direct interaction between MZMO and MZBs is mediated by MARCO--MZB binding, through a MARCO ligand expressed on these B cells, and provides a mechanism for the retention of MZBs by MARCO-expressing MZMO cells. Perturbation of this interaction either by disruption of adhesion and/or induction of macrophage activation by MARCO cross-linking results in the appearance of cells expressing a MZB surface phenotype in the follicular zone. To address the relevance of the MARCO^+^ MZMO and its retention of MZBs to its contribution to the development of an immune response to pathogens, we injected mice i.v. with rhodamine-conjugated *S. aureus*, which is a known ligand for the MARCO receptor ([@bib12]). Within 30 min of injection bacteria were visualized exclusively bound to the MZMO cells, a role consistent with the phagocytic property of these scavenger receptor--expressing cells ([Fig. 7](#fig7){ref-type="fig"}) Figure 7.*S. aureus* induce MZMO movement and displacement of MZBs. WT mice were injected i.v. with 250 μg heat-killed and rhodamine-conjugated *S. aureus* in PBS. 0.5 or 18 h later the mice were killed and the spleens were sectioned and stained. Representative stains from at least four mice are shown. MARCO^+^ MZMOs (left) are stained blue and B220^+^ B cells are stained brown. The middle shows the same stains as in the left, merged with the fluorescent stain of *S. aureus.* The right shows stains for the CD1^high^ MZB population (blue) and MOMA-1^+^ metallophilic macrophages (brown). ×10. The data shown are representative of two independent experiments. . 18 h after injection the microbes and the MZMO were found to have comigrated into the red pulp and cells with a MZB phenotype (CD1d^high^) were mostly found in the follicular region. These results are consistent with a model in which interaction of *S. aureus* with MARCO on MZMOs results in their migration into the red pulp and the concomitant migration of MZBs into the follicular region as has been reported for LPS and *E. coli* ([@bib8], [@bib9]). The deletion of the inhibitory signaling molecule SHIP results in a similar MZMO migration response, suggesting that MZMO activation can trigger migration into the red pulp. We presume that the likely explanation for the migration seen in response to *S. aureus* ingestion is the activation of MZMOs by their encounter with these bacteria as has been described ([@bib36], [@bib37]). A similar result was observed for *E. coli* suggesting a more general migratory response by MZMO cells to microbial challenge (unpublished data). The migratory response of the MZMO, carrying Ag to the red pulp, could simply be a method of clearance of particulate Ags or alternatively MZMOs could function as Ag transporters/presenters and supporters of plasmablast formation shown to take place in the red pulp ([Fig. 8](#fig8){ref-type="fig"} Figure 8.Proposed model for interactions between MZMO and MZB and the response of these cells to blood-borne pathogens. In the marginal zone (MZ), MZBs interact with the MZMO via the MARCO receptor (a) and with stromal elements via the ICAM/VCAM and their respective ligands LFA-1 and α4β1 (b). Upon phagocytosis of particulate Ags, the MARCO^+^ MZMOs migrate to the red pulp (c) and the majority of the MZBs migrate to the follicle where they interact with cells such as dendritic and follicular dendritic (d, DC and FDC). In the early response to T cell--independent Ags, the MZB also has the capacity to migrate to the red pulp to take part in plasma cell formation (e), where a possible interaction with MZMOs and MZBs may take place. ; references [@bib38]--[@bib40]). This has previously been reported to be a function of dendritic cells in the T/B cell border of the follicle and by macrophages supporting B1 B cells in the peritoneum ([@bib10]). Interestingly, Kang et al. ([@bib14]) recently showed that phagosomes in MZMOs, after uptake of dextran polysaccarides via SIGN-RI did not stain positive for the endosomal markers LAMP-1 and transferrin. This suggests that Ags taken up by MZMOs may not necessarily take the route of normal phagosome maturation ([@bib41]) resulting in destruction or Ag presentation and thus could provide a mechanism to transport intact Ag to the red pulp by MZMOs. These results suggest that the interaction of MZMO cells with MZBs is required to maintain the marginal zone structure and that this association is perturbed upon MZMO binding and activation by microbial pathogens. It is likely that the MZBs migrate into the follicular zone in response to CXCL13 ([@bib9]) in the absence of retention signals from the MARCO^+^ MZMO. This pathway is likely to be independent of the integrin pathway involving stromal VCAM/ICAM and B cell LFA-1/α4β1 because disruption of that pathway with antibodies to LFA-1 and α4β1 results in the release of MZBs to the blood stream ([@bib9]), not their migration into the follicle, in contrast to the results presented here ([Fig. 8](#fig8){ref-type="fig"}). In addition, we see no effect on the localization of MZMO cells using antibodies to the stromal integrins, nor do we observe effects on their ligand expression when MZMO cells are triggered to migrate (unpublished data). These pathways are thus likely to serve different functions in the organization of the marginal zone, with the MZMO pathway specific for the antimicrobial response, leading to internalization of the organism and trafficking of B cells into the follicular zone to propagate the immune responses. MZBs have the capacity to bind polysaccharide Ags through complement-mediated pathways and transport these to the follicular area of the spleen ([@bib6], [@bib8], [@bib42]). The events we have described appear to be another mechanism for delivery of MZBs and Ag to the T cell--rich follicular region. MZBs have mostly been implicated in the response to T cell--independent Ags, however, they are also capable of presenting Ags ([@bib43]) and may thus be important both for the T cell--dependent and --independent phase of the earliest defense against a pathogen. We would like to thank members of the Ravetch and Steinman labs at The Rockefeller University, especially Pierre Bruhns, Patrick Smith, Maggi Pack, Chae Gyu Park, and Sayori Yamazaki for technical assistance and comments on the manuscript. We also thank Dr. Jeffrey Pollard for op/op mice and Dr. Timo Pikkarainen for reagents and helpful comments. This work was supported by the Swedish Cancer Society and the NIH. *Abbreviations used in this paper:* Btk, Bruton\'s tyrosine kinase; ES, embryonic stem; MZB, marginal zone B cell; MZMO, marginal zone macrophage; SHIP, SH2-containing inositol-5-phosphatase 1.
Q: How can I Check the current value which is already passed or not in an array in nested foreach in php My array $key1=> Array ( [0] => 1 [1] => 2 [2] => 7 [3] => 11 [4] => 12 [5] => 17 [6] => 18 ) $_POST['name']=> Array ( [0] => General [1] => General [2] => Outdoors [3] => Dining [4] => Kitchen ) Here is my code, foreach ($key1 as $key => $value) { // echo $value; foreach ($_POST['name'] as $key => $value1) { //echo $value; $subQueryCond .=' AND '.$value1.' LIKE ' .$value ; } } While my Ajax calls this nested loop occurs.. Inside this I wrote a query.. If one value is passed. The query is in the format of AND 'General' LIKE 1. And if another value is passed in the $key1 it pass the query two times. It's like How many arrays are given that much time that query was passed.. So,here I would like to restrict the $value if it already came.. if two values were given,it pass the query in the following manner AND General LIKE 1 AND Outdoors LIKE 1 AND General LIKE 7 AND Outdoors LIKE 7 And my desired query must be in the form of AND General LIKE 1 AND General LIKE 7 AND Outdoors LIKE 7 can someone help me.. A: This will work for you... <?php $subQueryCond= ''; foreach ($key1 as $key => $value) { foreach ($_POST['name'] as $key => $value1) { $subQueryCond['AND '.$value1.' LIKE ' .$value] = ' AND '.$value1.' LIKE ' .$value ; } } echo "<pre>"; print_r($subQueryCond); $query = implode('',$subQueryCond) ; print_r($query); ?> just make an array with unique keys to value, then use implode() function to make query string...
Safety of union home care aides in Washington State. A rate-based understanding of home care aides' adverse occupational outcomes related to their work location and care tasks is lacking. Within a 30-month, dynamic cohort of 43 394 home care aides in Washington State, injury rates were calculated by aides' demographic and work characteristics. Injury narratives and focus groups provided contextual detail. Injury rates were higher for home care aides categorized as female, white, 50 to <65 years old, less experienced, with a primary language of English, and working through an agency (versus individual providers). In addition to direct occupational hazards, variability in workload, income, and supervisory/social support is of concern. Policies should address the roles and training of home care aides, consumers, and managers/supervisors. Home care aides' improved access to often-existing resources to identify, manage, and eliminate occupational hazards is called for to prevent injuries and address concerns related to the vulnerability of this needed workforce.
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Safe #-} {-# LANGUAGE Strict #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | -- -- This module implements a transformation from source to core -- Futhark. module Futhark.Internalise (internaliseProg) where import Control.Monad.Reader import Data.Bitraversable import Data.List (find, intercalate, intersperse, nub, transpose) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as M import qualified Data.Set as S import Futhark.IR.SOACS as I hiding (stmPattern) import Futhark.Internalise.AccurateSizes import Futhark.Internalise.Bindings import Futhark.Internalise.Defunctionalise as Defunctionalise import Futhark.Internalise.Defunctorise as Defunctorise import Futhark.Internalise.Lambdas import Futhark.Internalise.Monad as I import Futhark.Internalise.Monomorphise as Monomorphise import Futhark.Internalise.TypesValues import Futhark.Transform.Rename as I import Futhark.Util (splitAt3) import Language.Futhark as E hiding (TypeArg) import Language.Futhark.Semantic (Imports) -- | Convert a program in source Futhark to a program in the Futhark -- core language. internaliseProg :: MonadFreshNames m => Bool -> Imports -> m (I.Prog SOACS) internaliseProg always_safe prog = do prog_decs <- Defunctorise.transformProg prog prog_decs' <- Monomorphise.transformProg prog_decs prog_decs'' <- Defunctionalise.transformProg prog_decs' (consts, funs) <- runInternaliseM always_safe (internaliseValBinds prog_decs'') I.renameProg $ I.Prog consts funs internaliseAttr :: E.AttrInfo -> Attr internaliseAttr (E.AttrAtom v) = I.AttrAtom v internaliseAttr (E.AttrComp f attrs) = I.AttrComp f $ map internaliseAttr attrs internaliseAttrs :: [E.AttrInfo] -> Attrs internaliseAttrs = mconcat . map (oneAttr . internaliseAttr) internaliseValBinds :: [E.ValBind] -> InternaliseM () internaliseValBinds = mapM_ internaliseValBind internaliseFunName :: VName -> [E.Pattern] -> InternaliseM Name internaliseFunName ofname [] = return $ nameFromString $ pretty ofname ++ "f" internaliseFunName ofname _ = do info <- lookupFunction' ofname -- In some rare cases involving local functions, the same function -- name may be re-used in multiple places. We check whether the -- function name has already been used, and generate a new one if -- so. case info of Just _ -> nameFromString . pretty <$> newNameFromString (baseString ofname) Nothing -> return $ nameFromString $ pretty ofname internaliseValBind :: E.ValBind -> InternaliseM () internaliseValBind fb@(E.ValBind entry fname retdecl (Info (rettype, _)) tparams params body _ attrs loc) = do localConstsScope $ bindingParams tparams params $ \shapeparams params' -> do let shapenames = map I.paramName shapeparams normal_params = shapenames ++ map I.paramName (concat params') normal_param_names = namesFromList normal_params fname' <- internaliseFunName fname params msg <- case retdecl of Just dt -> errorMsg . ("Function return value does not match shape of type " :) <$> typeExpForError dt Nothing -> return $ errorMsg ["Function return value does not match shape of declared return type."] ((rettype', body_res), body_stms) <- collectStms $ do body_res <- internaliseExp "res" body rettype_bad <- internaliseReturnType rettype let rettype' = zeroExts rettype_bad return (rettype', body_res) body' <- ensureResultExtShape msg loc (map I.fromDecl rettype') $ mkBody body_stms body_res constants <- allConsts let free_in_fun = freeIn body' `namesSubtract` normal_param_names `namesSubtract` constants used_free_params <- forM (namesToList free_in_fun) $ \v -> do v_t <- lookupType v return $ Param v $ toDecl v_t Nonunique let free_shape_params = map (`Param` I.Prim int32) $ concatMap (I.shapeVars . I.arrayShape . I.paramType) used_free_params free_params = nub $ free_shape_params ++ used_free_params all_params = free_params ++ shapeparams ++ concat params' let fd = I.FunDef Nothing (internaliseAttrs attrs) fname' rettype' all_params body' if null params' then bindConstant fname fd else bindFunction fname fd ( fname', map I.paramName free_params, shapenames, map declTypeOf $ concat params', all_params, applyRetType rettype' all_params ) case entry of Just (Info entry') -> generateEntryPoint entry' fb Nothing -> return () where zeroExts ts = generaliseExtTypes ts ts allDimsFreshInType :: MonadFreshNames m => E.PatternType -> m E.PatternType allDimsFreshInType = bitraverse onDim pure where onDim (E.NamedDim v) = E.NamedDim . E.qualName <$> newVName (baseString $ E.qualLeaf v) onDim _ = E.NamedDim . E.qualName <$> newVName "size" -- | Replace all named dimensions with a fresh name, and remove all -- constant dimensions. The point is to remove the constraints, but -- keep the names around. We use this for constructing the entry -- point parameters. allDimsFreshInPat :: MonadFreshNames m => E.Pattern -> m E.Pattern allDimsFreshInPat (PatternAscription p _ _) = allDimsFreshInPat p allDimsFreshInPat (PatternParens p _) = allDimsFreshInPat p allDimsFreshInPat (Id v (Info t) loc) = Id v <$> (Info <$> allDimsFreshInType t) <*> pure loc allDimsFreshInPat (TuplePattern ps loc) = TuplePattern <$> mapM allDimsFreshInPat ps <*> pure loc allDimsFreshInPat (RecordPattern ps loc) = RecordPattern <$> mapM (traverse allDimsFreshInPat) ps <*> pure loc allDimsFreshInPat (Wildcard (Info t) loc) = Wildcard <$> (Info <$> allDimsFreshInType t) <*> pure loc allDimsFreshInPat (PatternLit e (Info t) loc) = PatternLit e <$> (Info <$> allDimsFreshInType t) <*> pure loc allDimsFreshInPat (PatternConstr c (Info t) pats loc) = PatternConstr c <$> (Info <$> allDimsFreshInType t) <*> mapM allDimsFreshInPat pats <*> pure loc generateEntryPoint :: E.EntryPoint -> E.ValBind -> InternaliseM () generateEntryPoint (E.EntryPoint e_paramts e_rettype) vb = localConstsScope $ do let (E.ValBind _ ofname _ (Info (rettype, _)) _ params _ _ attrs loc) = vb -- We replace all shape annotations, so there should be no constant -- parameters here. params_fresh <- mapM allDimsFreshInPat params let tparams = map (`E.TypeParamDim` mempty) $ S.toList $ mconcat $ map E.patternDimNames params_fresh bindingParams tparams params_fresh $ \shapeparams params' -> do entry_rettype <- internaliseEntryReturnType $ anySizes rettype let entry' = entryPoint (zip e_paramts params') (e_rettype, entry_rettype) args = map (I.Var . I.paramName) $ concat params' entry_body <- insertStmsM $ do -- Special case the (rare) situation where the entry point is -- not a function. maybe_const <- lookupConst ofname vals <- case maybe_const of Just ses -> return ses Nothing -> fst <$> funcall "entry_result" (E.qualName ofname) args loc ctx <- extractShapeContext (concat entry_rettype) <$> mapM (fmap I.arrayDims . subExpType) vals resultBodyM (ctx ++ vals) addFunDef $ I.FunDef (Just entry') (internaliseAttrs attrs) (baseName ofname) (concat entry_rettype) (shapeparams ++ concat params') entry_body entryPoint :: [(E.EntryType, [I.FParam])] -> ( E.EntryType, [[I.TypeBase ExtShape Uniqueness]] ) -> I.EntryPoint entryPoint params (eret, crets) = ( concatMap (entryPointType . preParam) params, case ( isTupleRecord $ entryType eret, entryAscribed eret ) of (Just ts, Just (E.TETuple e_ts _)) -> concatMap entryPointType $ zip (zipWith E.EntryType ts (map Just e_ts)) crets (Just ts, Nothing) -> concatMap entryPointType $ zip (map (`E.EntryType` Nothing) ts) crets _ -> entryPointType (eret, concat crets) ) where preParam (e_t, ps) = (e_t, staticShapes $ map I.paramDeclType ps) entryPointType (t, ts) | E.Scalar (E.Prim E.Unsigned {}) <- E.entryType t = [I.TypeUnsigned] | E.Array _ _ (E.Prim E.Unsigned {}) _ <- E.entryType t = [I.TypeUnsigned] | E.Scalar E.Prim {} <- E.entryType t = [I.TypeDirect] | E.Array _ _ E.Prim {} _ <- E.entryType t = [I.TypeDirect] | otherwise = [I.TypeOpaque desc $ length ts] where desc = maybe (pretty t') typeExpOpaqueName $ E.entryAscribed t t' = noSizes (E.entryType t) `E.setUniqueness` Nonunique typeExpOpaqueName (TEApply te TypeArgExpDim {} _) = typeExpOpaqueName te typeExpOpaqueName (TEArray te _ _) = let (d, te') = withoutDims te in "arr_" ++ typeExpOpaqueName te' ++ "_" ++ show (1 + d) ++ "d" typeExpOpaqueName te = pretty te withoutDims (TEArray te _ _) = let (d, te') = withoutDims te in (d + 1, te') withoutDims te = (0 :: Int, te) internaliseIdent :: E.Ident -> InternaliseM I.VName internaliseIdent (E.Ident name (Info tp) loc) = case tp of E.Scalar E.Prim {} -> return name _ -> error $ "Futhark.Internalise.internaliseIdent: asked to internalise non-prim-typed ident '" ++ pretty name ++ " of type " ++ pretty tp ++ " at " ++ locStr loc ++ "." internaliseBody :: E.Exp -> InternaliseM Body internaliseBody e = insertStmsM $ resultBody <$> internaliseExp "res" e bodyFromStms :: InternaliseM (Result, a) -> InternaliseM (Body, a) bodyFromStms m = do ((res, a), stms) <- collectStms m (,a) <$> mkBodyM stms res internaliseExp :: String -> E.Exp -> InternaliseM [I.SubExp] internaliseExp desc (E.Parens e _) = internaliseExp desc e internaliseExp desc (E.QualParens _ e _) = internaliseExp desc e internaliseExp desc (E.StringLit vs _) = fmap pure $ letSubExp desc $ I.BasicOp $ I.ArrayLit (map constant vs) $ I.Prim int8 internaliseExp _ (E.Var (E.QualName _ name) (Info t) loc) = do subst <- lookupSubst name case subst of Just substs -> return substs Nothing -> do -- If this identifier is the name of a constant, we have to turn it -- into a call to the corresponding function. is_const <- lookupConst name case is_const of Just ses -> return ses Nothing -> (: []) . I.Var <$> internaliseIdent (E.Ident name (Info t) loc) internaliseExp desc (E.Index e idxs (Info ret, Info retext) loc) = do vs <- internaliseExpToVars "indexed" e dims <- case vs of [] -> return [] -- Will this happen? v : _ -> I.arrayDims <$> lookupType v (idxs', cs) <- internaliseSlice loc dims idxs let index v = do v_t <- lookupType v return $ I.BasicOp $ I.Index v $ fullSlice v_t idxs' ses <- certifying cs $ letSubExps desc =<< mapM index vs bindExtSizes (E.toStruct ret) retext ses return ses -- XXX: we map empty records and tuples to bools, because otherwise -- arrays of unit will lose their sizes. internaliseExp _ (E.TupLit [] _) = return [constant True] internaliseExp _ (E.RecordLit [] _) = return [constant True] internaliseExp desc (E.TupLit es _) = concat <$> mapM (internaliseExp desc) es internaliseExp desc (E.RecordLit orig_fields _) = concatMap snd . sortFields . M.unions <$> mapM internaliseField orig_fields where internaliseField (E.RecordFieldExplicit name e _) = M.singleton name <$> internaliseExp desc e internaliseField (E.RecordFieldImplicit name t loc) = internaliseField $ E.RecordFieldExplicit (baseName name) (E.Var (E.qualName name) t loc) loc internaliseExp desc (E.ArrayLit es (Info arr_t) loc) -- If this is a multidimensional array literal of primitives, we -- treat it specially by flattening it out followed by a reshape. -- This cuts down on the amount of statements that are produced, and -- thus allows us to efficiently handle huge array literals - a -- corner case, but an important one. | Just ((eshape, e') : es') <- mapM isArrayLiteral es, not $ null eshape, all ((eshape ==) . fst) es', Just basetype <- E.peelArray (length eshape) arr_t = do let flat_lit = E.ArrayLit (e' ++ concatMap snd es') (Info basetype) loc new_shape = length es : eshape flat_arrs <- internaliseExpToVars "flat_literal" flat_lit forM flat_arrs $ \flat_arr -> do flat_arr_t <- lookupType flat_arr let new_shape' = reshapeOuter (map (DimNew . intConst Int32 . toInteger) new_shape) 1 $ I.arrayShape flat_arr_t letSubExp desc $ I.BasicOp $ I.Reshape new_shape' flat_arr | otherwise = do es' <- mapM (internaliseExp "arr_elem") es arr_t_ext <- internaliseReturnType (E.toStruct arr_t) rowtypes <- case mapM (fmap rowType . hasStaticShape . I.fromDecl) arr_t_ext of Just ts -> pure ts Nothing -> -- XXX: the monomorphiser may create single-element array -- literals with an unknown row type. In those cases we -- need to look at the types of the actual elements. -- Fixing this in the monomorphiser is a lot more tricky -- than just working around it here. case es' of [] -> error $ "internaliseExp ArrayLit: existential type: " ++ pretty arr_t e' : _ -> mapM subExpType e' let arraylit ks rt = do ks' <- mapM ( ensureShape "shape of element differs from shape of first element" loc rt "elem_reshaped" ) ks return $ I.BasicOp $ I.ArrayLit ks' rt letSubExps desc =<< if null es' then mapM (arraylit []) rowtypes else zipWithM arraylit (transpose es') rowtypes where isArrayLiteral :: E.Exp -> Maybe ([Int], [E.Exp]) isArrayLiteral (E.ArrayLit inner_es _ _) = do (eshape, e) : inner_es' <- mapM isArrayLiteral inner_es guard $ all ((eshape ==) . fst) inner_es' return (length inner_es : eshape, e ++ concatMap snd inner_es') isArrayLiteral e = Just ([], [e]) internaliseExp desc (E.Range start maybe_second end (Info ret, Info retext) loc) = do start' <- internaliseExp1 "range_start" start end' <- internaliseExp1 "range_end" $ case end of DownToExclusive e -> e ToInclusive e -> e UpToExclusive e -> e maybe_second' <- traverse (internaliseExp1 "range_second") maybe_second -- Construct an error message in case the range is invalid. let conv = case E.typeOf start of E.Scalar (E.Prim (E.Unsigned _)) -> asIntS Int32 _ -> asIntS Int32 start'_i32 <- conv start' end'_i32 <- conv end' maybe_second'_i32 <- traverse conv maybe_second' let errmsg = errorMsg $ ["Range "] ++ [ErrorInt32 start'_i32] ++ ( case maybe_second'_i32 of Nothing -> [] Just second_i32 -> ["..", ErrorInt32 second_i32] ) ++ ( case end of DownToExclusive {} -> ["..>"] ToInclusive {} -> ["..."] UpToExclusive {} -> ["..<"] ) ++ [ErrorInt32 end'_i32, " is invalid."] (it, le_op, lt_op) <- case E.typeOf start of E.Scalar (E.Prim (E.Signed it)) -> return (it, CmpSle it, CmpSlt it) E.Scalar (E.Prim (E.Unsigned it)) -> return (it, CmpUle it, CmpUlt it) start_t -> error $ "Start value in range has type " ++ pretty start_t let one = intConst it 1 negone = intConst it (-1) default_step = case end of DownToExclusive {} -> negone ToInclusive {} -> one UpToExclusive {} -> one (step, step_zero) <- case maybe_second' of Just second' -> do subtracted_step <- letSubExp "subtracted_step" $ I.BasicOp $ I.BinOp (I.Sub it I.OverflowWrap) second' start' step_zero <- letSubExp "step_zero" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) start' second' return (subtracted_step, step_zero) Nothing -> return (default_step, constant False) step_sign <- letSubExp "s_sign" $ BasicOp $ I.UnOp (I.SSignum it) step step_sign_i32 <- asIntS Int32 step_sign bounds_invalid_downwards <- letSubExp "bounds_invalid_downwards" $ I.BasicOp $ I.CmpOp le_op start' end' bounds_invalid_upwards <- letSubExp "bounds_invalid_upwards" $ I.BasicOp $ I.CmpOp lt_op end' start' (distance, step_wrong_dir, bounds_invalid) <- case end of DownToExclusive {} -> do step_wrong_dir <- letSubExp "step_wrong_dir" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) step_sign one distance <- letSubExp "distance" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) start' end' distance_i32 <- asIntS Int32 distance return (distance_i32, step_wrong_dir, bounds_invalid_downwards) UpToExclusive {} -> do step_wrong_dir <- letSubExp "step_wrong_dir" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) step_sign negone distance <- letSubExp "distance" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) end' start' distance_i32 <- asIntS Int32 distance return (distance_i32, step_wrong_dir, bounds_invalid_upwards) ToInclusive {} -> do downwards <- letSubExp "downwards" $ I.BasicOp $ I.CmpOp (I.CmpEq $ IntType it) step_sign negone distance_downwards_exclusive <- letSubExp "distance_downwards_exclusive" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) start' end' distance_upwards_exclusive <- letSubExp "distance_upwards_exclusive" $ I.BasicOp $ I.BinOp (Sub it I.OverflowWrap) end' start' bounds_invalid <- letSubExp "bounds_invalid" $ I.If downwards (resultBody [bounds_invalid_downwards]) (resultBody [bounds_invalid_upwards]) $ ifCommon [I.Prim I.Bool] distance_exclusive <- letSubExp "distance_exclusive" $ I.If downwards (resultBody [distance_downwards_exclusive]) (resultBody [distance_upwards_exclusive]) $ ifCommon [I.Prim $ IntType it] distance_exclusive_i32 <- asIntS Int32 distance_exclusive distance <- letSubExp "distance" $ I.BasicOp $ I.BinOp (Add Int32 I.OverflowWrap) distance_exclusive_i32 (intConst Int32 1) return (distance, constant False, bounds_invalid) step_invalid <- letSubExp "step_invalid" $ I.BasicOp $ I.BinOp I.LogOr step_wrong_dir step_zero invalid <- letSubExp "range_invalid" $ I.BasicOp $ I.BinOp I.LogOr step_invalid bounds_invalid valid <- letSubExp "valid" $ I.BasicOp $ I.UnOp I.Not invalid cs <- assert "range_valid_c" valid errmsg loc step_i32 <- asIntS Int32 step pos_step <- letSubExp "pos_step" $ I.BasicOp $ I.BinOp (Mul Int32 I.OverflowWrap) step_i32 step_sign_i32 num_elems <- certifying cs $ letSubExp "num_elems" $ I.BasicOp $ I.BinOp (SDivUp Int32 I.Unsafe) distance pos_step se <- letSubExp desc (I.BasicOp $ I.Iota num_elems start' step it) bindExtSizes (E.toStruct ret) retext [se] return [se] internaliseExp desc (E.Ascript e _ _) = internaliseExp desc e internaliseExp desc (E.Coerce e (TypeDecl dt (Info et)) (Info ret, Info retext) loc) = do ses <- internaliseExp desc e ts <- internaliseReturnType et dt' <- typeExpForError dt bindExtSizes (E.toStruct ret) retext ses forM (zip ses ts) $ \(e', t') -> do dims <- arrayDims <$> subExpType e' let parts = ["Value of (core language) shape ("] ++ intersperse ", " (map ErrorInt32 dims) ++ [") cannot match shape of type `"] ++ dt' ++ ["`."] ensureExtShape (errorMsg parts) loc (I.fromDecl t') desc e' internaliseExp desc (E.Negate e _) = do e' <- internaliseExp1 "negate_arg" e et <- subExpType e' case et of I.Prim (I.IntType t) -> letTupExp' desc $ I.BasicOp $ I.BinOp (I.Sub t I.OverflowWrap) (I.intConst t 0) e' I.Prim (I.FloatType t) -> letTupExp' desc $ I.BasicOp $ I.BinOp (I.FSub t) (I.floatConst t 0) e' _ -> error "Futhark.Internalise.internaliseExp: non-numeric type in Negate" internaliseExp desc e@E.Apply {} = do (qfname, args, ret, retext) <- findFuncall e -- Argument evaluation is outermost-in so that any existential sizes -- created by function applications can be brought into scope. let fname = nameFromString $ pretty $ baseName $ qualLeaf qfname loc = srclocOf e arg_desc = nameToString fname ++ "_arg" -- Some functions are magical (overloaded) and we handle that here. ses <- case () of -- Overloaded functions never take array arguments (except -- equality, but those cannot be existential), so we can safely -- ignore the existential dimensions. () | Just internalise <- isOverloadedFunction qfname (map fst args) loc -> internalise desc | Just (rettype, _) <- M.lookup fname I.builtInFunctions -> do let tag ses = [(se, I.Observe) | se <- ses] args' <- reverse <$> mapM (internaliseArg arg_desc) (reverse args) let args'' = concatMap tag args' letTupExp' desc $ I.Apply fname args'' [I.Prim rettype] (Safe, loc, []) | otherwise -> do args' <- concat . reverse <$> mapM (internaliseArg arg_desc) (reverse args) fst <$> funcall desc qfname args' loc bindExtSizes ret retext ses return ses internaliseExp desc (E.LetPat pat e body (Info ret, Info retext) _) = do ses <- internalisePat desc pat e body (internaliseExp desc) bindExtSizes (E.toStruct ret) retext ses return ses internaliseExp desc (E.LetFun ofname (tparams, params, retdecl, Info rettype, body) letbody _ loc) = do internaliseValBind $ E.ValBind Nothing ofname retdecl (Info (rettype, [])) tparams params body Nothing mempty loc internaliseExp desc letbody internaliseExp desc (E.DoLoop sparams mergepat mergeexp form loopbody (Info (ret, retext)) loc) = do ses <- internaliseExp "loop_init" mergeexp ((loopbody', (form', shapepat, mergepat', mergeinit')), initstms) <- collectStms $ handleForm ses form addStms initstms mergeinit_ts' <- mapM subExpType mergeinit' ctxinit <- argShapes (map I.paramName shapepat) mergepat' mergeinit_ts' let ctxmerge = zip shapepat ctxinit valmerge = zip mergepat' mergeinit' dropCond = case form of E.While {} -> drop 1 _ -> id -- Ensure that the result of the loop matches the shapes of the -- merge parameters. XXX: Ideally they should already match (by -- the source language type rules), but some of our -- transformations (esp. defunctionalisation) strips out some size -- information. For a type-correct source program, these reshapes -- should simplify away. let merge = ctxmerge ++ valmerge merge_ts = map (I.paramType . fst) merge loopbody'' <- localScope (scopeOfFParams $ map fst merge) $ inScopeOf form' $ insertStmsM $ resultBodyM =<< ensureArgShapes "shape of loop result does not match shapes in loop parameter" loc (map (I.paramName . fst) ctxmerge) merge_ts =<< bodyBind loopbody' attrs <- asks envAttrs loop_res <- map I.Var . dropCond <$> attributing attrs (letTupExp desc (I.DoLoop ctxmerge valmerge form' loopbody'')) bindExtSizes (E.toStruct ret) retext loop_res return loop_res where sparams' = map (`TypeParamDim` mempty) sparams forLoop mergepat' shapepat mergeinit form' = bodyFromStms $ inScopeOf form' $ do ses <- internaliseExp "loopres" loopbody sets <- mapM subExpType ses shapeargs <- argShapes (map I.paramName shapepat) mergepat' sets return ( shapeargs ++ ses, ( form', shapepat, mergepat', mergeinit ) ) handleForm mergeinit (E.ForIn x arr) = do arr' <- internaliseExpToVars "for_in_arr" arr arr_ts <- mapM lookupType arr' let w = arraysSize 0 arr_ts i <- newVName "i" bindingLoopParams sparams' mergepat $ \shapepat mergepat' -> bindingLambdaParams [x] (map rowType arr_ts) $ \x_params -> do let loopvars = zip x_params arr' forLoop mergepat' shapepat mergeinit $ I.ForLoop i Int32 w loopvars handleForm mergeinit (E.For i num_iterations) = do num_iterations' <- internaliseExp1 "upper_bound" num_iterations i' <- internaliseIdent i num_iterations_t <- I.subExpType num_iterations' it <- case num_iterations_t of I.Prim (IntType it) -> return it _ -> error "internaliseExp DoLoop: invalid type" bindingLoopParams sparams' mergepat $ \shapepat mergepat' -> forLoop mergepat' shapepat mergeinit $ I.ForLoop i' it num_iterations' [] handleForm mergeinit (E.While cond) = bindingLoopParams sparams' mergepat $ \shapepat mergepat' -> do mergeinit_ts <- mapM subExpType mergeinit -- We need to insert 'cond' twice - once for the initial -- condition (do we enter the loop at all?), and once with the -- result values of the loop (do we continue into the next -- iteration?). This is safe, as the type rules for the -- external language guarantees that 'cond' does not consume -- anything. shapeinit <- argShapes (map I.paramName shapepat) mergepat' mergeinit_ts (loop_initial_cond, init_loop_cond_bnds) <- collectStms $ do forM_ (zip shapepat shapeinit) $ \(p, se) -> letBindNames [paramName p] $ BasicOp $ SubExp se forM_ (zip mergepat' mergeinit) $ \(p, se) -> unless (se == I.Var (paramName p)) $ letBindNames [paramName p] $ BasicOp $ case se of I.Var v | not $ primType $ paramType p -> Reshape (map DimCoercion $ arrayDims $ paramType p) v _ -> SubExp se internaliseExp1 "loop_cond" cond addStms init_loop_cond_bnds bodyFromStms $ do ses <- internaliseExp "loopres" loopbody sets <- mapM subExpType ses loop_while <- newParam "loop_while" $ I.Prim I.Bool shapeargs <- argShapes (map I.paramName shapepat) mergepat' sets -- Careful not to clobber anything. loop_end_cond_body <- renameBody <=< insertStmsM $ do forM_ (zip shapepat shapeargs) $ \(p, se) -> unless (se == I.Var (paramName p)) $ letBindNames [paramName p] $ BasicOp $ SubExp se forM_ (zip mergepat' ses) $ \(p, se) -> unless (se == I.Var (paramName p)) $ letBindNames [paramName p] $ BasicOp $ case se of I.Var v | not $ primType $ paramType p -> Reshape (map DimCoercion $ arrayDims $ paramType p) v _ -> SubExp se resultBody <$> internaliseExp "loop_cond" cond loop_end_cond <- bodyBind loop_end_cond_body return ( shapeargs ++ loop_end_cond ++ ses, ( I.WhileLoop $ I.paramName loop_while, shapepat, loop_while : mergepat', loop_initial_cond : mergeinit ) ) internaliseExp desc (E.LetWith name src idxs ve body t loc) = do let pat = E.Id (E.identName name) (E.identType name) loc src_t = E.fromStruct <$> E.identType src e = E.Update (E.Var (E.qualName $ E.identName src) src_t loc) idxs ve loc internaliseExp desc $ E.LetPat pat e body (t, Info []) loc internaliseExp desc (E.Update src slice ve loc) = do ves <- internaliseExp "lw_val" ve srcs <- internaliseExpToVars "src" src dims <- case srcs of [] -> return [] -- Will this happen? v : _ -> I.arrayDims <$> lookupType v (idxs', cs) <- internaliseSlice loc dims slice let comb sname ve' = do sname_t <- lookupType sname let full_slice = fullSlice sname_t idxs' rowtype = sname_t `setArrayDims` sliceDims full_slice ve'' <- ensureShape "shape of value does not match shape of source array" loc rowtype "lw_val_correct_shape" ve' letInPlace desc sname full_slice $ BasicOp $ SubExp ve'' certifying cs $ map I.Var <$> zipWithM comb srcs ves internaliseExp desc (E.RecordUpdate src fields ve _ _) = do src' <- internaliseExp desc src ve' <- internaliseExp desc ve replace (E.typeOf src `setAliases` ()) fields ve' src' where replace (E.Scalar (E.Record m)) (f : fs) ve' src' | Just t <- M.lookup f m = do i <- fmap sum $ mapM (internalisedTypeSize . snd) $ takeWhile ((/= f) . fst) $ sortFields m k <- internalisedTypeSize t let (bef, to_update, aft) = splitAt3 i k src' src'' <- replace t fs ve' to_update return $ bef ++ src'' ++ aft replace _ _ ve' _ = return ve' internaliseExp desc (E.Attr attr e _) = local f $ internaliseExp desc e where attrs = oneAttr $ internaliseAttr attr f env | "unsafe" `inAttrs` attrs, not $ envSafe env = env {envDoBoundsChecks = False} | otherwise = env {envAttrs = envAttrs env <> attrs} internaliseExp desc (E.Assert e1 e2 (Info check) loc) = do e1' <- internaliseExp1 "assert_cond" e1 c <- assert "assert_c" e1' (errorMsg [ErrorString $ "Assertion is false: " <> check]) loc -- Make sure there are some bindings to certify. certifying c $ mapM rebind =<< internaliseExp desc e2 where rebind v = do v' <- newVName "assert_res" letBindNames [v'] $ I.BasicOp $ I.SubExp v return $ I.Var v' internaliseExp _ (E.Constr c es (Info (E.Scalar (E.Sum fs))) _) = do (ts, constr_map) <- internaliseSumType $ M.map (map E.toStruct) fs es' <- concat <$> mapM (internaliseExp "payload") es let noExt _ = return $ intConst Int32 0 ts' <- instantiateShapes noExt $ map fromDecl ts case M.lookup c constr_map of Just (i, js) -> (intConst Int8 (toInteger i) :) <$> clauses 0 ts' (zip js es') Nothing -> error "internaliseExp Constr: missing constructor" where clauses j (t : ts) js_to_es | Just e <- j `lookup` js_to_es = (e :) <$> clauses (j + 1) ts js_to_es | otherwise = do blank <- letSubExp "zero" =<< eBlank t (blank :) <$> clauses (j + 1) ts js_to_es clauses _ [] _ = return [] internaliseExp _ (E.Constr _ _ (Info t) loc) = error $ "internaliseExp: constructor with type " ++ pretty t ++ " at " ++ locStr loc internaliseExp desc (E.Match e cs (Info ret, Info retext) _) = do ses <- internaliseExp (desc ++ "_scrutinee") e res <- case NE.uncons cs of (CasePat pCase eCase _, Nothing) -> do (_, pertinent) <- generateCond pCase ses internalisePat' pCase pertinent eCase (internaliseExp desc) (c, Just cs') -> do let CasePat pLast eLast _ = NE.last cs' bFalse <- do (_, pertinent) <- generateCond pLast ses eLast' <- internalisePat' pLast pertinent eLast internaliseBody foldM (\bf c' -> eBody $ return $ generateCaseIf ses c' bf) eLast' $ reverse $ NE.init cs' letTupExp' desc =<< generateCaseIf ses c bFalse bindExtSizes (E.toStruct ret) retext res return res -- The "interesting" cases are over, now it's mostly boilerplate. internaliseExp _ (E.Literal v _) = return [I.Constant $ internalisePrimValue v] internaliseExp _ (E.IntLit v (Info t) _) = case t of E.Scalar (E.Prim (E.Signed it)) -> return [I.Constant $ I.IntValue $ intValue it v] E.Scalar (E.Prim (E.Unsigned it)) -> return [I.Constant $ I.IntValue $ intValue it v] E.Scalar (E.Prim (E.FloatType ft)) -> return [I.Constant $ I.FloatValue $ floatValue ft v] _ -> error $ "internaliseExp: nonsensical type for integer literal: " ++ pretty t internaliseExp _ (E.FloatLit v (Info t) _) = case t of E.Scalar (E.Prim (E.FloatType ft)) -> return [I.Constant $ I.FloatValue $ floatValue ft v] _ -> error $ "internaliseExp: nonsensical type for float literal: " ++ pretty t internaliseExp desc (E.If ce te fe (Info ret, Info retext) _) = do ses <- letTupExp' desc =<< eIf (BasicOp . SubExp <$> internaliseExp1 "cond" ce) (internaliseBody te) (internaliseBody fe) bindExtSizes (E.toStruct ret) retext ses return ses -- Builtin operators are handled specially because they are -- overloaded. internaliseExp desc (E.BinOp (op, _) _ (xe, _) (ye, _) _ _ loc) | Just internalise <- isOverloadedFunction op [xe, ye] loc = internalise desc -- User-defined operators are just the same as a function call. internaliseExp desc ( E.BinOp (op, oploc) (Info t) (xarg, Info (xt, xext)) (yarg, Info (yt, yext)) _ (Info retext) loc ) = internaliseExp desc $ E.Apply ( E.Apply (E.Var op (Info t) oploc) xarg (Info (E.diet xt, xext)) (Info $ foldFunType [E.fromStruct yt] t, Info []) loc ) yarg (Info (E.diet yt, yext)) (Info t, Info retext) loc internaliseExp desc (E.Project k e (Info rt) _) = do n <- internalisedTypeSize $ rt `setAliases` () i' <- fmap sum $ mapM internalisedTypeSize $ case E.typeOf e `setAliases` () of E.Scalar (Record fs) -> map snd $ takeWhile ((/= k) . fst) $ sortFields fs t -> [t] take n . drop i' <$> internaliseExp desc e internaliseExp _ e@E.Lambda {} = error $ "internaliseExp: Unexpected lambda at " ++ locStr (srclocOf e) internaliseExp _ e@E.OpSection {} = error $ "internaliseExp: Unexpected operator section at " ++ locStr (srclocOf e) internaliseExp _ e@E.OpSectionLeft {} = error $ "internaliseExp: Unexpected left operator section at " ++ locStr (srclocOf e) internaliseExp _ e@E.OpSectionRight {} = error $ "internaliseExp: Unexpected right operator section at " ++ locStr (srclocOf e) internaliseExp _ e@E.ProjectSection {} = error $ "internaliseExp: Unexpected projection section at " ++ locStr (srclocOf e) internaliseExp _ e@E.IndexSection {} = error $ "internaliseExp: Unexpected index section at " ++ locStr (srclocOf e) internaliseArg :: String -> (E.Exp, Maybe VName) -> InternaliseM [SubExp] internaliseArg desc (arg, argdim) = do arg' <- internaliseExp desc arg case (arg', argdim) of ([se], Just d) -> letBindNames [d] $ BasicOp $ SubExp se _ -> return () return arg' generateCond :: E.Pattern -> [I.SubExp] -> InternaliseM (I.SubExp, [I.SubExp]) generateCond orig_p orig_ses = do (cmps, pertinent, _) <- compares orig_p orig_ses cmp <- letSubExp "matches" =<< eAll cmps return (cmp, pertinent) where -- Literals are always primitive values. compares (E.PatternLit e _ _) (se : ses) = do e' <- internaliseExp1 "constant" e t' <- elemType <$> subExpType se cmp <- letSubExp "match_lit" $ I.BasicOp $ I.CmpOp (I.CmpEq t') e' se return ([cmp], [se], ses) compares (E.PatternConstr c (Info (E.Scalar (E.Sum fs))) pats _) (se : ses) = do (payload_ts, m) <- internaliseSumType $ M.map (map toStruct) fs case M.lookup c m of Just (i, payload_is) -> do let i' = intConst Int8 $ toInteger i let (payload_ses, ses') = splitAt (length payload_ts) ses cmp <- letSubExp "match_constr" $ I.BasicOp $ I.CmpOp (I.CmpEq int8) i' se (cmps, pertinent, _) <- comparesMany pats $ map (payload_ses !!) payload_is return (cmp : cmps, pertinent, ses') Nothing -> error "generateCond: missing constructor" compares (E.PatternConstr _ (Info t) _ _) _ = error $ "generateCond: PatternConstr has nonsensical type: " ++ pretty t compares (E.Id _ t loc) ses = compares (E.Wildcard t loc) ses compares (E.Wildcard (Info t) _) ses = do n <- internalisedTypeSize $ E.toStruct t let (id_ses, rest_ses) = splitAt n ses return ([], id_ses, rest_ses) compares (E.PatternParens pat _) ses = compares pat ses compares (E.TuplePattern pats _) ses = comparesMany pats ses compares (E.RecordPattern fs _) ses = comparesMany (map snd $ E.sortFields $ M.fromList fs) ses compares (E.PatternAscription pat _ _) ses = compares pat ses compares pat [] = error $ "generateCond: No values left for pattern " ++ pretty pat comparesMany [] ses = return ([], [], ses) comparesMany (pat : pats) ses = do (cmps1, pertinent1, ses') <- compares pat ses (cmps2, pertinent2, ses'') <- comparesMany pats ses' return ( cmps1 <> cmps2, pertinent1 <> pertinent2, ses'' ) generateCaseIf :: [I.SubExp] -> Case -> I.Body -> InternaliseM I.Exp generateCaseIf ses (CasePat p eCase _) bFail = do (cond, pertinent) <- generateCond p ses eCase' <- internalisePat' p pertinent eCase internaliseBody eIf (eSubExp cond) (return eCase') (return bFail) internalisePat :: String -> E.Pattern -> E.Exp -> E.Exp -> (E.Exp -> InternaliseM a) -> InternaliseM a internalisePat desc p e body m = do ses <- internaliseExp desc' e internalisePat' p ses body m where desc' = case S.toList $ E.patternIdents p of [v] -> baseString $ E.identName v _ -> desc internalisePat' :: E.Pattern -> [I.SubExp] -> E.Exp -> (E.Exp -> InternaliseM a) -> InternaliseM a internalisePat' p ses body m = do ses_ts <- mapM subExpType ses stmPattern p ses_ts $ \pat_names -> do forM_ (zip pat_names ses) $ \(v, se) -> letBindNames [v] $ I.BasicOp $ I.SubExp se m body internaliseSlice :: SrcLoc -> [SubExp] -> [E.DimIndex] -> InternaliseM ([I.DimIndex SubExp], Certificates) internaliseSlice loc dims idxs = do (idxs', oks, parts) <- unzip3 <$> zipWithM internaliseDimIndex dims idxs ok <- letSubExp "index_ok" =<< eAll oks let msg = errorMsg $ ["Index ["] ++ intercalate [", "] parts ++ ["] out of bounds for array of shape ["] ++ intersperse "][" (map ErrorInt32 $ take (length idxs) dims) ++ ["]."] c <- assert "index_certs" ok msg loc return (idxs', c) internaliseDimIndex :: SubExp -> E.DimIndex -> InternaliseM (I.DimIndex SubExp, SubExp, [ErrorMsgPart SubExp]) internaliseDimIndex w (E.DimFix i) = do (i', _) <- internaliseDimExp "i" i let lowerBound = I.BasicOp $ I.CmpOp (I.CmpSle I.Int32) (I.constant (0 :: I.Int32)) i' upperBound = I.BasicOp $ I.CmpOp (I.CmpSlt I.Int32) i' w ok <- letSubExp "bounds_check" =<< eBinOp I.LogAnd (pure lowerBound) (pure upperBound) return (I.DimFix i', ok, [ErrorInt32 i']) -- Special-case an important common case that otherwise leads to horrible code. internaliseDimIndex w ( E.DimSlice Nothing Nothing (Just (E.Negate (E.IntLit 1 _ _) _)) ) = do w_minus_1 <- letSubExp "w_minus_1" $ BasicOp $ I.BinOp (Sub Int32 I.OverflowWrap) w one return ( I.DimSlice w_minus_1 w $ intConst Int32 (-1), constant True, mempty ) where one = constant (1 :: Int32) internaliseDimIndex w (E.DimSlice i j s) = do s' <- maybe (return one) (fmap fst . internaliseDimExp "s") s s_sign <- letSubExp "s_sign" $ BasicOp $ I.UnOp (I.SSignum Int32) s' backwards <- letSubExp "backwards" $ I.BasicOp $ I.CmpOp (I.CmpEq int32) s_sign negone w_minus_1 <- letSubExp "w_minus_1" $ BasicOp $ I.BinOp (Sub Int32 I.OverflowWrap) w one let i_def = letSubExp "i_def" $ I.If backwards (resultBody [w_minus_1]) (resultBody [zero]) $ ifCommon [I.Prim int32] j_def = letSubExp "j_def" $ I.If backwards (resultBody [negone]) (resultBody [w]) $ ifCommon [I.Prim int32] i' <- maybe i_def (fmap fst . internaliseDimExp "i") i j' <- maybe j_def (fmap fst . internaliseDimExp "j") j j_m_i <- letSubExp "j_m_i" $ BasicOp $ I.BinOp (Sub Int32 I.OverflowWrap) j' i' -- Something like a division-rounding-up, but accomodating negative -- operands. let divRounding x y = eBinOp (SQuot Int32 Unsafe) ( eBinOp (Add Int32 I.OverflowWrap) x (eBinOp (Sub Int32 I.OverflowWrap) y (eSignum $ toExp s')) ) y n <- letSubExp "n" =<< divRounding (toExp j_m_i) (toExp s') -- Bounds checks depend on whether we are slicing forwards or -- backwards. If forwards, we must check '0 <= i && i <= j'. If -- backwards, '-1 <= j && j <= i'. In both cases, we check '0 <= -- i+n*s && i+(n-1)*s < w'. We only check if the slice is nonempty. empty_slice <- letSubExp "empty_slice" $ I.BasicOp $ I.CmpOp (CmpEq int32) n zero m <- letSubExp "m" $ I.BasicOp $ I.BinOp (Sub Int32 I.OverflowWrap) n one m_t_s <- letSubExp "m_t_s" $ I.BasicOp $ I.BinOp (Mul Int32 I.OverflowWrap) m s' i_p_m_t_s <- letSubExp "i_p_m_t_s" $ I.BasicOp $ I.BinOp (Add Int32 I.OverflowWrap) i' m_t_s zero_leq_i_p_m_t_s <- letSubExp "zero_leq_i_p_m_t_s" $ I.BasicOp $ I.CmpOp (I.CmpSle Int32) zero i_p_m_t_s i_p_m_t_s_leq_w <- letSubExp "i_p_m_t_s_leq_w" $ I.BasicOp $ I.CmpOp (I.CmpSle Int32) i_p_m_t_s w i_p_m_t_s_lth_w <- letSubExp "i_p_m_t_s_leq_w" $ I.BasicOp $ I.CmpOp (I.CmpSlt Int32) i_p_m_t_s w zero_lte_i <- letSubExp "zero_lte_i" $ I.BasicOp $ I.CmpOp (I.CmpSle Int32) zero i' i_lte_j <- letSubExp "i_lte_j" $ I.BasicOp $ I.CmpOp (I.CmpSle Int32) i' j' forwards_ok <- letSubExp "forwards_ok" =<< eAll [zero_lte_i, zero_lte_i, i_lte_j, zero_leq_i_p_m_t_s, i_p_m_t_s_lth_w] negone_lte_j <- letSubExp "negone_lte_j" $ I.BasicOp $ I.CmpOp (I.CmpSle Int32) negone j' j_lte_i <- letSubExp "j_lte_i" $ I.BasicOp $ I.CmpOp (I.CmpSle Int32) j' i' backwards_ok <- letSubExp "backwards_ok" =<< eAll [negone_lte_j, negone_lte_j, j_lte_i, zero_leq_i_p_m_t_s, i_p_m_t_s_leq_w] slice_ok <- letSubExp "slice_ok" $ I.If backwards (resultBody [backwards_ok]) (resultBody [forwards_ok]) $ ifCommon [I.Prim I.Bool] ok_or_empty <- letSubExp "ok_or_empty" $ I.BasicOp $ I.BinOp I.LogOr empty_slice slice_ok let parts = case (i, j, s) of (_, _, Just {}) -> [ maybe "" (const $ ErrorInt32 i') i, ":", maybe "" (const $ ErrorInt32 j') j, ":", ErrorInt32 s' ] (_, Just {}, _) -> [ maybe "" (const $ ErrorInt32 i') i, ":", ErrorInt32 j' ] ++ maybe mempty (const [":", ErrorInt32 s']) s (_, Nothing, Nothing) -> [ErrorInt32 i', ":"] return (I.DimSlice i' n s', ok_or_empty, parts) where zero = constant (0 :: Int32) negone = constant (-1 :: Int32) one = constant (1 :: Int32) internaliseScanOrReduce :: String -> String -> (SubExp -> I.Lambda -> [SubExp] -> [VName] -> InternaliseM (SOAC SOACS)) -> (E.Exp, E.Exp, E.Exp, SrcLoc) -> InternaliseM [SubExp] internaliseScanOrReduce desc what f (lam, ne, arr, loc) = do arrs <- internaliseExpToVars (what ++ "_arr") arr nes <- internaliseExp (what ++ "_ne") ne nes' <- forM (zip nes arrs) $ \(ne', arr') -> do rowtype <- I.stripArray 1 <$> lookupType arr' ensureShape "Row shape of input array does not match shape of neutral element" loc rowtype (what ++ "_ne_right_shape") ne' nests <- mapM I.subExpType nes' arrts <- mapM lookupType arrs lam' <- internaliseFoldLambda internaliseLambda lam nests arrts w <- arraysSize 0 <$> mapM lookupType arrs letTupExp' desc . I.Op =<< f w lam' nes' arrs internaliseHist :: String -> E.Exp -> E.Exp -> E.Exp -> E.Exp -> E.Exp -> E.Exp -> SrcLoc -> InternaliseM [SubExp] internaliseHist desc rf hist op ne buckets img loc = do rf' <- internaliseExp1 "hist_rf" rf ne' <- internaliseExp "hist_ne" ne hist' <- internaliseExpToVars "hist_hist" hist buckets' <- letExp "hist_buckets" . BasicOp . SubExp =<< internaliseExp1 "hist_buckets" buckets img' <- internaliseExpToVars "hist_img" img -- reshape neutral element to have same size as the destination array ne_shp <- forM (zip ne' hist') $ \(n, h) -> do rowtype <- I.stripArray 1 <$> lookupType h ensureShape "Row shape of destination array does not match shape of neutral element" loc rowtype "hist_ne_right_shape" n ne_ts <- mapM I.subExpType ne_shp his_ts <- mapM lookupType hist' op' <- internaliseFoldLambda internaliseLambda op ne_ts his_ts -- reshape return type of bucket function to have same size as neutral element -- (modulo the index) bucket_param <- newParam "bucket_p" $ I.Prim int32 img_params <- mapM (newParam "img_p" . rowType) =<< mapM lookupType img' let params = bucket_param : img_params rettype = I.Prim int32 : ne_ts body = mkBody mempty $ map (I.Var . paramName) params body' <- localScope (scopeOfLParams params) $ ensureResultShape "Row shape of value array does not match row shape of hist target" (srclocOf img) rettype body -- get sizes of histogram and image arrays w_hist <- arraysSize 0 <$> mapM lookupType hist' w_img <- arraysSize 0 <$> mapM lookupType img' -- Generate an assertion and reshapes to ensure that buckets' and -- img' are the same size. b_shape <- I.arrayShape <$> lookupType buckets' let b_w = shapeSize 0 b_shape cmp <- letSubExp "bucket_cmp" $ I.BasicOp $ I.CmpOp (I.CmpEq I.int32) b_w w_img c <- assert "bucket_cert" cmp "length of index and value array does not match" loc buckets'' <- certifying c $ letExp (baseString buckets') $ I.BasicOp $ I.Reshape (reshapeOuter [DimCoercion w_img] 1 b_shape) buckets' letTupExp' desc $ I.Op $ I.Hist w_img [HistOp w_hist rf' hist' ne_shp op'] (I.Lambda params body' rettype) $ buckets'' : img' internaliseStreamMap :: String -> StreamOrd -> E.Exp -> E.Exp -> InternaliseM [SubExp] internaliseStreamMap desc o lam arr = do arrs <- internaliseExpToVars "stream_input" arr lam' <- internaliseStreamMapLambda internaliseLambda lam $ map I.Var arrs w <- arraysSize 0 <$> mapM lookupType arrs let form = I.Parallel o Commutative (I.Lambda [] (mkBody mempty []) []) [] letTupExp' desc $ I.Op $ I.Stream w form lam' arrs internaliseStreamRed :: String -> StreamOrd -> Commutativity -> E.Exp -> E.Exp -> E.Exp -> InternaliseM [SubExp] internaliseStreamRed desc o comm lam0 lam arr = do arrs <- internaliseExpToVars "stream_input" arr rowts <- mapM (fmap I.rowType . lookupType) arrs (lam_params, lam_body) <- internaliseStreamLambda internaliseLambda lam rowts let (chunk_param, _, lam_val_params) = partitionChunkedFoldParameters 0 lam_params -- Synthesize neutral elements by applying the fold function -- to an empty chunk. letBindNames [I.paramName chunk_param] $ I.BasicOp $ I.SubExp $ constant (0 :: Int32) forM_ lam_val_params $ \p -> letBindNames [I.paramName p] $ I.BasicOp $ I.Scratch (I.elemType $ I.paramType p) $ I.arrayDims $ I.paramType p nes <- bodyBind =<< renameBody lam_body nes_ts <- mapM I.subExpType nes outsz <- arraysSize 0 <$> mapM lookupType arrs let acc_arr_tps = [I.arrayOf t (I.Shape [outsz]) NoUniqueness | t <- nes_ts] lam0' <- internaliseFoldLambda internaliseLambda lam0 nes_ts acc_arr_tps let lam0_acc_params = take (length nes) $ I.lambdaParams lam0' lam_acc_params <- forM lam0_acc_params $ \p -> do name <- newVName $ baseString $ I.paramName p return p {I.paramName = name} -- Make sure the chunk size parameter comes first. let lam_params' = chunk_param : lam_acc_params ++ lam_val_params body_with_lam0 <- ensureResultShape "shape of result does not match shape of initial value" (srclocOf lam0) nes_ts <=< insertStmsM $ localScope (scopeOfLParams lam_params') $ do lam_res <- bodyBind lam_body lam_res' <- ensureArgShapes "shape of chunk function result does not match shape of initial value" (srclocOf lam) [] (map I.typeOf $ I.lambdaParams lam0') lam_res new_lam_res <- eLambda lam0' $ map eSubExp $ map (I.Var . paramName) lam_acc_params ++ lam_res' return $ resultBody new_lam_res let form = I.Parallel o comm lam0' nes lam' = I.Lambda { lambdaParams = lam_params', lambdaBody = body_with_lam0, lambdaReturnType = nes_ts } w <- arraysSize 0 <$> mapM lookupType arrs letTupExp' desc $ I.Op $ I.Stream w form lam' arrs internaliseExp1 :: String -> E.Exp -> InternaliseM I.SubExp internaliseExp1 desc e = do vs <- internaliseExp desc e case vs of [se] -> return se _ -> error "Internalise.internaliseExp1: was passed not just a single subexpression" -- | Promote to dimension type as appropriate for the original type. -- Also return original type. internaliseDimExp :: String -> E.Exp -> InternaliseM (I.SubExp, IntType) internaliseDimExp s e = do e' <- internaliseExp1 s e case E.typeOf e of E.Scalar (E.Prim (Signed it)) -> (,it) <$> asIntS Int32 e' _ -> error "internaliseDimExp: bad type" internaliseExpToVars :: String -> E.Exp -> InternaliseM [I.VName] internaliseExpToVars desc e = mapM asIdent =<< internaliseExp desc e where asIdent (I.Var v) = return v asIdent se = letExp desc $ I.BasicOp $ I.SubExp se internaliseOperation :: String -> E.Exp -> (I.VName -> InternaliseM I.BasicOp) -> InternaliseM [I.SubExp] internaliseOperation s e op = do vs <- internaliseExpToVars s e letSubExps s =<< mapM (fmap I.BasicOp . op) vs certifyingNonzero :: SrcLoc -> IntType -> SubExp -> InternaliseM a -> InternaliseM a certifyingNonzero loc t x m = do zero <- letSubExp "zero" $ I.BasicOp $ CmpOp (CmpEq (IntType t)) x (intConst t 0) nonzero <- letSubExp "nonzero" $ I.BasicOp $ UnOp Not zero c <- assert "nonzero_cert" nonzero "division by zero" loc certifying c m certifyingNonnegative :: SrcLoc -> IntType -> SubExp -> InternaliseM a -> InternaliseM a certifyingNonnegative loc t x m = do nonnegative <- letSubExp "nonnegative" $ I.BasicOp $ CmpOp (CmpSle t) (intConst t 0) x c <- assert "nonzero_cert" nonnegative "negative exponent" loc certifying c m internaliseBinOp :: SrcLoc -> String -> E.BinOp -> I.SubExp -> I.SubExp -> E.PrimType -> E.PrimType -> InternaliseM [I.SubExp] internaliseBinOp _ desc E.Plus x y (E.Signed t) _ = simpleBinOp desc (I.Add t I.OverflowWrap) x y internaliseBinOp _ desc E.Plus x y (E.Unsigned t) _ = simpleBinOp desc (I.Add t I.OverflowWrap) x y internaliseBinOp _ desc E.Plus x y (E.FloatType t) _ = simpleBinOp desc (I.FAdd t) x y internaliseBinOp _ desc E.Minus x y (E.Signed t) _ = simpleBinOp desc (I.Sub t I.OverflowWrap) x y internaliseBinOp _ desc E.Minus x y (E.Unsigned t) _ = simpleBinOp desc (I.Sub t I.OverflowWrap) x y internaliseBinOp _ desc E.Minus x y (E.FloatType t) _ = simpleBinOp desc (I.FSub t) x y internaliseBinOp _ desc E.Times x y (E.Signed t) _ = simpleBinOp desc (I.Mul t I.OverflowWrap) x y internaliseBinOp _ desc E.Times x y (E.Unsigned t) _ = simpleBinOp desc (I.Mul t I.OverflowWrap) x y internaliseBinOp _ desc E.Times x y (E.FloatType t) _ = simpleBinOp desc (I.FMul t) x y internaliseBinOp loc desc E.Divide x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SDiv t I.Unsafe) x y internaliseBinOp loc desc E.Divide x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UDiv t I.Unsafe) x y internaliseBinOp _ desc E.Divide x y (E.FloatType t) _ = simpleBinOp desc (I.FDiv t) x y internaliseBinOp _ desc E.Pow x y (E.FloatType t) _ = simpleBinOp desc (I.FPow t) x y internaliseBinOp loc desc E.Pow x y (E.Signed t) _ = certifyingNonnegative loc t y $ simpleBinOp desc (I.Pow t) x y internaliseBinOp _ desc E.Pow x y (E.Unsigned t) _ = simpleBinOp desc (I.Pow t) x y internaliseBinOp loc desc E.Mod x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SMod t I.Unsafe) x y internaliseBinOp loc desc E.Mod x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UMod t I.Unsafe) x y internaliseBinOp _ desc E.Mod x y (E.FloatType t) _ = simpleBinOp desc (I.FMod t) x y internaliseBinOp loc desc E.Quot x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SQuot t I.Unsafe) x y internaliseBinOp loc desc E.Quot x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UDiv t I.Unsafe) x y internaliseBinOp loc desc E.Rem x y (E.Signed t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.SRem t I.Unsafe) x y internaliseBinOp loc desc E.Rem x y (E.Unsigned t) _ = certifyingNonzero loc t y $ simpleBinOp desc (I.UMod t I.Unsafe) x y internaliseBinOp _ desc E.ShiftR x y (E.Signed t) _ = simpleBinOp desc (I.AShr t) x y internaliseBinOp _ desc E.ShiftR x y (E.Unsigned t) _ = simpleBinOp desc (I.LShr t) x y internaliseBinOp _ desc E.ShiftL x y (E.Signed t) _ = simpleBinOp desc (I.Shl t) x y internaliseBinOp _ desc E.ShiftL x y (E.Unsigned t) _ = simpleBinOp desc (I.Shl t) x y internaliseBinOp _ desc E.Band x y (E.Signed t) _ = simpleBinOp desc (I.And t) x y internaliseBinOp _ desc E.Band x y (E.Unsigned t) _ = simpleBinOp desc (I.And t) x y internaliseBinOp _ desc E.Xor x y (E.Signed t) _ = simpleBinOp desc (I.Xor t) x y internaliseBinOp _ desc E.Xor x y (E.Unsigned t) _ = simpleBinOp desc (I.Xor t) x y internaliseBinOp _ desc E.Bor x y (E.Signed t) _ = simpleBinOp desc (I.Or t) x y internaliseBinOp _ desc E.Bor x y (E.Unsigned t) _ = simpleBinOp desc (I.Or t) x y internaliseBinOp _ desc E.Equal x y t _ = simpleCmpOp desc (I.CmpEq $ internalisePrimType t) x y internaliseBinOp _ desc E.NotEqual x y t _ = do eq <- letSubExp (desc ++ "true") $ I.BasicOp $ I.CmpOp (I.CmpEq $ internalisePrimType t) x y fmap pure $ letSubExp desc $ I.BasicOp $ I.UnOp I.Not eq internaliseBinOp _ desc E.Less x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSlt t) x y internaliseBinOp _ desc E.Less x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUlt t) x y internaliseBinOp _ desc E.Leq x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSle t) x y internaliseBinOp _ desc E.Leq x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUle t) x y internaliseBinOp _ desc E.Greater x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSlt t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Greater x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUlt t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y (E.Signed t) _ = simpleCmpOp desc (I.CmpSle t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y (E.Unsigned t) _ = simpleCmpOp desc (I.CmpUle t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Less x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLt t) x y internaliseBinOp _ desc E.Leq x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLe t) x y internaliseBinOp _ desc E.Greater x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLt t) y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y (E.FloatType t) _ = simpleCmpOp desc (I.FCmpLe t) y x -- Note the swapped x and y -- Relational operators for booleans. internaliseBinOp _ desc E.Less x y E.Bool _ = simpleCmpOp desc I.CmpLlt x y internaliseBinOp _ desc E.Leq x y E.Bool _ = simpleCmpOp desc I.CmpLle x y internaliseBinOp _ desc E.Greater x y E.Bool _ = simpleCmpOp desc I.CmpLlt y x -- Note the swapped x and y internaliseBinOp _ desc E.Geq x y E.Bool _ = simpleCmpOp desc I.CmpLle y x -- Note the swapped x and y internaliseBinOp _ _ op _ _ t1 t2 = error $ "Invalid binary operator " ++ pretty op ++ " with operand types " ++ pretty t1 ++ ", " ++ pretty t2 simpleBinOp :: String -> I.BinOp -> I.SubExp -> I.SubExp -> InternaliseM [I.SubExp] simpleBinOp desc bop x y = letTupExp' desc $ I.BasicOp $ I.BinOp bop x y simpleCmpOp :: String -> I.CmpOp -> I.SubExp -> I.SubExp -> InternaliseM [I.SubExp] simpleCmpOp desc op x y = letTupExp' desc $ I.BasicOp $ I.CmpOp op x y findFuncall :: E.Exp -> InternaliseM ( E.QualName VName, [(E.Exp, Maybe VName)], E.StructType, [VName] ) findFuncall (E.Var fname (Info t) _) = return (fname, [], E.toStruct t, []) findFuncall (E.Apply f arg (Info (_, argext)) (Info ret, Info retext) _) = do (fname, args, _, _) <- findFuncall f return (fname, args ++ [(arg, argext)], E.toStruct ret, retext) findFuncall e = error $ "Invalid function expression in application: " ++ pretty e internaliseLambda :: InternaliseLambda internaliseLambda (E.Parens e _) rowtypes = internaliseLambda e rowtypes internaliseLambda (E.Lambda params body _ (Info (_, rettype)) _) rowtypes = bindingLambdaParams params rowtypes $ \params' -> do body' <- internaliseBody body rettype' <- internaliseLambdaReturnType rettype return (params', body', rettype') internaliseLambda e _ = error $ "internaliseLambda: unexpected expression:\n" ++ pretty e -- | Some operators and functions are overloaded or otherwise special -- - we detect and treat them here. isOverloadedFunction :: E.QualName VName -> [E.Exp] -> SrcLoc -> Maybe (String -> InternaliseM [SubExp]) isOverloadedFunction qname args loc = do guard $ baseTag (qualLeaf qname) <= maxIntrinsicTag let handlers = [ handleSign, handleIntrinsicOps, handleOps, handleSOACs, handleRest ] msum [h args $ baseString $ qualLeaf qname | h <- handlers] where handleSign [x] "sign_i8" = Just $ toSigned I.Int8 x handleSign [x] "sign_i16" = Just $ toSigned I.Int16 x handleSign [x] "sign_i32" = Just $ toSigned I.Int32 x handleSign [x] "sign_i64" = Just $ toSigned I.Int64 x handleSign [x] "unsign_i8" = Just $ toUnsigned I.Int8 x handleSign [x] "unsign_i16" = Just $ toUnsigned I.Int16 x handleSign [x] "unsign_i32" = Just $ toUnsigned I.Int32 x handleSign [x] "unsign_i64" = Just $ toUnsigned I.Int64 x handleSign _ _ = Nothing handleIntrinsicOps [x] s | Just unop <- find ((== s) . pretty) allUnOps = Just $ \desc -> do x' <- internaliseExp1 "x" x fmap pure $ letSubExp desc $ I.BasicOp $ I.UnOp unop x' handleIntrinsicOps [TupLit [x, y] _] s | Just bop <- find ((== s) . pretty) allBinOps = Just $ \desc -> do x' <- internaliseExp1 "x" x y' <- internaliseExp1 "y" y fmap pure $ letSubExp desc $ I.BasicOp $ I.BinOp bop x' y' | Just cmp <- find ((== s) . pretty) allCmpOps = Just $ \desc -> do x' <- internaliseExp1 "x" x y' <- internaliseExp1 "y" y fmap pure $ letSubExp desc $ I.BasicOp $ I.CmpOp cmp x' y' handleIntrinsicOps [x] s | Just conv <- find ((== s) . pretty) allConvOps = Just $ \desc -> do x' <- internaliseExp1 "x" x fmap pure $ letSubExp desc $ I.BasicOp $ I.ConvOp conv x' handleIntrinsicOps _ _ = Nothing -- Short-circuiting operators are magical. handleOps [x, y] "&&" = Just $ \desc -> internaliseExp desc $ E.If x y (E.Literal (E.BoolValue False) mempty) (Info $ E.Scalar $ E.Prim E.Bool, Info []) mempty handleOps [x, y] "||" = Just $ \desc -> internaliseExp desc $ E.If x (E.Literal (E.BoolValue True) mempty) y (Info $ E.Scalar $ E.Prim E.Bool, Info []) mempty -- Handle equality and inequality specially, to treat the case of -- arrays. handleOps [xe, ye] op | Just cmp_f <- isEqlOp op = Just $ \desc -> do xe' <- internaliseExp "x" xe ye' <- internaliseExp "y" ye rs <- zipWithM (doComparison desc) xe' ye' cmp_f desc =<< letSubExp "eq" =<< eAll rs where isEqlOp "!=" = Just $ \desc eq -> letTupExp' desc $ I.BasicOp $ I.UnOp I.Not eq isEqlOp "==" = Just $ \_ eq -> return [eq] isEqlOp _ = Nothing doComparison desc x y = do x_t <- I.subExpType x y_t <- I.subExpType y case x_t of I.Prim t -> letSubExp desc $ I.BasicOp $ I.CmpOp (I.CmpEq t) x y _ -> do let x_dims = I.arrayDims x_t y_dims = I.arrayDims y_t dims_match <- forM (zip x_dims y_dims) $ \(x_dim, y_dim) -> letSubExp "dim_eq" $ I.BasicOp $ I.CmpOp (I.CmpEq int32) x_dim y_dim shapes_match <- letSubExp "shapes_match" =<< eAll dims_match compare_elems_body <- runBodyBinder $ do -- Flatten both x and y. x_num_elems <- letSubExp "x_num_elems" =<< foldBinOp (I.Mul Int32 I.OverflowUndef) (constant (1 :: Int32)) x_dims x' <- letExp "x" $ I.BasicOp $ I.SubExp x y' <- letExp "x" $ I.BasicOp $ I.SubExp y x_flat <- letExp "x_flat" $ I.BasicOp $ I.Reshape [I.DimNew x_num_elems] x' y_flat <- letExp "y_flat" $ I.BasicOp $ I.Reshape [I.DimNew x_num_elems] y' -- Compare the elements. cmp_lam <- cmpOpLambda $ I.CmpEq (elemType x_t) cmps <- letExp "cmps" $ I.Op $ I.Screma x_num_elems (I.mapSOAC cmp_lam) [x_flat, y_flat] -- Check that all were equal. and_lam <- binOpLambda I.LogAnd I.Bool reduce <- I.reduceSOAC [Reduce Commutative and_lam [constant True]] all_equal <- letSubExp "all_equal" $ I.Op $ I.Screma x_num_elems reduce [cmps] return $ resultBody [all_equal] letSubExp "arrays_equal" $ I.If shapes_match compare_elems_body (resultBody [constant False]) $ ifCommon [I.Prim I.Bool] handleOps [x, y] name | Just bop <- find ((name ==) . pretty) [minBound .. maxBound :: E.BinOp] = Just $ \desc -> do x' <- internaliseExp1 "x" x y' <- internaliseExp1 "y" y case (E.typeOf x, E.typeOf y) of (E.Scalar (E.Prim t1), E.Scalar (E.Prim t2)) -> internaliseBinOp loc desc bop x' y' t1 t2 _ -> error "Futhark.Internalise.internaliseExp: non-primitive type in BinOp." handleOps _ _ = Nothing handleSOACs [TupLit [lam, arr] _] "map" = Just $ \desc -> do arr' <- internaliseExpToVars "map_arr" arr lam' <- internaliseMapLambda internaliseLambda lam $ map I.Var arr' w <- arraysSize 0 <$> mapM lookupType arr' letTupExp' desc $ I.Op $ I.Screma w (I.mapSOAC lam') arr' handleSOACs [TupLit [k, lam, arr] _] "partition" = do k' <- fromIntegral <$> fromInt32 k Just $ \_desc -> do arrs <- internaliseExpToVars "partition_input" arr lam' <- internalisePartitionLambda internaliseLambda k' lam $ map I.Var arrs uncurry (++) <$> partitionWithSOACS k' lam' arrs where fromInt32 (Literal (SignedValue (Int32Value k')) _) = Just k' fromInt32 (IntLit k' (Info (E.Scalar (E.Prim (Signed Int32)))) _) = Just $ fromInteger k' fromInt32 _ = Nothing handleSOACs [TupLit [lam, ne, arr] _] "reduce" = Just $ \desc -> internaliseScanOrReduce desc "reduce" reduce (lam, ne, arr, loc) where reduce w red_lam nes arrs = I.Screma w <$> I.reduceSOAC [Reduce Noncommutative red_lam nes] <*> pure arrs handleSOACs [TupLit [lam, ne, arr] _] "reduce_comm" = Just $ \desc -> internaliseScanOrReduce desc "reduce" reduce (lam, ne, arr, loc) where reduce w red_lam nes arrs = I.Screma w <$> I.reduceSOAC [Reduce Commutative red_lam nes] <*> pure arrs handleSOACs [TupLit [lam, ne, arr] _] "scan" = Just $ \desc -> internaliseScanOrReduce desc "scan" reduce (lam, ne, arr, loc) where reduce w scan_lam nes arrs = I.Screma w <$> I.scanSOAC [Scan scan_lam nes] <*> pure arrs handleSOACs [TupLit [op, f, arr] _] "reduce_stream" = Just $ \desc -> internaliseStreamRed desc InOrder Noncommutative op f arr handleSOACs [TupLit [op, f, arr] _] "reduce_stream_per" = Just $ \desc -> internaliseStreamRed desc Disorder Commutative op f arr handleSOACs [TupLit [f, arr] _] "map_stream" = Just $ \desc -> internaliseStreamMap desc InOrder f arr handleSOACs [TupLit [f, arr] _] "map_stream_per" = Just $ \desc -> internaliseStreamMap desc Disorder f arr handleSOACs [TupLit [rf, dest, op, ne, buckets, img] _] "hist" = Just $ \desc -> internaliseHist desc rf dest op ne buckets img loc handleSOACs _ _ = Nothing handleRest [x] "!" = Just $ complementF x handleRest [x] "opaque" = Just $ \desc -> mapM (letSubExp desc . BasicOp . Opaque) =<< internaliseExp "opaque_arg" x handleRest [E.TupLit [a, si, v] _] "scatter" = Just $ scatterF a si v handleRest [E.TupLit [n, m, arr] _] "unflatten" = Just $ \desc -> do arrs <- internaliseExpToVars "unflatten_arr" arr n' <- internaliseExp1 "n" n m' <- internaliseExp1 "m" m -- The unflattened dimension needs to have the same number of elements -- as the original dimension. old_dim <- I.arraysSize 0 <$> mapM lookupType arrs dim_ok <- letSubExp "dim_ok" =<< eCmpOp (I.CmpEq I.int32) (eBinOp (I.Mul Int32 I.OverflowUndef) (eSubExp n') (eSubExp m')) (eSubExp old_dim) dim_ok_cert <- assert "dim_ok_cert" dim_ok "new shape has different number of elements than old shape" loc certifying dim_ok_cert $ forM arrs $ \arr' -> do arr_t <- lookupType arr' letSubExp desc $ I.BasicOp $ I.Reshape (reshapeOuter [DimNew n', DimNew m'] 1 $ I.arrayShape arr_t) arr' handleRest [arr] "flatten" = Just $ \desc -> do arrs <- internaliseExpToVars "flatten_arr" arr forM arrs $ \arr' -> do arr_t <- lookupType arr' let n = arraySize 0 arr_t m = arraySize 1 arr_t k <- letSubExp "flat_dim" $ I.BasicOp $ I.BinOp (Mul Int32 I.OverflowUndef) n m letSubExp desc $ I.BasicOp $ I.Reshape (reshapeOuter [DimNew k] 2 $ I.arrayShape arr_t) arr' handleRest [TupLit [x, y] _] "concat" = Just $ \desc -> do xs <- internaliseExpToVars "concat_x" x ys <- internaliseExpToVars "concat_y" y outer_size <- arraysSize 0 <$> mapM lookupType xs let sumdims xsize ysize = letSubExp "conc_tmp" $ I.BasicOp $ I.BinOp (I.Add I.Int32 I.OverflowUndef) xsize ysize ressize <- foldM sumdims outer_size =<< mapM (fmap (arraysSize 0) . mapM lookupType) [ys] let conc xarr yarr = I.BasicOp $ I.Concat 0 xarr [yarr] ressize letSubExps desc $ zipWith conc xs ys handleRest [TupLit [offset, e] _] "rotate" = Just $ \desc -> do offset' <- internaliseExp1 "rotation_offset" offset internaliseOperation desc e $ \v -> do r <- I.arrayRank <$> lookupType v let zero = intConst Int32 0 offsets = offset' : replicate (r -1) zero return $ I.Rotate offsets v handleRest [e] "transpose" = Just $ \desc -> internaliseOperation desc e $ \v -> do r <- I.arrayRank <$> lookupType v return $ I.Rearrange ([1, 0] ++ [2 .. r -1]) v handleRest [TupLit [x, y] _] "zip" = Just $ \desc -> (++) <$> internaliseExp (desc ++ "_zip_x") x <*> internaliseExp (desc ++ "_zip_y") y handleRest [x] "unzip" = Just $ flip internaliseExp x handleRest [x] "trace" = Just $ flip internaliseExp x handleRest [x] "break" = Just $ flip internaliseExp x handleRest _ _ = Nothing toSigned int_to e desc = do e' <- internaliseExp1 "trunc_arg" e case E.typeOf e of E.Scalar (E.Prim E.Bool) -> letTupExp' desc $ I.If e' (resultBody [intConst int_to 1]) (resultBody [intConst int_to 0]) $ ifCommon [I.Prim $ I.IntType int_to] E.Scalar (E.Prim (E.Signed int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.SExt int_from int_to) e' E.Scalar (E.Prim (E.Unsigned int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.ZExt int_from int_to) e' E.Scalar (E.Prim (E.FloatType float_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.FPToSI float_from int_to) e' _ -> error "Futhark.Internalise: non-numeric type in ToSigned" toUnsigned int_to e desc = do e' <- internaliseExp1 "trunc_arg" e case E.typeOf e of E.Scalar (E.Prim E.Bool) -> letTupExp' desc $ I.If e' (resultBody [intConst int_to 1]) (resultBody [intConst int_to 0]) $ ifCommon [I.Prim $ I.IntType int_to] E.Scalar (E.Prim (E.Signed int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.ZExt int_from int_to) e' E.Scalar (E.Prim (E.Unsigned int_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.ZExt int_from int_to) e' E.Scalar (E.Prim (E.FloatType float_from)) -> letTupExp' desc $ I.BasicOp $ I.ConvOp (I.FPToUI float_from int_to) e' _ -> error "Futhark.Internalise.internaliseExp: non-numeric type in ToUnsigned" complementF e desc = do e' <- internaliseExp1 "complement_arg" e et <- subExpType e' case et of I.Prim (I.IntType t) -> letTupExp' desc $ I.BasicOp $ I.UnOp (I.Complement t) e' I.Prim I.Bool -> letTupExp' desc $ I.BasicOp $ I.UnOp I.Not e' _ -> error "Futhark.Internalise.internaliseExp: non-int/bool type in Complement" scatterF a si v desc = do si' <- letExp "write_si" . BasicOp . SubExp =<< internaliseExp1 "write_arg_i" si svs <- internaliseExpToVars "write_arg_v" v sas <- internaliseExpToVars "write_arg_a" a si_shape <- I.arrayShape <$> lookupType si' let si_w = shapeSize 0 si_shape sv_ts <- mapM lookupType svs svs' <- forM (zip svs sv_ts) $ \(sv, sv_t) -> do let sv_shape = I.arrayShape sv_t sv_w = arraySize 0 sv_t -- Generate an assertion and reshapes to ensure that sv and si' are the same -- size. cmp <- letSubExp "write_cmp" $ I.BasicOp $ I.CmpOp (I.CmpEq I.int32) si_w sv_w c <- assert "write_cert" cmp "length of index and value array does not match" loc certifying c $ letExp (baseString sv ++ "_write_sv") $ I.BasicOp $ I.Reshape (reshapeOuter [DimCoercion si_w] 1 sv_shape) sv indexType <- rowType <$> lookupType si' indexName <- newVName "write_index" valueNames <- replicateM (length sv_ts) $ newVName "write_value" sa_ts <- mapM lookupType sas let bodyTypes = replicate (length sv_ts) indexType ++ map rowType sa_ts paramTypes = indexType : map rowType sv_ts bodyNames = indexName : valueNames bodyParams = zipWith I.Param bodyNames paramTypes -- This body is pretty boring right now, as every input is exactly the output. -- But it can get funky later on if fused with something else. body <- localScope (scopeOfLParams bodyParams) $ insertStmsM $ do let outs = replicate (length valueNames) indexName ++ valueNames results <- forM outs $ \name -> letSubExp "write_res" $ I.BasicOp $ I.SubExp $ I.Var name ensureResultShape "scatter value has wrong size" loc bodyTypes $ resultBody results let lam = I.Lambda { I.lambdaParams = bodyParams, I.lambdaReturnType = bodyTypes, I.lambdaBody = body } sivs = si' : svs' let sa_ws = map (arraySize 0) sa_ts letTupExp' desc $ I.Op $ I.Scatter si_w lam sivs $ zip3 sa_ws (repeat 1) sas funcall :: String -> QualName VName -> [SubExp] -> SrcLoc -> InternaliseM ([SubExp], [I.ExtType]) funcall desc (QualName _ fname) args loc = do (fname', closure, shapes, value_paramts, fun_params, rettype_fun) <- lookupFunction fname argts <- mapM subExpType args shapeargs <- argShapes shapes fun_params argts let diets = replicate (length closure + length shapeargs) I.ObservePrim ++ map I.diet value_paramts args' <- ensureArgShapes "function arguments of wrong shape" loc (map I.paramName fun_params) (map I.paramType fun_params) (map I.Var closure ++ shapeargs ++ args) argts' <- mapM subExpType args' case rettype_fun $ zip args' argts' of Nothing -> error $ "Cannot apply " ++ pretty fname ++ " to arguments\n " ++ pretty args' ++ "\nof types\n " ++ pretty argts' ++ "\nFunction has parameters\n " ++ pretty fun_params Just ts -> do safety <- askSafety attrs <- asks envAttrs ses <- attributing attrs $ letTupExp' desc $ I.Apply fname' (zip args' diets) ts (safety, loc, mempty) return (ses, map I.fromDecl ts) -- Bind existential names defined by an expression, based on the -- concrete values that expression evaluated to. This most -- importantly should be done after function calls, but also -- everything else that can produce existentials in the source -- language. bindExtSizes :: E.StructType -> [VName] -> [SubExp] -> InternaliseM () bindExtSizes ret retext ses = do ts <- internaliseType ret ses_ts <- mapM subExpType ses let combine t1 t2 = mconcat $ zipWith combine' (arrayExtDims t1) (arrayDims t2) combine' (I.Free (I.Var v)) se | v `elem` retext = M.singleton v se combine' _ _ = mempty forM_ (M.toList $ mconcat $ zipWith combine ts ses_ts) $ \(v, se) -> letBindNames [v] $ BasicOp $ SubExp se askSafety :: InternaliseM Safety askSafety = do check <- asks envDoBoundsChecks return $ if check then I.Safe else I.Unsafe -- Implement partitioning using maps, scans and writes. partitionWithSOACS :: Int -> I.Lambda -> [I.VName] -> InternaliseM ([I.SubExp], [I.SubExp]) partitionWithSOACS k lam arrs = do arr_ts <- mapM lookupType arrs let w = arraysSize 0 arr_ts classes_and_increments <- letTupExp "increments" $ I.Op $ I.Screma w (mapSOAC lam) arrs (classes, increments) <- case classes_and_increments of classes : increments -> return (classes, take k increments) _ -> error "partitionWithSOACS" add_lam_x_params <- replicateM k $ I.Param <$> newVName "x" <*> pure (I.Prim int32) add_lam_y_params <- replicateM k $ I.Param <$> newVName "y" <*> pure (I.Prim int32) add_lam_body <- runBodyBinder $ localScope (scopeOfLParams $ add_lam_x_params ++ add_lam_y_params) $ fmap resultBody $ forM (zip add_lam_x_params add_lam_y_params) $ \(x, y) -> letSubExp "z" $ I.BasicOp $ I.BinOp (I.Add Int32 I.OverflowUndef) (I.Var $ I.paramName x) (I.Var $ I.paramName y) let add_lam = I.Lambda { I.lambdaBody = add_lam_body, I.lambdaParams = add_lam_x_params ++ add_lam_y_params, I.lambdaReturnType = replicate k $ I.Prim int32 } nes = replicate (length increments) $ constant (0 :: Int32) scan <- I.scanSOAC [I.Scan add_lam nes] all_offsets <- letTupExp "offsets" $ I.Op $ I.Screma w scan increments -- We have the offsets for each of the partitions, but we also need -- the total sizes, which are the last elements in the offests. We -- just have to be careful in case the array is empty. last_index <- letSubExp "last_index" $ I.BasicOp $ I.BinOp (I.Sub Int32 OverflowUndef) w $ constant (1 :: Int32) nonempty_body <- runBodyBinder $ fmap resultBody $ forM all_offsets $ \offset_array -> letSubExp "last_offset" $ I.BasicOp $ I.Index offset_array [I.DimFix last_index] let empty_body = resultBody $ replicate k $ constant (0 :: Int32) is_empty <- letSubExp "is_empty" $ I.BasicOp $ I.CmpOp (CmpEq int32) w $ constant (0 :: Int32) sizes <- letTupExp "partition_size" $ I.If is_empty empty_body nonempty_body $ ifCommon $ replicate k $ I.Prim int32 -- The total size of all partitions must necessarily be equal to the -- size of the input array. -- Create scratch arrays for the result. blanks <- forM arr_ts $ \arr_t -> letExp "partition_dest" $ I.BasicOp $ Scratch (elemType arr_t) (w : drop 1 (I.arrayDims arr_t)) -- Now write into the result. write_lam <- do c_param <- I.Param <$> newVName "c" <*> pure (I.Prim int32) offset_params <- replicateM k $ I.Param <$> newVName "offset" <*> pure (I.Prim int32) value_params <- forM arr_ts $ \arr_t -> I.Param <$> newVName "v" <*> pure (I.rowType arr_t) (offset, offset_stms) <- collectStms $ mkOffsetLambdaBody (map I.Var sizes) (I.Var $ I.paramName c_param) 0 offset_params return I.Lambda { I.lambdaParams = c_param : offset_params ++ value_params, I.lambdaReturnType = replicate (length arr_ts) (I.Prim int32) ++ map I.rowType arr_ts, I.lambdaBody = mkBody offset_stms $ replicate (length arr_ts) offset ++ map (I.Var . I.paramName) value_params } results <- letTupExp "partition_res" $ I.Op $ I.Scatter w write_lam (classes : all_offsets ++ arrs) $ zip3 (repeat w) (repeat 1) blanks sizes' <- letSubExp "partition_sizes" $ I.BasicOp $ I.ArrayLit (map I.Var sizes) $ I.Prim int32 return (map I.Var results, [sizes']) where mkOffsetLambdaBody :: [SubExp] -> SubExp -> Int -> [I.LParam] -> InternaliseM SubExp mkOffsetLambdaBody _ _ _ [] = return $ constant (-1 :: Int32) mkOffsetLambdaBody sizes c i (p : ps) = do is_this_one <- letSubExp "is_this_one" $ I.BasicOp $ I.CmpOp (CmpEq int32) c $ intConst Int32 $ toInteger i next_one <- mkOffsetLambdaBody sizes c (i + 1) ps this_one <- letSubExp "this_offset" =<< foldBinOp (Add Int32 OverflowUndef) (constant (-1 :: Int32)) (I.Var (I.paramName p) : take i sizes) letSubExp "total_res" $ I.If is_this_one (resultBody [this_one]) (resultBody [next_one]) $ ifCommon [I.Prim int32] typeExpForError :: E.TypeExp VName -> InternaliseM [ErrorMsgPart SubExp] typeExpForError (E.TEVar qn _) = return [ErrorString $ pretty qn] typeExpForError (E.TEUnique te _) = ("*" :) <$> typeExpForError te typeExpForError (E.TEArray te d _) = do d' <- dimExpForError d te' <- typeExpForError te return $ ["[", d', "]"] ++ te' typeExpForError (E.TETuple tes _) = do tes' <- mapM typeExpForError tes return $ ["("] ++ intercalate [", "] tes' ++ [")"] typeExpForError (E.TERecord fields _) = do fields' <- mapM onField fields return $ ["{"] ++ intercalate [", "] fields' ++ ["}"] where onField (k, te) = (ErrorString (pretty k ++ ": ") :) <$> typeExpForError te typeExpForError (E.TEArrow _ t1 t2 _) = do t1' <- typeExpForError t1 t2' <- typeExpForError t2 return $ t1' ++ [" -> "] ++ t2' typeExpForError (E.TEApply t arg _) = do t' <- typeExpForError t arg' <- case arg of TypeArgExpType argt -> typeExpForError argt TypeArgExpDim d _ -> pure <$> dimExpForError d return $ t' ++ [" "] ++ arg' typeExpForError (E.TESum cs _) = do cs' <- mapM (onClause . snd) cs return $ intercalate [" | "] cs' where onClause c = do c' <- mapM typeExpForError c return $ intercalate [" "] c' dimExpForError :: E.DimExp VName -> InternaliseM (ErrorMsgPart SubExp) dimExpForError (DimExpNamed d _) = do substs <- lookupSubst $ E.qualLeaf d d' <- case substs of Just [v] -> return v _ -> return $ I.Var $ E.qualLeaf d return $ ErrorInt32 d' dimExpForError (DimExpConst d _) = return $ ErrorString $ pretty d dimExpForError DimExpAny = return "" -- A smart constructor that compacts neighbouring literals for easier -- reading in the IR. errorMsg :: [ErrorMsgPart a] -> ErrorMsg a errorMsg = ErrorMsg . compact where compact [] = [] compact (ErrorString x : ErrorString y : parts) = compact (ErrorString (x ++ y) : parts) compact (x : y) = x : compact y
A new book has been published on Hindi movie music, called "Gaata Rahe Mera Dil". It is written by Anirudha Bhattacharjee and Balaji Vittal, who had earlier written a book called "R D Burman- the man and the music". The book discusss 50 classic songs from the history of Hindi movies. The oldest song is from" Street Singer" ( 1937) sung by K L Saigal. The latest is "Ae ajnabi tu bhi kabhi" (Dil Se). The 300 page book published by Harper Collins discusses the history and other information behind the making of the songs. This book is getting good reviews. Unfortunately this book is not available in small towns (I am a small town person living in a small town). From the review of this book as well as from what I read in the earlier book on R D Burman, I find that the "Technical" details that the authors discuss about the songs is nothing but bullcrap. Here is what the authors say about the "Dosti" (1964) song- Mera toh jo bhi kadam hai. The composers use two Komal notes—Dha and Ni—in the mukhra where all the other five shudh notes give the song a major-scale colour. The antara, with the emphasis shifting to a Komal Re, creates the transitory feel of a change in scale. The use of Komal notes—the Ga and Ni—creates an aura of unconventiality and underlines the desolate cry of grief…” I feel that the above "technical" discussion makes no sense whatsoever. I request SL, our technical guru, to tell us what he thinks of the above comment on the song. S L, if you can get hold of this book, please give us your review of this book. Will do. FIrst I am unable to recollect this song. Have to hear it.The book I will have to order over amazon I guess given I am in a smaller town than what you are in.. I certainly will do the prelims as far as this song is concerned. The extract you have given itself is sort of iffy there.. My preliminary thoughts. First off, this song is in rag Yaman Kalayan. Mood for this raga is "serene" and "haunting" (depending on the rendition) but I would not necessarily call it grief.. a more appropriate word would be feeling lost, or feeling of longing but not grief. The "haunting" nature comes from the mM (yes mM and not M) rather than anything else which makes in yaman kalyan instead of pure yaman (which would have a "M" instead. ). Compare that to Koi jab tumhara hriday tod de, tadapta hua jab koi chod de.. (Kalyan) which is again 'haunting' not sad.. I think the author intended to use the term melancholous instead of "sad" as in tragic or rondu as we would say in hindi. (cos of my leg, I cannot really play my KB right now (position of the foot pedals pls the distance were the KB will have to be cos of my leg and my back posture etc, and so cannot really "judge" by ear alone the impact of the komal dha and ni as the author suggests.. so I will not say they are wrong but my priliminary thought suggest the mM being more uumphaatic than anything else.) m=Pure maM=Dirgh/tivra Ma (ma does not have a komal). (Note: Modern musicians consider Yaman, Kalyan (carnatic eq Kalyani) and Yaman-kalyan as one and the same but traditionalists consider them three distinct ragas). Also given it is Yaman-Kalyan (I am 100% certain) there is no room for any kind of komal dha or ni there!! where did the author hear that is a big question for me. The raga has all shuddha swars except for the tivra Ma! BTW kalyan can be romantic and very at that. Yaad rahega payaar ka ye, rangeen zamaana yaad rahega. While songs like Tasvir Banaata Hun, Tasvir Nahin Banati are in raag pahaadi) are extremely haunting.. so it is more of the lyrics plus progression rather than the scale that gives the "feel" even though the notes have about 50% contribution. In some cases, it can be complete opposite feel.. same raga..eg Nache Man Mora Magan Dhig Dha Dhigi Dhigi (Bhairavi) vs Mujhko is raat ki tanhahi mein aawaaz na do... or Tera jaana dil ke armanon ka (both bhairavi again). (I know raja pai would have my pants off if not for this disclaimer!! He knows his music stuff). Thanks for your prompt impromptu technical review. And what about the authors going technobabble viz. "... give the song a major-scale colour." There is not concept of major scale or its equivalent in Hindustani classical music. We have "raag" in Hindustani classical music instead. And also "....creates the transitory feel of a change in scale. " Do they mean anything whatsoever, or they are supposed to impress the ignorants. Honestly I have never come across such jargon ever. Trasitionary nature basically means nothing.. there is no such thing. You change scales as in a ragamalika but what exactly a transitionary nature of a scale is foreign to me. And another thing, the major and minor "nature" of a scale is determined by its aroha avaroha progression (pakad) and not by gamaks at all. I am not sure I understand that piece of gobledygook at all. And another point.. Major scale usually signifies (in western jargon), an upbeat song.. like lungi dance lungi dance.. the one that gets your blood pumping and a minor scale is more serene, romatic and all those soft feel (hotel california).. so how can a minor scale impart a Major scale color is beyond my technical know how. I editied a few posts above for accuracy (I type as thoughts come to me). Change of raga or mix of them is raga malika. But shift of scales does not change the raga or the feel.. for instance Jai ho.. in the ending crescendo, the scale shifts up by half a note but the ENTIRE progression shifts up. It only adds the "fervor" part or emphasis to the feel.. like say from fan to a die hard fan kinds... same is there in the MJ number man in the mirror in the ending stages. One can argue that it might shift moods.. like in case of "pyarr hamen kis mod pe le aaya ke dil kare hai, koi ye bataye kyaa hoga".. when it becomes a fast dance number in the end.. but notice it starts out as a COMICAL/frivolous/chewtiyaagiri song at the outset (only pretending to be a sad song).. and becomes ultra comic by the end (movie satte pe satta). The authors were expecting that people will not question all this technobabble rather get "impressed" by it. I suspect that they have come up with similar "technical" analysis in case of all the 50 songs that they have discussed in the book. That should make it a very interesting read, though not in a manner that the authors intended. peaceful wrote:Can you teach me how to download only one song from you tube? Because when I post certain song, others already open on right hand side.I want to learn more.I heard you are my technical gurus. Yes SC, it would be fun to see their treatment of rather esoteric ragas like bilaval, asavari etc.. those are dyamic and the most dynamic (Strictly in my opinion) is malkauns. I think they will use rather quixotic phrases.. like blanket ones to suggest something very exotic but then would not really be saying anything... I love such highly educational pieces A review of this book was posted in a blog by someone who is my facebook friend as well as the facebook friend of the author of this book. I have questioned the "technical" analysis of this song as mentioned in the review. The author refused to accept that the song is in Yaman Kalyan. Please have a look at the vehement denial by the author in his comments in this post: Well then what raga is it based on? I am willing to be proven wrong but with my limited and rusty knowledge, I am almost willing to bet a bit that it is YAMAN KALYAN. what else is that? I cannot think of any other raga that it may belong to. Also the argument "Tonic does not change" hmm.. what does he mean by that? Modulation or something else See, ragas are based on notes and both komal and shuddh and teevra are notes by their own right. Changing from the shudh to komal or dirga, usually will NOT change the tonic (And note tonic can be loosely termed as vadi in hindustani).. modulation is a tonic shift and that also is not quite the same as a raga jump... instances of that happen all the time with NO shift in raga at all (abrupt in kind) (Mozarts K160). But lets not get into all that. I think the authors want a reasonable book to sell.. Let them. Why pee in their party man. People will read it with passing facination, remember some old songs, feel educated and they get some money..all is well.. no harm done. Intrsting. I will have to play it to confirm then. Patdeep ka ek gaana hai megha chaye aadhi raat baran ban gayi niniyaa.. trying to hum those together does not give me the feel.. I will have to play it on the kb to be sure. I am still going to stick to yaman kalyan for the interim (apne aap ko wrong bolne me sharm aata hai naa khud ko..). Madhuvanti mein even if not a good example I can think of only one song and that is way obscure one.. Rasm-e-Ulfat Ko Nibhaen To Nibhaen Kaise from movie Dil Ki Rahen and hindustani/carnatic music is an ocean.. I got trained for a few years and that in a mixed martial arts style.. a little boxing and karate and taikwando thrown in.. i.e hindustani, carnatic and western theory.. so it is impossible that I will be an "expert" to know all the ragas out there and recognize them(jack of all perhaps but master not at all ). There are tons of ragas that I might not even heard or or styles there of.. It is highly possible that I am wrong here but my gut feel stll leans towards yaman-kalyan or its variant. But I will not say now that it is a 100% sure case as I did earlier. Ab your other friend has firmly planted that doubt in my bird brain. Yaar re to hai aaroha mein.. which both patdeep and madhuvanti do not have as far as I can recall! Jara confirm karoge from your friend? But hindi movies do not conform to the rules of classical music strictly. So vo bhi ek locha hai.
Predictors of neurobehavioral symptoms in a university population: a multivariate approach using a postconcussive symptom questionnaire. Several factors have been linked to severity of postconcussive-type (neurobehavioral) symptoms. In this study, predictors of neurobehavioral symptoms were examined using multivariate methods to determine the relative importance of each. Data regarding demographics, symptoms, current alcohol use, history of traumatic brain injury (TBI), orthopedic injuries, and psychiatric/developmental diagnoses were collected via questionnaire from 3027 university students. The most prominent predictors of symptoms were gender, history of depression or anxiety, history of attention-deficit/hyperactivity disorder or learning disability diagnosis, and frequency of alcohol use. Prior mild TBI was significantly related to overall symptoms, but this effect was small in comparison to other predictors. These results provide further evidence that neurobehavioral symptoms are multi-determined phenomena, and highlight the importance of psychiatric comorbidity, demographic factors, and health behaviors to neurobehavioral symptom presentation after mild TBI.
The Difficult Crossing The Difficult Crossing (La traversée difficile) is the name given to two oil-on-canvas paintings by the Belgian surrealist René Magritte. The original version was completed in 1926 during Magritte's early prolific years of surrealism and is currently held in a private collection. A later version was completed in 1963 and is also held in a private collection. The 1926 version The 1926 version contains a number of curious elements, some of which are common to many of Magritte's works. The bilboquet or baluster (the object which looks like the bishop from a chess set) first appears in the painting The Lost Jockey (1926). In this and some other works—for example The Secret Player (1927) and The Art of Conversation (1961)—the bilboquet seems to play an inanimate role analogous to a tree or plant. In other instances, such as here with The Difficult Crossing, the bilboquet is given the anthropomorphic feature of a single eye. Another common feature of Magritte's works seen here is the ambiguity between windows and paintings. The back of the room shows a boat in a thunderstorm, but the viewer is left to wonder if the depiction is a painting or the view out a window. Magritte elevated the idea to another level in his series of works based on The Human Condition where "outdoor" paintings and windows both appear and even overlap. Near the bilboquet stands a table. On the top, a disembodied hand is holding a red bird, as if clutching it. The front right leg of the table resembles a human leg. The 1963 version In the 1963 version, a number of elements have changed or disappeared. Instead of taking place in a room, the action has moved outside. There is no table or hand clutching a bird and the scene of the rough sea in the ambiguous window/painting at the rear becomes the entire new background. Near the front a low brick wall is seen with a bilboquet behind and a suited figure with an eyeball for a head in front. There is ambiguity as to whether the suited figure is a man or another bilboquet. Some bilboquet figures, for example those in The Encounter (1929), have similar eyeball heads, however the suit covers the body and no clear identification can be made. If the suited figure is a man, it could be a self-portrait, which means that the eyeball is covering his face. Covering Magritte's face with an object was another common theme for himself, Son of Man being a good example. Relation to other paintings Both versions of The Difficult Crossing show a strong similarity to Magritte's painting The Birth of the Idol, also from 1926. The scene is outside and depicts a rough sea in the background (this time without ship). Objects which appear include a bilboquet (the non-anthropomorphic variety), a mannequin arm (similar to the hand which clutches the bird) and a wooden board with window-like holes cut out which is nearly identical to those flanking both sides of the room in earlier version. All three paintings may have been inspired by Giorgio de Chirico's Metaphysical Interior (1916) which features a room with a number of strange objects and an ambiguous window/painting showing a boat. Magritte was certainly aware of De Chirico's work and was emotionally moved by his first viewing of a reproduction of Song of Love (1913–14). References Category:Paintings by René Magritte Category:Surrealist paintings Category:1926 paintings Category:1963 paintings Category:Maritime paintings
God’s 4 Signs to Moses: The Staff That Turned into a Serpent The LORD said to him, “What is that in your hand?” And he said, “A staff.” Then He said, “Throw it on the ground.” So he threw it on the ground, and it became a serpent; and Moses fled from it. But the LORD said to Moses, “Stretch out your hand and grasp it by its tail”—so he stretched out his hand and caught it, and it became a staff in his hand… – Exodus 4:2-4 Oh Father, our heavenly Father, wash us in the blood of Your Son again today. Let us come to you with a clean conscious. Wash us in the Water of your Word. Open the eyes of our hearts to see Christ, receive Christ, and enjoy Christ. In Jesus’ Name, which is above all names, Amen! In Egypt, Moses had the highest education and was skilled in speech (Acts 7:22). When the Lord came to give Moses the revelation that He would free the Israelites, Moses tried to achieve the Lord’s will in his own strength and ended up killing an Egyptian. Trying in his own strength, just led to death. The Lord took Moses through 40 years of death in the wilderness. Moses was a broken man when the Lord appeared to him again. Moses could no longer speak well (Exodus 4:10) and he needed a staff for walking. We all have many staffs that we rely on. Every earthly thing that you rely on for your daily living is a staff. Your career is a staff. Your education is a staff. Your news is a staff. Your hobby is a staff. Your caffeine is a staff. Your sweets are a staff. Your family is a staff. Your car is a staff. Your intellect is a staff. Your emotions are a staff. Your television is a staff. Your video games are a staff. Your internet is a staff. There is no Life in these staffs. These staffs are dead wood. When Moses threw his staff down it became a serpent. Not only is your staff dead, but it is also a serpent. Whatever you rely on, other than the Lord, becomes a serpent. Your staffs must be thrown down and put to death. Only then, by the Lord’s command, can you grasp the serpent by the tail, and lift the staff up in resurrection. Don’t abandon your family. Don’t set up a law in your heart on what you may eat or drink. But turn to the Lord, beholding Him and giving Him your ear. Give everything that you rely on to Him and let Him give you back what you need in resurrection. In resurrection, you are no longer reliant upon the staff, you are reliant on God alone. Father, we cast our staffs down before you. Open our eyes to see the things that your enemy uses to usurp your rightful throne in our hearts. You provide everything we need as we seek Your Kingdom and Your Righteousness first. Let us grasp the enemy by the tail in Your Resurrection Life, that we may be overcomers in Your Victory. In Jesus’ Name, Amen. 1 If I’d know Christ’s risen power. I must ever love the Cross; Life from death alone arises; There’s no gain except by loss. Chorus If no death, no life, If no death, no life; Life from death alone arises; If no death, no life. 2 If I’d have Christ formed within me, I must breathe my final breath, Live within the Cross’s shadow, Put my soul-life e’er to death. 3 If God thru th’ Eternal Spirit Nail me ever with the Lord; Only then as death is working Will His life thru me be poured.
# -*- coding: utf-8 -*- from ... import OratorTestCase from orator import Model as BaseModel from orator.orm import ( morph_to, has_one, has_many, belongs_to_many, morph_many, belongs_to, ) from orator.orm.model import ModelRegister from orator.connections import SQLiteConnection from orator.connectors.sqlite_connector import SQLiteConnector class DecoratorsTestCase(OratorTestCase): @classmethod def setUpClass(cls): Model.set_connection_resolver(DatabaseIntegrationConnectionResolver()) @classmethod def tearDownClass(cls): Model.unset_connection_resolver() def setUp(self): with self.schema().create("test_users") as table: table.increments("id") table.string("email").unique() table.timestamps() with self.schema().create("test_friends") as table: table.increments("id") table.integer("user_id") table.integer("friend_id") with self.schema().create("test_posts") as table: table.increments("id") table.integer("user_id") table.string("name") table.timestamps() table.soft_deletes() with self.schema().create("test_photos") as table: table.increments("id") table.morphs("imageable") table.string("name") table.timestamps() def tearDown(self): self.schema().drop("test_users") self.schema().drop("test_friends") self.schema().drop("test_posts") self.schema().drop("test_photos") def test_extra_queries_are_properly_set_on_relations(self): self.create() # With eager loading user = OratorTestUser.with_("friends", "posts", "post", "photos").find(1) post = OratorTestPost.with_("user", "photos").find(1) self.assertEqual(1, len(user.friends)) self.assertEqual(2, len(user.posts)) self.assertIsInstance(user.post, OratorTestPost) self.assertEqual(3, len(user.photos)) self.assertIsInstance(post.user, OratorTestUser) self.assertEqual(2, len(post.photos)) self.assertEqual( 'SELECT * FROM "test_users" INNER JOIN "test_friends" ON "test_users"."id" = "test_friends"."friend_id" ' 'WHERE "test_friends"."user_id" = ? ORDER BY "friend_id" ASC', user.friends().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_posts" WHERE "deleted_at" IS NULL AND "test_posts"."user_id" = ?', user.posts().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_posts" WHERE "test_posts"."user_id" = ? ORDER BY "name" DESC', user.post().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_photos" WHERE "name" IS NOT NULL AND "test_photos"."imageable_id" = ? AND "test_photos"."imageable_type" = ?', user.photos().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_users" WHERE "test_users"."id" = ? ORDER BY "id" ASC', post.user().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_photos" WHERE "test_photos"."imageable_id" = ? AND "test_photos"."imageable_type" = ?', post.photos().to_sql(), ) # Without eager loading user = OratorTestUser.find(1) post = OratorTestPost.find(1) self.assertEqual(1, len(user.friends)) self.assertEqual(2, len(user.posts)) self.assertIsInstance(user.post, OratorTestPost) self.assertEqual(3, len(user.photos)) self.assertIsInstance(post.user, OratorTestUser) self.assertEqual(2, len(post.photos)) self.assertEqual( 'SELECT * FROM "test_users" INNER JOIN "test_friends" ON "test_users"."id" = "test_friends"."friend_id" ' 'WHERE "test_friends"."user_id" = ? ORDER BY "friend_id" ASC', user.friends().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_posts" WHERE "deleted_at" IS NULL AND "test_posts"."user_id" = ?', user.posts().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_posts" WHERE "test_posts"."user_id" = ? ORDER BY "name" DESC', user.post().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_photos" WHERE "name" IS NOT NULL AND "test_photos"."imageable_id" = ? AND "test_photos"."imageable_type" = ?', user.photos().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_users" WHERE "test_users"."id" = ? ORDER BY "id" ASC', post.user().to_sql(), ) self.assertEqual( 'SELECT * FROM "test_photos" WHERE "test_photos"."imageable_id" = ? AND "test_photos"."imageable_type" = ?', post.photos().to_sql(), ) self.assertEqual( 'SELECT DISTINCT * FROM "test_posts" WHERE "deleted_at" IS NULL AND "test_posts"."user_id" = ? ORDER BY "user_id" ASC', user.posts().order_by("user_id").distinct().to_sql(), ) def create(self): user = OratorTestUser.create(id=1, email="john@doe.com") friend = OratorTestUser.create(id=2, email="jane@doe.com") user.friends().attach(friend) post1 = user.posts().create(name="First Post") post2 = user.posts().create(name="Second Post") user.photos().create(name="Avatar 1") user.photos().create(name="Avatar 2") user.photos().create(name="Avatar 3") post1.photos().create(name="Hero 1") post1.photos().create(name="Hero 2") def connection(self): return Model.get_connection_resolver().connection() def schema(self): return self.connection().get_schema_builder() class Model(BaseModel): _register = ModelRegister() class OratorTestUser(Model): __table__ = "test_users" __guarded__ = [] @belongs_to_many("test_friends", "user_id", "friend_id", with_pivot=["id"]) def friends(self): return OratorTestUser.order_by("friend_id") @has_many("user_id") def posts(self): return OratorTestPost.where_null("deleted_at") @has_one("user_id") def post(self): return OratorTestPost.order_by("name", "desc") @morph_many("imageable") def photos(self): return OratorTestPhoto.where_not_null("name") class OratorTestPost(Model): __table__ = "test_posts" __guarded__ = [] @belongs_to("user_id") def user(self): return OratorTestUser.order_by("id") @morph_many("imageable") def photos(self): return "test_photos" class OratorTestPhoto(Model): __table__ = "test_photos" __guarded__ = [] @morph_to def imageable(self): return class DatabaseIntegrationConnectionResolver(object): _connection = None def connection(self, name=None): if self._connection: return self._connection self._connection = SQLiteConnection( SQLiteConnector().connect({"database": ":memory:"}) ) return self._connection def get_default_connection(self): return "default" def set_default_connection(self, name): pass
Saturday, May 30, 2009 On solid grounds: Campground owners hope that spending on improvements pays off with more visitors in slumping economy From the Wisconsin State Journal By Marv Balousek While some businesses may be making cutbacks because of the recession, Wisconsin's private campground owners have been spending money to make their properties more attractive to prospective customers this year. They've invested hundreds of thousands of dollars to improve their facilities even without the benefit of federal stimulus dollars. The owners expect to cash in as families scale back their Disney World plans this summer in favor of less-expensive weekend camping trips. Reservations are up this year for the 16-week season that began on Memorial Day weekend, according to two Wisconsin campground owners. "Camping, even in stressful times, can be the outdoor activity of choice,"said Bud Styer, who operates five Wisconsin campgrounds. "People with families especially are still going to recreate and they're going to do something with their kids." Styer said he is spending $565,000 this year at his five campgrounds and expects to recoup that investment in three to five years through camping fees. He's spent money on things such as a Jumping Pillow for Baraboo Hills Campground north of Baraboo, blacktop for a circle around the pond at Merry Mac's Campground near Merrimac and a remodeled camp store at River Bend Campground, which he manages but doesn't own, west of Watertown. River Bend, which features a 300-foot water slide, was closed last summer because of extensive flooding when the Crawfish River overflowed its banks. It didn't reopen until August. Styer said the campground had to be cleaned before improvements were made. He also has upgraded Smokey Hollow Campground near Lodi and Tilleda Falls Campground west of Shawano. Water-related features such as Water Wars -- a competition with water balloons -- or floating water slides and climbing walls are popular improvements at many parks. "Years ago, we camped in a Coleman tent with a kerosene lantern," Styer said. "Nowadays, everybody's got to have electric, water, box fans and rope lights." Styer said he's a great believer in "stuff" and that the more stuff you have, the more you can charge for campsites. A private Wisconsin campground with amenities can charge $39 to $50 a night, he said, compared to $25 to $35 a night for a standard campground. "If you want to expand your business and generate additional revenues, then you have to have a better facility,"he said. "It has to have the bells and whistles. People are going to camp closer to home and look for the best value." Upgrading campground facilities this year is a national trend, said Linda Pfofaizer, president of the National Association of RV Parks and Campgrounds in Larkspur, Colo. The association represents 8,000 private campground owners. Although the investments could benefit them this summer, she said, most campground owners also are looking beyond the recession, "The recession is temporary," she said. "Most campground and RV park operators believe that it behooves them to move forward with their improvement plans to remain competitive with other travel and tourism options." "We try to keep adding what the customers are asking for," he said. "A few years ago, during a downturn, there were many people who didn't travel West or take a large vacation, and we're seeing that again." At Fox Hill RV Park south of Wisconsin Dells near Ho Chunk Casino, roads have been repaved with recycled asphalt, the pool was retiled, the bath house was remodeled and a disc golf course was added, said owner Jim Tracy. He said the overall construction slowdown helped him negotiate a good deal on the bath house remodeling. "I'm still pretty bullish on the summer," Tracy said. "I want to give (campers) reasons to come back and talk me up to their friends and families." Bud Styer Media Bud Styer, left, and Keith Stachurski, manager of Smokey Hollow Campground near Lodi, confer at a beach area of the campground. Styer has invested $565,000 this year in improvements at the five campgrounds he operates. Zachary Zirbel cuts the grass at Smokey Hollow Campground as he prepares the sites for another influx of weekend campers. Stachurski patrols Smokey Hollow on a Segway, a small electric vehicle. He also offers riding lessons to campers. The red structure behind him is used for Spaceball, a game that combines the skills of trampoline and basketball. Furnished conastoga wagons and beachfront yurts are among the camping options at Smokey Hollow Campground near Lodi. Children play on a Jumping Pillow at Chetek River Campground near Chetek, north of Eau Claire. A row of furnished yurts, or circular tents, is another camping option at Merry Mac's Campground in Merrimac.
Q: Drag and drop in jquery I didn't get the id of dropped div on dropping on another div i get the id_droppable i but didn't get the id_dropped div The alert id_dropped give undefined as result Please help me verify my code and correct my error. $(".full-circle").droppable({ accept: ".unseated_guest", drop: function(event, ui) { var id_droppable = this.id; alert(id_droppable); var id_dropped = ui.id; alert(id_dropped); var name=document.getElementById("div_name_0").value; $(this).css("background-color","red"); $(this).append(ui.draggable); //$(this).draggable('disable'); } }); A: The ui parameter does not have an id attribute, as it is a reference to the element being drug. You need to get the id like ui.draggable.attr('id'), or whatever method you prefer to get the id of an element. $(".full-circle").droppable({ accept: ".unseated_guest", drop: function(event, ui) { //Stuff above var id_dropped = ui.draggable.attr('id'); alert(id_dropped); //Stuff below } });
Girmal Falls General This waterfall extends to a height of up to 100 feet, making it the highest waterfall of Gujarat. The picturesque beauty of this site makes it popular among visitors and people of the region alike. The water swiftly falls from a great height, creating a fog like condition that’s eye catching. The government of this state is working on many projects to make this place an ideal picnic spot and a tourist attraction. The fall comes to its best form at the time of monsoon and provides an immensely striking appearance. Some of the best natural features of Gujarat can be explored in this place. This place is a nice and refreshing retreat for any traveler.
Be afraid, England and Wales 2019. The Aussies are coming. Or rather, the Aussies are still coming, after an 86-run defeat of a New Zealand team who seemed consumed by the occasion at Lord’s. At times in the Black Caps’ attempts to chase 243 this felt a bit like a Sunday morning junior age group game. Steve Smith sent down some weird, wonky all-sorts. Wickets were greeted with jokey huddles. It took the return of Mitchell Starc to restore a sense of World Cup order, figures of five for 26 reflecting a spell of brutal, high-grade, white-ball fast-bowling that blew away the tail. Pakistan’s Imad Wasim holds nerve to see off Afghanistan in thriller Read more Victory leaves Australia on their own at the top of the group stage table with seven wins from eight, and with some of their own question marks finding an answer or two. They had some help along the way, not least from Kane Williamson’s diffident captaincy. On a sun-baked north London day New Zealand had first shown how to beat Australia; then almost immediately they showed how to fail to beat Australia. Exposing that thin-looking middle order had always looked a plan. Failing to punch through by taking off your best bowlers was where the game got away, captured by the sight of the skipper wheeling out seven overs of mid-innings part-time leg-spin. Trent Boult even had time at the end of Australia’s innings to conjure a largely pointless World Cup hat-trick. Instead it was a gutsy, occasionally streaky 107-run sixth-wicket partnership between Usman Khawaja and Alex Carey that decided this game. From the start Lord’s was a place of Trans-Tasman good cheer as the grey shroud of the last few weeks lifted. Australia had won the toss and elected to bat. In any list of David Warner’s top five career sledges, the line “You’re not f-ing facing Trent Boult’s 80mph half-volleys now, mate” – yelled at Joe Root as he took guard during the Cardiff Ashes Test of 2015 – might just make it on grounds of subtlety alone. This time it was Warner’s turn to face the Boult music, a tricky prospect at the start of a heat-hazed day. Boult’s third over saw Aaron Finch out lbw falling over an inswinger. Colin de Grandhomme shared the new ball, toiling in manfully from the nursery end like a man with a two-seat sofa strapped to his back. But it was Lockie Ferguson who made the most telling incision. Ferguson was a joy to watch, a thrillingly athletic fast bowler with an air of the old school adventurer about him, so much so you half expect to see him handing the umpire his fedora and bull-whip before every over. Here Ferguson took out Warner and Steve Smith for two runs in seven balls. First he bounced out Warner. Smith was booed on. And Ferguson soon did for him too, thanks to another moment of brilliance. Smith pulled another short one, middling it with a lovely, sweet clump. At short backward square leg Martin Guptill dived full length and stuck out a hand. Eventually he stood up, raised his hand and threw a ball – apparently the same one – into the sky. It was a catch that will look good in replay. In real time it was a moment to stop the days and spin it back on its axis. James Neesham entered the attack and 81 for three became 81 for four as Marcus Stoinis was caught behind, before Neesham held a one-handed caught and bowled just above the grass to get rid of Glenn Maxwell. New Zealand had Australia wobbling around the ring at five for 92 after 21 overs. But Khawaja found a partner in Carey, who clipped and carved at assorted short-pitch offerings as New Zealand struggled to adapt their length to his punchy style. The fifty partnership arrived off 51 balls, at the same time as Khawaja’s own half-century, an innings that will be doubly satisfying on a day when no one else in Australia’s top six got to 25. Carey inside-edged to the pavilion fence to reach a battling 51 off 41 balls. There is a jaunty fearlessness to his cricket. Best of all he averages 50 now at No 7 for Australia and has made that tricky slot a position of strength in the last month. There will be regrets for New Zealand. Not least in Boult’s disappearance from the attack until the 42nd over. Their chase never really got started. Jason Behrendorff dismissed both openers and a 20-over score of 61 for two deteriorated to 157 all out as only Williamson seemed to have the skill to score on a crabby pitch. Australia were talked down at the World Cup’s start as a team overly reliant on five star players. At Lord’s it was the underrated back-up cast who dug in to turn this game, maintaining the air of a team finding other gears as this tournament narrows towards its end point.
README.md exists but content is empty.
Downloads last month
38