text
stringlengths 121
672k
|
|---|
A Reference Resource
Life Before the Presidency
Herbert Clark Hoover was born on August 10, 1874. For the first nine years of his life, he lived in the small town of West Branch, Iowa, the place of his birth. His Quaker father, Jessie Clark Hoover, a blacksmith and farm equipment salesman, suffered a heart attack and died when Herbert was six years old. Three years later, the boy's mother, Huldah Minthorn Hoover, developed pneumonia and also passed away, orphaning Herbert, his older brother Theodore, and little sister Mary. Passed around among relatives for a few years, Hoover ended up with his uncle, Dr. John Minthorn, who lived in Oregon.
The young Hoover was shy, sensitive, introverted, and somewhat suspicious, characteristics that developed, at least in part, in reaction to the loss of his parents at such a young age. He attended Friends Pacific Academy in Newberg, Oregon, earning average to failing grades in all subjects except math. Determined, nevertheless, to go to the newly established Stanford University in Palo Alto, California, Hoover studied hard and barely passed the university's entrance exam. He went on to major in geology and participated in a host of extracurricular activities, serving as class treasurer of the junior and senior student bodies and managing the school baseball and football teams. To pay his tuition, Hoover worked as a clerk in the registration office and showed considerable entrepreneurial skill by starting a student laundry service.
Career and Monetary Success
During the summers, Hoover worked as a student assistant on geological survey teams in Arkansas, California, and Nevada. After his graduation in 1895, he looked hard to find work as a surveyor but ended up laboring seventy hours a week at a gold mine near Nevada City, California, pushing ore carts. Luck came his way with an office job in San Francisco, putting him in touch with a firm in need of an engineer to inspect and evaluate mines for potential purchase. Hoover then moved to Australia in 1897 and China in 1899, where he worked as a mining engineer until 1902. A string of similar jobs took him all over the world and helped Hoover become a giant in his field. He opened his own mining consulting business in 1908; by 1914, Hoover was financially secure, earning his wealth from high-salaried positions, his ownership of profitable Burmese silver mines, and royalties from writing the leading textbook on mining engineering.
His wife, Lou Henry Hoover, traveled with him everywhere he went. Herbert and Lou met in college, where she was the sole female geology major at Stanford. He proposed to her by cable from Australia as he prepared to move to China; she accepted by return wire and they married in 1899. The couple was in China during the Boxer Rebellion of 1900, a time when Lou helped nurse wounded Western diplomats and soldiers while Herbert assisted in the fighting to defend Tianjin, a city near the uprising. By the time the couple returned home to America in 1917, Lou had learned to shoot a gun and had mastered eight languages.
Over the course of his career as a mining engineer and businessman, Hoover's intellect and understanding of the world matured considerably. Hoover was raised a Quaker and although he rarely went to Meeting as an adult, he internalized that faith's belief in the power of the individual, the importance of freedom, and the value of "conscientious work" and charity. Hoover also applied the ethos of engineering to the world in general, believing that scientific expertise, when employed thoughtfully and properly, led to human progress. Hoover worked comfortably in a capitalist economy but believed in labor's right to organize and hoped that cooperation (between labor and management and among competitors) might come to characterize economic relations. During these years, Hoover repeatedly made known to friends his desire for public service.
Politically, Hoover identified with the progressive wing of the Republican Party, supporting Theodore Roosevelt's third-party bid in 1912. World War I brought Hoover to prominence in American politics and thrust him into the international spotlight. In London when the war broke out, he was asked by the U.S. consul to organize the evacuation of 120,000 Americans trapped in Europe. Germany's devastating invasion of Belgium led Hoover to pool his money with several wealthy friends to organize the Committee for the Relief of Belgium. Working without direct government support, Hoover raised millions of dollars for food and medicine to help desperate Belgians.
In 1917, after the United States entered the war, President Woodrow Wilson asked Hoover to run the U.S. Food Administration. Hoover performed quite admirably, guiding the effort to conserve resources and supplies needed for the war and to feed America's European allies. Hoover even became a household name during the war; nearly all Americans knew that the verb "to Hooverize" meant the rationing of household materials. After the armistice treaty was signed in November 1918, officially ending World War I, Wilson appointed Hoover to head the European Relief and Rehabilitation Administration. In this capacity, Hoover channeled 34 million tons of American food, clothing, and supplies to war-torn Europe, aiding people in twenty nations.
His service during World War I made Hoover one of the few Republicans trusted by Wilson. Because of Hoover's knowledge of world affairs, Wilson relied him at the Versailles Peace Conference and as director of the President's Supreme Economic Council in 1918. The following year, Hoover founded the Hoover Library on War, Revolution, and Peace at Stanford University as an archive for the records of World War I. This privately endowed organization later became the Hoover Institution, devoted to the study of peace and war. No isolationist, Hoover supported American participation in the League of Nations. He believed, though, that Wilson's stubborn idealism led Congress to reject American participation in the League.
Secretary of Commerce
In 1920, Hoover emerged as a contender for the Republican presidential nomination. His run was blocked, however, by fellow a Californian, Senator Hiram Johnson, who objected to Hoover's support for the League. Republican Warren Harding won the White House in 1920 and appointed Hoover as his secretary of commerce, a position that Hoover retained under Harding's successor, President Calvin Coolidge.
Under Hoover's leadership, the Department of Commerce became as influential and important a government agency as the Departments of State and Treasury. Hoover encouraged research into measures designed to counteract harmful business cycles. He supported government regulation of new industries like aviation and radio. He brought together more than one hundred different industries and convinced them to adopt standardized tools, hardware, building materials, and automobile parts. Finally, he aggressively pursued international trade opportunities for American business. To win these reforms, Hoover strengthened existing agencies in the Commerce Department, like the Bureau of Foreign and Domestic Commerce, or simply established new ones, like the Bureau of Standards, for the standardization project. He also formed commissions that brought together government officials, experts, and leaders of the relevant economic sectors to work towards reform.
The initiatives Hoover supported as commerce secretary—and the ways in which he pursued them—reveal his thinking about contemporary life in the United States and about the federal government's role in American society. Hoover hoped to create a more organized economy that would regularize the business cycle, eliminating damaging ebbs and flows and generating higher rates of economic growth. He believed that eradicating waste and improving efficiency would achieve some of these results— thus, his support for standardization and for statistical research into the workings of the economy. He also believed that the American economy would be healthier if business leaders worked together, and with government officials and experts from the social sciences, in a form of private-sector economic planning. This stance led him to support trade associations—industry-wide cooperative groups wherein information on prices, markets, and products could be exchanged among competitors—which Hoover saw as a middle way between competition and monopoly. He insisted, though, that participation in these associations remain voluntary and that the government merely promote and encourage, rather than require, their establishment.
Hoover hoped that these innovations would strengthen what he saw as the central component of the American experience: individualism. In 1922, Hoover published a small book, entitled American Individualism, that examined the Western intellectual tradition's major social philosophies, including individualism, socialism, communism, capitalism, and autocracy. Hoover concluded that individualism was the superior principle around which to organize society. He rejected the laissez-faire capitalism of the Right and the socialism and communism of the Left because he believed that these ideologies hindered rather than helped the individual. Instead, Hoover sought a "balance of perspective" between Right and Left that theoretically would create and maintain opportunities for Americans to succeed. Through enterprises like those he championed as commerce secretary, Hoover believed the federal government could facilitate the creation of political, social, and economic conditions in which individual Americans could flourish.
Hoover's positions and thinking placed him solidly in the progressive camp of the Republican Party. As secretary of commerce, Hoover emerged as a potential running-mate for Coolidge in the 1924 presidential election, though that effort fell short. Hoover's reputation with the American people reached its peak in 1927, when he took charge of relief efforts following disastrous floods along the Mississippi River. The episode displayed Hoover at his best: as a humanitarian and leader with the ability to solve problems. When Coolidge announced in 1927 that he would not seek reelection, Hoover became the leading candidate for the Republican presidential nomination.
|
#ifndef LEMON_LTABLE_H
#define LEMON_LTABLE_H
struct lobject;
struct ltable {
struct lobject object;
int count;
int length;
void *items;
};
void *
ltable_create(struct lemon *lemon);
struct ltype *
ltable_type_create(struct lemon *lemon);
#endif /* LEMON_LTABLE_H */
|
Monday, January 28, 2013
Plant trees, disband the army, work together: the Tuscan way of escaping the growth trap
You probably know the story of the man who invented the game of chess. It is said that he presented the game to the king and that he asked in exchange a grain of rice on the first square of the board, two on the second, four on the third and so on, for all the 64 squares. The story says that the king agreed to the deal, only to find out, later on, that the amount of rice he was supposed to provide was gigantic, larger than the amount existing in the whole world.
The story doesn't say what happened at that point, but we may suppose that the king was not happy and that the inventor of the game received a reward much different than what he had asked for. So, we learn that growth is a trap and that doesn't apply just to grains of rice on a chessboard. It is always difficult to understand the consequences of exponential growth and everyone can fall in the trap; even whole civilizations. Today, we are still trying to go after the mythical "growth" that many think will magically solve all problems. Yet, many of us have this terrible feeling that it will be all useless and not just that. The feeling is that economic growth is taking us straight into the abyss.
So, is there a way to get free? We don't know what our destiny will be, but there have been examples of civilizations who managed a long term equilibrium. One is Japan of Edo times, another one is Tuscany after the Renaissance. There was a fateful moment in Tuscan history when people understood that the solution to the terrible times they were experiencing was not growth but adaptation. It came gradually, but we can identify the turning point with the rule of Grand Duke Ferdinando 1st, who put Tuscany on a path that in a personal interpretation of mine I can describe as, "plant trees, disband the army and work together". A path that led to a few centuries of peace (or at least without major wars) and to a moderate prosperity.
Tuscany: escaping the growth trap
Tuscany is a region of central Italy stuck between the mountains and the Mediterranean Sea. It is a land of gentle hills and plains; of grain fields and of cypress trees, of farms and of walled cities. It has been like that from the time of the Etruscans, the first dwellers of the area and from whom the old name of Tuscia comes.
Even though small and relatively isolated, Tuscany came to play an important role in the world's history with the Renaissance; an age of poets, painters, sculptors, bankers, and explorers. For a while, the main city of Tuscany, Florence, was the center of the Western World; the place of the financial power, the center of commerce, the place where artists, literates, and professionals would go to learn their trade.
But the golden age of the Renaissance didn't last for long. Its peak times were maybe one or two centuries long. Then, with the 16th century, decline started. Plagues, famines, economic crisis, military invasions, gradually led Tuscany to become one of the poorest countries of Europe. Yet, population never collapsed and something survived of the old spirit of freedom and intellectual independence. In the early 17th century, Tuscany became a refuge for the Jews fleeing from persecution in Spain. Tuscany kept her universities and academies and, in 1786, it was the first European state to officially abolish torture and the death penalty. So, the Tuscan collapse was not total - it was managed; it was "soft" and not so disastrous as it could have been. How was it done? It is a long story that deserves to be told.
Growth and collapse in Tuscany
Emerging out of the terrible times of the Great Plague, in 14th century, Tuscany's agriculture was able to create the resources needed to restart population growth and to embark in that age of economic growth and of great artistic accomplishments that we call "Renaissance." But nothing can grow forever: a growing population meant that more and more land was needed to feed it, and that could be obtained only by clearing forests. That, in turn opened the way to erosion. And erosion destroys the fertile soil that supports agriculture.
Still today, you can see how bad the erosion problem was during those times by looking at the city of Pisa. Today, it is an inland city but, during the Middle Ages, it had been a thriving harbor. It is reported that, already in the 15th century, Pisa’s harbor had been silting because of sediments carried by the Arno River. In the 17th century, silting became so serious that the harbor had to be abandoned. The sediments that destroyed the harbor of Pisa were the rich soil that had once supported Tuscan agriculture and, with it, the Tuscan population.
With the decline of agriculture, the Tuscan economic system started imploding; commerce and industry could not survive without food. Famines became common. The proud citizens of Florence, the city that had been called the “New Athens," started going hungry. According to a chronicler, in 1590 Florentines were reduced to eat a kind of bread that “in older times would have been given to dogs, and perhaps dogs would have refused it."
The Tuscan cities declined also in terms of military strength and the once free cities of Tuscany fell one by one to foreign invaders. The republic of Florence fell to the Spanish Imperial Armies in 1530. The republic of Siena fell to the combined armies of Spain and of the Florentine Medici in 1555. Afterwards, Tuscany became a province of the Spanish Empire, although still maintaining some degree of independence.
Plant trees, disband the army, work together
From the beginning, the Grand Dukes who ruled first Florence and then the whole Tuscany were turning their attention inward, to the management of the Tuscan territory. Already in 1559, at the time of Cosimo 1st of the Medici family, Tuscany had started a policy of protection of agriculture with a severe law that forbade cutting trees in the Appennino mountains, even on pain of death! That policy was continued by later rulers and Grand-Duke Ferdinando 1st was probably the turning point in abandoning all dreams of growth and expansion.
The monument to Ferdinando 1st (1549-1609), Grand Duke of Tuscany from 1587 to 1609. He was perhaps the first Tuscan ruler to recognize the end of growth times
Ferdinando ruled Tuscany from 1587 until his death in 1609. He was fond of saying that he ruled not by force but by "dignity only"; as his motto in Latin said: "maiestate tantum." He did a lot for agriculture, among other things enacting laws that reduced the tax burden on farmers. He went some steps further and he spoke of Tuscans as “worker bees" (“api operose") meaning that they had to work hard all together. Here is the symbol of the working bees in a bronze plate on Ferdinando's monument in Florence.
The “Working Bees", (“Api Operose") symbol of Ferdinando 1st. Image on the monument in Piazza SS. Annunziata, Firenze.
Some warlike spirit remained in Tuscany during Ferdinando's rule and that led to skirmishes with the Turkish Empire. But, on the whole, this age was the start of a period of careful management of the territory, of reducing military expenses, of seeking for social harmony and justice. We could define this policy as "plant trees, disband the army, work together", even though Ferdinando himself never used these terms.
The Dukes who followed Ferdinando 1st, continued this policy. Agriculture remained a focus of the policy of the government. The laws protecting trees were maintained and expanded and, in 1753, Grand Duke Pietro Leopoldo created the “Georgofili" academy with the specific task of promoting agriculture. The academy still exists today and its motto is “For the sake of public prosperity."
The symbol of the Georgofili Academy established in Florence in 1753. The writing says “Prosperitati Publicae Augendae" (“In favor of public prosperity")
The Tuscan government also progressively reduced military expenses. The navy had basically ceased to exist with the first years of the 18th century and the army created by the Medici family was progressively reduced in strength until it was formally disbanded in 1753 by Grand Duke Francesco Stefano. New kinds of armies were created in later times but, basically, Tuscany just couldn’t afford war. Often, her borders had to be opened to invaders; it caused less harm than fighting them. Tuscany underwent a good number of invasions but, on the whole, these wars never brought great destruction. After the fall of Siena, in 1555, Tuscany didn’t see one of her cities besieged and bombarded until 1944, almost four centuries later.
It took time but, eventually, these policies had their effects on reducing the severity of the decline and of bringing Tuscany back from collapse. From the 18th century onward, agriculture managed a comeback. Famines didn’t disappear but could be contained while commerce and industry restarted with a new network of riverways and roads.
Not everything was perfect during this period. One problem was that Tuscany never really succeeded in stabilizing population, which slowly grew from less than half a million in 15th century to more than a million in 18th century. As a consequence, there remained a strong pressure to find new land for agriculture. So, the rules that protected trees were relaxed more than once. It is reported that, in 1780, a group of woodcutters fell on their knees in front of Grand Duke Pietro Leopoldo, pleading hunger. This resulted in a decree liberalizing tree cutting. But the mountains were reforested and the policies of protecting agriculture maintained.
Our times
With the 19th century, Tuscany merged with the newly created Italian state and the industrial revolution generated a new phase of rapid population growth and economic expansion. With the improvement of the transportation network and the development of railroads, famines became a thing of the past. The last recorded one in Tuscany was in 1898-1899. Forest suffered during this period of expansion; nevertheless, today Tuscany remains one of the most forested regions of Italy, a legacy of the policy of the old Grand-Dukes.
But times have changed and the latest wave of building frenzy seems to be transforming some of the once fertile areas of Tuscany into areas that look like suburbs of Los Angeles. With a population four times larger than it was at the time of the famines and with climate change and the oil crisis looming, Tuscany is facing difficult times. But we have a tradition of caring for the land that has helped us in the past. It will help us also in the uncertain future.
Can Tuscany be seen as a model of “soft collapse" for other regions of the world? Perhaps; at least it gives us a recipe that worked from the time of Grand Dukes: "plant trees, disband the army, work together. It is not exactly what we are doing right now, but we may learn.
This is a revised version of a post published in 2006 on the blog "Transition Culture.It was one my first posts in English and, some years later, I think it is appropriate to repost it on "Cassandra's legacy" with some modifications and corrections. I am grateful to Susan Kucera for leading me to return to this subject and for suggesting to me the analogy with the "grains on the chessboard" story .
Most of the data that I report about Tuscan agriculture in ancient times come from the book "ALPI" by Matteo Biffi Tolomei published for the first time in the early 1800s and re-published in 2004 with a post-faction by Fabio Clauser. (Libreria Editrice Fiorentina)
Data on the history of the Tuscan army at the time of the Grand Dukes are also not so easy to find, but a description can be found in "Corpi armati e ordine pubblico in Italia (XVI-XIX sec.)": Seminario di studi, Castello Visconti di San Vito, Somma Lombardo, 10-11 novembre 2000 Livio Antonielli, Claudio Donati Rubbettino Editore, 2003. For a history of the Tuscan Navy, see the relative article in Wikipedia
Data on the population of Tuscany from Middle Ages to present times can be found in the paper (in Italian) by Marco Breschi and Paolo Malanima, ""Demografia e Economia in Toscana"
A list of famines in Tuscany up to 1736 can be found in this document, by the Georgofili Academy. There aren't many data available about the famine of 1898-99 that affected all Italy and that was, probably, the last recorded famine in the country. A description can be found in this document (in Italian)
The site of the Georgofili academy.
Monday, January 21, 2013
Ugo Bardi speaks about limits to growth
This is the video record of the talk on resource depletion I gave in the University of Bielefeld, Germany, in November of 2012. It is almost one hour and a half long, so I am not sure that anyone would really want to watch it. In any case, if you are interested in the subject, you may try.
The gist of the talk, anyway, is that depletion is not an isolated problem. Minerals are part of the geological cycles of the Earth. When we extract a mineral and we disperse it all over the ecosystem we cause changes of all kinds, besides the obvious fact that we use non renewable resources. So, for instance, when we extract fossil fuels we alter the climate. The two problems: fossil fuel depletion and climate change are two sides of the same coin. And that is true of all the minerals we use - in most cases depletion is just one side of a larger problem.
Thanks to professor Marcus Kracht for having organized this presentation in Bielefeld.
Tuesday, January 15, 2013
The story of the E-Cat, the "cold fusion" device proposed by Mr. Andrea Rossi seems to be losing interest everywhere. Yesterday, Jan 14, another of Rossi's supporters, Mr. Daniele Passerini, announced that he is abandoning the fray and closing down his blog, at least for the time being.
Mr Passerini's blog, titled "22 steps of love" has been the main focus of support for the E-Cat in Italy up to now. He says in his last post, titled "ad maiora" that "Some time ago, I wrote that, after that two years would have passed from the date of January 14 2011, I would quit in any case in the absence of official and certain announcements on the reality of the E-Cat." Passerini states that he will be waiting patiently and "will return when the news that we have been waiting for during the past two years will arrive"
The closing of Mr. Passerini's blog comes after that, in November of last year, another of Mr. Rossi's supporters, Mr. Paul Story of "eCatNews" declared that he would close his blog because, "with scant hope of Rossi delivering on his promises, I find myself wondering why I would waste any more time on him. If he is committing fraud, he should be pursued by the police. Interest in the man or the subject is now relegated to the level of curiosity, not dedication."
Earlier on, in April 2012, Mr. Sterling Allen of the blog PESN (Pure Energy Systems) had been appalled at Rossi's behavior and had stated, "I apologize to anyone that I've encouraged to try and do business with Andrea Rossi, and I retract my endorsement" even though he later continued to cover announcements about the E-Cat. (*)
The supporters of the E-Cat are still numerous and the marketing techniques of Mr. Rossi have generated a remarkable number of imitators. So, what we are seeing is not likely to be the end of the story. However, these defections are a clear symptom that the interest in the E-Cat is winding down. After two years of impossible claims, missed demonstrations, broken promises, and unverifiable endorsements, no other outcome was possible.
(*)Mr. Sterling Allen commented on this post stating that "But a few months after that I felt he (Rossi) was back on a better track, and worth giving my confidence in again... Though I don't know for sure, I have a high extent of confidence in Rossi and his group.
Sunday, January 13, 2013
Can we trust the reporting of environmental issues by the mainstream media?
Guest Post by Max Iacono:
Among the various lessons we learned in 2012 there is also whether or not the so-called “mainstream media” really can be trusted to tell the truth about environmental issues. Or can it be trusted to do just the opposite, and in various diverse and difficult to detect ways?
This additional “lesson to be learned” is in fact the subject of an entire excellent –and also recently published book by the title “Project Censored 2013”, which describes quite well many of the important issues which the mainstream media has mostly (or fully) censored, or completely misled us about, over this past year or so.
The book is available on Amazon in both Kindle and hard copy versions. I recently purchased it and have been reading it. I thought the Foreword by Dr. Nafeez Mosssadeq Ahmed was particularly clear and convincing and nicely summed up the current situation with respect to mainstream media censorship of “inconvenient topics” and in particular those which are of interest and concern to Cassandra Legacy readers and that deal with the environment and its various aspects. And also with Al Gore’s extremely “inconvenient truth” which is becoming more and more inconvenient by the day to some, but much more convenient to the millions or even billions of people who think something should be done urgently about climate change. Some have said that the ratio of persons on one side to those on the other is 1 to 99 (or 99 to 1) but I will leave that particular quantitative aspect aside for the time being.
The book –and this particular post which tries to give an idea of what the book is about - also offers an additional perspective or amicable warning to us all regarding the ubiquitous “mainstream media” - is also a kind of logical follow-on to my own earlier post on Cassandra Legacy by the title “Limits to Growth” : An Alternative History
In that post I tried to argue that the old book Limits to Growth (first published in 1972) might have been better received -or at least less poorly received and less “demonized”- if it had taken into account in its World Model (or at least had done so qualitatively, separately) not only the variables which it did consider and model –namely a series of economic, industrial, resources, pollution, and demographic variables all in interaction within its dynamic systems model-, but also selected variables of culture, identity, politics, political science, political economy, societal institutions, and ideology.
This second set of variables I believe were those that had caused the book to be “demonized” once its central message that there are limits to growth and that “economic growth forever” is not possible on a finite planet, clearly came up against them, in the so called real (social) world. That is, “the real world” of business, politics, economics, religions, and their various academic disciplines and professions, and up against their many representatives and advocates. And this also since to many who are active in those disciplines and professions apparently the “real world of physics, chemistry and biology” (and ecology) regrettably is either considered to be “pretty unreal” or is secondary, or at least is not particularly worthy of much serious or top priority policy consideration. And of course one very important player in that broad social context -and one which also significantly influences and affects all the rest- is the so-called mainstream (or corporate) media in all of its forms. That is, mainstream –and generally corporate-owned, newspapers, magazines, TV channels, radio, and etc. etc. including also some Internet media.
Did the mainstream media “inform” the wider public, or did it misinform, or “dis-inform and mislead” the public with respect to the book Limits to Growth? And even more significant at this specific time, is it informing or dis-informing right now with respect to the ongoing and continuing significant range of serious environmental problems, topics and issues? And in particular with respect to climate change, peak oil, limits to growth and other particularly important environmental topics and issues such as Arctic methane, ocean acidification, Arctic and Antarctic ice melt, diminishing or dwindling fish stocks, biodiversity and habitat loss, ongoing deforestation, advancing desertification, and several others. The reader can make up her / his own mind about that, but I would like to offer the following for consideration:
First, below follows a list of the titles of the 15 chapters of the book Project Censored 2013 which provides a pretty good idea of what topics those who wrote or compiled the book –and there were many contributing chapter authors- think the mainstream media has either censored or lied to us (the wider public) about. And, moreover, most often in quite clever and deceptive ways which are very difficult to detect, pick up and deconstruct. And for those who may be interested in reviewing some of the specific ways and techniques through which the mainstream media (in this specific instance Fox News Channel) (but they are by no means the only ones) lies to us and tries to deceive us, they can read the following very good article which summarizes their top 14 techniques: “Fourteen Propaganda Techniques Fox “News” Uses to Brainwash Americans
Some of the topics and book sections in “Project Censored 2013” deal with some of the main issues treated by Cassandra Legacy -namely climate change, peak oil and limits to growth- and some deal instead with other issues related to politics, democracy, and U.S. foreign and domestic policy, which often are equally censored or lied about. And if one reads the book one might also consider quite apt an alternative possible title for the book that I came up with myself (only in “jest”) and namely:
“Project Dissembled, Denied, Distorted, Delayed, Deleted, Deflected and Deceived
About by the Mainstream Media”, or perhaps more succinctly and humorously simply “Mainstream Media Project-7D”. In any case, here is the list of the book’s chapters:
1. “The top 25 Censored Stories from 2011-2012 and Censored News. Clusters:
i) The Police State and Civil Liberties
ii) From “Bankster Bailout” to “Blessed Unrest”: News we can use to create a US economy for the 99 percent
iii) Environment and Health
iv) Human Costs of War and Violence
v) Women and Gender, Race and Ethnicity
2. Déjà vu: What happened to previous censored stories?
3. American Idle: Junk Food News, News Abuse, and the Voice of Freedumb
4. Media Democracy in Action
5. Ownership Backfires: A Taxonomy of Concepts Related to Censorship
6. The Global 1 Percent Ruling Class Exposed
7. The Information War: How Government is Seeking Total Information Awareness and What This Portends for Freedom and Democracy
8. GerM Warfare: How to Reclaim the Education Debate from Corporate Occupation
9. Kent State: Was it about Civil Rights or Murdering Student Protesters?
10. The Creative Tension of the Emerging Future: Facing the Seven Challenges of Humanity
11. Guantanamospeak and the Manufacture of Consent
12. Framing Al-Awlaki: How Government Officials and Corporate Media Legitimised a Targeted Killing
13. A Morally Disengaged America: Sacrificing Iraqi Refugees to Terrorism Fears and Anti-Immigration
14. On the Road to Fukushima: The Unreported Story Behind Japan’s Nuclear-Media-Industrial Complex
15. An Occupation of Truth: Indian Administered Kashmir”
As a conclusion, below I add a quote containing several specific examples regarding the recent treatment by the mainstream media of peak oil and climate change –including also what Dr. Nafeez Mosaddeq Ahmed says about each- in his excellent foreword to the book.
At a time when the world faces tipping points in the escalation of multiple crises, the publication of this volume is of momentous significance.
As I write, a sampling of the latest “mainstream” corporate news illustrates the unprecedented nature of our current predicament as a civilization. The bizarre and extreme weather of the early United States summer prompted one leading climate scientist to state boldly that we are “certainly seeing climate change in action,” as a window on a worsening future. Record-shattering heat waves, wildfires, and freak storms are a taste of things to come – “This is just the beginning” said one meteorologist.
Simultaneously, the International Monetary Fund cut its growth forecast for the US economy, warning that the ongoing Eurozone crisis, along with the weak housing market, risks triggering a recession by 2013 while the jobless rate morphs into “higher structural unemployment”.
As the defunct neoliberal model of casino capitalism wreaks havoc at home, it is doing the same abroad. Global food prices doubled between 2006 and 2008, and despite some fluctuation, remain largely at record levels. One of the key causes has been speculation in derivatives –thirteen trillion dollars was invested in food commodities in 2006, then pulled out in 2008, and then reinvested again by 2011. The rocketing food prices for the global poor have generated an unprecedented global food crisis across the developing world
But another driver of the food crisis is climate change, which has already led to crop failures in key food basket regions. This is only going to get worse on a business-as-usual model, which could lead to a minimum 4 degrees Celsius rise by mid-century. Even a 2-degree rise could lead to a minimum 4 degrees Celsius rise by mid-century. Even a 2-degreee rise would lead to dramatic crop failures and soaring meat prices; at 4 degrees Celsius, rice crops could be reduced by about 30 percent, leading to global food shortages and hunger.
Amid this escalating frenzy of perfect storms, however, over the last year the corporate media has focused on one apparent light at the end of the tunnel: unconventional oil and gas. “Has Oil Peaked? Read one headline in the Wall Street Journal. Across the pond, BBC News asked, “Shortages: Is ‘Peak Oil’ Idea Dead?” Environmentalists have also jumped on the bandwagon. Andrew C. Revkin in the New York Times took “A Fresh Look at Oil’s Long Goodbye, while George Monbiot wrote in the Guardian that “We Were Wrong on Peak Oil. There’s Enough to Fry Us All”
The essence of this uniform message is that the new drilling methods – like hydraulic fracturing, i.e. “fracking” among others- have allowed the fossil fuel industry to exploit previously untapped reserves of tar sands, oil shale, and shale gas, bringing them to market at much cheaper prices than hitherto imaginable, and effectively turning the US from net oil importer into a leading exporter.
But it should come as no great surprise to Project Censored readers that, once again, the corporate news media has obfuscated the facts. The latest figures from the US Energy Information Administration (EIA) confirm that the supposedly massive boost in unconventional oil production that is pitched to launch the world into a glorious future of petroleum abundance – capable of sustaining the wonders of capitalist economic growth ad infinitum – has had negligible impact on world oil production. On the contrary, despite the US producing a “total oil supply” of ten million barrels per day – up by 2.1 million since January 2005 – world crude oil production remains on the largely flat, undulating plateau it has been on since it stopped rising around that very year. As reported by oil markets journalist Gregor Macdonald, who has previously reported for the Financial Times and Harvard Business Review, among other publications:
Since 2005, despite a phase transition in prices, global oil production has been trapped below a ceiling of 74 mmbpd (million barrels per day). New production from new fields and new discoveries comes on line, but it has not been at a rate fast enough to overcome declines from existing fields. Overall, global decline has been estimated at a minimum of 4% per year and as high as 6+% pa year. Given that new oil resources are developed and flow at much slower rates, the existing declines present a formidable challenge to the task of increasing supply I see no set of factors, in combination that would take global production of crude oil higher in 2012, or next year, or thereafter.
Yet this stark fact has not been reported in any mass media news outlet whatsoever, anywhere in the world. Indeed, Macdonald points out that data from British Petroleum’s Statistical Review of World Energy shows that oil’s heyday is well and truly in decline. In 1973, oil as a percentage of global energy use had peaked at around 48.5 percent. Forty years later, “oil is barely hanging on as a the world’s primary energy source, with a much reduced role as a supplier of only 33.5% of all world energy consumption.”
The disparity in reporting is instructive. In June 2012, the corporate media focus on the unconventional oil boom revolved around one study in particular by oil company executive Leonardo Maugeri – former executive vice president of Italian oil major ENI. The report was not peer-reviewed but as published at Harvard University’s Belfer Center for Science and International Affairs by the Geopolitics of Energy Project, “which is supported in part by a general grant from the (same) oil major (i.e. ENI),” conceded the WSJ. Hardly an impartial perspective, then.
Meanwhile, a series of peer-reviewed reports by independent scientists published in highly reputable science journals from January through to June 2012 – Science, Nature, and Energy – have been blacked out in corporate news reporting. In Energy Gail Tverberg documented that since 2005, “world oil supply has not increased”, that this was “a primary cause of the 2008-2009 recession,” and that the “expected impact of reduced oil supply” will mean the “financial crisis may eventually worsen.” An even more damning analysis was published in Nature by James Murray and Sir David King, the latter being the British government’s former chief scientific adviser. Murray and King’s analysis found that despite reported increases in oil reserves, tar sands production, and hydrofracturing-generated natural gas, depletion of the world’s existing fields is still running at 4.5 percent to 6.7 percent per year, and production at shale gas wells could drop by as much as 60 to 90 percent in the first year of operation
Curiously forgotten in the spate of reporting on the opportunities opened up by fracking is a New York Times investigation from 2011, which found that “the gas may not be as easy and cheap to extract from shale formations deep underground as the companies are saying, according to hundreds of industry e-mails and internal documents and an analysis of data from thousands of wells.” The e-mail revealed industry executives, lawyers, state geologists, and market analysts voicing “skepticism about lofty forecasts” and questioning “whether companies are intentionally, and even illegally, overstating the productivity of their wells and the size of their reserves.” A year later, it seems, such revelations were merely destined for their memory hole”
Following the above opening section the Foreword to the book goes on to describe additional examples and also the role which a book such as “Project Censored 2013” can play in at least exposing the disinformation or the non-information so often “put out” or censored by the mainstream media. Which is something it often does instead of putting forward real facts and truthful stories and their respective most plausible and most sensible overall descriptive or explanatory or prescriptive narratives, which could help tie together and integrate i.e. “connect the dots” regarding the important evidence and facts, and thereby also support and be able to provide significant help to those who are concerned and are trying to do something about the issues….through their various ongoing struggles. And I say “ongoing” because the key issues and problems (already listed above) are certainly NOT going to go away in 2013. So we had better be ready also for the long haul and will need all of the intellectual and other help we can get. And having access to accurate, reliable and valid information is of course quintessential, just as it is quintessential for democracy itself to function properly.
But I am not a “conspiracy theorist” and moreover nothing is black and white. Is all of the “mainstream media” and its countless writers and protagonists equally bad and misleading or is it always omitting important stories, and is it bad and lying all of the time and in every instance? And is everything which is reported in the “non-mainstream” media always factual, truthful and correct? And although “exceptions often prove the rule” there remains always, and in any case, a key element of personal responsibility to try to figure out what actually is true or false and what is just or fair or not, and which narratives and story-lines make the most sense and which do not. So it is probably also useful to try to consult multiple sources even if perhaps only one among the many later will be shown to have contained the facts and have been correct. Also remembering of course that a lie or a deception repeated fifty times, is still a lie. But I think it can be of great “ex ante” “heuristic help” when navigating the information territory to know at least generally speaking who one’s friends are -and whether they are only “fair weather” friends and NOT also “fair climate” friends- and who instead are the self-serving liars and the promulgators of assorted exercises in deception, i.e. “the spin starts here” sorts of people.
Friday, January 4, 2013
A New Year's tale
In 1960, Vladimir Dudintsev (1918-1998) published a short novel titled "A New Year's tale." This story greatly impressed me when I read it, many years ago, in an Italian translation in a collection titled "Russian Science Fiction"
Some 50 years ago, I received as a Christmas present a book titled "Russian Science Fiction." All the stories in that book made a deep impression on me, but there was one that has remained in my mind more than the others; a curious story titled "A New Year's Tale".
I was, maybe, 12 at that time and, of course, I couldn't understand everything of that story and I didn't pay attention to the name of the author. But, as time went by, I didn't forget it; rather, it became entrenched in my mind, progressively acquiring more meaning and more importance. I reread it not long ago, and it came back to my mind during a recent trip to Russia. So, let me tell you this story as I remember it.
"A New Year's Tale" tells of one year of life of the protagonist, a researcher in a scientific laboratory somewhere in the Soviet Union. Dudintsev manages to tell the story without ever giving specific details about anything: no place names, no names of the characters, not even of the protagonist. It is a feat of literary virtuosity; it gives to the story an atmosphere of fairy tale but, at the same time, it is very, very specific.
It took me time before I could understand the hints that Dudintsev gives all over the text, but after many trips to Russia everything fell in place. It is curious how Dudintsev managed to catch so well the atmosphere of a research lab in the Soviet Union; he was not a scientific researcher. But that's what makes a great story teller, after all: understanding what one is describing - and feeling something for it.
The story starts with a debate - rather, a quarrel - that the protagonist has with someone termed "a provincial academic" (of course, we are not told his name). This provincial academic should be nothing more than a nuisance, but the protagonist can't stop from engaging in the debate. He understands that he is losing time, that he should be doing something more useful, more important. But he just can't sit down and do his job.
While the protagonist is entangled in this useless quarrel, the chief of the laboratory (again, we are not told his name) dabbles in archeology and one day he tells his coworkers of a research of his somewhere in the Caucasus, where they found an ancient tomb. There was an owl engraved on the tombstone and an inscription that they could decipher. It says "...and the years of his life were 900...."
Now, what could that mean? Could the man buried there have lived 900 years? No, of course not. But then, what does the inscription mean? Well, someone says, that must mean that this man spent his life so well and so fully that it was like his years had been 900.
The discussion goes on. What does it mean to live such a full life? The researchers try to find an answer but, at some moment, they hear the voice of someone who usually keeps silent at these reunions. We are told that he is from far away, not Russian, that is. We can imagine that this man doesn't have a Russian name, but we are not told names. So, he is an outsider and he comes with a completely different viewpoint; let me call him "the foreign scientist" even though in the old Soviet Union, theoretically, there was no such distinction. "You see, comrades," he says, "it is very simple. To live a full life, you must always choose the greatest satisfactions, the highest joys you can find."
At this point, we hear the voice of the political commissioner of the lab. Apparently, there was usually someone in scientific academies in the Soviet Union who was in charge of making sure that Soviet Scientists would not fall into doing decadent capitalist science. So, he stands up and he tells the foreign scientist, "Well, comrade, don't you think one should also work for the people or something like that?" And the foreign scientist answers, "You are so backward, comrade. Don't you understand? The greatest satisfaction, the highest joy one can have in life is exactly that: working for the people!"
After that the discussion is over, the protagonist of the story reflects on the words of the foreign scientist and he resolves to start doing something serious in his life. He decides to start doing experiments, advance his theory. We are not told exactly what he is doing, but we understand that he is working on something important; a great discovery that has to do with capturing and storing solar light. And he manages to work on that for some time. Then, his colleagues bring to him another paper written by his provincial antagonist. So, he feels he has to answer that, and then the provincial academician responds.... and the protagonist finds himself entangled again into this argument that he can't abandon.
Things are back to the silly normalcy of before, but then something happens. The protagonist finds that he is being stalked. Someone, or something, is following him all the time. When he sees it in full he discovers that it is an owl. A giant owl, almost as big as a man, looking at him. He thinks it is a hallucination, which of course it must be. But he keeps seeing this owl over and over.
So, the protagonist goes to see a doctor and the doctor asks him what made him come there. "An owl" he says, and the doctor pales. After a thorough physical examination the doctor tells him: "you have one year to live, more or less." We are not told of what specific sickness the protagonist suffers. He asks, "but why the owl?" And the doctor answers, "we are studying that. You are not the only one. The owl is a symptom." Then, the doctor looks at the protagonist straight in his eyes and he says, "I can tell you something. Those who see the owl, have a chance to be saved."
In the meantime, there had been a long discussion between the protagonist and the foreign scientist, the one who had so well silenced the political commissioner. So, the foreign scientist had told to the protagonist his story, obliquely, yes, but clearly understandable. His fellow countrymen had not liked the idea that he had left the country to become a scientist. They are described as gangsters and criminals, but we have a feeling that there was something more at stake than just petty crimes. This man had made a choice and that had meant to make a clean break from his country and his culture; it had meant to accept the new Soviet Communist society. Now, he was spending his time in this new world trying to get his "greatest satisfactions and highest joys" by working for the people. And, because of that, his former countrymen had condemned him to death. So, he had changed his name and his identity, and he had even surgically changed his face to become unrecognizable. But he knew that "they" were looking for him and they would find him at some moment.
So, the destiny of the protagonist and of the foreign scientist are somehow parallel, they both have a limited time. After having seen the doctor, the protagonist understands the situation and he rushes to search for the foreign scientist. They can work together, they can join forces, in this way, maybe they can.... but in horror he discovers that the scientist has been killed.
In panic, the protagonist desperately looks for the notes he had collected over the years. But the cleaning lady tells him that she had used them to start the fire in the stove. She had no idea that they could have been important. The protagonist feels like he is walking in a nightmare. Just one year and he has lost his notes. He starts from scratch.... his great discovery.... how can he do? Yet, he decides to try.
He becomes absorbed in his work. He works harder and harder. Staying in the lab night and day and, when he goes home, he keeps working. His colleagues note the change; they are surprised that he doesn't react any more to the attacks of the provincial academician, but he doesn't care (which is, by the way, a good lesson on how to handle Internet flames). He still sees the owl; always bigger and coming closer to him, the owl has become something of a familiar creature, almost a friend.
Then, someone appears. It is a woman with well formed shoulders (of course, we are not told her name!). The protagonist recognizes her. It is not the first time he has seen her. He remembers having seen her with the now dead foreign Scientist.
The protagonist has no time for a love story. He has to work. He tries to ignore the woman but he is also attracted to her. He can concede her just a few words. Ten minutes, maybe. So they talk and the woman tells him. "It is you, I recognize you! You can't fool me!" The protagonist remembers something that the foreign scientist had told him; that he had his face surgically changed to escape from his enemies. Now, this woman thinks that the protagonist is really her former lover, who changed again face and appearance and didn't tell that not even to her.
The protagonist tries to deny that he is the former lover of the woman but, curiously, he doesn't succeed, not even to himself. In a way, he becomes the other, acting like him in his complete immersion in his work. The protagonist discovers that the foreign scientist had assembled a complete laboratory at home, much better than the lab at the academy. So he moves there, with the woman with the well formed shoulders (and the owl comes, too, perching on a branch just outside the window). Then, the protagonist even discovers that the foreign scientist was secretly copying his notes and he gave them to the woman, who has kept them for him. With these notes, he can gain months of work. Maybe he can make it in one year, maybe.....
The last part of the story goes on at a feverish pace. The protagonist becomes sicker and sicker; to the point that he has to stay in bed and it is the woman with the well formed shoulders who takes up the work in the lab. And the owl perches on the bed head. But they manage to get some important results and that's enough to catch the attention of the lab boss. He orders to everyone in the lab to come there and help the protagonist (and the woman with the well formed shoulders) to move on with the experiments.
In the final scene, the year has ended and we see the protagonist in bed, dying. But his colleagues show him the results of the experiment: something so bright, so beautiful; we are not told exactly what: anyway it is a way to catch sunlight in a compact form: a new form of energy, a new understanding of the working of the sun - we don't know, but it is something fantastic. Even the owl looks at that thing, curious. The protagonist hears the sound of bells from the window. A new year is starting. We are not told whether he lives or not, but in any case it is a new beginning and, whatever it happens, they'll tell of him that the years of his life had been 900.
And here we are. You see, it is a magic story. It keeps your attention; you want to know if the protagonist lives or not and you want to know if he manages to make his great discovery. But it is also the story of the life and of the mind of scientists that I think you can't find anywhere else in novels or short stories. It is curious that Dudintsev did so well because, as I said, he wasn't a scientist; he was a literate. But he managed to catch so incredibly well the life of a scientist - of a scientist working in the Soviet Union, yes, but not just that. Dudintsev's portrait of science and scientists goes beyond the quirks of the old Soviet world.
Yes, in Soviet science there were things that look strange for us, such having a political commissioner in the lab to watch what scientists are doing. But that's just a minor feature and today we have plenty of different constraints on what we do that don't involve a dumb political commissioner. The point is that scientists often work as if their life were to last just one year; at least during the productive time of their life; when they are trying to compress each year as if it were to be 900 years long. It is their lot: the search for the discovery, being so deeply absorbed in their work, being remote from everyone else; obsessed with owls that they alone can see.
And yet, Dudintsev's story is so universal that it goes beyond the peculiar mind of scientists. It is the story of all men, all over the world, of what we do and how we spend our life. And the key of the story is the woman with the well formed shoulders. She recognizes her former lover in the protagonist, or she feigns to recognize him. It is him or it is not him - it doesn't matter, but her devotion to her man is so touching: you perceive true love in this attitude. In the end, that's the key of the whole story: whatever we do in life, we do it for those we love.
Some of us are scientists, some aren't. But it is not a bad advice to live your life as if you wanted each year to be 900 years long. And every new year is a new beginning.
Thursday, January 3, 2013
What future for petroleum?
by Marco Pagani
x y
Crude oil 20 0,95
To be developed 5 0,80
To be discovered 3 0,67
LNG 5 0,80
Non conventional oil 2 0,50
Shale Oil 2 0,50
Tuesday, January 1, 2013
The cracked pot: a little hope for 2013
Painting by Giovanni Segantini (1858-1899)
The old story of the cracked pot explains the basic mechanism of the universe. The continuous spilling of energy from one energy level to another is the true engine of creation that generates those structures that we call "life". Real perfection, apparently, lies in a little imperfection.
Of course, the perfect pot was proud of its accomplishments.
h/t "Attack on Earth"
|
Coal has a rich heritage in West Virginia and has contributed significantly to the progress and well-being of West Virginians since it was first discovered in what is now Boone County in 1742 by Peter Salley, more than a century before West Virginia became a state.
The coal industry has played a major leadership role in the state’s economic, political and social history. The industry has also been a center of controversy and the brunt of unfounded criticism, giving rise to battles in the arenas of labor, environment and safety. It was coal that transformed West Virginia from a frontier state to an industrial state. Coal in 62 recoverable seams can be found in 43 of the state’s 55 counties.
The first widespread use of West Virginia coal began when the salt works along the Kanawha River expanded dramatically in the decades before the Civil War. Coal was used to heat the brine pumped from salt beds underneath the river. That modest use soon was dwarfed by the demands of a growing nation that looked to coal to heat its homes, power its factories and fuel its locomotives and steamships. When the anthracite fields of Pennsylvania no longer could provide the tonnage needed, American industrialists discovered the massive coalfields of West Virginia. Large-scale investment soon opened the remote valleys along the New, Bluestone, Tug, Monongahela, and Guyandotte rivers.
The Chesapeake & Ohio and Norfolk & Western railroads were built specifically to penetrate the rugged terrain of the coalfields, and investors purchased extensive tracts of land to lease to independent coal operators, Later, the Virginian and the Baltimore & Ohio also became coal-hauling lines as well. In those days, coal mining was highly labor intensive, but only a few rugged mountaineers lived in the remote, isolated hills and hollows where the operations developed. Thus, operators recruited much of their labor from two human migrations underway around 1900. Thousands of African-Americans fleeing discrimination and segregation left the Deep South, and many exchanged the poverty of the cotton fields for the bustling coalfields. Meanwhile, European immigrants fleeing religious persecution and impending war came to America to find jobs and homes, and many came from coal-bearing regions of Europe to the prosperous mines in West Virginia.
Today many decry conditions in the “coal camps,” but miners and their families fared as well as most working class Americans, and better than those unfortunate souls who labored in urban sweatshops or as rural sharecroppers.
West Virginia’s coalfields were home to some of the most significant labor strife in this nation’s history, as the United Mine Workers battled coal operators for control of the industry. Spectacular incidents such as the famed Matewan Massacre and the Battle of Blair Mountain, landmarks in American labor history, showed the strategic importance of the state’s crucial industry, and its national significance.
Today, West Virginia’s coal industry contains more than 500 mines, provides more than 44,000 direct and contract jobs, pays $1 billion dollars in annual payroll and hundreds of million dollars to state and local governments in taxes and contributions. Coal is still the rock-solid backbone of West Virginia’s industrial economy.
|
Deep-space communication improved with electromagnetic radiation antenna
- Robert C. Dye
- Technology Transfer
- (505) 667-3404
Electromagnetic radiation antenna has potential for deep-space communication
- Directed Energy
- Long-range communications
- Medicine (Oncology)
- RADAR imaging applications are countermeasure-resistant
- Communications can be spatially-encrypted
- 4-dimensional volumes of energy can be aimed at a single space-time point for directed energy applications
- Nonspherical decay of the cusp enables low-power communications and propagation over great distances
Los Alamos National Laboratory (LANL) researchers have developed the Lightslinger, a completely new type of antenna that produces tightly-focused packets of electromagnetic radiation fundamentally different from the emissions of conventional transmitters. The device has potential applications in RADAR, directed-energy (non-kinetic kill), secure communications, ultra-long-range communications (e.g., deep-space), medicine (oncology) and astrophysics.
The Lightslinger functions by producing a moving polarization pattern in a ring of alumina. By careful timing of voltages applied to electrodes that surround the alumina, the polarization pattern can be made to move superluminally, i.e., faster than the speed of light in a vacuum. Nobel laureate Vitaly Ginzberg showed both that such superluminal polarization patterns do not violate the principles of special relativity and that they emit electromagnetic radiation. Once a source travels faster than the waves that it emits, it can make contributions at multiple retarded times to a signal received instantaneously at a distance. This effect is already well known in acoustics; when a supersonic airplane accelerates through the speed of sound, a violent “sonic boom” is heard many miles away, even if the airplane itself is rather quiet. The Lightslinger enables the same thing to be done with electromagnetic radiation; i.e., a relatively low-power source can make an “electromagnetic boom”, an intense concentration of radiowaves at a great distance.
The “electromagnetic boom” is due to temporal focusing, that is, focusing in the time domain. Because of this effect, part of the emitted radiation possesses an intensity that decays with distance r as 1/r rather than as the conventional inverse square law, 1/r2. These nonspherically-decaying wavepackets represent a game-changing technology in the applications of electromagnetic radiation.
Development stage: Working prototype
Patent status: Patent pending
Licensing status: Available for exclusive or non-exclusive licensing
|
#ifndef BF_ASSETIO_MODEL_LOADER_HPP
#define BF_ASSETIO_MODEL_LOADER_HPP
#include "bf/memory/bf_imemory_manager.hpp" // IMemoryManager
#include "bf/bf_api_types.h" // bfStringRange
#include "bf/bifrost_math.hpp" // Math Structs
#include <array> // array
#include <cstdint> // uint32_t
#include <memory> // uninitialized_fill_n
namespace bf
{
using AssetIndexType = std::uint32_t;
////////////////////
struct AABB final
{
float min[3];
float max[3];
AABB() = default;
AABB(const bfTransform& transform);
AABB(const Vector3f& vmin, const Vector3f& vmax)
{
min[0] = vmin.x;
min[1] = vmin.y;
min[2] = vmin.z;
max[0] = vmax.x;
max[1] = vmax.y;
max[2] = vmax.z;
}
Vector3f center() const
{
return {
(max[0] + min[0]) * 0.5f,
(max[1] + min[1]) * 0.5f,
(max[2] + min[2]) * 0.5f,
1.0f,
};
}
Vector3f dimensions() const
{
return {
(max[0] - min[0]),
(max[1] - min[1]),
(max[2] - min[2]),
0.0f,
};
}
Vector3f extents() const
{
return dimensions() * 0.5f;
}
bool canContain(const AABB& rhs) const
{
for (int i = 0; i < 3; ++i)
{
if (rhs.min[i] < min[i] && !math::isAlmostEqual(min[i], rhs.min[i]) ||
rhs.max[i] > max[i] && !math::isAlmostEqual(max[i], rhs.max[i]))
{
return false;
}
}
return true;
}
bool operator==(const AABB& rhs) const
{
for (int i = 0; i < 3; ++i)
{
if (!math::isAlmostEqual(min[i], rhs.min[i]) || !math::isAlmostEqual(max[i], rhs.max[i]))
{
return false;
}
}
return true;
}
bool operator!=(const AABB& rhs) const
{
return !(*this == rhs);
}
};
namespace aabb
{
/*!
* @brief
* Creates a new bounding box that contains both \p a and \p b.
*
* @param out
* The result of this function.
*
* @param a
* The first AABB to merge.
*
* @param b
* The second AABB to merge.
*/
inline void mergeBounds(AABB& out, const AABB& a, const AABB& b)
{
for (int i = 0; i < 3; ++i)
{
out.min[i] = a.min[i] < b.min[i] ? a.min[i] : b.min[i];
out.max[i] = a.max[i] > b.max[i] ? a.max[i] : b.max[i];
}
}
inline AABB mergeBounds(const AABB& a, const AABB& b)
{
AABB out; // NOLINT
mergeBounds(out, a, b);
return out;
}
inline void expandBy(AABB& self, float amount)
{
for (int i = 0; i < 3; ++i)
{
self.min[i] = self.min[i] - amount;
self.max[i] = self.max[i] + amount;
}
}
inline AABB expandedBy(const AABB& self, float amount)
{
AABB clone = self;
expandBy(clone, amount);
return clone;
}
inline float surfaceArea(const AABB& self)
{
const float d[3] =
{
self.max[0] - self.min[0],
self.max[1] - self.min[1],
self.max[2] - self.min[2],
};
return 2.0f * (d[0] * d[1] + d[1] * d[2] + d[2] * d[0]);
}
inline AABB fromPoints(const Vector3f* points, std::size_t num_points)
{
AABB result;
result.min[0] = result.max[0] = points[0].x;
result.min[1] = result.max[1] = points[0].y;
result.min[2] = result.max[2] = points[0].z;
for (std::size_t i = 1; i < num_points; ++i)
{
const Vector3f& point = points[i];
result.min[0] = std::min(result.min[0], point.x);
result.min[1] = std::min(result.min[1], point.y);
result.min[2] = std::min(result.min[2], point.z);
result.max[0] = std::max(result.max[0], point.x);
result.max[1] = std::max(result.max[1], point.y);
result.max[2] = std::max(result.max[2], point.z);
}
return result;
}
AABB transform(const AABB& aabb, const Mat4x4& matrix);
} // namespace aabb
////////////////////
struct Mesh
{
AssetIndexType index_offset;
AssetIndexType num_indices;
std::uint32_t material_idx;
};
static constexpr std::size_t k_MaxVertexBones = 4;
static constexpr std::size_t k_MaxBones = 128;
struct AssetModelLoadResult;
struct AssetModelLoadSettings;
AssetModelLoadResult loadModel(const AssetModelLoadSettings& load_settings) noexcept;
// Lovely Simple DataStructures that lend themselves to a linear allocator.
//
// Due to this using a 'Variable Length Member' anytime you store an object of
// this type it should be a pointer as it always needs to be dynamically allocated.
// T must be default constructable.
//
template<typename T>
struct AssetTempArray
{
std::size_t length; //!< The number of elements in 'AssetTempArray::data'.
T data[1]; //!< Fake Variable Length Member, really 'AssetTempArray::length' in size.
T* begin() noexcept { return data; }
T* end() noexcept { return data + length; }
};
// using AssetTempString = AssetTempArray<char>;
template<std::size_t kSize>
struct AssetTempString
{
std::size_t length;
char data[kSize];
operator bfStringRange() const noexcept
{
return {data, data + length};
}
operator bool() const noexcept
{
return length != 0;
}
void copyOverString(const char* src, std::size_t src_length) noexcept
{
src_length = std::min(kSize - 1, src_length);
std::memcpy(data, src, src_length);
length = src_length;
data[src_length] = '\0';
}
};
using AssetTempLargeString = AssetTempString<1024>;
using AssetTempSmallString = AssetTempString<256>;
template<typename T>
AssetTempArray<T>* allocateTempArray(IMemoryManager& mem, std::size_t num_elements, T default_value = T()) noexcept
{
static_assert(std::is_trivially_destructible_v<T>, "Destructors of T will not be called.");
AssetTempArray<T>* result = new (mem.allocate(offsetof(AssetTempArray<T>, data) + sizeof(T) * num_elements)) AssetTempArray<T>;
result->length = num_elements;
std::uninitialized_fill_n(result->data, num_elements, default_value);
return result;
}
template<typename T>
void deallocateTempArray(IMemoryManager& mem, AssetTempArray<T>* temp_array)
{
temp_array->~AssetTempArray<T>();
mem.deallocate(temp_array, offsetof(AssetTempArray<T>, data) + sizeof(T) * temp_array->length);
}
// The Meats and Bones
struct AssetModelLoadSettings
{
private:
bfStringRange file_path;
IMemoryManager* memory;
bool import_animations;
bool import_lights;
bool import_cameras;
bool smooth_normals;
bool row_major;
float scale_factor;
public:
///
/// 'filename' is not required to be nul terminated :)
///
AssetModelLoadSettings(bfStringRange filename, IMemoryManager& mem) noexcept :
file_path{filename},
memory{&mem},
import_animations{true},
import_lights{false},
import_cameras{false},
smooth_normals{true},
row_major{false},
scale_factor{1.0f}
{
}
AssetModelLoadSettings& importAnimations(bool value)
{
import_animations = value;
return *this;
}
friend AssetModelLoadResult bf::loadModel(const AssetModelLoadSettings&) noexcept;
};
namespace PBRTextureType
{
enum
{
DIFFUSE,
NORMAL,
METALLIC,
ROUGHNESS,
AO,
MAX,
};
}
struct AssetModelVertex
{
Vector3f position;
Vector3f normal;
Vector3f tangent;
Vector3f bitangent;
color4f color;
Vector2f uv;
float bone_weights[k_MaxVertexBones];
std::uint8_t bone_indices[k_MaxVertexBones];
};
namespace detail
{
template<typename T>
struct PtrDeleter
{
IMemoryManager* memory;
void operator()(T* ptr) const noexcept
{
deallocateTempArray(*memory, ptr);
}
};
template<typename T>
using Ptr = std::unique_ptr<T, PtrDeleter<T>>;
template<typename T>
Ptr<T> makeUnique(T* ptr, IMemoryManager* owning_allocator) noexcept
{
return Ptr<T>(ptr, PtrDeleter<T>{owning_allocator});
}
template<typename T>
Ptr<AssetTempArray<T>> makeUniqueTempArray(IMemoryManager& mem, std::size_t num_elements, T default_value = T())
{
return makeUnique(allocateTempArray(mem, num_elements, std::move(default_value)), &mem);
}
//
// This pointer nulls itself out when moved.
//
template<typename T>
struct MovablePtr
{
T* ptr = nullptr;
MovablePtr() = default;
MovablePtr(MovablePtr&& rhs) noexcept :
ptr{std::exchange(rhs.ptr, nullptr)}
{
}
MovablePtr& operator=(MovablePtr&& rhs) noexcept = delete;
MovablePtr& operator=(T* rhs) noexcept
{
// assert(!ptr);
ptr = rhs;
return *this;
}
T& operator[](int i)
{
return ptr[i];
}
const T& operator[](int i) const
{
return ptr[i];
}
operator T*() const
{
return ptr;
}
};
} // namespace detail
struct AssetPBRMaterial
{
AssetTempLargeString textures[PBRTextureType::MAX];
float diffuse_color[4];
bool isOpaque() const { return diffuse_color[3] == 0.0f; }
};
struct AnimationKey
{
double time;
float data[4];
};
// all_keys = [pos, rot, scale]
struct ModelAnimationChannel
{
AssetTempSmallString name = {};
AssetTempArray<AnimationKey>* all_keys = {};
std::uint32_t rotation_key_offset = 0u;
std::uint32_t scale_key_offset = 0u;
std::uint32_t num_position_keys = 0u;
std::uint32_t num_rotation_keys = 0u;
std::uint32_t num_scale_keys = 0u;
};
struct ModelAnimation
{
AssetTempSmallString name = {};
double duration = 0.0; // Duration in ticks.
double ticks_per_second = 0.0; // Ticks per second. 0 if not specified in the imported file
AssetTempArray<ModelAnimationChannel>* channels = {};
};
using Matrix4x4f = ::Mat4x4;
struct AssetNode
{
AssetTempSmallString name = {};
Matrix4x4f transform = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
std::uint8_t model_to_bone_idx = static_cast<std::uint8_t>(-1);
unsigned int first_child = static_cast<unsigned int>(-1);
unsigned int num_children = 0;
};
struct ModelSkeleton
{
Matrix4x4f global_inv_transform;
unsigned int num_nodes;
detail::MovablePtr<AssetNode> nodes;
std::uint8_t num_bones;
std::pair<unsigned int, Matrix4x4f> bones[k_MaxBones]; // <node index, transform>
};
using AssetMeshArray = AssetTempArray<Mesh>;
using AssetVertexArray = AssetTempArray<AssetModelVertex>;
using AssetIndexArray = AssetTempArray<AssetIndexType>;
using AssetMaterialArray = AssetTempArray<AssetPBRMaterial>;
using AssetAnimationArray = AssetTempArray<ModelAnimation>;
struct AssetModelLoadResult
{
IMemoryManager* memory = nullptr;
detail::Ptr<AssetMeshArray> mesh_list = nullptr;
detail::Ptr<AssetVertexArray> vertices = nullptr;
detail::Ptr<AssetIndexArray> indices = nullptr;
detail::Ptr<AssetMaterialArray> materials = nullptr;
detail::Ptr<AssetAnimationArray> animations = nullptr;
ModelSkeleton skeleton = {};
AABB object_space_bounds = {};
bfStringRange error = {nullptr, nullptr};
std::array<char, 128> error_buffer = {'\0'}; //!< Private Do not use. Read from 'AssetModelLoadResult::error' instead.
AssetModelLoadResult() = default;
AssetModelLoadResult(const AssetModelLoadResult& rhs) noexcept = delete;
AssetModelLoadResult(AssetModelLoadResult&& rhs) noexcept = default;
AssetModelLoadResult& operator=(const AssetModelLoadResult& rhs) noexcept = delete;
AssetModelLoadResult& operator=(AssetModelLoadResult&& rhs) noexcept = delete;
operator bool() const noexcept
{
return error.str_bgn == nullptr;
}
// Private API
void setError(const char* err_message) noexcept;
~AssetModelLoadResult()
{
if (skeleton.nodes)
{
for (ModelAnimation& animation : *animations)
{
for (ModelAnimationChannel& channel : *animation.channels)
{
deallocateTempArray(*memory, channel.all_keys);
}
deallocateTempArray(*memory, animation.channels);
}
memory->deallocateArray<AssetNode>(skeleton.nodes);
}
}
};
} // namespace bf
#endif /* BF_ASSETIO_MODEL_LOADER_HPP */
|
#include "queryresult.h"
#include "ui_queryresult.h"
#include <QMainWindow>
#include <QStyle>
#include <QStyleFactory>
using namespace GeoStar::Utility::Data;
QueryResult::QueryResult(QWidget *parent) :
QDialog(parent),
ui(new Ui::QueryResult)
{
ui->setupUi(this);
ui->treeWidget->setHeaderHidden(true);
//设置树图的式样为windows式样
QStyle* style = QStyleFactory::create(tr("Windows"));
QStringList keys = QStyleFactory::keys() ;
ui->treeWidget->setStyle(style);
m_nCount = 0;
m_bInner = false;
}
QueryResult::~QueryResult()
{
UnAdvise();
delete ui;
}
void QueryResult::BindMap(GsMap* pMap)
{
UnAdvise();
m_ptrMap = pMap;
Advise();
}
void QueryResult::UnAdvise()
{
if(!m_ptrMap)
return;
m_ptrMap->ScreenDisplay()->OnBeforeEndDrawing.Remove(this,&QueryResult::OnTrackerDraw);
}
void QueryResult::OnTrackerDraw(GsDisplay* pDisp)
{
if(m_nCount <=0)
return;
if((m_nCount % 2) == 0)
return;
if(!m_ptrSymbol || !m_ptrGeometry)
return;
m_ptrSymbol->StartDrawing(pDisp->Canvas(),pDisp->DisplayTransformation());
m_ptrSymbol->Draw(m_ptrGeometry);
m_ptrSymbol->EndDrawing();
}
void QueryResult::Advise()
{
if(!m_ptrMap)
return;
m_ptrMap->ScreenDisplay()->OnBeforeEndDrawing.Add(this,&QueryResult::OnTrackerDraw);
}
QTreeWidgetItem* QueryResult::CreateTreeItem(GsSelectionSet* pSet,GsFeatureLayer* pFeaLyr)
{
QStringList list;
list<<QString::fromStdString(pFeaLyr->Name());
QTreeWidgetItem* pItem = new QTreeWidgetItem(list);
GsEnumIDsPtr ptrEnum = pSet->EnumIDs();
long long nID = ptrEnum->Next();
while(nID >=0)
{
list.clear();
list<<QString::number(nID);
QTreeWidgetItem* c = new QTreeWidgetItem(pItem,list);
nID = ptrEnum->Next();
}
return pItem;
}
void QueryResult::Add(GsSelectionSet* pSet,GsFeatureLayer* pFeaLyr)
{
ui->treeWidget->addTopLevelItem(CreateTreeItem(pSet,pFeaLyr));
}
void QueryResult::ShowResult(std::vector<GsFeatureLayerPtr>& vec,GsSpatialQueryFilter* pQF)
{
m_bInner = true;
ui->treeWidget->clear();
ui->listWidget->clear();
std::vector<GsFeatureLayerPtr>::iterator it = vec.begin();
for(;it != vec.end();it++)
{
GsSelectionSetPtr ptrSel =(*it)->FeatureClass()->Select(pQF);
Add(ptrSel,*it);
}
m_vec = vec;
m_bInner = false;
if(!this->isVisible())
{
this->setWindowFlags(Qt::WindowStaysOnTopHint);
this->show();
}
}
void QueryResult::ShowProperty(GsFeature* pFea)
{
ui->listWidget->clear();
if(NULL == pFea)
return;
GsFields fs = pFea->FeatureClass()->Fields();
new QListWidgetItem(QString("OID\t") + QString::number(pFea->OID()),ui->listWidget);
for(int i =2;i<fs.Fields.size();i++)
{
GsField f = fs.Fields[i];
QString strField = QString::fromStdString( f.Name);
strField+="\t";
switch(f.Type)
{
case eErrorType:
strField+="Empty";
break;
/// \brief BOOL类型
case eBoolType:
strField+="Empty";
break;
/// \brief 32位的整型
case eIntType:
strField+=QString::number(pFea->ValueInt(i));
break;
/// \brief 32位的无符号整型
case eUIntType:
strField+=QString::number(pFea->ValueUInt(i));
break;
/// \brief 64位的整型
case eInt64Type:
strField+=QString::number(pFea->ValueInt64(i));
break;
/// \brief 64位的无符号整型
case eUInt64Type:
strField+=QString::number(pFea->ValueUInt64(i));
break;
/// \brief 字符串类型
case eStringType:
{
GeoStar::Utility::GsString str = pFea->ValueString(i);
strField+=QString::fromUtf8(str.c_str());
break;
}
/// \brief 二进制类型
case eBlobType:
strField+="Blob";
break;
/// \brief 浮点型
case eFloatType:
strField+=QString::number(pFea->ValueFloat(i));
break;
/// \brief 双精度浮点型
case eDoubleType:
strField+=QString::number(pFea->ValueDouble(i));
break;
/// \brief 几何类型
case eGeometryType:
strField+="Geometry";
break;
}
new QListWidgetItem(strField,ui->listWidget);
}
}
void QueryResult::HighLight(GsFeature* pFea)
{
ShowProperty(pFea);
if(!pFea)
return;
m_ptrGeometry = pFea->Geometry();
if(!m_ptrGeometry)
return;
if(!m_ptrPointSymbol)
m_ptrPointSymbol = new GsSimplePointSymbol(GsColor(GsColor::Red),4);
if(!m_ptrLineSymbol)
m_ptrLineSymbol = new GsSimpleLineSymbol(GsColor(GsColor::Red),1);
if(!m_ptrFillSymbol)
m_ptrFillSymbol = new GsSimpleFillSymbol(GsColor(GsColor::Red));
int nDim = GsGeometry::GeometryTypeDimension(m_ptrGeometry->GeometryType());
if(nDim ==0)
m_ptrSymbol = m_ptrPointSymbol.p;
else if(nDim ==1)
m_ptrSymbol = m_ptrLineSymbol.p;
else if(nDim ==2)
m_ptrSymbol = m_ptrFillSymbol.p;
m_nCount = 4;
m_Timer.start(100);
}
GsFeatureLayerPtr QueryResult::FindLayer(const QString& str)
{
std::vector<GsFeatureLayerPtr>::iterator it = m_vec.begin();
for(;it != m_vec.end();it++)
{
QString strName = QString::fromStdString((*it)->Name());
if(strName.compare(str,Qt::CaseInsensitive) ==0)
return *it;
}
return 0;
}
void QueryResult::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
if(m_bInner)
return ;
ui->listWidget->clear();
if(item == NULL)
return;
if(item->parent() == NULL)
return;
QTreeWidgetItem* pParent = item->parent();
GsFeatureLayerPtr ptrFeaLyr = FindLayer(pParent->text(0));
if(!ptrFeaLyr)
return ;
long long oid = item->text(0).toLongLong();
GsFeaturePtr pFea = ptrFeaLyr->FeatureClass()->Feature(oid);
HighLight(pFea);
}
|
Saturday, November 29, 2008
Hot Springs Village trunk - Chinese tourism scenic spots
China hot spring located in the trunk 12 km south of County Office. 80 km from the city of Yuxi, Yunnan Province, from the office 148 kilometers, covers an area of 2.3 square kilometers, the construction area of 70,000 m2. Hot Springs is a deep fault zone along the natural water cycle of the outcrop, the flow of 3760m3 /day, the water temperature 39-41 degrees, colorless and tasteless, State Department of Geology and Mineral Resources, and other technology to identify units that are re-chuen, carbonated, contain Piangui Suan, strontium and lithium, and other 11 kinds of human essential elements of macro and micronutrients 13, the appropriate temperature, the four seasons can be bath, second only to the quality of international Stephen France of the Peili Ai quality mineral water, tea bath is a valuable dual-use high-quality mineral water. Hot Springs early Eastern Han Dynasty have been found that drinking mineral water after a shower can be refreshing, fitness, disease-drive, the beauty of the skin results are obvious. During the Ming Dynasty by the masses as "Shen Shui", has been the development and utilization. Hot springs in the vicinity Cui over trees, there are banks of Stephen Jinsuo Old Bridge Resort and beautiful environment, health care is the Four Seasons Zengshou, drink-bath in convalescence, State tourism, leisure ideal place.
Hot springs from the trunk trunk, Jinsuo Bridge, Cui Pingshan, the composition of the nursing home. Beautiful, beautiful. Cliffs steep ridge trunk, thick, heavy shade, such as huge as the view down to drink. Since the hot trunk pouring between Shek Pik Ling Ha, a moderate temperature (at 39 Between ~ 40 ?), four-bath can be. Two dozen meters away from the spring, into separate bathrooms for men and women. Sulfur spring water, skin diseases, rheumatism patients have a certain effect.
Xiren praise is a hot trunk, "Shen Ke In addition to washing dirty cloud, a deep source of cinnabar." Once upon a time, during the winter and the beginning of the Lunar New Year, Huaning Near the sea, Jiangchuan, to build water and other places of the masses, have come to visit, bathing. They group together in Quanbian ignite the fire, Zaiyang chickens, drinking song, Tunghsiao up to Dan. Qing Zhang Lingyun who Huaning hot trunk title poem: "Man Mo Tang Quan boast the world, so that rumors Wen de Sai (Yuan Dynasty Huaning County had 000 West) If the trunk is no different from Ling Ling, water tranquil water more than Kerry. Bathing solution and teaches people how to Siyu, the arrival of many flowery appearance. I want to frequent cold as this, the Acura Le Tong Guan Hua-year-old. "It can be seen that the object of love springs nose. Hot clean water, according to laboratory tests showed that the hot spring is a re-chuen, carbonated category, the human body contains 13 kinds of beneficial micro-yuan And macro elements, which Piangui Suan, strontium and lithium content of up to three elements of the national standard for drinking natural mineral water, known as "high-quality precious drinking water." Radium, radon, and other elements of the human body will have the effect of a variety of diseases. Luan stacked heavily on Stephen Cheung, Longdong River outlet clear as a mirror, Lilikeshuo gravel bottom. Cross-strait pines Tsui , Wild flowers fragrant grass, the pleasant scenery.
Nursing home was founded in October 1986, is located about 200 meters away from the hot springs of Longdong River? Covers an area of 70 acres. Housing construction in accordance with the mountain covered, Cuolayouzhi to locally-produced yellow glazed tile roof of the coverage, style flavor, unique. In a nursing home after Chengkungling trunk, stands a 6? Block of various styles of the pavilion, Chui-verdant slopes decorate more enchanting charm. Nursing home also has physical therapy rooms, restaurant, conference room, dance hall, and so on, around the cultivation of fruits, flowers, evergreen the four seasons, the smell assail the nostrils. Entire nursing homes and shade trees in the hot springs, towering tall and straight as the Ridge, slowly flowing river of Longdong, magnificent bridge Jinsuo add radiance to each other, an integral whole.
Jinsuo bridge in the trunk near Hot Springs, across the River Cave, Elephant Trunk Hill West Ridge, lying like Changhong Jin Bo, like jade belt Jinchan play, a magnificent view. Bridge 10 years Qianlong Dynasty (1745 AD) for single double Steeple arc stone arch bridge, 9 meters wide, 37 meters in length, 14 meters high. 18 m-span bridge opening,? Arc with a radius of 11.5 meters, 2.1 meters high vector, Yunnan Province is the largest single-span stone arch bridge one. On the north side of the middle of the bridge has a Shihfang, there is Yin-ting South, North and South symmetrical structure of the unique, exquisite stone carvings Li, a beautiful environment. Jinsuo around the scenic bridge, bridge numerous bamboos, gurgling water under the bridge, tree-lined both sides of the strait. Although the earthquake and weathering several times, still stand tall.
Cuiping Shan and Cheung Pei Shan confrontation, the screen like a Qing Cui For drop, named. Shek Pik a mountainside, traditional costumes and smooth. The shape of the moon "The moon rock," Lam around in the grass under a foil to the fascinating glory.
Click for more
No comments:
|
// license:BSD-3-Clause
// copyright-holders:Carlos A. Lozano, Uki
/***************************************************************************
video/aeroboto.c
***************************************************************************/
#include "emu.h"
#include "includes/aeroboto.h"
// how the starfield ROM is interpreted: 0=256x256x1 linear bitmap, 1=8x8x1x1024 tilemap
#define STARS_LAYOUT 1
// scroll speed of the stars: 1=normal, 2=half, 3=one-third...etc.(possitive integers only)
#define SCROLL_SPEED 1
/***************************************************************************
Callbacks for the TileMap code
***************************************************************************/
TILE_GET_INFO_MEMBER(aeroboto_state::get_tile_info)
{
uint8_t code = m_videoram[tile_index];
tileinfo.set(0,
code + (m_charbank << 8),
m_tilecolor[code],
(m_tilecolor[code] >= 0x33) ? 0 : TILE_FORCE_LAYER0);
}
// transparency should only affect tiles with color 0x33 or higher
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
void aeroboto_state::video_start()
{
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(aeroboto_state::get_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 64);
m_bg_tilemap->set_transparent_pen(0);
m_bg_tilemap->set_scroll_rows(64);
save_item(NAME(m_charbank));
save_item(NAME(m_starsoff));
save_item(NAME(m_sx));
save_item(NAME(m_sy));
save_item(NAME(m_ox));
save_item(NAME(m_oy));
#if STARS_LAYOUT
{
int i;
std::vector<uint8_t> temp(m_stars_length);
memcpy(&temp[0], m_stars_rom, m_stars_length);
for (i = 0; i < m_stars_length; i++)
m_stars_rom[(i & ~0xff) + (i << 5 & 0xe0) + (i >> 3 & 0x1f)] = temp[i];
}
#endif
}
/***************************************************************************
Memory handlers
***************************************************************************/
uint8_t aeroboto_state::aeroboto_in0_r()
{
return ioport(flip_screen() ? "P2" : "P1")->read();
}
void aeroboto_state::aeroboto_3000_w(uint8_t data)
{
/* bit 0 selects both flip screen and player1/player2 controls */
flip_screen_set(data & 0x01);
/* bit 1 = char bank select */
if (m_charbank != ((data & 0x02) >> 1))
{
m_bg_tilemap->mark_all_dirty();
m_charbank = (data & 0x02) >> 1;
}
/* bit 2 = disable star field? */
m_starsoff = data & 0x4;
}
void aeroboto_state::aeroboto_videoram_w(offs_t offset, uint8_t data)
{
m_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
}
void aeroboto_state::aeroboto_tilecolor_w(offs_t offset, uint8_t data)
{
if (m_tilecolor[offset] != data)
{
m_tilecolor[offset] = data;
m_bg_tilemap->mark_all_dirty();
}
}
/***************************************************************************
Display refresh
***************************************************************************/
void aeroboto_state::draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect )
{
for (int offs = 0; offs < m_spriteram.bytes(); offs += 4)
{
int x = m_spriteram[offs + 3];
int y = 240 - m_spriteram[offs];
if (flip_screen())
{
x = 248 - x;
y = 240 - y;
}
m_gfxdecode->gfx(1)->transpen(bitmap,cliprect,
m_spriteram[offs + 1],
m_spriteram[offs + 2] & 0x07,
flip_screen(), flip_screen(),
((x + 8) & 0xff) - 8, y, 0);
}
}
uint32_t aeroboto_state::screen_update_aeroboto(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
rectangle const splitrect1(0, 255, 0, 39);
rectangle const splitrect2(0, 255, 40, 255);
int sky_color, star_color;
sky_color = star_color = *m_bgcolor << 2;
// the star field is supposed to be seen through tile pen 0 when active
if (!m_starsoff)
{
if (star_color < 0xd0)
{
star_color = 0xd0;
sky_color = 0;
}
star_color += 2;
bitmap.fill(sky_color, cliprect);
// actual scroll speed is unknown but it can be adjusted by changing the SCROLL_SPEED constant
m_sx += char(*m_starx - m_ox);
m_ox = *m_starx;
int const x = m_sx / SCROLL_SPEED;
if (*m_vscroll != 0xff)
m_sy += char(*m_stary - m_oy);
m_oy = *m_stary;
int const y = m_sy / SCROLL_SPEED;
uint8_t const *const src_base = m_stars_rom;
for (int i = 0; i < 256; i++)
{
int src_offsx = (x + i) & 0xff;
int const src_colmask = 1 << (src_offsx & 7);
src_offsx >>= 3;
uint8_t const *const src_colptr = src_base + src_offsx;
int const pen = star_color + ((i + 8) >> 4 & 1);
for (int j = 0; j < 256; j++)
{
uint8_t const *const src_rowptr = src_colptr + (((y + j) & 0xff) << 5 );
if (!((unsigned)*src_rowptr & src_colmask))
bitmap.pix(j, i) = pen;
}
}
}
else
{
m_sx = m_ox = *m_starx;
m_sy = m_oy = *m_stary;
bitmap.fill(sky_color, cliprect);
}
for (int y = 0; y < 64; y++)
m_bg_tilemap->set_scrollx(y, m_hscroll[y]);
// the playfield is part of a splitscreen and should not overlap with status display
m_bg_tilemap->set_scrolly(0, *m_vscroll);
m_bg_tilemap->draw(screen, bitmap, splitrect2, 0, 0);
draw_sprites(bitmap, cliprect);
// the status display behaves more closely to a 40-line splitscreen than an overlay
m_bg_tilemap->set_scrolly(0, 0);
m_bg_tilemap->draw(screen, bitmap, splitrect1, 0, 0);
return 0;
}
|
#pragma once
/*
Simple library for access the local file system.
*/
#include <vector>
#include <string>
#include <cstdint>
#include <map>
struct VRelativePath {
std::string fRelativePath;
};
struct VAbsolutePath {
std::string fAbsolutePath;
};
// Path is absolute and with native path separators.
std::vector<std::uint8_t> LoadFile(const std::string& completePath);
// Path is absolute and with native path separators.
std::string LoadTextFile(const std::string& completePath);
// Path is absolute and with native path separators.
bool DoesEntryExist(const std::string& completePath);
/////////////////////////////////////////////////// DIRECTOR ROOTS
//??? Add help creating the directory with the correct name.
struct directories_t {
//??? add app resource root.
// Directory where your executable or bundle lives.
std::string process_dir;
// Current logged-in user's home directory. Ex: "/Users/marcus"
// User-visible files.
std::string home_dir;
// Current logged-in user's documents directory. Ex: "/Users/marcus/Documents"
// User-visible files.
std::string documents_dir;
// Current logged-in user's desktop directory. Ex: "/Users/marcus/Desktop"
// User-visible files.
std::string desktop_dir;
// Current logged-in user's preference directory. Ex: "/Users/marcus/Library/Preferences"
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// User don't see these files.
std::string preferences_dir;
// Current logged-in user's cache directory. Ex: "/Users/marcus/Library/Caches"
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// User don't see these files.
std::string cache_dir;
// Temporary directory. Will be erased soon.
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// User don't see these files.
std::string temp_dir;
// Current logged-in user's Application Support directory. Ex: "/Users/marcus/Library/Application Support"
// Notice that this points to a directory shared by many applications: store your data in a sub directory!
// App creates and manages on behalf of the user and can include files that contain user data.
// User don't see these files.
std::string application_support;
};
directories_t GetDirectories();
struct process_info_t {
std::string process_path;
};
process_info_t get_process_info();
std::string get_working_dir();
/////////////////////////////////////////////////// ADVANCED
// Path is absolute and with native path separators.
// Will _create_ any needed directories in the save-path.
void SaveFile(const std::string& completePath, const std::uint8_t data[], std::size_t byteCount);
/*
dir_a
dir_b
file_5
dir_d
file_4
file_2
dir_e
file_1
file_2
file_3
dir_c
DeleteDeep("dir_b") will delete file_5, file_4, file_2, file_1, file_2, file_3, dir_e, dir_d, dir_b
*/
void DeleteDeep(const std::string& path);
void RenameEntry(const std::string& path, const std::string& n);
void MakeDirectoriesDeep(const std::string& nativePath);
std::string UpDir(const std::string& path);
std::pair<std::string, std::string> UpDir2(const std::string& path);
struct TFileInfo {
bool fDirFlag;
// Dates are undefined unit, but can be compared.
std::uint64_t fCreationDate;
std::uint64_t fModificationDate;
std::uint64_t fFileSize;
};
bool GetFileInfo(const std::string& completePath, TFileInfo& outInfo);
struct TDirEntry {
enum EType {
kFile = 200,
kDir = 201
};
EType fType;
// Name of file or dir.
std::string fNameOnly;
// Parent path.
std::string fParent;
};
// Never includes "." or "..".
std::vector<TDirEntry> GetDirItems(const std::string& dir);
// Returns a entiry directory tree deeply.
// Each TDirEntry name will be prefixed by _prefix_.
// Contents of sub-directories will be also be prefixed by the sub-directory names.
// All path names are relative to the input directory - not absolute to file system.
// Never includes "." or "..".
std::vector<TDirEntry> GetDirItemsDeep(const std::string& dir);
// Converts all forward slashes "/" to the path separator of the current operating system:
// Windows is "\"
// Unix is "/"
// Mac OS 9 is ":"
std::string ToNativePath(const std::string& path);
std::string FromNativePath(const std::string& path);
std::string RemoveExtension(const std::string& s);
// Returns "" when there is no extension.
// Returned extension includes the leading ".".
// Examples:
// ".wav"
// ""
// ".doc"
// ".AIFF"
std::string GetExtension(const std::string& s);
std::pair<std::string, std::string> SplitExtension(const std::string& s);
struct TPathParts {
public: TPathParts();
public: TPathParts(const std::string& path, const std::string& name, const std::string& extension);
// "/Volumes/MyHD/SomeDir/"
std::string fPath;
// "MyFileName"
std::string fName;
// ".txt"
std::string fExtension;
};
TPathParts SplitPath(const std::string& path);
std::vector<std::string> SplitPath2(const std::string& path);
/*
base relativePath
"/users/marcus/" "resources/hello.jpg" "/users/marcus/resources/hello.jpg"
*/
std::string MakeAbsolutePath(const std::string& base, const std::string& relativePath);
//////////////////////////// COMMAND LINE ARGUMENTS
std::vector<std::string> args_to_vector(int argc, const char * argv[]);
// Flags: x: means x supports parameter.
struct command_line_args_t {
std::string command;
std::string subcommand;
// Key: flag character, value: parameter or ""
std::map<std::string, std::string> flags;
// Extra arguments, after the flags have been parsed.
std::vector<std::string> extra_arguments;
};
command_line_args_t parse_command_line_args(const std::vector<std::string>& args, const std::string& flags);
/*
git commit -m "Commit message"
command: "git"
subcommand: "commit"
flags
m: ""
extra_arguments
"Commit message"
*/
command_line_args_t parse_command_line_args_subcommands(const std::vector<std::string>& args, const std::string& flags);
std::string read_text_file(const std::string& abs_path);
|
Make your own free website on
From: Steven Ng <>
Sat, 01 May 1999 10:31:53 +0800
A interesting but albeit quite a long article by Britt S Phillips, in one of his internet postings. Enjoy reading!
I've heard it said often... "You can't put all your eggs in one basket". What a novel concept and moreover a very sound strategy. That single statement sums up many things but sadly it is the reason most will never experience true joy.The same is true about many things in life.
Most take an idea or concept and kick it around in their mind. They actually talk themselves right out of even the best idea or strategy in about the same time it takes to make a deposit. Worse than this are those who don't even trust themselves to make the decision. No, no that won't do, they need to pass the idea around to family, friends or co-workers. How many of us are guilty of this? The fact is we all are.
The sad thing is most will never change. They don't know any other pattern and that's their choice. One of my favorite quotes is "Never listen to anyone in life unless they are doing better than you". Now, let's talk about the alternative for a moment. I'm going to ask you to do one simple thing now and I really want you to do this. You do not have to move from your chair and it will only take a
few moments. Please do this and don't skip past it. This is very important to your understanding of this article and how it will greatly benefit you.
Ok, take just 30 seconds (or longer of you like) and look around the room you are now in. Notice everything in it. Look at the simple things and the complicated ones as well. Now as your eyes travel, think about how everything you see started with a thought or an idea. As you do this, also think about how every item around you, came from a thought in someone's mind. Now imagine how our world would be if it didn't have people who could also not only imagine an idea or concept but also put it into practical use. These people are directly responsible for many things we enjoy and could never dream of being without. Yes, you guessed it, most things you and I take for granted each and every day.
You may be asking yourself right about now, "how can this help me become a better person?" Well here's how it has helped me!!! As I look back a few short years ago, I realize I indeed have come a long way. I also know that if I had not decided to stop listening to others around me, I would still be right where they wanted me to be today, STUCK on the same level they are on.
Yes that's right, most never even realize our friends and family subconsciously do not want us to succeed. They don't intentionally try to hold you or I back from our dreams it just happens and sadly it will always prevail.
A close friend (Buddy) is one of those people who like me is a dreamer. He often talks about how "one day" he will do this or "one day he will do that. I asked him once while we were eating lunch (after he had told me his latest idea had not materialized) what his girlfriend thought about his idea. He sadly replied "oh man, she said it was no good and that it couldn't work". I asked him immediately what he thought of his idea. He enthusiastically said "I think it could easily work and it would be great" I then asked him if he felt this way, why he had bothered to ask her or anyone else. His answer was "I don't know".
Well the sad truth in this example is that this sort of thing happen a billion times a day and it has stopped many from the much deserved success that awaits them. In my own businesses, people have commented many times to me... "Britt, you're a worker, you make things happen and you are always involved in one thing or another to make money".
What are these people really telling me? Aren't they in a way admitting to me they wish they indeed had inside the same thing that drives me to pursue my goals? Of course you and I know they do possess what it takes, we all do as no one is better than another. Another favorite quote is... "Unless you're the lead dog, the view never changes".
Remember my friend Buddy? About a year ago I asked him if he wanted me to teach him how to place classified ads. He asked me how much money I was making and I told him it was more than he would believe if I told him.He insisted and of course just as I expected he didn't believe me. We had many conversations and I would from time to time share the fact that the ads were continuing to be a real money maker for me.
Once I remember showing him my new car. His first comment was of course that it was a nice ride. Next he asked "what kind of payments did you get?" My reply was zero down and zero per month. he asked what I meant and with much pride I stated the car was paid in full and that I never did like making payments. Did this turn him around? It sure did, in fact he was so fired up he was ready to get serious about running his own classified ads. That was until he got home and started (you guessed it) talking to his girlfriend again.
Finally one day I asked him to have lunch and although it was not planned beforehand, I did enjoy it later when I saw his reaction to what happened after we had eaten. I had told him several times before how I had very
steadily pulled in many orders in a day. I could tell while he knew itwas possible, he still was going to have to see it first hand.
On the way back to my office, I picked up the day's mail and asked Buddy to help mecarryit inside. His energy was high and he was getting pumped up once again.Aswe opened random envelopes from around the world, his enthusiasm grew and grew. We sat there and did a count which revealed proof positive to him that almost $4,000.00 had came in that day !
Buddy was ready to explode he was now serious as I had never seen him before. I really thought he had gotten bitten by the bug to take actionandreally make a change in his life for the better.I wish I could tell you that today Buddy is super successful. The factishe is in his early thirties and still lives in his parent's basement.Heworks one job he hates after another for a hardly substantial hourlywage.
On a good day he will again get that gleam in his eye. He will get that glow of the dreamer tucked awaydeep inside him. The sad part is he doesn't do anything about it. I doubt he ever will. Does Buddy describe anyone that you know? Does Buddy describe you ?
My grandmother used to always tell me, "Britt, you can have anything inlife you want but only if you want it bad enough". I can hear her sweetvoice saying those words to me right now. She wanted to share with me amessage she knew would make the biggest difference in my life. She's only with me in spirit now as she died at age 83 two Thanks givings ago.
She left me with not only memories I will never forget but also a message thatshaped who I am today.In closing I'll just share that true success comes from having morethan asingle source of income. It also is imperative that you not allowanyone totalk you out of your dreams.
And whatever you do... DON'T sit and talkyourself out of them either! What will you do after you finish reading this article? For those of you wanting a dramatic change in your life will you let this be what moves you to take some action and make it happen? If you're already successful, is where you're at today as far as you can go ? I hope this article has touched you in a personal way and it will encourage you to never give up on your dreams.
|
//using g++ 6.3.0 ; aka MinGW.org GCC-6.3.0-1
/**
* logic tree of Morse code
*
* @author andythebreaker
* @version 0.0.1, 07/04/2021
*/
#include <algorithm>
#include <iostream>
#include <string>
#include <list>
#include <map>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <fstream>
#include <regex>
#include <sstream>
#include <queue>
#include <utility>
#define ALL_MOS_PAT_NUM 56
#define MORSE_ARRAY_TO_VECTOR(MORSE_ARRAY_INPUT, MORSE_ARRAY_NNAME) vector<int> MORSE_ARRAY_NNAME(MORSE_ARRAY_INPUT, MORSE_ARRAY_INPUT + sizeof(MORSE_ARRAY_INPUT) / sizeof(MORSE_ARRAY_INPUT[0]))
using namespace std;
class cell
{
public:
// Default constructor
cell() {}
// Initialize a Box with custom dimensions
cell(string name, vector<int> morse)
: m_name(name), m_morse(morse)
{
}
string name(void) { return m_name; };
vector<int> morse(void) { return m_morse; }
private:
// Will have value of 0 when default constructor is called.
// If we didn't zero-init here, default constructor would
// leave them uninitialized with garbage values.
string m_name{NULL};
vector<int> m_morse{NULL};
};
// 宣告類別
class tree_node
{
// 宣告 public 成員
public:
tree_node()
{
numb = count;
count++;
}
static int count;
int numb;
tree_node *dot;
tree_node *dash;
vector<cell> endof;
};
int tree_node::count = 0;
string print_int_ary(int *int_ary)
{
string output_str = "";
int arrSize = sizeof(int_ary) / sizeof(int_ary[0]);
for (size_t i = 0; i < arrSize; i++)
{
output_str += to_string(int_ary[i]) + " ,";
}
return output_str;
}
string int_vec_2_str(vector<int> int_vec)
{
string str_out = "";
vector<int>::iterator it;
for (it = int_vec.begin(); it != int_vec.end(); it++)
{
str_out += to_string(*it) + ", ";
}
return str_out;
}
int main()
{
cout << "Running..." << endl;
//56
int morse_ary_A[] = {1, 2, 0};
int morse_ary_B[] = {2, 1, 1, 1, 0};
int morse_ary_C[] = {2, 1, 2, 1, 0};
int morse_ary_D[] = {2, 1, 1, 0};
int morse_ary_E[] = {1, 0};
int morse_ary_F[] = {1, 1, 2, 1, 0};
int morse_ary_G[] = {2, 2, 1, 0};
int morse_ary_H[] = {1, 1, 1, 1, 0};
int morse_ary_I[] = {1, 1, 0};
int morse_ary_J[] = {1, 2, 2, 2, 0};
int morse_ary_K[] = {2, 1, 2, 0};
int morse_ary_L[] = {1, 2, 1, 1, 0};
int morse_ary_M[] = {2, 2, 0};
int morse_ary_N[] = {2, 1, 0};
int morse_ary_O[] = {2, 2, 2, 0};
int morse_ary_P[] = {1, 2, 2, 1, 0};
int morse_ary_Q[] = {2, 2, 1, 2, 0};
int morse_ary_R[] = {1, 2, 1, 0};
int morse_ary_S[] = {1, 1, 1, 0};
int morse_ary_T[] = {2, 0};
int morse_ary_U[] = {1, 1, 2, 0};
int morse_ary_V[] = {1, 1, 1, 2, 0};
int morse_ary_W[] = {1, 2, 2, 0};
int morse_ary_X[] = {2, 1, 1, 2, 0};
int morse_ary_Y[] = {2, 1, 2, 2, 0};
int morse_ary_Z[] = {2, 2, 1, 1, 0};
int morse_ary_0[] = {2, 2, 2, 2, 2, 0};
int morse_ary_1[] = {1, 2, 2, 2, 2, 0};
int morse_ary_2[] = {1, 1, 2, 2, 2, 0};
int morse_ary_3[] = {1, 1, 1, 2, 2, 0};
int morse_ary_4[] = {1, 1, 1, 1, 2, 0};
int morse_ary_5[] = {1, 1, 1, 1, 1, 0};
int morse_ary_6[] = {2, 1, 1, 1, 1, 0};
int morse_ary_7[] = {2, 2, 1, 1, 1, 0};
int morse_ary_8[] = {2, 2, 2, 1, 1, 0};
int morse_ary_9[] = {2, 2, 2, 2, 1, 0};
int morse_ary_DOT[] = {1, 2, 1, 2, 1, 2, 0};
int morse_ary_LB[] = {2, 1, 2, 2, 1, 0};
int morse_ary_RB[] = {2, 1, 2, 2, 1, 2, 0};
int morse_ary_PLUS[] = {1, 2, 1, 2, 1, 0};
int morse_ary_SP[] = {2, 1, 2, 1, 2, 1, 0};
int morse_ary_UQ[] = {1, 1, 2, 1, 2, 0};
int morse_ary_COMA[] = {2, 2, 1, 1, 2, 2, 0};
int morse_ary_DASH[] = {2, 1, 1, 1, 1, 2, 0};
int morse_ary_EQ[] = {2, 1, 1, 1, 2, 0};
int morse_ary_UEXC[] = {2, 2, 1, 1, 1, 2, 0};
int morse_ary_QM[] = {1, 1, 2, 2, 1, 1, 0};
int morse_ary_AND[] = {1, 2, 1, 1, 1, 0};
int morse_ary_DD[] = {1, 1, 2, 2, 1, 2, 0};
int morse_ary_MONY[] = {1, 1, 1, 2, 1, 1, 2, 0};
int morse_ary_EXC[] = {2, 1, 2, 1, 2, 2, 0};
int morse_ary_SQUT[] = {1, 2, 2, 2, 2, 1, 0};
int morse_ary_COLN[] = {2, 2, 2, 1, 1, 1, 0};
int morse_ary_DQUT[] = {1, 2, 1, 1, 2, 1, 0};
int morse_ary_AT[] = {1, 2, 2, 1, 2, 1, 0};
int morse_ary_SLAH[] = {2, 1, 1, 2, 1, 0};
MORSE_ARRAY_TO_VECTOR(morse_ary_A, NNAME_morse_ary_A);
MORSE_ARRAY_TO_VECTOR(morse_ary_B, NNAME_morse_ary_B);
MORSE_ARRAY_TO_VECTOR(morse_ary_C, NNAME_morse_ary_C);
MORSE_ARRAY_TO_VECTOR(morse_ary_D, NNAME_morse_ary_D);
MORSE_ARRAY_TO_VECTOR(morse_ary_E, NNAME_morse_ary_E);
MORSE_ARRAY_TO_VECTOR(morse_ary_F, NNAME_morse_ary_F);
MORSE_ARRAY_TO_VECTOR(morse_ary_G, NNAME_morse_ary_G);
MORSE_ARRAY_TO_VECTOR(morse_ary_H, NNAME_morse_ary_H);
MORSE_ARRAY_TO_VECTOR(morse_ary_I, NNAME_morse_ary_I);
MORSE_ARRAY_TO_VECTOR(morse_ary_J, NNAME_morse_ary_J);
MORSE_ARRAY_TO_VECTOR(morse_ary_K, NNAME_morse_ary_K);
MORSE_ARRAY_TO_VECTOR(morse_ary_L, NNAME_morse_ary_L);
MORSE_ARRAY_TO_VECTOR(morse_ary_M, NNAME_morse_ary_M);
MORSE_ARRAY_TO_VECTOR(morse_ary_N, NNAME_morse_ary_N);
MORSE_ARRAY_TO_VECTOR(morse_ary_O, NNAME_morse_ary_O);
MORSE_ARRAY_TO_VECTOR(morse_ary_P, NNAME_morse_ary_P);
MORSE_ARRAY_TO_VECTOR(morse_ary_Q, NNAME_morse_ary_Q);
MORSE_ARRAY_TO_VECTOR(morse_ary_R, NNAME_morse_ary_R);
MORSE_ARRAY_TO_VECTOR(morse_ary_S, NNAME_morse_ary_S);
MORSE_ARRAY_TO_VECTOR(morse_ary_T, NNAME_morse_ary_T);
MORSE_ARRAY_TO_VECTOR(morse_ary_U, NNAME_morse_ary_U);
MORSE_ARRAY_TO_VECTOR(morse_ary_V, NNAME_morse_ary_V);
MORSE_ARRAY_TO_VECTOR(morse_ary_W, NNAME_morse_ary_W);
MORSE_ARRAY_TO_VECTOR(morse_ary_X, NNAME_morse_ary_X);
MORSE_ARRAY_TO_VECTOR(morse_ary_Y, NNAME_morse_ary_Y);
MORSE_ARRAY_TO_VECTOR(morse_ary_Z, NNAME_morse_ary_Z);
MORSE_ARRAY_TO_VECTOR(morse_ary_0, NNAME_morse_ary_0);
MORSE_ARRAY_TO_VECTOR(morse_ary_1, NNAME_morse_ary_1);
MORSE_ARRAY_TO_VECTOR(morse_ary_2, NNAME_morse_ary_2);
MORSE_ARRAY_TO_VECTOR(morse_ary_3, NNAME_morse_ary_3);
MORSE_ARRAY_TO_VECTOR(morse_ary_4, NNAME_morse_ary_4);
MORSE_ARRAY_TO_VECTOR(morse_ary_5, NNAME_morse_ary_5);
MORSE_ARRAY_TO_VECTOR(morse_ary_6, NNAME_morse_ary_6);
MORSE_ARRAY_TO_VECTOR(morse_ary_7, NNAME_morse_ary_7);
MORSE_ARRAY_TO_VECTOR(morse_ary_8, NNAME_morse_ary_8);
MORSE_ARRAY_TO_VECTOR(morse_ary_9, NNAME_morse_ary_9);
MORSE_ARRAY_TO_VECTOR(morse_ary_DOT, NNAME_morse_ary_DOT);
MORSE_ARRAY_TO_VECTOR(morse_ary_LB, NNAME_morse_ary_LB);
MORSE_ARRAY_TO_VECTOR(morse_ary_RB, NNAME_morse_ary_RB);
MORSE_ARRAY_TO_VECTOR(morse_ary_PLUS, NNAME_morse_ary_PLUS);
MORSE_ARRAY_TO_VECTOR(morse_ary_SP, NNAME_morse_ary_SP);
MORSE_ARRAY_TO_VECTOR(morse_ary_UQ, NNAME_morse_ary_UQ);
MORSE_ARRAY_TO_VECTOR(morse_ary_COMA, NNAME_morse_ary_COMA);
MORSE_ARRAY_TO_VECTOR(morse_ary_DASH, NNAME_morse_ary_DASH);
MORSE_ARRAY_TO_VECTOR(morse_ary_EQ, NNAME_morse_ary_EQ);
MORSE_ARRAY_TO_VECTOR(morse_ary_UEXC, NNAME_morse_ary_UEXC);
MORSE_ARRAY_TO_VECTOR(morse_ary_QM, NNAME_morse_ary_QM);
MORSE_ARRAY_TO_VECTOR(morse_ary_AND, NNAME_morse_ary_AND);
MORSE_ARRAY_TO_VECTOR(morse_ary_DD, NNAME_morse_ary_DD);
MORSE_ARRAY_TO_VECTOR(morse_ary_MONY, NNAME_morse_ary_MONY);
MORSE_ARRAY_TO_VECTOR(morse_ary_EXC, NNAME_morse_ary_EXC);
MORSE_ARRAY_TO_VECTOR(morse_ary_SQUT, NNAME_morse_ary_SQUT);
MORSE_ARRAY_TO_VECTOR(morse_ary_COLN, NNAME_morse_ary_COLN);
MORSE_ARRAY_TO_VECTOR(morse_ary_DQUT, NNAME_morse_ary_DQUT);
MORSE_ARRAY_TO_VECTOR(morse_ary_AT, NNAME_morse_ary_AT);
MORSE_ARRAY_TO_VECTOR(morse_ary_SLAH, NNAME_morse_ary_SLAH);
cell morse_ary[ALL_MOS_PAT_NUM] = {
{"ASCII88PATTERN_A", NNAME_morse_ary_A},
{"ASCII88PATTERN_B", NNAME_morse_ary_B},
{"ASCII88PATTERN_C", NNAME_morse_ary_C},
{"ASCII88PATTERN_D", NNAME_morse_ary_D},
{"ASCII88PATTERN_E", NNAME_morse_ary_E},
{"ASCII88PATTERN_F", NNAME_morse_ary_F},
{"ASCII88PATTERN_G", NNAME_morse_ary_G},
{"ASCII88PATTERN_H", NNAME_morse_ary_H},
{"ASCII88PATTERN_I", NNAME_morse_ary_I},
{"ASCII88PATTERN_J", NNAME_morse_ary_J},
{"ASCII88PATTERN_K", NNAME_morse_ary_K},
{"ASCII88PATTERN_L", NNAME_morse_ary_L},
{"ASCII88PATTERN_M", NNAME_morse_ary_M},
{"ASCII88PATTERN_N", NNAME_morse_ary_N},
{"ASCII88PATTERN_O", NNAME_morse_ary_O},
{"ASCII88PATTERN_P", NNAME_morse_ary_P},
{"ASCII88PATTERN_Q", NNAME_morse_ary_Q},
{"ASCII88PATTERN_R", NNAME_morse_ary_R},
{"ASCII88PATTERN_S", NNAME_morse_ary_S},
{"ASCII88PATTERN_T", NNAME_morse_ary_T},
{"ASCII88PATTERN_U", NNAME_morse_ary_U},
{"ASCII88PATTERN_V", NNAME_morse_ary_V},
{"ASCII88PATTERN_W", NNAME_morse_ary_W},
{"ASCII88PATTERN_X", NNAME_morse_ary_X},
{"ASCII88PATTERN_Y", NNAME_morse_ary_Y},
{"ASCII88PATTERN_Z", NNAME_morse_ary_Z},
{"ASCII88PATTERN_0", NNAME_morse_ary_0},
{"ASCII88PATTERN_1", NNAME_morse_ary_1},
{"ASCII88PATTERN_2", NNAME_morse_ary_2},
{"ASCII88PATTERN_3", NNAME_morse_ary_3},
{"ASCII88PATTERN_4", NNAME_morse_ary_4},
{"ASCII88PATTERN_5", NNAME_morse_ary_5},
{"ASCII88PATTERN_6", NNAME_morse_ary_6},
{"ASCII88PATTERN_7", NNAME_morse_ary_7},
{"ASCII88PATTERN_8", NNAME_morse_ary_8},
{"ASCII88PATTERN_9", NNAME_morse_ary_9},
{"ASCII88PATTERN_DOT", NNAME_morse_ary_DOT},
{"ASCII88PATTERN_LB", NNAME_morse_ary_LB},
{"ASCII88PATTERN_RB", NNAME_morse_ary_RB},
{"ASCII88PATTERN_PLUS", NNAME_morse_ary_PLUS},
{"ASCII88PATTERN_SP", NNAME_morse_ary_SP},
{"ASCII88PATTERN_UQ", NNAME_morse_ary_UQ},
{"ASCII88PATTERN_COMA", NNAME_morse_ary_COMA},
{"ASCII88PATTERN_DASH", NNAME_morse_ary_DASH},
{"ASCII88PATTERN_EQ", NNAME_morse_ary_EQ},
{"ASCII88PATTERN_UEXC", NNAME_morse_ary_UEXC},
{"ASCII88PATTERN_QM", NNAME_morse_ary_QM},
{"ASCII88PATTERN_AND", NNAME_morse_ary_AND},
{"ASCII88PATTERN_DD", NNAME_morse_ary_DD},
{"ASCII88PATTERN_MONY", NNAME_morse_ary_MONY},
{"ASCII88PATTERN_EXC", NNAME_morse_ary_EXC},
{"ASCII88PATTERN_SQUT", NNAME_morse_ary_SQUT},
{"ASCII88PATTERN_COLN", NNAME_morse_ary_COLN},
{"ASCII88PATTERN_DQUT", NNAME_morse_ary_DQUT},
{"ASCII88PATTERN_AT", NNAME_morse_ary_AT},
{"ASCII88PATTERN_SLAH", NNAME_morse_ary_SLAH},
};
int max_step_numb = 0;
for (size_t i = 0; i < ALL_MOS_PAT_NUM; i++)
{
cout << morse_ary[i].name() << endl;
cout << int_vec_2_str(morse_ary[i].morse()) << endl;
max_step_numb = (morse_ary[i].morse().size() > max_step_numb) ? morse_ary[i].morse().size() : max_step_numb;
}
cout << "\t\tmax_step_numb:" << to_string(max_step_numb) << endl;
double length_of_all_tree_node = 0;
double pause_point = 0;
for (size_t i = 0; i < max_step_numb; i++)
{
length_of_all_tree_node += pow((double)2, (double)i);
if (i + 2 == max_step_numb)
{
pause_point = length_of_all_tree_node;
}
}
cout << "\t\tlength_of_all_tree_node:" << to_string(length_of_all_tree_node) << endl;
cout << "\t\tpause_point:" << to_string(pause_point) << endl;
vector<tree_node> tree_all;
for (double i = 0; i < length_of_all_tree_node; i++)
{
tree_all.push_back(tree_node());
}
for (double i = 0; i < pause_point; i++)
{
tree_all[int(i)].dot = &tree_all[(int(i) + 1) * 2 - 1];
tree_all[int(i)].dash = &tree_all[(int(i) + 1) * 2];
}
for (double i = pause_point; i < length_of_all_tree_node; i++)
{
tree_all[int(i)].dot = NULL;
tree_all[int(i)].dash = NULL;
}
for (size_t i = 0; i < ALL_MOS_PAT_NUM; i++)
{
tree_node *tmp_tn = &tree_all[0];
cout << "pattern:" + to_string(i);
for (size_t ii = 0; ii < max_step_numb; ii++)
{
cout << ", " + to_string(morse_ary[i].morse()[ii]);
if (morse_ary[i].morse()[ii] == 1)
{
cout << "[dot](" << to_string((*tmp_tn).numb);
tmp_tn = tmp_tn->dot;
cout << "->" << to_string((*tmp_tn).numb) << ")";
}
else if (morse_ary[i].morse()[ii] == 2)
{
cout << "[dash](" << to_string((*tmp_tn).numb);
tmp_tn = tmp_tn->dash;
cout << "->" << to_string((*tmp_tn).numb) << ")";
}
else
{
cout << "[endof](" << to_string((*tmp_tn).numb);
(*tmp_tn).endof.push_back(morse_ary[i]);
cout << "->" << to_string((*tmp_tn).numb) << ")";
break;
}
}
cout << endl;
}
string main_output = "";
for (double i = 0; i < length_of_all_tree_node; i++)
{
main_output += "case " + to_string(tree_all[int(i)].numb) + ":\nif(input_bool==1){\n" + ((tree_all[int(i)].dot) ? ("morse_pattern_status=" + to_string((*(tree_all[int(i)].dot)).numb) + ";") : "target_morse_pattern_error_event();") +
"\n}else if(input_bool==2){\n" + ((tree_all[int(i)].dash) ? ("morse_pattern_status=" + to_string((*(tree_all[int(i)].dash)).numb) + ";") : "target_morse_pattern_error_event();") +
"\n}else{\n" +
((tree_all[int(i)].endof.size() > 0) ? ("morse_pattern_status=0;\nSCREEN_SHOW_FRAM(" + (*(tree_all[int(i)].endof.begin())).name() + ")") : "target_morse_pattern_error_event();") + "\n}break;";
}
cout << "================================================================" << endl;
cout << main_output << endl;
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h"
#include "base/containers/adapters.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_info.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_logical_line_item.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
namespace {
bool IsLeftMostOffset(const ShapeResult& shape_result, unsigned offset) {
if (shape_result.IsRtl())
return offset == shape_result.NumCharacters();
return offset == 0;
}
bool IsRightMostOffset(const ShapeResult& shape_result, unsigned offset) {
if (shape_result.IsRtl())
return offset == 0;
return offset == shape_result.NumCharacters();
}
} // namespace
NGLineTruncator::NGLineTruncator(const NGLineInfo& line_info)
: line_style_(&line_info.LineStyle()),
available_width_(line_info.AvailableWidth() - line_info.TextIndent()),
line_direction_(line_info.BaseDirection()) {}
const ComputedStyle& NGLineTruncator::EllipsisStyle() const {
// The ellipsis is styled according to the line style.
// https://drafts.csswg.org/css-ui/#ellipsing-details
DCHECK(line_style_);
return *line_style_;
}
void NGLineTruncator::SetupEllipsis() {
const Font& font = EllipsisStyle().GetFont();
ellipsis_font_data_ = font.PrimaryFont();
DCHECK(ellipsis_font_data_);
ellipsis_text_ =
ellipsis_font_data_ && ellipsis_font_data_->GlyphForCharacter(
kHorizontalEllipsisCharacter)
? String(&kHorizontalEllipsisCharacter, 1)
: String(u"...");
HarfBuzzShaper shaper(ellipsis_text_);
ellipsis_shape_result_ =
ShapeResultView::Create(shaper.Shape(&font, line_direction_).get());
ellipsis_width_ = ellipsis_shape_result_->SnappedWidth();
}
LayoutUnit NGLineTruncator::PlaceEllipsisNextTo(
NGLogicalLineItems* line_box,
NGLogicalLineItem* ellipsized_child) {
// Create the ellipsis, associating it with the ellipsized child.
DCHECK(ellipsized_child->HasInFlowFragment());
const LayoutObject* ellipsized_layout_object =
ellipsized_child->GetMutableLayoutObject();
DCHECK(ellipsized_layout_object);
DCHECK(ellipsized_layout_object->IsInline());
DCHECK(ellipsized_layout_object->IsText() ||
ellipsized_layout_object->IsAtomicInlineLevel());
// Now the offset of the ellpisis is determined. Place the ellpisis into the
// line box.
LayoutUnit ellipsis_inline_offset =
IsLtr(line_direction_)
? ellipsized_child->InlineOffset() + ellipsized_child->inline_size
: ellipsized_child->InlineOffset() - ellipsis_width_;
FontHeight ellipsis_metrics;
DCHECK(ellipsis_font_data_);
if (ellipsis_font_data_) {
ellipsis_metrics = ellipsis_font_data_->GetFontMetrics().GetFontHeight(
line_style_->GetFontBaseline());
}
DCHECK(ellipsis_text_);
DCHECK(ellipsis_shape_result_.get());
line_box->AddChild(
*ellipsized_layout_object, NGStyleVariant::kEllipsis,
std::move(ellipsis_shape_result_), ellipsis_text_,
LogicalRect(ellipsis_inline_offset, -ellipsis_metrics.ascent,
ellipsis_width_, ellipsis_metrics.LineHeight()),
/* bidi_level */ 0);
return ellipsis_inline_offset;
}
wtf_size_t NGLineTruncator::AddTruncatedChild(
wtf_size_t source_index,
bool leave_one_character,
LayoutUnit position,
TextDirection edge,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) {
NGLogicalLineItems& line = *line_box;
const NGLogicalLineItem& source_item = line[source_index];
DCHECK(source_item.shape_result);
scoped_refptr<ShapeResult> shape_result =
source_item.shape_result->CreateShapeResult();
unsigned text_offset = shape_result->OffsetToFit(position, edge);
if (IsLtr(edge) ? IsLeftMostOffset(*shape_result, text_offset)
: IsRightMostOffset(*shape_result, text_offset)) {
if (!leave_one_character)
return kDidNotAddChild;
text_offset =
shape_result->OffsetToFit(shape_result->PositionForOffset(
IsRtl(edge) == shape_result->IsRtl()
? 1
: shape_result->NumCharacters() - 1),
edge);
}
const wtf_size_t new_index = line.size();
line.AddChild(TruncateText(source_item, *shape_result, text_offset, edge));
box_states->ChildInserted(new_index);
return new_index;
}
LayoutUnit NGLineTruncator::TruncateLine(LayoutUnit line_width,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) {
// Shape the ellipsis and compute its inline size.
SetupEllipsis();
// Loop children from the logical last to the logical first to determine where
// to place the ellipsis. Children maybe truncated or moved as part of the
// process.
NGLogicalLineItem* ellipsized_child = nullptr;
absl::optional<NGLogicalLineItem> truncated_child;
if (IsLtr(line_direction_)) {
NGLogicalLineItem* first_child = line_box->FirstInFlowChild();
for (auto& child : base::Reversed(*line_box)) {
if (EllipsizeChild(line_width, ellipsis_width_, &child == first_child,
&child, &truncated_child)) {
ellipsized_child = &child;
break;
}
}
} else {
NGLogicalLineItem* first_child = line_box->LastInFlowChild();
for (auto& child : *line_box) {
if (EllipsizeChild(line_width, ellipsis_width_, &child == first_child,
&child, &truncated_child)) {
ellipsized_child = &child;
break;
}
}
}
// Abort if ellipsis could not be placed.
if (!ellipsized_child)
return line_width;
// Truncate the text fragment if needed.
if (truncated_child) {
// In order to preserve layout information before truncated, hide the
// original fragment and insert a truncated one.
size_t child_index_to_truncate = ellipsized_child - line_box->begin();
line_box->InsertChild(child_index_to_truncate + 1,
std::move(*truncated_child));
box_states->ChildInserted(child_index_to_truncate + 1);
NGLogicalLineItem* child_to_truncate =
&(*line_box)[child_index_to_truncate];
ellipsized_child = std::next(child_to_truncate);
HideChild(child_to_truncate);
DCHECK_LE(ellipsized_child->inline_size, child_to_truncate->inline_size);
if (UNLIKELY(IsRtl(line_direction_))) {
ellipsized_child->rect.offset.inline_offset +=
child_to_truncate->inline_size - ellipsized_child->inline_size;
}
}
// Create the ellipsis, associating it with the ellipsized child.
LayoutUnit ellipsis_inline_offset =
PlaceEllipsisNextTo(line_box, ellipsized_child);
return std::max(ellipsis_inline_offset + ellipsis_width_, line_width);
}
// This function was designed to work only with <input type=file>.
// We assume the line box contains:
// (Optional) children without in-flow fragments
// Children with in-flow fragments, and
// (Optional) children without in-flow fragments
// in this order, and the children with in-flow fragments have no padding,
// no border, and no margin.
// Children with IsPlaceholder() can appear anywhere.
LayoutUnit NGLineTruncator::TruncateLineInTheMiddle(
LayoutUnit line_width,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) {
// Shape the ellipsis and compute its inline size.
SetupEllipsis();
NGLogicalLineItems& line = *line_box;
wtf_size_t initial_index_left = kNotFound;
wtf_size_t initial_index_right = kNotFound;
for (wtf_size_t i = 0; i < line_box->size(); ++i) {
auto& child = line[i];
if (child.IsPlaceholder())
continue;
if (!child.shape_result) {
if (initial_index_right != kNotFound)
break;
continue;
}
// Skip pseudo elements like ::before.
if (!child.GetNode())
continue;
if (initial_index_left == kNotFound)
initial_index_left = i;
initial_index_right = i;
}
// There are no truncatable children.
if (initial_index_left == kNotFound)
return line_width;
DCHECK_NE(initial_index_right, kNotFound);
DCHECK(line[initial_index_left].HasInFlowFragment());
DCHECK(line[initial_index_right].HasInFlowFragment());
// line[]:
// s s s p f f p f f s s
// ^ ^
// initial_index_left |
// initial_index_right
// s: child without in-flow fragment
// p: placeholder child
// f: child with in-flow fragment
const LayoutUnit static_width_left = line[initial_index_left].InlineOffset();
LayoutUnit static_width_right = LayoutUnit(0);
if (initial_index_right + 1 < line.size()) {
const NGLogicalLineItem& item = line[initial_index_right + 1];
// |line_width| and/or InlineOffset() might be saturated.
if (line_width <= item.InlineOffset())
return line_width;
// We can do nothing if the right-side static item sticks out to the both
// sides.
if (item.InlineOffset() < 0)
return line_width;
static_width_right =
line_width - item.InlineOffset() + item.margin_line_left;
}
const LayoutUnit available_width =
available_width_ - static_width_left - static_width_right;
if (available_width <= ellipsis_width_)
return line_width;
LayoutUnit available_width_left = (available_width - ellipsis_width_) / 2;
LayoutUnit available_width_right = available_width_left;
// Children for ellipsis and truncated fragments will have index which
// is >= new_child_start.
const wtf_size_t new_child_start = line.size();
wtf_size_t index_left = initial_index_left;
wtf_size_t index_right = initial_index_right;
if (IsLtr(line_direction_)) {
// Find truncation point at the left, truncate, and add an ellipsis.
while (available_width_left >= line[index_left].inline_size) {
available_width_left -= line[index_left++].inline_size;
if (index_left >= line.size()) {
// We have a logic bug. Do nothing.
return line_width;
}
}
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_left].IsPlaceholder());
wtf_size_t new_index = AddTruncatedChild(
index_left, index_left == initial_index_left, available_width_left,
TextDirection::kLtr, line_box, box_states);
if (new_index == kDidNotAddChild) {
DCHECK_GT(index_left, initial_index_left);
DCHECK_GT(index_left, 0u);
wtf_size_t i = index_left;
while (!line[--i].HasInFlowFragment())
DCHECK(line[i].IsPlaceholder());
PlaceEllipsisNextTo(line_box, &line[i]);
available_width_right += available_width_left;
} else {
PlaceEllipsisNextTo(line_box, &line[new_index]);
available_width_right +=
available_width_left - line[new_index].inline_size;
}
// Find truncation point at the right.
while (available_width_right >= line[index_right].inline_size) {
available_width_right -= line[index_right].inline_size;
if (index_right == 0) {
// We have a logic bug. We proceed anyway because |line| was already
// modified.
break;
}
--index_right;
}
LayoutUnit new_modified_right_offset =
line[line.size() - 1].InlineOffset() + ellipsis_width_;
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_right].IsPlaceholder());
if (available_width_right > 0) {
new_index = AddTruncatedChild(
index_right, false,
line[index_right].inline_size - available_width_right,
TextDirection::kRtl, line_box, box_states);
if (new_index != kDidNotAddChild) {
line[new_index].rect.offset.inline_offset = new_modified_right_offset;
new_modified_right_offset += line[new_index].inline_size;
}
}
// Shift unchanged children at the right of the truncated child.
// It's ok to modify existing children's offsets because they are not
// web-exposed.
LayoutUnit offset_diff = line[index_right].InlineOffset() +
line[index_right].inline_size -
new_modified_right_offset;
for (wtf_size_t i = index_right + 1; i < new_child_start; ++i)
line[i].rect.offset.inline_offset -= offset_diff;
line_width -= offset_diff;
} else {
// Find truncation point at the right, truncate, and add an ellipsis.
while (available_width_right >= line[index_right].inline_size) {
available_width_right -= line[index_right].inline_size;
if (index_right == 0) {
// We have a logic bug. Do nothing.
return line_width;
}
--index_right;
}
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_right].IsPlaceholder());
wtf_size_t new_index =
AddTruncatedChild(index_right, index_right == initial_index_right,
line[index_right].inline_size - available_width_right,
TextDirection::kRtl, line_box, box_states);
if (new_index == kDidNotAddChild) {
DCHECK_LT(index_right, initial_index_right);
wtf_size_t i = index_right;
while (!line[++i].HasInFlowFragment())
DCHECK(line[i].IsPlaceholder());
PlaceEllipsisNextTo(line_box, &line[i]);
available_width_left += available_width_right;
} else {
line[new_index].rect.offset.inline_offset +=
line[index_right].inline_size - line[new_index].inline_size;
PlaceEllipsisNextTo(line_box, &line[new_index]);
available_width_left +=
available_width_right - line[new_index].inline_size;
}
LayoutUnit ellipsis_offset = line[line.size() - 1].InlineOffset();
// Find truncation point at the left.
while (available_width_left >= line[index_left].inline_size) {
available_width_left -= line[index_left++].inline_size;
if (index_left >= line.size()) {
// We have a logic bug. We proceed anyway because |line| was already
// modified.
break;
}
}
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_left].IsPlaceholder());
if (available_width_left > 0) {
new_index = AddTruncatedChild(index_left, false, available_width_left,
TextDirection::kLtr, line_box, box_states);
if (new_index != kDidNotAddChild) {
line[new_index].rect.offset.inline_offset =
ellipsis_offset - line[new_index].inline_size;
}
}
// Shift unchanged children at the left of the truncated child.
// It's ok to modify existing children's offsets because they are not
// web-exposed.
LayoutUnit offset_diff =
line[line.size() - 1].InlineOffset() - line[index_left].InlineOffset();
for (wtf_size_t i = index_left; i > 0; --i)
line[i - 1].rect.offset.inline_offset += offset_diff;
line_width -= offset_diff;
}
// Hide left/right truncated children and children between them.
for (wtf_size_t i = index_left; i <= index_right; ++i) {
if (line[i].HasInFlowFragment())
HideChild(&line[i]);
}
return line_width;
}
// Hide this child from being painted. Leaves a hidden fragment so that layout
// queries such as |offsetWidth| work as if it is not truncated.
void NGLineTruncator::HideChild(NGLogicalLineItem* child) {
DCHECK(child->HasInFlowFragment());
if (const NGLayoutResult* layout_result = child->layout_result.get()) {
// Need to propagate OOF descendants in this inline-block child.
const auto& fragment =
To<NGPhysicalBoxFragment>(layout_result->PhysicalFragment());
if (fragment.HasOutOfFlowPositionedDescendants())
return;
// Truncate this object. Atomic inline is monolithic.
DCHECK(fragment.IsMonolithic());
LayoutObject* layout_object = fragment.GetMutableLayoutObject();
DCHECK(layout_object);
DCHECK(layout_object->IsAtomicInlineLevel());
layout_object->SetIsTruncated(true);
return;
}
if (child->inline_item) {
child->is_hidden_for_paint = true;
return;
}
NOTREACHED();
}
// Return the offset to place the ellipsis.
//
// This function may truncate or move the child so that the ellipsis can fit.
bool NGLineTruncator::EllipsizeChild(
LayoutUnit line_width,
LayoutUnit ellipsis_width,
bool is_first_child,
NGLogicalLineItem* child,
absl::optional<NGLogicalLineItem>* truncated_child) {
DCHECK(truncated_child && !*truncated_child);
// Leave out-of-flow children as is.
if (!child->HasInFlowFragment())
return false;
// Inline boxes should not be ellipsized. Usually they will be created in the
// later phase, but empty inline box are already created.
if (child->IsInlineBox())
return false;
// Can't place ellipsis if this child is completely outside of the box.
LayoutUnit child_inline_offset =
IsLtr(line_direction_)
? child->InlineOffset()
: line_width - (child->InlineOffset() + child->inline_size);
LayoutUnit space_for_child = available_width_ - child_inline_offset;
if (space_for_child <= 0) {
// This child is outside of the content box, but we still need to hide it.
// When the box has paddings, this child outside of the content box maybe
// still inside of the clipping box.
if (!is_first_child)
HideChild(child);
return false;
}
// At least part of this child is in the box.
// If |child| can fit in the space, truncate this line at the end of |child|.
space_for_child -= ellipsis_width;
if (space_for_child >= child->inline_size)
return true;
// If not all of this child can fit, try to truncate.
if (TruncateChild(space_for_child, is_first_child, *child, truncated_child))
return true;
// This child is partially in the box, but it can't be truncated to fit. It
// should not be visible because earlier sibling will be truncated.
if (!is_first_child)
HideChild(child);
return false;
}
// Truncate the specified child. Returns true if truncated successfully, false
// otherwise.
//
// Note that this function may return true even if it can't fit the child when
// |is_first_child|, because the spec defines that the first character or atomic
// inline-level element on a line must be clipped rather than ellipsed.
// https://drafts.csswg.org/css-ui/#text-overflow
bool NGLineTruncator::TruncateChild(
LayoutUnit space_for_child,
bool is_first_child,
const NGLogicalLineItem& child,
absl::optional<NGLogicalLineItem>* truncated_child) {
DCHECK(truncated_child && !*truncated_child);
// If the space is not enough, try the next child.
if (space_for_child <= 0 && !is_first_child)
return false;
// Only text fragments can be truncated.
if (!child.shape_result)
return is_first_child;
// TODO(layout-dev): Add support for OffsetToFit to ShapeResultView to avoid
// this copy.
scoped_refptr<ShapeResult> shape_result =
child.shape_result->CreateShapeResult();
DCHECK(shape_result);
const NGTextOffset original_offset = child.text_offset;
// Compute the offset to truncate.
unsigned offset_to_fit = shape_result->OffsetToFit(
IsLtr(line_direction_) ? space_for_child
: shape_result->Width() - space_for_child,
line_direction_);
DCHECK_LE(offset_to_fit, original_offset.Length());
if (!offset_to_fit || offset_to_fit == original_offset.Length()) {
if (!is_first_child)
return false;
offset_to_fit = !offset_to_fit ? 1 : offset_to_fit - 1;
}
*truncated_child =
TruncateText(child, *shape_result, offset_to_fit, line_direction_);
return true;
}
NGLogicalLineItem NGLineTruncator::TruncateText(const NGLogicalLineItem& item,
const ShapeResult& shape_result,
unsigned offset_to_fit,
TextDirection direction) {
const NGTextOffset new_text_offset =
direction == shape_result.Direction()
? NGTextOffset(item.StartOffset(), item.StartOffset() + offset_to_fit)
: NGTextOffset(item.StartOffset() + offset_to_fit, item.EndOffset());
scoped_refptr<ShapeResultView> new_shape_result = ShapeResultView::Create(
&shape_result, new_text_offset.start, new_text_offset.end);
DCHECK(item.inline_item);
return NGLogicalLineItem(item, std::move(new_shape_result), new_text_offset);
}
} // namespace blink
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
EmptyRenderTarget.cpp: Empty render target implementation.
=============================================================================*/
#include "EmptyRHIPrivate.h"
#include "ScreenRendering.h"
void FEmptyDynamicRHI::RHICopyToResolveTarget(FTextureRHIParamRef SourceTextureRHI, FTextureRHIParamRef DestTextureRHI, bool bKeepOriginalSurface, const FResolveParams& ResolveParams)
{
}
void FEmptyDynamicRHI::RHIReadSurfaceData(FTextureRHIParamRef TextureRHI, FIntRect Rect, TArray<FColor>& OutData, FReadSurfaceDataFlags InFlags)
{
}
void FEmptyDynamicRHI::RHIMapStagingSurface(FTextureRHIParamRef TextureRHI,void*& OutData,int32& OutWidth,int32& OutHeight)
{
}
void FEmptyDynamicRHI::RHIUnmapStagingSurface(FTextureRHIParamRef TextureRHI)
{
}
void FEmptyDynamicRHI::RHIReadSurfaceFloatData(FTextureRHIParamRef TextureRHI, FIntRect Rect, TArray<FFloat16Color>& OutData, ECubeFace CubeFace,int32 ArrayIndex,int32 MipIndex)
{
}
void FEmptyDynamicRHI::RHIRead3DSurfaceFloatData(FTextureRHIParamRef TextureRHI,FIntRect InRect,FIntPoint ZMinMax,TArray<FFloat16Color>& OutData)
{
}
|
/*
* This file is part of staq.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* \file optimization/rotation_folding.hpp
* \brief Rotation folding algorithm
*/
#pragma once
#include "ast/visitor.hpp"
#include "ast/replacer.hpp"
#include "gates/channel.hpp"
#include <list>
#include <unordered_map>
#include <sstream>
namespace staq {
namespace optimization {
/**
* \class staq::optimization::RotationOptimizer
* \brief Rotation gate merging algorithm based on arXiv:1903.12456
*
* Returns a replacement list giving the nodes to the be replaced (or erased)
*/
class RotationOptimizer final : public ast::Visitor {
using Gatelib = gates::ChannelRepr<ast::VarAccess>;
public:
struct config {
bool correct_global_phase = true;
};
RotationOptimizer() = default;
RotationOptimizer(const config& params) : Visitor(), config_(params) {}
~RotationOptimizer() = default;
std::unordered_map<int, std::list<ast::ptr<ast::Gate>>>
run(ast::ASTNode& node) {
reset();
node.accept(*this);
return std::move(replacement_list_);
}
/* Variables */
void visit(ast::VarAccess&) {}
/* Expressions */
void visit(ast::BExpr&) {}
void visit(ast::UExpr&) {}
void visit(ast::PiExpr&) {}
void visit(ast::IntExpr&) {}
void visit(ast::RealExpr&) {}
void visit(ast::VarExpr&) {}
/* Statements */
void visit(ast::MeasureStmt& stmt) {
push_uninterp(Gatelib::Uninterp({stmt.q_arg()}));
}
void visit(ast::ResetStmt& stmt) {
push_uninterp(Gatelib::Uninterp({stmt.arg()}));
}
void visit(ast::IfStmt& stmt) {
mergeable_ = false;
stmt.then().accept(*this);
mergeable_ = true;
}
/* Gates */
void visit(ast::UGate& gate) {
push_uninterp(Gatelib::Uninterp({gate.arg()}));
}
void visit(ast::CNOTGate& gate) {
auto ctrl = gate.ctrl();
auto tgt = gate.tgt();
if (mergeable_) {
current_clifford_ *= Gatelib::Clifford::cnot(ctrl, tgt);
} else {
push_uninterp(Gatelib::Uninterp({ctrl, tgt}));
}
}
void visit(ast::BarrierGate& gate) {
push_uninterp(Gatelib::Uninterp({gate.args()}));
}
void visit(ast::DeclaredGate& gate) {
auto name = gate.name();
if (mergeable_) {
if (name == "cx")
current_clifford_ *=
Gatelib::Clifford::cnot(gate.qarg(0), gate.qarg(1));
else if (name == "h")
current_clifford_ *= Gatelib::Clifford::h(gate.qarg(0));
else if (name == "x")
current_clifford_ *= Gatelib::Clifford::x(gate.qarg(0));
else if (name == "y")
current_clifford_ *= Gatelib::Clifford::y(gate.qarg(0));
else if (name == "z")
current_clifford_ *= Gatelib::Clifford::z(gate.qarg(0));
else if (name == "s")
current_clifford_ *= Gatelib::Clifford::sdg(gate.qarg(0));
else if (name == "sdg")
current_clifford_ *= Gatelib::Clifford::s(gate.qarg(0));
else if (name == "t") {
auto rot = Gatelib::Rotation::t(gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::z,
gate.qarg(0)};
accum_.push_back(
std::make_pair(info, rot.commute_left(current_clifford_)));
} else if (name == "tdg") {
auto rot = Gatelib::Rotation::tdg(gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::z,
gate.qarg(0)};
accum_.push_back(
std::make_pair(info, rot.commute_left(current_clifford_)));
} else if (name == "rz") {
auto angle = gate.carg(0).constant_eval();
if (angle) {
auto rot = Gatelib::Rotation::rz(utils::Angle(*angle),
gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::z,
gate.qarg(0)};
accum_.push_back(std::make_pair(
info, rot.commute_left(current_clifford_)));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
} else if (name == "rx") {
auto angle = gate.carg(0).constant_eval();
if (angle) {
auto rot = Gatelib::Rotation::rx(utils::Angle(*angle),
gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::x,
gate.qarg(0)};
accum_.push_back(std::make_pair(
info, rot.commute_left(current_clifford_)));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
} else if (name == "ry") {
auto angle = gate.carg(0).constant_eval();
if (angle) {
auto rot = Gatelib::Rotation::ry(utils::Angle(*angle),
gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::y,
gate.qarg(0)};
accum_.push_back(std::make_pair(
info, rot.commute_left(current_clifford_)));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
} else
push_uninterp(Gatelib::Uninterp(gate.qargs()));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
}
/* Declarations */
void visit(ast::GateDecl& decl) {
// Initialize a new local state
circuit_callback local_state;
Gatelib::Clifford local_clifford;
std::swap(accum_, local_state);
std::swap(current_clifford_, local_clifford);
// Process gate body
decl.foreach_stmt([this](auto& stmt) { stmt.accept(*this); });
accum_.push_back(current_clifford_);
// Fold the gate body
fold(accum_, true);
// Reset the state
std::swap(accum_, local_state);
std::swap(current_clifford_, local_clifford);
}
void visit(ast::OracleDecl&) {}
void visit(ast::RegisterDecl&) {}
void visit(ast::AncillaDecl&) {}
/* Program */
void visit(ast::Program& prog) {
prog.foreach_stmt([this](auto& stmt) { stmt.accept(*this); });
accum_.push_back(current_clifford_);
fold(accum_, config_.correct_global_phase);
}
private:
// Store information necessary for generating a replacement of <node> with a
// different angle
struct rotation_info {
enum class axis { x, y, z };
int uid;
axis rotation_axis;
ast::VarAccess arg;
};
using circuit_callback =
std::list<std::variant<Gatelib::Uninterp, Gatelib::Clifford,
std::pair<rotation_info, Gatelib::Rotation>>>;
config config_;
std::unordered_map<int, std::list<ast::ptr<ast::Gate>>> replacement_list_;
/* Algorithm state */
circuit_callback
accum_; // The currently accumulating circuit (in channel repr.)
bool mergeable_ =
true; // Whether we're in a context where a gate can be merged
Gatelib::Clifford current_clifford_; // The current clifford operator
// Note: current clifford is stored as the dagger of the actual Clifford
// gate this is so that left commutation (i.e. conjugation) actually
// right-commutes the rotation gate, allowing us to walk the circuit
// forwards rather than backwards That is, we want to end up with the form
// C_0R_1R_2R_3...R_n
// rather than the form
// R_n...R_3R_2R_1C_0
// as in the paper
void reset() {
replacement_list_.clear();
accum_.clear();
mergeable_ = true;
current_clifford_ = Gatelib::Clifford();
}
/* Phase two of the algorithm */
void fold(circuit_callback& circuit, bool phase_correction) {
auto global_phase = utils::angles::zero;
ast::VarAccess* tgt = nullptr;
std::list<ast::ptr<ast::Gate>>* subst_ref = nullptr;
for (auto it = circuit.rbegin(); it != circuit.rend(); it++) {
auto& op = *it;
if (auto tmp =
std::get_if<std::pair<rotation_info, Gatelib::Rotation>>(
&op)) {
auto [new_phase, new_R] =
fold_forward(circuit, std::next(it), tmp->second);
global_phase += new_phase;
if (!(new_R == tmp->second)) {
std::list<ast::ptr<ast::Gate>> subst;
auto rot = alloc_rot(tmp->first, new_R.rotation_angle());
if (rot)
subst.emplace_back(rot);
replacement_list_[tmp->first.uid] = std::move(subst);
// WARNING: this is a massive hack so that the global phase
// correction can be performed by the replacement engine. We
// append the final phase correction to the last gate
// substitution in-place in the replacement list. Since we
// need a qubit to apply the phase correction on, we select
// the qubit on which the rotation itself was applied.
tgt = &(tmp->first.arg);
subst_ref = &(replacement_list_[tmp->first.uid]);
}
}
}
if (phase_correction && (global_phase != utils::angles::zero)) {
if (global_phase == utils::angles::pi) {
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "z", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "z", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
} else if (global_phase == utils::angles::pi_half) {
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
} else if (global_phase == -utils::angles::pi_half) {
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
} else if (global_phase == utils::angles::pi_quarter) {
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
} else if (global_phase == -utils::angles::pi_quarter) {
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
} else {
std::vector<ast::ptr<ast::Expr>> tmp1;
std::vector<ast::ptr<ast::Expr>> tmp2;
tmp1.emplace_back(ast::angle_to_expr(global_phase));
tmp2.emplace_back(ast::angle_to_expr(global_phase));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "rz", std::move(tmp1), {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "rz", std::move(tmp2), {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
}
}
}
std::pair<utils::Angle, Gatelib::Rotation>
fold_forward(circuit_callback& circuit,
circuit_callback::reverse_iterator it, Gatelib::Rotation R) {
// Tries to commute op backward as much as possible, merging with
// applicable gates and deleting them as it goes Note: We go backwards
// so that we only commute **left** past C^*/**right** past C
auto phase = utils::angles::zero;
bool cont = true;
for (; cont && it != circuit.rend(); it++) {
auto visitor = utils::overloaded{
[this, it, &R, &phase,
&circuit](std::pair<rotation_info, Gatelib::Rotation>& P) {
auto res = R.try_merge(P.second);
if (res) {
auto& [new_phase, new_R] = res.value();
phase += new_phase;
R = new_R;
// Delete R in circuit & the node
replacement_list_[P.first.uid] =
std::move(std::list<ast::ptr<ast::Gate>>());
circuit.erase(std::next(it).base());
return false;
} else if (R.commutes_with(P.second)) {
return true;
} else {
return false;
}
},
[&R](Gatelib::Clifford& C) {
R = R.commute_left(C);
return true;
},
[&R](Gatelib::Uninterp& U) {
if (!R.commutes_with(U))
return false;
else
return true;
}};
cont = std::visit(visitor, *it);
}
return std::make_pair(phase, R);
}
/* Utilities */
void push_uninterp(Gatelib::Uninterp op) {
accum_.push_back(current_clifford_);
accum_.push_back(op);
// Clear the current clifford
current_clifford_ = Gatelib::Clifford();
}
// Assumes basic gates (x, y, z, s, sdg, t, tdg, rx, ry, rz) are defined
ast::Gate* alloc_rot(const rotation_info& rinfo,
const utils::Angle& theta) {
if (theta.numeric_value() == 0)
return nullptr;
parser::Position pos;
std::string name;
std::vector<ast::ptr<ast::Expr>> cargs;
std::vector<ast::VarAccess> qargs{rinfo.arg};
// Determine the name & classical arguments
if (theta.is_numeric()) {
// Angle is real-valued
switch (rinfo.rotation_axis) {
case rotation_info::axis::x:
name = "rx";
break;
case rotation_info::axis::y:
name = "ry";
break;
case rotation_info::axis::z:
name = "rz";
break;
}
cargs.emplace_back(ast::angle_to_expr(theta));
} else {
// Angle is of the form pi*(a/b) for a & b integers
auto [a, b] = *(theta.symbolic_value());
switch (rinfo.rotation_axis) {
case rotation_info::axis::x:
if ((a == 1) && (b == 1)) {
// X gate
name = "x";
} else {
// Rx gate
name = "rx";
cargs.emplace_back(ast::angle_to_expr(theta));
}
break;
case rotation_info::axis::y:
if ((a == 1) && (b == 1)) {
// Y gate
name = "y";
} else {
// Ry gate
name = "ry";
cargs.emplace_back(ast::angle_to_expr(theta));
}
break;
case rotation_info::axis::z:
if ((a == 1) && (b == 1)) {
// Z gate
name = "z";
} else if (((a == 1) || (a == -3)) && (b == 2)) {
// S gate
name = "s";
} else if (((a == -1) || (a == 3)) && (b == 2)) {
// Sdg gate
name = "sdg";
} else if (((a == 1) || (a == -7)) && (b == 4)) {
// T gate
name = "t";
} else if (((a == -1) || (a == 7)) && (b == 4)) {
// Tdg gate
name = "tdg";
} else {
// Rz gate
name = "rz";
cargs.emplace_back(ast::angle_to_expr(theta));
}
break;
}
}
return new ast::DeclaredGate(pos, name, std::move(cargs),
std::move(qargs));
}
};
/** \brief Performs the rotation folding optimization */
inline void fold_rotations(ast::ASTNode& node) {
RotationOptimizer optimizer;
auto res = optimizer.run(node);
replace_gates(node, std::move(res));
}
/** \brief Performs the rotation folding optimization with configuration */
inline void fold_rotations(ast::ASTNode& node,
const RotationOptimizer::config& params) {
RotationOptimizer optimizer(params);
auto res = optimizer.run(node);
replace_gates(node, std::move(res));
}
} // namespace optimization
} // namespace staq
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOMLSInput.hpp 527149 2007-04-10 14:56:39Z amassari $
*/
#if !defined(XERCESC_INCLUDE_GUARD_DOMLSINPUT_HPP)
#define XERCESC_INCLUDE_GUARD_DOMLSINPUT_HPP
#include <xercesc/util/XercesDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class InputSource;
/**
* This interface represents a single input source for an XML entity.
*
* <p>This interface allows an application to encapsulate information about
* an input source in a single object, which may include a public identifier,
* a system identifier, a byte stream (possibly with a specified encoding),
* and/or a character stream.</p>
*
* <p>There are two places that the application will deliver this input source
* to the parser: as the argument to the parse method, or as the return value
* of the DOMLSResourceResolver.resolveResource method.</p>
*
* <p>The DOMLSParser will use the DOMLSInput object to determine how to
* read XML input. If there is a character stream available, the parser will
* read that stream directly; if not, the parser will use a byte stream, if
* available; if neither a character stream nor a byte stream is available,
* the parser will attempt to open a URI connection to the resource identified
* by the system identifier.</p>
*
* <p>A DOMLSInput object belongs to the application: the parser shall
* never modify it in any way (it may modify a copy if necessary).</p>
*
* @see DOMLSParser#parse
* @see DOMLSResourceResolver#resolveResource
* @since DOM Level 3
*/
class CDOM_EXPORT DOMLSInput
{
protected:
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
/** @name Hidden constructors */
//@{
DOMLSInput() {};
//@}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
/** @name Unimplemented constructors and operators */
//@{
DOMLSInput(const DOMLSInput &);
DOMLSInput & operator = (const DOMLSInput &);
//@}
public:
// -----------------------------------------------------------------------
// All constructors are hidden, just the destructor is available
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
/**
* Destructor
*
*/
virtual ~DOMLSInput() {};
//@}
// -----------------------------------------------------------------------
// Virtual DOMLSInput interface
// -----------------------------------------------------------------------
/** @name Functions introduced in DOM Level 3 */
//@{
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/**
* String data to parse. If provided, this will always be treated as a sequence of 16-bit units (UTF-16 encoded characters).
* It is not a requirement to have an XML declaration when using stringData. If an XML declaration is present, the value of
* the encoding attribute will be ignored.
*
*/
virtual const XMLCh* getStringData() const = 0;
/**
* Returns the byte stream for this input source.
*
* @see InputSource
*/
virtual InputSource* getByteStream() const = 0;
/**
* An input source can be set to force the parser to assume a particular
* encoding for the data that input source reprsents, via the setEncoding()
* method. This method returns name of the encoding that is to be forced.
* If the encoding has never been forced, it returns a null pointer.
*
* @return The forced encoding, or null if none was supplied.
* @see #setEncoding
* @since DOM Level 3
*/
virtual const XMLCh* getEncoding() const = 0;
/**
* Get the public identifier for this input source.
*
* @return The public identifier, or null if none was supplied.
* @see #setPublicId
* @since DOM Level 3
*/
virtual const XMLCh* getPublicId() const = 0;
/**
* Get the system identifier for this input source.
*
* <p>If the system ID is a URL, it will be fully resolved.</p>
*
* @return The system identifier.
* @see #setSystemId
* @since DOM Level 3
*/
virtual const XMLCh* getSystemId() const = 0;
/**
* Get the base URI to be used for resolving relative URIs to absolute
* URIs. If the baseURI is itself a relative URI, the behavior is
* implementation dependent.
*
* @return The base URI.
* @see #setBaseURI
* @since DOM Level 3
*/
virtual const XMLCh* getBaseURI() const = 0;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/**
* Sets the UTF-16 string for this input source.
*
*/
virtual void setStringData(const XMLCh* data) = 0;
/**
* Sets the byte stream for this input source.
*
* @see BinInputStream
*/
virtual void setByteStream(InputSource* stream) = 0;
/**
* Set the encoding which will be required for use with the XML text read
* via a stream opened by this input source.
*
* <p>This is usually not set, allowing the encoding to be sensed in the
* usual XML way. However, in some cases, the encoding in the file is known
* to be incorrect because of intermediate transcoding, for instance
* encapsulation within a MIME document.
*
* @param encodingStr The name of the encoding to force.
* @since DOM Level 3
*/
virtual void setEncoding(const XMLCh* const encodingStr) = 0;
/**
* Set the public identifier for this input source.
*
* <p>The public identifier is always optional: if the application writer
* includes one, it will be provided as part of the location information.</p>
*
* @param publicId The public identifier as a string.
* @see #getPublicId
* @since DOM Level 3
*/
virtual void setPublicId(const XMLCh* const publicId) = 0;
/**
* Set the system identifier for this input source.
*
* <p>The system id is always required. The public id may be used to map
* to another system id, but the system id must always be present as a fall
* back.</p>
*
* <p>If the system ID is a URL, it must be fully resolved.</p>
*
* @param systemId The system identifier as a string.
* @see #getSystemId
* @since DOM Level 3
*/
virtual void setSystemId(const XMLCh* const systemId) = 0;
/**
* Set the base URI to be used for resolving relative URIs to absolute
* URIs. If the baseURI is itself a relative URI, the behavior is
* implementation dependent.
*
* @param baseURI The base URI.
* @see #getBaseURI
* @since DOM Level 3
*/
virtual void setBaseURI(const XMLCh* const baseURI) = 0;
//@}
// -----------------------------------------------------------------------
// Non-standard Extension
// -----------------------------------------------------------------------
/** @name Non-standard Extension */
//@{
/**
* Indicates if the parser should issue fatal error if this input source
* is not found. If set to false, the parser issue warning message instead.
*
* @param flag True if the parser should issue fatal error if this input source is not found.
* If set to false, the parser issue warning message instead. (Default: true)
*
* @see #getIssueFatalErrorIfNotFound
*/
virtual void setIssueFatalErrorIfNotFound(bool flag) = 0;
/**
* Get the flag that indicates if the parser should issue fatal error if this input source
* is not found.
*
* @return True if the parser should issue fatal error if this input source is not found.
* False if the parser issue warning message instead.
* @see #setIssueFatalErrorIfNotFound
*/
virtual bool getIssueFatalErrorIfNotFound() const = 0;
/**
* Called to indicate that this DOMLSInput is no longer in use
* and that the implementation may relinquish any resources associated with it.
*
* Access to a released object will lead to unexpected result.
*/
virtual void release() = 0;
//@}
};
XERCES_CPP_NAMESPACE_END
#endif
|
#include <bits/stdc++.h>
using namespace std;
int main() {
// Taking the length of the array
int n;
cin >> n;
vector<int> arr(n);
// Taking the array elements and storing it in arr.
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
// Printing the input array without sort
cout << "Your unsorted array: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
make_heap(arr.begin(), arr.end()); // Building the heap from the array.
sort_heap(arr.begin(), arr.end()); // Sorting the heap
// Printing the sorted array
cout << "Your sorted array: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
|
Pay the ransom, and then pay some more: Security teams should bet on defense
By Carl Herberger, Vice President of Security, Radware
When a movie character is kidnapped, paying the ransom doesn’t always result in the hostage’s release. Quite often, the kidnappers simply ask for more money.
In real life, companies who have become victims of a ransom attack face a similar situation. Paying the ransom encourages the hackers to attack again, and certainly keeps them in business to attack others.
Ransom attacks have come primarily in two forms: Distributed Denial-of-Service (DDoS) attacks flood a network or website with requests, paralyzing it, while a second form, so-called non-volumetric attacks, exploit vulnerabilities in a system to encrypt and lock a hard drive. Both models, as you probably know, have the same outcome: To free your frozen data or prevent an impending DDoS attack, hackers demand payment, usually in the form of a hard-to-trace cryptocurrency like Bitcoin.
Whether it’s a classic phishing scheme or an SSL based attack, the threat of DDoS, or another variant, ransom attacks are here to stay. They’re finding new victims and leveraging new tools. If your systems are locked down or under threat of a flood of malicious traffic, should you pay up? If you take the right steps, you might not need to.
Ransom attacks find new, vulnerable targets
Financial institutions remain a favorite target of hackers. That’s where the money is, after all. But cybercriminals have also turned their attention to healthcare facilities, which have proven themselves to be unprepared for attacks and more willing to pay than other organizations.
Hospitals require constant access to health records and their network, and ransomware can cripple operations. At the same time, the private health information sold on Darknet marketplaces commands higher prices than credit card data. In March, for example, an Austin, Texas-based urology practice began notifying 279,000 patients that a ransomware attack may have exposed their confidential financial and medical records.
The healthcare industry isn’t the only sector ripe for extortion – the critical factor is the nexus of money and a desperate need for access to data. The money doesn’t have to be high stakes. College students sometimes pay ransoms of $50 or $100 to unlock the coursework on their hard drives.
New tools, new threats
Ransom attacks have grown sneakier, and more powerful, as hackers try different methods. SSL-based attacks have increased by approximately 10 percent over the past year, according to our research. About 39 percent of companies experienced an SSL-based attack last year, and 75 percent of companies said they aren’t confident they can handle one. SSL attacks are one way hackers are dropping ransomware onto a victim’s system, taking advantage of the encryption to strike vulnerable organizations before they’re aware.
As for ransom DDoS, hackers can up the ante on their threats with powerful botnets harnessed by the Mirai malware. Capable of DDoS attacks above 1 TB, a Mirai botnet offers significant incentive to pay up. Of course, like with any ransom DDoS, no one knows if the hacker can make good on the threat until payment is refused.
To pay or not to pay?
Deciding whether to pay a ransom requires executives to weigh issues of business expediency against their morals. If your IT system is locked down, and you’re caught flat-footed, you can pay the ransom and get back to business, but you put a big target on your organization by doing so, essentially exclaiming that you’re willing to pay to avert an attack.
On the other hand, you can refuse to pay and deal with the loss of data, productivity, and revenue. It’s not an easy choice, but consider the moral question: Do organizations do themselves any favors by keeping criminals in business?
If you’re going to pay, do so knowing that you’ll likely keep paying. The alternative? Shore up your defenses, segment your backups, and build a system that can easily be restored to normal if a user clicks on a bad link. It’s cheaper in the long run, and it slows the flow of cash into the pockets of criminals.
|
/**@file tests/UT_NOK_missing_mandatory-4.cpp
* @author Luc Hermitte <EMAIL:luc{dot}hermitte{at}gmail{dot}com>
*
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
*/
#define BOOST_TEST_MODULE "Named parameters related tests"
#define BOOST_TEST_DYN_LINK
#include "named-parameters.hpp"
#include <boost/test/unit_test.hpp>
#include <vector>
using namespace na::literals;
// ===[ copy_no_default1 ]==================================== {{{1
template <typename ...Args>
void f_copy_with_default4(Args&& ...args)
{
auto a = na::get("a"_na = 1 , std::forward<Args>(args)...);
auto b = na::get("b"_na , std::forward<Args>(args)...);
auto c = na::get("c"_na = "bar", std::forward<Args>(args)...);
auto d = na::get("d"_na = 24.5 , std::forward<Args>(args)...);
}
BOOST_AUTO_TEST_CASE(copy_no_default5)
{
auto v = std::vector<int>{ 1, 2, 3, 4, 5};
auto const x = std::vector<int>{ 11, 12, 13, 14, 15};
f_copy_with_default4(
"a"_na=42,
// "b"_na=v,
"c"_na="foo",
"d"_na=12.5
);
BOOST_CHECK_EQUAL(v.size(), 5); // check v was copied
}
// =========================================================== }}}1
// vim:set fdm=marker:
|
This insightful research by respected Israeli scholar Nurit Peled-Elhanan will confirm what Palestinian researchers have always known: Israel's prevailing culture of racism, fundamentalism, support for war crimes, and apartheid against Palestinians is mainly a product of an educational system that indoctrinates Jewish-Israeli students with militant colonial values and extreme racism that turn them into "monsters" once in uniform.
Guardian: Academic claims Israeli school textbooks contain bias "Nurit Peled-Elhanan of Hebrew University says textbooks depict Palestinians as 'terrorists, refugees and primitive farmers"
"Peled-Elhanan, a professor of language and education at the Hebrew University of Jerusalem, has studied the content of Israeli school books for the past five years, and her account, Palestine in Israeli School Books: Ideology and Propaganda in Education, is to be published in the UK this month. She describes what she found as racism– but, more than that, a racism that prepares young Israelis for their compulsory military service.
"People don't really know what their children are reading in textbooks," she said. "One question that bothers many people is how do you explain the cruel behaviour of Israeli soldiers towards Palestinians, an indifference to human suffering, the inflicting of suffering. People ask how can these nice Jewish boys and girls become monsters once they put on a uniform. I think the major reason for that is education. So I wanted to see how school books represent Palestinians."
In "hundreds and hundreds" of books, she claims she did not find one photograph that depicted an Arab as a "normal person". The most important finding in the books she studied – all authorised by the ministry of education – concerned the historical narrative of events in 1948, the year in which Israel fought a war to establish itself as an independent state, and hundreds of thousands of Palestinians fled the ensuing conflict.
The killing of Palestinians is depicted as something that was necessary for the survival of the nascent Jewish state, she claims."
Those who see this as an aberration of Zionism seem to lack sufficient understanding of what Zionism really is and the central role it plays as a patently racist ideology in justifying ethnic cleansing and racist domination over Palestinians.
One should not wonder then why, at the height of the Israeli massacre in Gaza 2008-09, a Tel Aviv University poll (reported in the Jerusalem Post, Jan. '09) of Jewish-Israeli opinion showed a shocking 94% support for the assault, despite full knowledge of the enormous suffering this Israeli aggression had inflicted upon the 1.5 million Palestinians incarcerated in the Gaza "prison camp" and of the massive destruction of their civilian infrastructure.
As in every other colonial system, only sustained and effective pressure from within as well as from without can put an end to this downward spiral of criminality, impunity and unspoken racism. More BDS is needed to end Israeli occupation, colonialism and apartheid. Other than the obvious benefits to indigenous Palestinians, suffering more than six decades of this three-tiered system of Israeli oppression, an end to this system of oppression may well transform most Israelis from colonial "monsters" into normal humans.
(ed note: Nurit Peled-Elhanan is author of Palestine in Israeli School Books: Ideology and Propaganda in Education. International publisher I.B.TAURIS description: "She analyzes the presentation of images, maps, layouts and use of language in History, Geography and Civic Studies textbooks, and reveals how the books might be seen to marginalize Palestinians, legitimize Israeli military action and reinforce Jewish-Israeli territorial identity. This book provides a fresh scholarly contribution to the Israeli-Palestinian debate, and will be relevant to the fields of Middle East Studies and Politics more widely.")
|
The test team views the use of a pulley as an intermediate step only, and has planned to shift to a reliance on windlasses like those that apparently were used to hoist sails on Egyptian ships.
"The whole approach has been to downgrade the technology," Gharib said. "We first wanted to show that a kite could raise a huge weight at all. Now that we're raising larger and larger stones, we're also preparing to replace the steel scaffolding with wooden poles and the steel pulleys with wooden pulleys like the ones they may have used on Egyptian ships."
For Gharib, the idea of accomplishing heavy tasks with limited manpower is appealing from an engineer's standpoint because it makes more logistical sense.
"You can imagine how hard it is to coordinate the activities of hundreds if not thousands of laborers to accomplish an intricate task," said Gharib. "It's one thing to send thousands of soldiers to attack another army on a battlefield. But an engineering project requires everything to be put precisely into place.
"I prefer to think of the technology as simple, with relatively few people involved," he explained.
Gharib and Graff came up with a way of building a simple structure around the obelisk, with a pulley system mounted in front of the stone. That way, the base of the obelisk would drag on the ground for a few feet as the kite lifted the stone, and the stone would be quite stable once it was pulled upright into a vertical position. If the obelisk were raised with the base as a pivot, the stone would tend to swing past the vertical position and fall the other way.
The top of the obelisk is tied with ropes threaded through the pulleys and attached to the kite. The operation is guided by a couple of workers using ropes attached to the pulleys.
No one has found any evidence that the ancient Egyptians moved stones or any other objects with kites and pulleys. But Clemmons has found some tantalizing hints that the project is on the right track. On a building frieze in a Cairo museum, there is a wing pattern in bas-relief that does not resemble any living bird. Directly below are several men standing near vertical objects that could be ropes.
Gharib's interest in the project is mainly to demonstrate that the technique may be viable.
"We're not Egyptologists," he said. "We're mainly interested in determining whether there is a possibility that the Egyptians were aware of wind power, and whether they used it to make their lives better."
Now that Gharib and his team have successfully raised the four-ton concrete obelisk, they plan to further test the approach using a ten-ton stone, and perhaps an even heavier one after that. Eventually they hope to obtain permission to try using their technique to raise one of the obelisks that still lie in an Egyptian quarry.
"In fact, we may not even need a kite. It could be we can get along with just a drag chute," Gharib said.
An important question is: Was there enough wind in Egypt for a kite or a drag chute to fly? Probably so, as steady winds of up to 30 miles per hour are not unusual in the areas where pyramids and obelisks were found.
(c) 2001 Caltech
SOURCES AND RELATED WEB SITES
|
W 5 km/h
FITV Banner
Reliving the horror in Orlando
Univision’s weekly news show Crónicas de Sábado recently aired a special re-enactment of the 2016 Pulse nightclub mass shooting complete with actors and special effects. They called it Baño de Sangre. Translated, it means Blood Bath.
The producers interviewed the survivors shortly after the massacre which killed 49, many of whom were still in shock and emotionally traumatized. Some had no memory of the interviews while others claim they thought they were speaking with news reporters.
Just months later, Univision began promoting the episode that included actors and special effects. So it’s no surprise that the victims along with Orlando’s LGBTQ community condemned the show and asked Univision to re-think its broadcast.
Univision responded by removing the commercials promoting the show and releasing a statement that the show would be “deeply respectful of the many people whose lives were impacted by this tragedy.” Then they aired the show as planned.
In this age when nearly everyone has a Smart Phone and generations are developing a narcissistic need to share their images with the world, television news has unlimited access to real-time video. Networks air footage of a police stand-off at a college campus while it’s still going on thanks to bystanders uploading images at alarming speeds.
Consequently, we have clearer – and yet more unclear – information about the events in our world. They’re blurry, full of panic and horror, offering more shock and awe than actual facts. But they get ratings.
And true crime partial re-enactments have been a popular television tool for decades. So is it any surprise that these producers went one step further with added blood and special effects? After all, realism is necessary to get the complete picture.
The question is: Do we need this picture?
Shortly after a woman was killed on Highway 61 this past January, dashcam footage of the three-car accident was aired during the TBT News Hour. Was this appropriate? Or necessary?
With the growing concern over the safety of that stretch of road, there was a strong argument that the video would have educational value to the public. The images were slightly blurry and at a distance so no one’s privacy was invaded. No one’s personal loss exploited. However, it did clarify what happened better than the post-accident photos.
Can Univision say the same? Given the preponderance of violence in entertainment, most adults can imagine what it was like with a gunman shooting inside the crowded Pulse nightclub.
And what is the educational value? Is this a how-to video for the next generation of crazed killers?
Every day, television news must decide what kind of visuals to add to their stories. It can be a fine line between information and intrusion. Education and glorification.
Real news focuses on the former. Fake news takes advantage of the latter.
Obviously, the survivors and the victims’ families didn’t have to watch Blood Bath’s violent re-enactment. Most probably didn’t. But now it’s out there. And it should have been enough for everyone the first time.
|
#include "BinaryEntity.hpp"
#include <Entity/EntityData.hh>
#include <Entity/ArchetypeManager.hpp>
#include <Core/AScene.hh>
#include <cereal/types/vector.hpp>
#include <cereal/types/map.hpp>
#include <cereal/types/string.hpp>
#include <Components\ComponentRegistrationManager.hpp>
#include "Components/ArchetypeComponent.hpp"
#include <Utils/Debug.hpp>
namespace AGE
{
BinaryEntity::BinaryEntity()
{}
BinaryEntity::~BinaryEntity()
{}
void BinaryEntity::save(cereal::PortableBinaryOutputArchive &ar, const std::uint32_t version) const
{
AGE::Link link = entity->getLink();
ENTITY_FLAGS flags = entity.getFlags();
ar(cereal::make_nvp("link", link)
, cereal::make_nvp("children", children)
, cereal::make_nvp("flags", flags)
, cereal::make_nvp("components_number", componentTypes)
, CEREAL_NVP(archetypesDependency)
);
for (auto &e : components)
{
ComponentRegistrationManager::getInstance().serializeBinary(e, ar);
}
}
void BinaryEntity::load(cereal::PortableBinaryInputArchive &ar, const std::uint32_t version)
{
ENTITY_FLAGS flags;
AGE_ASSERT(typesMap != nullptr);
ar(entity->getLink()
, children
, flags
, componentTypes
, archetypesDependency);
auto archetypeManager = entity->getScene()->getInstance<AGE::IArchetypeManager>();
// we load archetypes dependency
if (!archetypesDependency.empty())
{
for (auto &dep : archetypesDependency)
{
archetypeManager->loadOne(dep);
}
}
entity->getLink().setPosition(entity->getLink().getPosition());
entity->getLink().setOrientation(entity->getLink().getOrientation());
entity->getLink().setScale(entity->getLink().getScale());
//entity.setFlags(f);
for (auto &e : componentTypes)
{
auto hashType = (*typesMap)[e];
auto newComponent = ComponentRegistrationManager::getInstance().loadBinary(hashType, entity, ar);
}
if (entity->haveComponent<ArchetypeComponent>())
{
auto archetypeName = entity->getComponent<ArchetypeComponent>()->archetypeName;
archetypeManager->spawn(entity, archetypeName);
}
}
}
|
Tutorial Categories:
HTML/CSS JavaScript/AJAX Server-Side Marketing General Comp-Sci
How Java Garbage Collection Works
By Justin Poirier
In the Classroom306 article Details of C/C++ Dereferences and C++ Calls to delete, it is explained that a C/C++ program's heap is contained in a contiguous block of memory, and calls to allocation and deallocation functions/operators (e.g. "new") are solely responsible for managing the heap's contents (dynamically-allocated variables). This article will build on the contents of that article, to explain how memory management works in Java.
The most basic function of the Java Virtual Machine (JVM) is to convert java bytecode to native machine code at run-time. This may be accomplished using interpreting, by which each line of bytecode is converted to machine code just before being executed; or just-in-time compilation, by which conversion is done on several lines of bytecode at a time, and such a block may be reused later in the execution without re-compiling. With either system, the JVM, as opposed to code written by the Java programmer, is frequently in control of the CPU. During certain bouts of control, the JVM performs the additional task of deleting items on the heap that are no longer referenced. This process is called garbage collection, and it does the work that calls to the deallocation functions/operators do in C/C++, making such calls unnecessary in Java.
If garbage collection is implemented with reference counting, the JVM is continuously at work monitoring each heap item, before the time comes to actually delete it. A count is kept for each heap item, of the number of references to it at a given time. The JVM must increment this count whenever a variable in the Java code is set equal to the item, and decrement the count when a variable that previously referenced the item is set equal to null or some other item, or goes out of scope. When this count becomes zero, the item can be deleted.
In modern JVM's, garbage collection is more commonly implemented using tracing. Instead of keeping track of the number of references to an item over time, a tracing collector periodically identifies all references that have been created by the Java program and might be used again (live references), and deletes all items that are not the object of such a reference. The first phase is called marking because referenced objects must be marked in some way--for example, by setting a bit flag in the actual heap space used to store an object. The majority of live references will typically be found in the form of variables local to some active function (ie. existing on the call stack), or as member variables of class instances that are themselves objects of other live references. Therefore a JVM must search for references in both these areas of memory. To do so it must have knowledge of how the raw bits within each function's typical stack frame and each class's typical instance are divided up into variables. However, a JVM may not always distinguish between the types of variables it encounters, and may therefore ignore some live references in favour of discerning whether they are references or other primitive types.
The second phase of tracing, where unreferenced objects are deleted, is called sweeping. As with C/C++, a Java program's heap may suffer from fragmentation after objects are allocated and then deleted. JVM's may try to reduce this effect. In addition to combining adjacent free blocks of memory like C/C++ systems, JVM's may combine non-adjacent free blocks by moving allocated items around using compacting or copying. In order to avoid having to update every reference to an item that has been moved, Java is typically implemented such that a reference points not to the allocated block of an object itself, but to an entry in a lookup table that contains the address of each object referenced. Each access to an object implicitly uses this table. This is similar to the technique used in the dynamically-allocated memory system presented in the Classroom306 article A System to Dynamically-Allocate Memory With Minimal Fragmentation.
|
Refraction and Acceleration
Name: Christopher S.
Why is it that when light travels from a more dense to a
less dense medium, its speed is higher? I've read answers to this
question in your archives but, sadly, still don't get it. One answer
(Jasjeet S Bagla) says that we must not ask the question because light is
massless, hence questions of acceleration don't make sense. It does,
however, seem to be OK to talk about different speeds of light. If you
start at one speed and end at a higher one, why is one not allowed to
talk about acceleration? Bagla goes on to say that it depends on how the
em fields behave in a given medium. It begs the question: what is it
about, say, Perspex and air that makes light accelerate, oops, travel at
different speeds? If you're dealing with the same ray of light, one is
forced to speak of acceleration, no? What other explanation is there for
final velocity>initial velocity? Arthur Smith mentioned a very small
"evanescent" component that travels ahead at c. Where can I learn more
about this? Sorry for the long question. I understand that F=ma and if
there is no m, you cannot talk about a, but, again, you have one velocity
higher than another for the same thing. I need to know more than "that's
just the way em fields are!"
An explanation that satisfies me relates to travel through an interactive
medium. When light interacts with an atom, the photon of light is absorbed
and then emitted. For a moment, the energy of the light is within the atom.
This causes a slight delay. Light travels at the standard speed of light
until interacting with another atom. It is absorbed and emitted, causing
another slight delay. The average effect is taking more time to travel a
meter through glass than through air. This works like a slower speed. An
individual photon does not actually slow down. It gets delayed repeatedly by
the atoms of the medium. A more dense medium has more atoms per meter to
Dr. Ken Mellendorf
Illinois Central College
Congratulations! on not being willing to accept "that is just the way em
fields are!" The answer to your inquiry is not all that simple (my opinion),
but I won't try to do so in the limited space allowed here, not to say my
own limitations of knowledge.
Like so many "simple" physics questions, I find the most lucid, but
accurate, explanation in
Richard Feynman's, "Lectures on Physics" which most libraries will have.
Volume I, Chapter 31-1 through 31-6, which describes refraction, dispersion,
diffraction. The "answer" has to do with how matter alters the electric
field of incident radiation, but I won't pretend to be able to do a better
job than Feynman.
The answer is that you are not dealing with the same ray of light. In
vacuum a photon just keeps going at the speed of light. In a medium,
however, it interacts with the atoms, often being absorbed while bumping
an atomic or molecular motion into a higher energy state. The excited
atom/molecule then can jump to a lower energy state, emitting a photon
while doing so. This can obviously make light appear to travel slower in a
In detail, it is a very complicated question, requiring at least a
graduate course in electromagnetism to begin to understand. Why, for
example do the emitted photons tend to travel in the same direction?
Best, Richard J. Plano
Click here to return to the Physics Archives
Update: June 2012
|
Quality Essay Paper at The Attractive Price
Every day, thousands of students all over the world receive the task to prepare a writing project. The grade for such assignment influences the overall picture of academic performance of a student. It should be noted that preparing essay paper is not the only task. Except for preparing some writing assignment, a student is supposed to attend classes and take part in different activities like sports. What is more, family matters and household are not supposed to be disregarded as well. Meanwhile, each and every student wants to go to the parties or throw them by him or herself. Therefore, the question arises, how to find time for everything? How to achieve the optimum balance?
Unfortunately, for a great number of students it is almost impossible. It is very hard to provide in-depth research when your friends are hanging out at the party and you are supposed to spend hours in the dusty library. Some students give up and fail to maintain a balance in their life. Consequently, they make a poor fist of preparing good paper and receive low grades. Thus, let us focus on the main problems connected with preparing essay papers and clarify why students decide to order the assignments from the different online writing services.
We have conducted a short interview connected with the problems that arise when dealing with essay paper writing. So, these are the most commonly used explanations.
1. Preparing the writing task is time-consuming.
It is not a secret that one has to provide an in-depth research to prepare a good piece of writing. What is more, all the sources used are supposed to be academic and reliable. The next thing is to prepare at least few drafts to make sure that a student is moving in the right direction. One should not forget that deadlines can be very short; it means that everything should be done quickly. References are the cornerstone of the whole essay paper. The reason is that each assignment is supposed to be based on proper evidence. There are a lot of different types of references that can be used in the paper, i. e. scholar journals and magazines, books, interviews, records, documentaries, and others. By and large, there are various sources, but the hardest thing is to pick the right ones.
2.Preparing writing task limit the time that can be spend with friend and family.
It is not a secret that preparing custom essay papers takes a lot of time. Therefore, a student must burn the midnight oil writing the required assignment instead of spending time with friends. What is more, less time will be spent with family. One can conclude that such student will probably miss a great number of fun activities sitting in the library with books.
3. When writing is not your forte, preparing a paper turns into a huge challenge.
Considering the information provided above, it becomes clear that even preparing a draft can become a nightmare for some students. Not to mention the fact that writing is not an easy task for many of those whose writing skills are not very good. Sometimes, it seems that you can easily speak on some topic, but when it comes to writing – tabula rasa. You can spend hours sitting before the screen, but putting your thoughts into writing seems totally impossible. The reason is that not all of us are good writers In this case, ordering custom essay paper is the best solution. One can purchase quality paper from the seasoned professionals who know how to meet all the requirements of the assignment.
If you do not want to worry about your grades any more, choosing our writing service is the best solution. Every customized essay paper that is prepared by our talented and highly qualified writers will bring high grade. At Custom-Essays-Online.com, thousands of students have already received professional writing help. Our company has been working for years and a lot of returning customers are a sign of high quality. Our writing service is totally reliable! All the papers that we propose are at a reasonable price. It should be noted that we hire only those writers who obtain academic degrees and are experienced in preparing assignments of different levels, such as high school, college, and university.
|
How much fun is it to be a child in your home? Do you ever stop to think about how the house looks from their point of view? My task for this week is to conduct a Child’s Eye Audit of our living space, to try and make the rooms more child- and play-friendly. The audit need only take a few minutes and might suggest simple changes to make to improve the play space.
To conduct a child’s eye audit, sit or kneel down so you’re at your child’s eye-level and consider the following things.
1. Safety first. Most importantly, the room needs to be safe and it’s useful t0 review this aspect of your home from time to time as children grow taller, become more mobile or more adventurous. Think about what your child can reach, what you don’t want them to reach and make any necessary adjustments.
2. Child’s eye view. Sit back for a minute on the floor and scan the room. What’s visible to your child at their height, and what’s not? You might display all their lovely paintings on the wall and fridge door – but are they too high for your child to actually see? Is their view just of empty walls? Hang some art work at a lower level or set up a low shelf or table with a display of things they can enjoy.
3. Within reach. Consider how accessible your toys are. Do you have an enabling environment where your child can independently help themselves to toys and resources to use in their play or is everything out of reach? Try to find a balance so you can keep the space tidy whilst still allowing free access. Open shelving and low baskets work well for us with some materials such as paint stored higher up.
4. Ring the changes. Do you always have they same toys out? Sometimes putting away familiar toys and bringing out some forgotten ones can spark new creativity and fun. Don’t have a complete change of resources though, as children do like to know where favourite toys are. With Christmas on the way now is a good time to have a toy audit, donating ones your child has grown out of to the charity shop and getting ideas for their Christmas list.
5. Invitation to play. Do you have any toys that never get played with, or activities that you child rarely takes part in? What can you change to make things more inviting? If you’d like to encourage some more reading, perhaps you could set up a cosy reading corner or story tent – with comfy cushions, a basket of tempting books and a favourite teddy to share with? If your toy kitchen has been ignored for a while, add some new resources to catch your child’s eye: a muffin tin and paper cake cases, some jars of real dried pasta, a recipe book from your shelf or lay the table for a birthday tea and surprise your child with a new play possibility.
Do you sometimes review things from your child’s point of view? What changes have you made to make your space more child- and play- friendly? Leave a comment and share an idea with us.
I’m writing this at one o’clock in the afternoon and the sky is grey and the rain is tumbling down. It’s making me think about how the weather affects our play, and particularly I’m thinking about how much time we spend outdoors in autumn and winter. I don’t think there’s any question that playing outside is wonderful for children: the fresh air, the feeling of space, the sensory benefits of being in nature. I certainly know with my own two girls, and all the children I’ve looked after, that if we’re having a grumpy sort of day, getting outside – in the garden, park or just for a walk – most often is all that’s needed to lighten everyone’s mood.
But it’s getting colder now, and windy and rainy and dark. If you’re the type who is happy to be outside all the time in all weathers, I really do salute you. I however am naturally inclined to prefer a hot cup of coffee and a warm blanket inside! We do play outside everyday, whatever the weather, but there’s no denying we play outdoors less in winter – which I’m guessing is the same for lots of you? So, I’m resolving to put more thought into getting out there and planning on bringing you some posts over the next few months that inspire us to venture out. I’d also like to invite you to share your ideas too. The Play Academy carnival on Friday is open to any of your posts and I’d also love to hear from you if you’d like to write a guest post here. (On any play subject in fact, not just on playing outside. You can e-mail me cathy (at) nurturestore (dot) co (dot) uk if you have an idea you’d like to write about).
To start us off, my top three tips for getting outside, whatever the weather are…
- Keep yourself warm. If you’re wearing the right clothes, you’re much more likely to enjoy your time outside. Pretty much all the children I know don’t care if it’s cold, windy or raining – they are active kids and just love being outside. So, to help everyone enjoy themselves outside, and to stop you cutting short the children’s outdoor fun because you’ve had enough, my first tip is to make sure you are wearing the right clothes. Layer up, don’t forget your hat and gloves and make sure you are cosy.
- Get active. We’re going to shift our outdoor play away from fairy gardens and dinosaur world’s and include lots more active games. Hopscotch, skipping, what’s the time Mr. Wolf are great fun and will keep everyone on the move.
- Audit your outdoor space. Now is a good time to review your garden and get it ready for the colder months. Think about what you play outside and re-locate things or make changes to suit the weather. We’ll move the sandpit and den to under our covered area and make sure there are lots of props outside ready to spark active play (bikes, balls, kites, hula hoops). We’re not likely to do as much water play outside, so I’ll be thinking of ways to bring this inside.
What about you – are you an all weather family? How do you promote lots of outdoor play, whatever the weather?
Back in January I resolved to make 2010 our Year of Play. I’ve been thinking about this again this month as L has started at school. In last week’s Play Academy link-up I talked about wanting to make sure the girls still have lots of opportunity for playing, as well as schooling. So this weeks Twitter Tips are dedicated to having a playful return to school. The Twitter Tips get tweeted on a Friday at 8.30pm and in previous weeks they’ve started great twitter conversations, with people swapping ideas. The main thing I love about blogging is it being a forum to get inspiration and encouragement from others, so please feel free to add your own ideas in the comments or on our Facebook page. Join in, swap ideas, go play!
How to have a playful Back to School
#goplay Twitter Tip #1If you’re using after school clubs check how playful they are: do they offer free play after a structured school day
#goplay Twitter Tip #2Make the school run fun: cycle, scoot or play i-spy. Leave a little earlier to let the kids play a bit before class
#goplay Twitter Tip #3 Set up a play invitation in the morning to entice the kids to play before they switch on the TV
#goplay Twitter Tip #4 Rediscover some old school favourites such as conkers or fortune tellers
#goplay Twitter Tip #5 Consider how many clubs to join so after school play time isn’t lost in a busy schedule.
#goplay Twitter Tip #6 Encourage playground fun by packing a skipping rope in the book bag. Ready for Ten has a great skipping tutuorial
#goplay Twitter Tip #7 Plan family time for the weekend: it doesn’t have to be expensive or extravagant but do make sure it happens.
#goplay Twitter Tip #8 Consider screen time. Could your kids live without TV for an hour, a day, a week? What could they play instead?
#goplay Twitter Tip #9 Locate the park nearest your school and stop off any day day you can on the way home. Enjoy some #playoutdoors
#goplay Twitter Tip#10 Instead of only setting up a homework area set up a play area too. Add untoys & let them #goplay
How do you feel about the balance between school and play time? How do you manage homework at the weekend? Do your kids attend a playful school?
Happily shared with Top Ten Tuesday.
Use the linky below to add your post to the Play Academy
Our summer holidays are drawing to a close and my Little is starting school on Monday (oh my!). I feel very strongly that our play should keep going. B is moving up to the Juniors and although her school offers are great curriculum including play, art, music, drama and experiments I think it’s inevitable that her lessons will become more and more about schooling. September always feels like the start of the year to me, so I’m keeping in mind my resolution to make 2010 our Year of Play, and we’ll certainly be limiting our after school clubs and weekend commitments to allow plenty of time for playing. How do you feel about finding a balance between schooling (or home educating) and play?
I’m looking forward to getting even more inspiration from your Play Academy ideas this week – hope you’ll add a link.
1. Add your post to the Linky below. Remember to link to the individual post rather than your homepage. If you are not a blogger please visit the NurtureStore Facebook page and share your photo there.
2. Go and visit some of the other blogs on the Linky. Leave a comment and say hi. Get ideas. Tell them you’re visiting from the Play Academy.
3. Add a link back from your own post to this Play Academy – your readers can then come and get ideas too. You can use the Play Academy badge if you like.(Grab the code from the column on the left.)
4. Come back next Friday and swap some more play ideas. The next Play Academy linky will be Friday 10th September.
|
Q. How is the value of "my" car determined?
Most insurance companies use a service that maintains late model vehicle values. Like, Kelley Blue Book, or Edmunds. Establishing a value for your car is simply using one of the available formulas to compute the value of your car based upon the general condition of your car, its mileage, plus the options and equipment package on your car and other allowed factors.
|
Steve Jobs Al Davis is dead. The Apple chairman and former CEO who made personal computers, smartphones, tablets, and digital animation mass market products NFL owner who built the Oakland Raiders and became an NFL icon, passed away today. We're going to miss him. Deeply, and personally.
Steven P. Jobs Al Davis passed away on October 5th 8th, 2011 after a long struggle with pancreatic cancer...various illnesses. He was just 56 82 years old. We mourn his passing, and wish his family the very best.
Let's address this up front: Gizmodo Deadspin and Steve Jobs Al Davis had, at best, a tumultuous an imaginary relationship. Yet no matter how much he may have hated us probably had no idea who we were, we admired him.
No, that's not quite right. We loved him.
He was the reason many of us got into this industry N.W.A, or even care about technology gangsta rap at all. He made the computer black and white tracksuits cool and smartphone firing Lane Kiffin a national spectacle. Bill Gates may have put a computer on every office desk, but it was Steve Jobs Al Davis who put one in every dorm room and bedroom and living room brought back the overhead projector. And then years later, he repeated the trick, putting one in every bag and every pocket, thanks to the iPad and iPhone. If you use a computer or smartphone today, it is either one he created, or an imitation of his genius. he hired Tom Cable without investigating his qualifications.
He changed the way movies are made, the way music is sold, the way stories are told, the very way we interact with the world around us. offensive game plans were executed. He helped us work, and gave us new ways to play open up the passing game. He was a myth made Sid Gillman man.
Prior to Steve Jobs Al Davis, computers the Raiders were alien to most of us. They were accessible to few people without an engineering degree a terrible team before he took over head coaching duties in 1963. Not merely because of their complex operating procedures antiquated ground attack, but also because they were so cold and so inhuman boring. Jobs Davis understood that they could be something more than that. That while computersThe Raiders would never be people losers again, he could would endow them with humanity swagger and a "commitment to excellence." He could transform them into machines that not only anyone could use black and silver menaces, but that everyday people would enjoy using with new garish uniforms, thanks to the art of great design. He made them something that would be part of our lives. And he did that again and again. with great pride.
His life story is familiar, but it deserves repeating. He was given up for adoption by his unmarried parents. He grew up in California Flatbush, and was very much a product of that place and time. He took drugs went to Wittenburg University and Syracuse University. He got into phone hacking coaching at Adelphi College. Both were precursers to what would always be his interest: changing the status quo.
In 1976 1960 he started Apple in a garage as an assistant coach with the Los Angeles/San Diego Chargers. Together with Steve Wozniak Gillman, he shipped the first true fully-built personal computer tweaked the West Coast Offense, with, the Apple I"vertical passing game." He drove development of the Mac, threw early and often, understanding that it was the future of computers scoring lots of points. The great thing that we would all see. He brought in a grown up himself in to run the company. And that grown up forced him the Raiders out of the company that he built Oakland and into the wilderness Los Angeles.
While he wasgone in Los Angeles, he started NeXT computer to get greedy. The RaidersNeXT operating system would form the underpinnings of Apple's OS X, and iOS would even flirt with moving to Irwindale.
He also started the best movie studio of the past 30 years "black and silver" movement. Pixar's filmsThe Raiders' uniforms were innovative, to be sure. It pushed the boundaries of CGI team insignias to such an extent that even today its early films iterations still work. But technology is smirking football pirates are only a tool helmet logo. As with everything else he understood that great technology apparel marketing alone is not enough. ItThe Raiders must be human win consistently to have an impact. Pixar Raider moviesfootball tell storiesgames are an event. They make grown men cry dress in barbaric skeleton costumes on humid autumn Sundays. That was the impact of Steve Jobs Al Davis.
He became a family man obsessed with carrying a towel in public. He reunited with his biological mother, and his sister, the writer Mona Simpson. He married. He had children. He was, by all accounts, a great dad. It was his role as husband and father that helped drive his second act at Apple him be more human.
After his return, to Apple, the companythe Raiders began shipping iconic product head coach after iconic product head coach away. Products Moves that defined a decade. The iMac, OS X, the iPod, iTunes Mike White, Joe Bugel, Jon Gruden (which was very good, before it he was very badshipped to Tampa Bay), the iPhone, the iPad Bill Callahan, Lane Kiffin, Tom Cable, Hue Jackson. All of these were deeply human products head football coaches. They reflected his understanding of how technology was used not only in the workplace, but in the home capricious an owner he could be. In his keynotes later years, product demos press conferences typically showed not executives, but families his terrifying visage snarling and covered in Band-Aids.
He made AppleThe Raiders into the most valuable company in the world a sometimes great football team.
He never met his biological father Tom Cable.
He accomplished so many things, in so many fields professional football that it's tempting to compare Jobs Davis to someone from the past. A Thomas Edison Pete Rozelle or a Ben Franklin George Halas, even a Leonardo Da Vinci Nosferatu. We tend to do that because it helps us understand. But it does him a disservice. He was unique. His own person. Our own person.
He was our emblematic genius team owner. In 100 years, when historians talk about the emergence of the age of intelligent machines terrifying football executives, it is Steve Jobs Al Davis they will hold up as the great exemplar of our era.
They will remember his flaws, too. When Atari Davis hired JobsKiffin and Woz Cable to write coach the code for the iconic Atari game Breakoutorganization, the pair earned a $5000 bonus for completing the work, largely done by Woz were both colossal assholes. But Jobs Davis kept the bonus a secret, and only paid his partner $375 living. When his daughter Lisa a gargoyle was born in 1978, he spent two years denying he was her its father. His denials forced her it and her its mother to support themselves on welfare. In the workplace he's often been described as temperamental and even petulant. He could be arrogant and unforgiving.
He was not a god. He was simply a man.
Yet for all his faults, he changed the world. He made it better.
He once famously asked of a press corps critic "what have you done that's so great?" called ESPN's Chris Mortensen a "professional liar." For Jobs Davis, the answer to that question was very nearly unlimited that was a pretty good day.
Our world will be less interesting, less exciting, and less meaningful without him.
Goodbye, Mr. Jobs Davis. We will miss you so very much.
(Ed. Note: Portions of this obit were borrowed from Gizmodo.)
|
#pragma once
/**
* Familyline logging functions
*
* Copyright (C) 2020 Arthur Mendes
*/
#include <chrono>
#include <cstdio>
#include <memory>
#include <vector>
#include <string>
namespace familyline
{
#define LOGDEBUG(log, tag, format, ...) log->write(tag, LogType::Debug, format, __VA_ARGS__)
enum LogType { Debug, Info, Warning, Error, Fatal };
class Logger
{
private:
FILE* _out = nullptr;
LogType _minlog;
std::vector<std::string> blockTags_;
std::chrono::steady_clock::time_point _start;
double getDelta();
public:
Logger(
FILE* out = stderr, LogType minlog = LogType::Info, std::vector<std::string> blockTags = {})
: _out(out),
_minlog(minlog),
_start(std::chrono::steady_clock::now()),
blockTags_(blockTags)
{
}
void write(std::string_view tag, LogType type, const char* format, ...);
};
class LoggerService
{
private:
static std::unique_ptr<Logger> _logger;
public:
static void createLogger(
FILE* out = stderr, LogType minlog = LogType::Debug,
std::vector<std::string> blockTags = {})
{
_logger = std::make_unique<Logger>(out, minlog, blockTags);
}
static std::unique_ptr<Logger>& getLogger() { return _logger; }
};
} // namespace familyline
|
Topics covered: Encapsulation, inheritance, shadowing
Instructor: Prof. Eric Grimson, Prof. John Guttag
OPERATOR: The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To make a donation or view additional materials from hundreds of MIT courses, visit MIT OpenCourseWare at ocw.mit.edu.
PROFESSOR: Last lecture we were talking about classes, and object-oriented programming, and we're going to come back to it today. I'm going to remind you, we were talking about it because we suggested it is a really powerful way of structuring systems, and that's really why we want to use it, It's a very common way of structuring systems. So today I'm going to pick up on a bunch of more nuanced, or more complex if you like, ways of leveraging the power of classes. But we're going to see a bunch of examples that are going to give us a sense. I'm going to talk about inheritance, we're going to talk about shadowing, we're going to talk about iterators. But before get to it, I want to start by just highlighting, sort of, what was the point of classes? So I'll remind you.
A class, I said, was basically a template for an abstract data type. And this was really to drive home this idea of modularity. I want the ability to say, I've got a set of things that naturally belong together, I'm going to cluster them together, I want to treat it like it's a primitive, I want to treat it like it's a float or an int or a string. Is this going to be a point or a segment or something different like that. So it's really a way, as I said, of just trying to cluster data together. And this is a notion of modularity slash abstraction where I'm treating them as primitives. But the second thing we talked about is that we also have a set of methods, using the special name method because we're talking classes. But basically functions that are designed to deal with this data structure. We're trying to group those together as well. So we cluster data and methods.
Second key thing we said was, in the ideal case, which unfortunately Python isn't, but we'll come back to that, in the ideal case, we would have data hiding, and by data hiding, which is sort of a version of encapsulation, what we meant was that you could only get to the internal pieces of that data structure through a proscribed method. Proscribed meaning it's something I set up. So data hiding saying, you would only access the parts through a method. And as we said, unfortunately Python does not enforce this. Meaning that I could create one of these data structures, ideally I'd have a method, that I'm going to see some examples of that I used to get the parts out, unfortunately in Python you could take the name the instance dot some internal variable you'll get it back. It is exposed. And this is actually just not a good idea. So I suggested in my very bad humor, that you practice computational hygiene and you only use appropriate methods to get the parts out. OK didn't laugh the joke last time, you're not going to laugh at it this time, I don't blame you. All right, and then the last piece of this is that we said the class is a template. When we call that class, it makes an instance. So class is used to make instances, meaning particular versions, of that structure, and we said inside the instances we have a set of attributes. Internal variables, methods, that are going to belong to that structure.
OK, so with that in mind, here's what I want to do. I'm going to show you a set of examples, and I want to warn you ahead of time, the code handout today is a little longer than normal because we want to build essentially an extended example of a sequence of examples of classes. We're going to see the idea, of which we're gonna talk about, of inheritance or hierarchy, in which we can have classes that are specializations of other classes. We're gonna see how we can inherit methods, how we can shadow methods, how we can use methods in a variety of ways. So this is a way of suggesting you may find it more convenient to put notes on the code handout rather than in your own notes. Do whatever you like, but I just wanted to alert you, we're going to go through a little more code than normal.
So, the little environment I'm going to build is an environment of people. I'll build a simple little simulation of people. So I'm going to start off with the first class, which I've got up on the screen, and it's on your handout as well, which is I'm going to build an instance, or a class rather, of persons. I'm going to draw a diagram, which I'm gonna try and see if I can do well, over here, of the different objects we're going to have. So I've got, a class, and by the way a class is an object. Instances are also objects, but classes are objects. We're gonna see why we want that in a second. Because I'm gonna build an object, sorry a class, called a person. Now, let's walk through some of the pieces here. The first one is, there's something a little different. Remember last time we had that keyword class and then a name, that name, in this case, person says this is the name for the class, and then we would have just had the semicolon and a bunch of internal things. Here I've got something in parens, and I want to stress this is not a variable. All right, this is not a def, this is a class. I'm going to come back to it, but what this is basically saying is that the person class is going to inherit from another class, which in this case is just the built-in Python object class. Hold on to that thought, it's going to make more sense when we look at a little more interesting example, but I want to highlight that. All right now, if we do this, as I said before, we can create a version of a person, let me just call it per, person.
OK? And what we said last time is, when we wanted to create an instance inside of this class definition, we've got one of those built-in things called init. I'm gonna again remind you, some of the methods we have, Underbar underbar init is going to be the thing that creates the instance. Actually slightly misspeaking, actually Python creates the instance, but it's one thing that fills it in. So in this case, I'm going to give it 2 arguments: Frank Foobar Now, you might have said, wait a minute, init here has 3 arguments: self, family name, and first name. So again, just to remind you, what we said happens here is that when I call this class, person, I'm creating an instance. We'll draw a little instance diagram down here. I'm going to give it the name per. And I should have said inside of person, we've got a set of things. We've got our underbar underbar init, we've got, what else do I have up there? Family name. And a bunch of other methods, down to say.
What happens inside of Python is, when we called the class definition, person, it creates an instance, there it is. Think of it as a pointer to a spot in memory, and then what we do is, we call, or find, that init method, up here, and we apply it. And the first argument self, points to the instance. So this object here is what self looks at. Now you can see what init's going to do. It says, oh, inside of self, which is pointing to here, let me bind a variable, which was, can read that very carefully, it's family underbar name, to the value I passed in, which was 4. Same thing with first name. OK, so the reason I'm stressing this is, self we do not supply explicitly, it is supplied as pointing to the instance, it's giving us that piece of memory. And that is what then gets created. So here's, now, the instance for per. OK, and I put a little label on there, I'm going to call that an isALink, because it is an instance of that class. God bless you.
All right, so once we got this, let's look at what we can do with person. That's why I built person here. And as I said, I've already bound basically, those two pieces. If I want to get a value out, I can give person, or per, rather, this instance, a messaging. In this case I want to get family, what did I say, family name out, now, again I want to stress, what is happening here? per is an instance, it's this thing here. When I say per dot family name, I'm sending it a message, in essence what that does is, it says, from here it's going to go up the chain to this class object and find the appropriate method, which was family name. It is then going to apply that to self, which points to this instance. And that allows it, therefore, is you can see on the code, to look up under self, what's the binding for family name, and print it back up. So self is always going to point to the instance I want and I can use it. OK what else do we have in here? We can get the first name, that's not particularly interesting.
We've got 2 other special methods: that's cmp and str. All right, cmp is our comparison method. And since I, I was about to say I blew it last time, I misspoke last time, a wonderful phrase that politicians like to use, I misspoke last time. Let me clarify again what cmp will do. Underbar underbar cmp is going to be the method you're going to use to compare two instances of an object. Now, let's back up for second. If I wanted to test equality, in fact I could use underbar underbar eq, under under. It's natural to think about an equality tester as returning a Boolean, it's either gonna be true or false, because something's either equal to or not. In many languages, comparisons also return Booleans, which is why I went down this slippery slope. For many languages, either it's greater than or it's not. But Python is different. Python use cmp, in fact it has a built in cmp, which is what we're relying on here. Where am I, right there. And what cmp returns is 1 of 3 values. Given 2 objects, it says if the first one is less than the second one, it returns -1, if it's equal it returns 0, if it's greater than, it returns 1.
So it allows you this broader range of comparisons. And if you think about it, cmp, you could apply on integers, you could apply it on floats, apply it on strings. So it's overloaded, it has the ability to do all of those. And in this case what we're saying is, given 2 objects, let's create a tuple of the first, sorry, family and first name of ourselves, and other is another object, family and first name of that, and then just use cmp to compare them. All right, so it's going to use the base pieces. OK, so it gives me a way of doing comparisons. And str we saw last time as well, this is cmp does comparison, and str is our printed representation.
OK. So what we've got now, is a simple little class. We've also got two methods there. I want to look at them, we're gonna come back to them, but they start to highlight things we can do with our classes. So I've built one simple version of it here, which is per. And notice I've got another method, right up here, called say. And say takes two arguments, for the moment the second argument, or the first argument's, not going to make a lot of sense, but say takes two arguments besides itself. It's going to take another object to which it's saying something and the thing to say. Since I only have one object here, I'm going to have person talk to himself. You may have met a few other undergraduates who have this behavior. I'll have him talk to himself and say, just some random message the faculty members occasionally worry about. OK, what does this thing do? Now you're going to see some of the power of this. Again, remember, I'm down here, I'm sending this the message say, it's going to go up the chain to find the say message in person. And what does say do, it says given another object and some string, it's going to return, oh, and interesting things, part of which you can't see on the screen. First what it does, is it gets first name of self. Remember self is pointing to this instance, so it's simply looks up that binding, which is Frank. It's going to create a string in which it adds to that the family name of self, and then another thing that says to, and then ah, I'm now going to send a message to the other object, saying give me your first name. Going to add that to the second piece, and you can see in this case it happens to be the same first and family name. And then at the end of it, which you can't see here but you can see in your handout, I just append the whole string, so it spits it out.
What's the point of this, other than I can get it to say things? Notice, I can now reference values of the instance. But I can also get values of other instances, by sending in a message. And that's why we have that form right there. And then it glued all together. If you think about this for a second, you might say, wait a minute, actually you might have said wait a minute a while ago, why am I just using the variable name there in the function over here? Well in fact, I could've used the function here, first name open close, right? It would have done the same thing. But because I know I'm inside the instance, it's perfectly reasonable to just look up the value. OK, I could have, although I don't want you to do it, have done the same thing there and used underbar, sorry, first name underbar, sorry, first underbar name, but that's really breaking this contract that I want to happen. I should send the message to get the method back out. So again the standard practices is if you know you're inside the object, you can just access the values. If you're doing it with any other objects, send it a message to get it out.
OK, now, that gives you an ability to say, let's look at one more example here, and then we're going to start building our hierarchy, which is, that this person can also sing. And we've got a little sing method here. And notice what it does, it's going to sing to somebody, I guess you're part of the Chorallaries. You're going to sing something, and notice what it does, it's simply going to use its say method, but add at the end of whatever's being said, just tra la la at the end. So this is now an example of a method using another method. Why would you want that? It's nice modularly. I have one method that's doing saying, I have another method that's just building on it. So if I have is person sing to themselves, not a highly recommended activity, it would help if I had it sing to itself, not sing to sing, sorry about that. Notice what it does. Looks like exactly like a say method, except it's got tra la la at the end. Don't worry I'm not going to sing to you. I'll simply say the words. Power of this, other than the silly examples. You see how I can access variables of the instance, how I can access variables of other instances, going to come back to that, and how I can use versions of my own methods to implement other methods. In this case sing is using say as part of what it wants to get out.
OK, so we got a simple little example. Now, let's start adding some other pieces to this. OK, and what do I want to add. Find my spot here. OK, we're going to add an MIT person. Sorry, machine is -- do this, let's go down. OK so I'm going to add an MIT person. Look at the code for second. Aha! Notice what this says. MIT person says it inherits from person. That is, that's the first thing in parens up there. It says, you know, class of MIT person is person. What that is saying is, that this is a specialization of the person class. Or another way of saying it is, we have a super class, in this case it's person. And we have a subclass, in this case its MIT person. And we're going to walk through some examples, but what it says is that that subclass of MIT person can inherit the attributes of the person class. Can inherit the methods, it can inherit variables.
OK, what does MIT person do? Well, here's 1 of the new things it does. It has a local variable called next id num, which is initially set to 0. See that up there. And then it's got some methods, it's got an init method, a get id method, a few other things. OK, let's run this. In particular, I go back down to this one. Let me just uncomment this and do it here. Assuming my machine will do what I want it to do, which it really doesn't seem to want to do today. Try one more time. Thank you, yep. Still not doing it for me, John. OK, we type it. No idea what Python doesn't like me today, but it doesn't. So we're gonna define p 1, I've lost my keyboard, indeed I have. Try one more time. p 1 MIT person, see how fast I can type here -- OK, now, let's look at what the code does, because again it's going to highlight some things. I called MIT person, push this up slightly, it's going to create an instance down here, I called p 1. And when I would do that, I'm gonna initialize it. So I've got, right up here, an initializer, init for MIT person, takes in the family name and the first name. Notice what it does. Huh. It says, if I'm sitting here at MIT person, I'm going to go up and inherit from person its init function and call it. And what am I calling it on? I'm calling it on self, which is pointing to this object, so I've still got it, and then I'm then going to apply the base initialization. And that does exactly what you'd expect, which is just going to create a binding for family name down here. As well as some other things. So this is an example of inheritance. MIT person inherits the init method from person, can get access to by simply referring to it, and I refer to it right there. And it's take the person class, get its init and apply it to my instance plus those things. So I'm just using the same piece of code
Notice the second thing it does. It says inside of self, I'm going to bind the local variable id name to the value of next id name in MIT person. Self is down here, id num, sorry, not id name. I'm going to bind that to the value that I find my going up to here, which is 0, and having done that, I simply increment that value. OK? So what has this done? It says I now have captured in the class, a local variable that I can keep track of. And when I use it, every time I generate an example, let me build another one. I make p 2 another MIT person. OK, I can do things like saying, what is the id number for each of these. First one is 0, second one is 1, which makes sense, right? I'm just incrementing a global variable. Now, things I want you to see about this. Now that I've got a beginning of a hierarchy, I have this notion of inheritance. I can ask a function inside one class to use a function from a class that it can reach by going up the chain. I just did it there. I can ask it to go get values of variables, right, so that looks good. What else do we have in person or MIT person? Well, we can get the id number, we just did. We have a thing to do with this string. Notice it's going to print out something a little different. In fact, there's a kind of funky form there. Which just says, if I want to print it out, I'm gonna create, what this says to do is, I'm gonna create an output template that has that structure to it, but where I see that percent s I'm going to substitute this value for the first one, that value for the second. So if I say, what is p 1? It says ok, MIT person Fred Smith. On the other hand, if I said, what is per, which is that thing I build earlier, it had a different string method, which is just print out person, those pieces.
All right, one last piece to this and we're going to add to it. Suppose I want Fred to say something. Say something to Jane. OK, he said it. Where's the say method? OK, Fred is an instance of an MIT person. where's the say method? Well, there isn't one there, but again, that's where the hierarchy comes in. Fred is this object here, I'm sending it the message say. That turns into going up the chain to this object, which is the class object, and saying find a say method and apply it to that instance. Fudge-knuckle, it ain't here. Don't worry about it, because it says if I can't find one there, I'm going to go up the chain to this method, sorry to this class, and look for a method there. Which there was one, I have a say method. It's going to use that say method. Apply to it. Well, you might say, OK, what happens if it isn't there? Well, that's where, remember I defined person to be an instance of an object, it will go up the chain one last time to the base object in Python to see is there a method there or not. Probably isn't a say method for an object, so at that point it's going to raise an exception or throw an error. But now you again see this idea that the inheritance lets you capture methods.
Now you might say, why not just put a say method inside of MIT person? Well, if you wanted it to do something different, that would be the right thing to do. But the whole notion here's that I'm capturing modularity, I've got base methods up in my base class. If I just want to use them I'm just going to inherit them by following that chain, if you like, basically up the track. OK, so we've got an MIT person, we can use that. Let's add a little bit more to our hierarchy here. I'm going to create, if I can do this right, a specialization of an MIT person, which is an undergraduate. A special kind of MIT person. All right, so if I go back up here, even though my thing is not going to let me do it, let's build an undergraduate. OK, there's the class definition for an undergrad. We're just starting to see some of the pieces, right, so in an undergraduate, where am I here, an undergraduate. OK, it's also got an initialization function. So if I call undergrad, I'm gonna make an undergrad here, again let me go back down here, line ug 2 it's making undergrad, Jane Doe. Now, what happens when I do the initialization here? Notice what goes on. It simply calls the person initialization method. All right, so I'm down here. I'm going to call the person initialization method, what did do? Sorry, the MIT person method, it calls the person method. Just walking up the chain, that's going to do exactly what I did with all the other ones, so I now have a family name and a first name. So I can, for example, say family name and get it back out. All right?
And then, other things that I can do, well I can set what year the person's in, I can figure out what year they're in, there's this unfortunate overflow error if you've hung around too long, but that's not going to happen to you. And I've now got a say method here, so let's look what happens if I ask the undergraduate to say something. OK, it's not a realistic dialogue I know, but, what did this method do? I asked this object to do a say. And notice what it does. It simply passes it back up to MIT person. There's that inheritance again. It's saying, I'm going to have my base say method say something. I'm going to say it to a person, but all I'm going to do because undergraduates in my experience, at least, are always very polite, I'm going to put "Excuse me but" at the front of it. OK, what am I trying to show you here? I know the jokes are awful, but what am I trying to show you here? That I can simply pass up the chain to get it. In fact, what method does the final say here? What class does it come from? Person class, yes, thank you. It goes all the way up to person, right, because MIT person didn't have a say. So I can simply walk up the chain until I find the method I want to have.
Now this is an example of shadowing. Not a great example, but it's a beginning example of shadowing, in that this same method for an undergraduate, shadows the base say method, it happens to call it, but it changes it. It puts "Excuse me but" at the front, before it goes on to do something. Now again, I could have decided here to actually copy what the original say method did, stitch all the other things together. But again, that loses my modularity. I'd really to only have to change it in one place. So by putting my say method up in person, I can add these nuances to it, and it lets me have something that has that variation. If I decide I want to change what say does, I only have to change it in one place. It is in the person class definition, and everything else will follow through for free.
OK, so now I've got an undergrad, right? Let's look at a couple of variations of what happens here. So first of all, I can -- yes?
PROFESSOR 2: Shadowing here is often sometimes called overriding.
PROFESSOR: Yes, thank you, because I'm going to do a pure example of shadowing in a second, John right. Also called overriding. Part of the reason I like the phrase shadow is, if you think about it as looking at it from this direction, you see this version of init before you see the other ones, or you see that version of say, but it is overriding the base say example. OK, so I can say, what does p 1, sorry, yes, what does undergrad look like? And I said wait a minute, MIT person, not undergrad, is that right? Well, where's the str method? I didn't define one in undergrad, so it again tracks up the chain and finds the str method here, so it's OK undergrads are MIT people most the time, so it's perfectly fine.
OK, now, I have built into this also these cmp methods. So I've got two examples. I've got undergrad, or ug. And then I've got poor old Frank Foobar back there, per person. So suppose I want to compare them? What do you think happens here? Compare sounds weird, right, I compare an undergraduate to a person. I don't know what that's doing, some kind of weird psychological thing, but what do you think happens in terms of the code here if I run this. I know it's a little hard because you got a lot of code to look at. Do I have a cmp method defined somewhere? Yeah. So, it's hard to know what it's going to do, but let's look at it. Hmm. Now sometimes I type things and I got errors I don't expect, this one I did expect. So what happened here? Well let's talk about what happens if I do that comparison I was doing, what was I doing? Ug greater than per? What unwinds into is, I'm going to send to ug, that instance, a cmp method. This is really going to become something like ug dot under under cmp under under applied to per. I think that's close.
What does that do? It says starting in ug, I'm going to look for the first cmp method I could find, which is actually sitting here. I had a cmp method in MIT person. If you look at your code, what does it do? It looks up the id numbers to compare them. Well the, ug has an id number because it was created along this chamber. Remember per over here was just created as a person. It doesn't have an id number, so that's why it complaints. Ok, happens if I do that? Compare per to ug. How many people think I get an error? Wow. How many people think I'm going to get either true or false out of this? A few brave hands. Why? Can I ask you, please? Why do you think I'm going to get a, doesn't matter whether it's true or false, why am I going to have something work this time that didn't work last time?
PROFESSOR: Yeah, exactly. And in case you didn't hear it, thank you, great answer, sorry, terrible throw. In this case I'm using per, that's the first part, so it's not symmetric. It's gonna use per to do the look up. And as it was said there, per over here goes up and finds a cmp method here which it can apply. In that case, it simply looked at, remember, it took the tuples of first and last name which are both defined here, and did some comparison on that. So this is a way of again pointing out to you that the things are not always symmetric, and I have to be careful about where do I find the methods as I want to use them.
Ok? All right. Let's add, I'm gonna do two more classes here. Let's add one more class, some people debate whether these are really people or not, but we're going to add a class called a professor. OK. Now what am I doing? I'm creating another version of class down here. Which again is an instance, or a subclass, sorry, not an instance, a subclass of an MIT person. I see that because I built it to be there. Again I've got an initialization that's going to call the person initialization, which we know is going to go up -- I keep saying that -- going to call the MIT person initialization, which is going to go up and call this one. So again I'm going to be able to find names. And I do a couple of other different things here. I'm gonna pass in a rank, full professor, associate professor, assistant professor, which I'm just going to bind locally. But I'm gonna add one other piece here, which is I'm gonna add a little dictionary on teaching. So when I create a professor, I'm gonna associate with it a dictionary that says, what have you been teaching?
And then notice the methods I create. I've got a method here called add teaching, takes, obviously a pointer to the instance. A term, which will just be a string, and a subject. And let's look at what it does right here. OK. In fact the call I'm going to make, I'm not certain I'm going to be able to get away with it, my machine is still wonderfully broken, all right, it is, let me just show you what the calls would look like. As you can see here I'm not going to be able to do them. But I'm going to add teaching, as a method call with this with a string for term, and a subject number. What is this going to do? Yeah, I know I'm just worried if I restart Python, I may not be able to pull the thing back in, so I'm going to try and wing it, John, and see if I can make it happen.
Right, what does that teaching do? It's got one of those try except methods. So what does it say it's going to do? It's going to go into the dictionary associated with teaching, under the value of term, and get out a list. And it's going to append to the end of the list the new subject. So it's going to be stored in there, is then going to be term, and a list of what I taught, in case I teach more than one thing each term. It's going to do that, but notice it's a try. If in fact there is no term currently in the dictionary, started out empty, it's going to throw an error, sorry, not throw an error, it's going to raise an exception. Which is a key error, in which case notice what I'm going to do, I'm not going to treat it as an error. I'm simply going to say, in that case, just start off with an empty, with an initial list with just that subject in and put it in the dictionary. As I add more things in, I'll just keep adding things to this dictionary under that term. And if I want to find out what I'm doing, well I can use get teaching, which says given the term, find the thing in the dictionary under that term and return it. If I get an error, I'm going to raise it, which says there is nothing for that term, and in that case I guess I'm just going to return none.
OK? And then the other two pieces we're going to have here, and we want to look at a little more carefully, I just wanted to show you that example, is a professor can lecture, and a professor can say something. Look at the say method, because this now add one more nuance to what we want to do here. And I think in interest of making this go, let me actually, since I'm not going to get my machine to do this right, let me create a couple of professors. If I look at what that is, it's an MIT person because I didn't have any separate string thing there, and we will create a more important professor. What rank do you want, John? Do you want to stay full?
PROFESSOR 2: Undergraduate.
PROFESSOR: Undergraduate, right, a lot more fun I agree. Sorry about that, and we can again just see what that looks like. And that of course, we'll print out, he's also an MIT person. But now here's what I want to do. I want to say something to my good colleague Professor Guttag. Actually I'm going to start a separate -- I'm going to say something to a smart undergraduate. So if I say, remember we have ug defined as an undergraduate, let me do something a little different here. Well let, me do it that way. It says, I don't understand why you say you were enjoying 6.00. Not a good thing to say, right, but if I say to my good colleague Professor Guttag. I have to spell say right, I know, I need help with this, what can I say? We flatter each other all the time. It's part of what makes us feel good about ourselves. Why is the sky blue? I enjoyed your paper, but why is the sky blue?
OK, terrible examples, but what's going on here? One more piece that I want to add. Here's my say method for professor, and now I'm actually taking advantage of to whom I am saying something. Notice again, what does it do? There's the self argument, that's just pointing to the instance of me. I'm passing in another argument, going to call it to who, in one case it was ug, in one case it was Guttag. And then the thing I want to say, ah, look what it does, it says, check the type. And the type is going to take that instance, I had an instance, for example, of a professor down here, and it's going to pick up what type of object it is. So if the type of the person I'm speaking to is undergrad, let's pause for second. Remember I started away back saying we're building abstract data types. Well, here's a great example of how I'm using exactly that, right? I've got int, I've got float, I now have ug, it's a type. So it's says if the object to whom I'm speaking is an undergrad, then use the same method from person where I'm going to put this on the front. On the other hand, if the object to whom I'm speaking is a professor, then I'm going to tag this on the front and use the underlying say method. On the other hand, if I'm speaking to somebody else, I'm just going to go lecture. All right, and when a professor lectures, they just put it's obvious on the end of things, as you may have noticed.
What's the point I want you to see here? I'm now using the instances to help me to find what the code should do. I'm looking at the type. If the type is this, do that. If the type is this, do something different, ok? And I can now sort of build those pieces up. OK, I said one more class. Notice what we're doing. I know they're silly examples, but, sorry, they are cleverly designed examples to highlight key points. What I'm trying to do is show you how we have methods inherit methods, how have message shadow methods, how we have methods override methods, how we can use instances as types to define what the method should do.
Let me show you one last class, because I'm gonna have one more piece that we want to use. And the last class is, sort of, once you've got a set of professors, you can have an aggregate of them. And I don't know, if a group of geese are gaggle, I don't know what a set of professors are, John. Flamers? I, you know, we've got to figure out what the right collective noun here is. We're going to call them a faculty for lack of a better term, right? Now the reason I want to show you this example is, this class, notice, it only is going to inherit from object. It actually makes sense. This is going to be a collection of things, but it's not a subclass of a particular kind of person. And what I want the faculty to do, is to be able to gather together a set of faculty. So if I go down here, grab this for second, and pull it down so you can see it. It looks like I'm not going to be able to run this because my machine is broken, but basically I'm gonna define a set of professors, and then I'm gonna create a new class called faculty. There's the definition of it. It's got an init. You can kind of see what it does. It's going to set up an internal variable called names, which is initially an empty list, internal variable called ids, which is empty, an internal variable called members, which is empty, and another special variable called place, which we're going to come back to in a second, initially bound to none.
OK, I've got a method called add which I'm going to use down here to add professors to the course 6 faculty. Here's what I want to add to do. First of all, notice I'm going to check the type. If this is not a professor, I'm gonna raise an error, a type error, it's the wrong type of object to pass in. The second thing I'm gonna do is say, if that's okay, then let me go off and get the id number. Now remember, that's right up here, so I'm asking the instance of the professor to go up and get the id number. And I want to make sure I only have one instance of each professor in my faculty, so if the id number is in the list of ids already, I'm going to raise an error, sorry, raise an exception as well, saying I've got a duplicate id. OK? And the reason that's going to come up is, notice what I do now. Inside of the instant self, I take the variable names and I add to it the family name of the person I just added. OK, notice the form. I'm using the method, there's the parens to get the family name of the person. I'm just adding it to the list. I've got the id number, I've added the ids, and I add the object itself into members. So as I do this, what am I doing? I'm creating a list, actually several lists: a list of ids, a list of the actual instances, and a list of the family names. And as a cost I want to add, that's why I can check and see, is this in here already or not?
Now, the last reason I want to do this is, I want to be able to support things like that. This is now different, right, this instance is a collection. I want to be able to do things like, for all the things in that collection, do something, like print out the family names. And to do that, I need two special forms: iter and next. OK, now let me see if I can say this cleanly. Whenever I use a for, in structure, even if it was on just a normal list you built, what Python is doing is returning an, what is called an iterator. Which is something that we talked earlier. It's keeping track of where are you in the list, and how do I get to the next thing in the list?
I'm going to do the same thing here, and I'm going to create it for this particular structure. So this little thing iter, when I call a for something in, one of these instances, it calls iter, and notice what it does. It initializes place to 0. That was that variable I had up there. That's basically saying I'm at the beginning of the list. It's a pointer to the beginning of the list, and it returns self. Just gives me back a pointer to the instance. That now allows me at each step in that loop to call next. And what does next do? Next says, check to see if that value is too long, if it's longer than, for example, the list of names, raise an exception called stop iteration, which the for loop will use to say OK, I'm done. I'm going to break out of the for loop. Otherwise, what am I going to do? I'll increment place by 1, that's going to move me to the next place in the list, and then in this case I'll just return the instance itself, right? Members is a list of instances, place I've incremented by 1, I take 1 off of it, I get to it. So iter and next work together. Iter creates this method, that's going to give you a pointer to the place in the structure, and then next literally walks along the structure giving you the next element and returning elements in turn so you can do something with it.
Right, so now what that says is, I can have classes that just have local variables. I can have classes that get methods from other variables, and I can also have classes that are collections. And I've supported that by adding in this last piece. OK once you have all of that, in principle we could start doing some fun things. So let's see what happens if we try and make all of this go. And let me, since I'm not going to be able to run it, let me simply do it this way. If I have my undergraduate, ug. I can -- sorry, let's not do it that way -- I can have undergraduate say things like -- all right, what did I just do wrong here? Do I not have undergrad defined? I do. Oh, I didn't have Grimson, sorry, it's me, isn't it? Thank you. The undergraduate very politely asks why he didn't understand, you can have the professor respond. Again, it simply puts a different thing into there. On the other hand, if Professor Guttag asks me something about understanding, I say I really like this paper on, you do not understand, it's a deep paper on programming languages 5, I think, John, isn't it? What else can you do with this thing, right? You can have an undergraduate talk to an undergraduate, in which case they're still polite. Or you could have -- sorry, let me do that the other way -- you could also have an undergraduate simply talk to a normal person. All right, but the good news is you know eventually you get it done, and when you're really done you can have the undergraduate be really happy about this, and so she sings to herself.
OK it's a little silly, but notice what we've just illustrated. And this is where I want to pull it together. With a simple set of classes, and the following abilities, an ability to inherit methods from subclasses, sorry from superclasses, that is having this hierarchy of things. I can create a fairly complex kind of interaction. I can take advantage of the types of the objects to help me decide what to do. And if you think about that, I know it sounds very straightforward, but you would do exactly that if you were writing earlier code to deal with some numerical problem. All right, if the thing is an integer, do this, if it's a float, do that, if it's a string, do something else. I'm now giving you exactly the same ability, but the types now can be things that you could create. And what I've also got is now the ability to inherit those methods as they go up the chain. So another way of saying it is, things that you want to come away from here, are, in terms of these classes. We now have this idea of encapsulation. I'm gathering together data that naturally belongs as a unit, and I'm gathering together with it methods that apply to that unit. Just like we would have done with float or int. Ideally, we data hide, we don't happen to do it here, which is too bad.
Basically we've got the idea of encapsulation. The second thing we've got is this idea of inheritance. Inheritance both meaning I can inherit attributes or field values. I can inherit methods by moving up the chain. I can also the shadow or override methods, so that I can specialise. And I do all of that with this nice hierarchy of classes. So what hopefully you've seen, between these two lectures, and we're going to come back to it in some subsequent lectures, is that this is now a different way of just structuring a computational system. Now, you'll also get arguments, polite arguments from faculty members or other experts about which is a better way of doing it. So I'll give you my bias, Professor Guttag will give you his bias next time around. My view, object-oriented system are great when you're trying to model systems that consist of a large number of units that interact in very specific ways. So, modeling a system of people's a great idea. Modeling a system of molecules is probably a great idea. Modeling a system where it is natural to associate things together and where the number of interactions between them is very controlled. These systems work really well. And we'll see some examples of that next week. Thanks.
|
// Bracelet-Decoder algo app
// (c) Shahar Gino, September-2017, [email protected]
#include "detect_marks.hpp"
double find_possible_marks(mark_list_t &possible_marks_final, cv::Mat &frame_gray, cv::Mat &frame_thresh, unsigned int MinPixelWidth,
unsigned int MaxPixelWidth, unsigned int MinPixelHeight, unsigned int MaxPixelHeight, double MinAspectRatio,
double MaxAspectRatio, unsigned int MinPixelArea, unsigned int MaxPixelArea, double MinExtent, double MaxExtent,
double MinTexture, double MaxTexture, double MaxDrift, unsigned int PerspectiveMode, std::string FindContoursMode,
unsigned int HoughParams1, unsigned int HoughParams2, unsigned int HoughParams3,unsigned int HoughParams4,
unsigned int HoughParams5, unsigned int HoughParams6, bool debugMode, std::map<std::string,cv::Mat>* debug_imgs) {
char buffer[1000];
double rotation_angle_deg;
rotation_align_t rotation_align;
unsigned int possible_marks_cntr=0;
mark_list_t possible_marks_list, possible_marks_wo_outliers;
// Find all contours in the image:
std::vector<std::vector<cv::Point>> contours;
if (FindContoursMode == "Legacy") {
cv::findContours(frame_thresh.clone(), contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE);
}
else if (FindContoursMode == "Hough") {
std::vector<cv::Vec3f> circles;
cv::HoughCircles(
frame_thresh.clone(), // 8-bit, single channel image
circles, // detected circles (results)
cv::HOUGH_GRADIENT, // Defines the method to detect circles in images
(HoughParams1 > 0 ? HoughParams1 : 1), // Large dp values --> smaller accumulator array
(HoughParams2 > 0 ? HoughParams2 : 60), // Min distance between the detected circles centers
(HoughParams3 > 0 ? HoughParams3 : 50), // Gradient value used to handle edge detection
(HoughParams4 > 0 ? HoughParams4 : 18), // Accumulator thresh val (smaller = more circles)
(HoughParams5 > 0 ? HoughParams5 : 20), // Minimum size of the radius (in pixels)
(HoughParams6 > 0 ? HoughParams6 : 50) // Maximum size of the radius (in pixels)
);
if (!circles.empty()) {
for (auto it = circles.begin(); it != circles.end(); it++) {
contours.push_back(circle_to_contour(*it, 50, 0.7));
}
}
}
else {
error("Unsupported FindContoursMode mode: " + FindContoursMode);
}
// Foreach contour, check if it describes a possible character:
cv::Mat frame_contours = cv::Mat::zeros(frame_thresh.size(), CV_8UC3);
for (unsigned int i = 0; i < contours.size(); i++) {
// Register the contour as a possible character (+calculate intrinsic metrics):
PossibleMark possible_mark = PossibleMark(contours[i], frame_gray,
MinPixelWidth, MaxPixelWidth,
MinPixelHeight, MaxPixelHeight,
MinAspectRatio, MaxAspectRatio,
MinPixelArea, MaxPixelArea,
MinExtent, MaxExtent,
MinTexture, MaxTexture,
debugMode);
// If contour is a possible char, increment count of possible chars and add to list of possible chars:
if (possible_mark.checkIfPossibleMark()) {
possible_marks_cntr++;
possible_marks_list.push_back(possible_mark);
}
if (debugMode || debug_imgs) {
cv::drawContours(frame_contours, contours, i, SCALAR_WHITE);
}
}
if (possible_marks_list.size() == 0) {
possible_marks_final = possible_marks_list;
return 0;
}
// Remove outliers in a PCA scheme, i.e. possible marks which are too faraway from the group or interiors:
possible_marks_wo_outliers = remove_outliers(possible_marks_list, MaxDrift, debugMode);
// Rotation and Perspective alignments:
rotation_angle_deg = 0;
if (possible_marks_wo_outliers.size() > 0) {
// Rotation Alignment (SVD decomposition):
rotation_align = rotation_alignment(possible_marks_wo_outliers, debugMode);
rotation_angle_deg = rotation_align.rotation_angle_deg;
// Perspective Alignment (Homography+PerspectiveWarp):
possible_marks_final = possible_marks_wo_outliers;
perspective_alignment(possible_marks_final, PerspectiveMode, rotation_angle_deg, debugMode);
}
// -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- ..
if (debugMode || debug_imgs) {
int kx, ky;
unsigned int X_xc, X_yc;
mark_list_t::iterator it;
cv::Mat frame_possible_marks = cv::Mat::zeros(frame_thresh.size(), CV_8UC3);
for(it=possible_marks_wo_outliers.begin(); it<possible_marks_wo_outliers.end(); it++) {
std::vector<std::vector<cv::Point>> contours;
contours.push_back(it->contour);
cv::drawContours(frame_possible_marks, contours, 0, SCALAR_WHITE);
for (ky=-3; ky<=3; ky++) {
for (kx=-3; kx<=3; kx++) {
if ((it->intCenterY+ky >= 0) && (it->intCenterY+ky < frame_thresh.size().height) &&
(it->intCenterX+kx >= 0) && (it->intCenterX+kx < frame_thresh.size().width)) {
frame_possible_marks.at<cv::Vec3b>(it->intCenterY+ky,it->intCenterX+kx)[2] = 255;
}
if ((it->intCenterY_r+ky >= 0) && (it->intCenterY_r+ky < frame_thresh.size().height) &&
(it->intCenterX_r+kx >= 0) && (it->intCenterX_r+kx < frame_thresh.size().width)) {
frame_possible_marks.at<cv::Vec3b>(it->intCenterY_r+ky,it->intCenterX_r+kx)[0] = 255;
}
}
}
}
for(it=possible_marks_final.begin(); it<possible_marks_final.end(); it++) {
for (ky=-3; ky<=3; ky++) {
for (kx=-3; kx<=3; kx++) {
if ((it->intCenterY_r+ky >= 0) && (it->intCenterY_r+ky < frame_thresh.size().height) &&
(it->intCenterX_r+kx >= 0) && (it->intCenterX_r+kx < frame_thresh.size().width)) {
frame_possible_marks.at<cv::Vec3b>(it->intCenterY_r+ky,it->intCenterX_r+kx)[1] = 255;
frame_possible_marks.at<cv::Vec3b>(it->intCenterY_r+ky,it->intCenterX_r+kx)[2] = 255;
}
}
}
}
cv::putText(frame_possible_marks, "Original", cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_RED, 2);
cv::putText(frame_possible_marks, "Rotation fix (SVD)", cv::Point(10, 70), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_BLUE, 2);
cv::putText(frame_possible_marks, "Centroid", cv::Point(10, 110), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_GREEN, 2);
cv::putText(frame_possible_marks, "Perspective fix", cv::Point(10, 150), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_YELLOW, 2);
if (PerspectiveMode == 1) {
// place-holder (TBD: translate from Python):
//frame_possible_marks = polylines(frame_possible_marks, array([rect_src]), True, (255, 0, 0), 1, LINE_AA)
//frame_possible_marks = polylines(frame_possible_marks, array([rect_dst]), True, (0, 255, 255), 1, LINE_AA)
}
X_xc = std::max(3,int(rotation_align.centroid_x));
X_yc = std::max(3,int(rotation_align.centroid_y));
for (ky=-3; ky<=3; ky++) {
for (kx=-3; kx<=3; kx++) {
frame_possible_marks.at<cv::Vec3b>(X_yc+ky,X_xc+kx)[1] = 255;
}
}
if (debugMode) {
sprintf(buffer, "Amount of detected contours: %d", contours.size());
debug(buffer);
sprintf(buffer, "Amount of possible marks: %d", possible_marks_cntr);
debug(buffer);
sprintf(buffer, "Amount of possible marks w/o outliers: %d", possible_marks_wo_outliers.size());
debug(buffer);
sprintf(buffer, "Rotation: %.2f", rotation_angle_deg);
debug(buffer);
cv::imwrite("img_contours_all.jpg", frame_contours);
cv::imwrite("img_possible_marks.jpg", frame_possible_marks);
}
if (debug_imgs) {
(*debug_imgs)["img_contours_all"] = frame_contours;
(*debug_imgs)["img_possible_marks"] = frame_possible_marks;
}
}
return rotation_angle_deg;
}
// ------------------------------------------------------------------------------------------------------------------------------
mark_list_t remove_outliers(mark_list_t possible_marks_list, double MaxDrift, bool debugMode) {
std::string dbg;
bool is_interior;
char buffer[1000];
cv::Point2f p1, p2;
std::vector<double> dist;
mark_list_t::iterator it;
mark_list_t possible_marks_list_final;
double median_x, median_y, median_dist, d, dr;
std::vector<unsigned int> median_x_vec, median_y_vec;
// Extract marks relevant data (Median calculation):
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
median_x_vec.push_back(it->intCenterX);
median_y_vec.push_back(it->intCenterY);
}
median_x = median_calc<unsigned int>(median_x_vec);
median_y = median_calc<unsigned int>(median_y_vec);
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
p1 = cv::Point2f(it->intCenterX, it->intCenterY);
p2 = cv::Point2f(median_x, median_y);
d = distance_mse(p1,p2);
dist.push_back(d);
}
median_dist = median_calc<double>(dist);
if (debugMode) {
sprintf(buffer, "median_x=%.2f, median_y=%.2f, median_dist=%.2f", median_x, median_y, median_dist);
debug(buffer);
}
// Exclude marks with a too-high drift or interiors:
for (unsigned k=0; k<possible_marks_list.size(); k++) {
dbg = "";
PossibleMark possible_mark = possible_marks_list.at(k);
dr = (median_dist == 0) ? 0 : dist.at(k)/median_dist;
is_interior = false;
for (unsigned l=0; l<possible_marks_list.size(); l++) {
if (l == k) {
continue;
}
p1 = cv::Point2f(possible_mark.intCenterX, possible_mark.intCenterY);
p2 = cv::Point2f(possible_marks_list.at(l).intCenterX, possible_marks_list.at(l).intCenterY);
d = distance_mse(p1,p2);
if ((d < 2*MaxDrift) && (possible_mark.intBoundingRectArea < possible_marks_list.at(l).intBoundingRectArea)) {
is_interior = true;
dbg = "(X)";
}
}
if ((dr < MaxDrift) && !is_interior) {
possible_marks_list_final.push_back(possible_mark);
dbg = "(*)";
}
if (debugMode) {
sprintf(buffer, "possible_mark=%s, dist[%d]=%.2f, disr_r=%.2f %s", possible_mark.to_string().c_str(), k, dist.at(k), dr, dbg.c_str());
debug(buffer);
}
}
return possible_marks_list_final;
}
// ------------------------------------------------------------------------------------------------------------------------------
rotation_align_t rotation_alignment(mark_list_t &possible_marks_list, bool debugMode) {
cv::SVD svdMat;
cv::Mat S, U, Vt;
char buffer[1000];
mark_list_t::iterator it;
std::vector<cv::Point> H;
rotation_align_t rotation_align;
unsigned int n=1, centroid_x=0, centroid_y=0;
double mean_x=0, mean_y=0, rotation_angle_deg=0, rotation_angle;
// Calculate Centroid:
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
mean_x += (it->intCenterX - mean_x)/n;
mean_y += (it->intCenterY - mean_y)/n;
n++;
}
// Calculate covariance matrix (H):
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
H.push_back(cv::Point(round(it->intCenterX - mean_x), round(it->intCenterY - mean_y)));
}
if (debugMode) {
debug("Covariance matrix (H):");
print_point_vec<cv::Point>(H);
}
// SVD decomposition:
if (0) {
cv::SVD::compute(H, S, U, Vt, cv::SVD::FULL_UV);
}
else {
int num = possible_marks_list.size();
float arr[num][2];
for(int i=0; i<num; i++) {
arr[i][1] = possible_marks_list[i].intCenterY;
arr[i][0] = possible_marks_list[i].intCenterX;
}
cv::Mat mat = cv::Mat(num, 2, CV_32FC1, &arr);
cv::Mat cov, mean;
cv::calcCovarMatrix(mat, cov, mean, cv::COVAR_NORMAL | cv::COVAR_ROWS);
cov = cov / (mat.rows - 1);
cv::eigen(cov, S, Vt);
Vt *= -1;
}
// Calculate rotation angle:
rotation_angle = std::atan2(Vt.at<double>(0,1), Vt.at<double>(0,0));
rotation_angle_deg = rotation_angle * (180 / CV_PI);
// Rotation alignment:
int k=0;
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++, k++) {
it->intCenterX_r = (int)(H[k].x * cos(rotation_angle) + H[k].y * sin(rotation_angle) + (int)(mean_x));
it->intCenterY_r = (int)(H[k].x * -sin(rotation_angle) + H[k].y * cos(rotation_angle) + (int)(mean_y));
if (debugMode) {
sprintf(buffer, "possible_mark=%s", it->to_string().c_str());
debug(buffer);
}
}
rotation_align.rotation_angle_deg = rotation_angle_deg;
rotation_align.centroid_x = centroid_x;
rotation_align.centroid_y = centroid_y;
return rotation_align;
}
// ------------------------------------------------------------------------------------------------------------------------------
void perspective_alignment(mark_list_t &possible_marks_list, unsigned int PerspectiveMode, double rotation_angle_deg, bool debugMode) {
if (PerspectiveMode == 0) {
return perspective_alignment_opt0(possible_marks_list, rotation_angle_deg, debugMode);
}
else if (PerspectiveMode == 1) {
return perspective_alignment_opt1(possible_marks_list, debugMode);
}
else {
error("Invalid PerspectiveMode (%d)" + std::to_string(PerspectiveMode));
}
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
void perspective_alignment_opt0(mark_list_t &possible_marks_list, double rotation_angle_deg, bool debugMode) {
double mean_x = 0;
unsigned int n = 1;
unsigned int dist_x;
mark_list_t::iterator it;
// Calculate meanX:
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
mean_x += (it->intCenterX_r - mean_x)/n;
n++;
}
// Update marks coordinates (adaptive with angle):
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
dist_x = std::abs(it->intCenterX_r - mean_x);
if (std::abs(rotation_angle_deg) > 90) {
if (std::abs(rotation_angle_deg) < 170) {
it->intCenterY_r -= (unsigned int)(2 * sqrt(dist_x));
}
else {
it->intCenterY_r -= (unsigned int)(1 * sqrt(dist_x));
}
}
else {
it->intCenterY_r += (unsigned int)(2 * sqrt(dist_x));
}
}
// Debug:
if (debugMode) {
debug("(xR,yR) after Perspective Fix:");
print_mark_vec<PossibleMark>(possible_marks_list);
}
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
void perspective_alignment_opt1(mark_list_t &possible_marks_list, bool debugMode) {
error("PerspectiveMode=1 is Not supported at the moment in CPP edition");
}
// ------------------------------------------------------------------------------------------------------------------------------
std::vector<cv::Point> circle_to_contour(cv::Vec3f circle, unsigned int points_per_contour, float resize_factor) {
cv::Point center(round(circle[0]), round(circle[1]));
int xc = center.x;
int yc = center.y;
double r = cvRound(circle[2]);
r *= resize_factor;
std::vector<cv::Point> contour;
const double pi2 = 2*M_PI;
for (double i=0; i<pi2; i+=pi2/points_per_contour) {
int y = int(yc + r * sin(i));
int x = int(xc + r * cos(i));
contour.push_back(cv::Point(x,y));
}
return contour;
}
// ------------------------------------------------------------------------------------------------------------------------------
template <class T>
double median_calc(std::vector<T> data_vec) {
double median;
sort(data_vec.begin(), data_vec.end());
if(data_vec.size()%2==0) median = ( data_vec[ data_vec.size()/2 - 1 ] + data_vec[ data_vec.size()/2 ] )/2.0;
else median = data_vec[ data_vec.size()/2 ];
return median;
}
// ------------------------------------------------------------------------------------------------------------------------------
template <class T>
void print_point_vec(std::vector<T> data_vec) {
std::cout << "[[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->x << " " << std::flush;
}
std::cout << "]" << std::endl << "[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->y << " " << std::flush;
}
std::cout << "]]" << std::endl << std::flush;
}
// ---------------------------------------------------------------------------------------------------------------
template <class T>
void print_mark_vec(std::vector<T> data_vec) {
std::cout << "[[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->intCenterX_r << " " << std::flush;
}
std::cout << "]" << std::endl << "[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->intCenterY_r << " " << std::flush;
}
std::cout << "]]" << std::endl << std::flush;
}
|
China's successful launch of the sixth beidou navigation satellite
Xichang 1 nov this website today 0 26 points, xichang satellite launch center in China with the "long March 3 c rocket, success will be the sixth beidou navigation satellite into space, this is our country this year continuous network satellite launch of the fourth beidou navigation system.
BeiDou satellite navigation system (COMPASS, Chinese transliteration name BeiDou), as China's independent development, independent operation of the global satellite navigation system, is the national important spatial information infrastructure is under construction. Through the development of 19 years, beidou system in surveying and mapping, fishery, transportation, telecommunications, water conservancy, forest fire prevention, disaster reduction and relief, and has been applied many fields, such as national security, produce remarkable economic benefit and social benefit. Especially in the sichuan wenchuan, yushu in qinghai has played a very important role in earthquake relief.
Beidou satellite navigation system is one of the four big suppliers in today's global satellite navigation system. Beidou system construction, promote the global cooperation and development in the field of satellite navigation, promote the technological progress of the global satellite navigation system.
In accordance with the "three-step" development strategy, the beidou satellite navigation system will be 2012 years ago in the capacity of regional services in the asia-pacific region; Around 2020, global coverage ability in service. China's satellite navigation system management office in the launch on the rocket for the first time use the beidou satellite navigation system. Blue circle logo contains the big dipper, SiNa, grid elements such as earth and beidou satellite navigation system in both Chinese and English names, indicate beidou star system, with high precision and high reliable for global positioning, navigation and timing services industry characteristics, to show its open compatible, towards the world, the construction of the global service tenet.
The launch of a satellite and carrier rocket respectively by China aerospace science and technology group corporation, China academy of space technology and China academy of launch vehicle technology development. This is the 133th long march rocket flight.
TypeInfo: Industrial Policy
Keywords for the information:
|
On Monday the American Library Association will announce the winner of its highest award for a picture book, named for the great English illustrator Randolph Caldecott (1846–1886). Why was Caldecott so important? Here’s an answer from Maurice Sendak, who won the Caldecott Medal for Where the Wild Things Are:
“Caldecott’s work heralds the beginning of the modern picture book. He devised an ingenious juxtaposition of picture and word, a counterpoint that had never happened before. Words are left out – but the picture says it. Pictures are left out – but the word says it. In short, it is the invention of the picture book.”
* * *
“My favorite example of Caldecott’s fearless honesty is the final page of Hey Diddle Diddle. After we read, ‘And the Dish ran away with the spoon,’ accompanied by a drawing of the happy couple, there is the shock of turning the page and finding a picture of the dish broken into ten pieces – obviously dead – and the spoon being hustled away by her angry parents. There are no words that suggest such an end to the adventure; it is purely a Caldecottian invention. Apparently, he could not resist enlarging the dimensions of this jaunty nursery rhyme by adding a last sorrowful touch.”
Maurice Sendak in Caldecott & Co.: Notes on Books & Pictures (Farrar, Straus and Giroux, 1988), a collection of Sendak’s reviews and other writing for adults. The first quote comes from his essay “Randolph Caldecott” and the second from his acceptance speech for the 1964 Caldecott Medal. Sendak is one of the few great picture-book artists who is also a great critic. Caldecott & Co. has only a dozen pages of pictures but doesn’t need more, because Sendak makes you see books without them.
(c) 2008 Janice Harayda. All rights reserved.
|
// Prototypes for GLIBC thread locale __-prefixed functions -*- C++ -*-
// Copyright (C) 2002-2020 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/c++locale_internal.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{locale}
*/
// Written by Jakub Jelinek <[email protected]>
#include <bits/c++config.h>
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <langinfo.h>
#include <vector>
#include <string.h> // ::strdup
#include <ext/concurrence.h>
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2)
extern "C" __typeof(nl_langinfo_l) __nl_langinfo_l;
extern "C" __typeof(strcoll_l) __strcoll_l;
extern "C" __typeof(strftime_l) __strftime_l;
extern "C" __typeof(strtod_l) __strtod_l;
extern "C" __typeof(strtof_l) __strtof_l;
extern "C" __typeof(strtold_l) __strtold_l;
extern "C" __typeof(strxfrm_l) __strxfrm_l;
extern "C" __typeof(newlocale) __newlocale;
extern "C" __typeof(freelocale) __freelocale;
extern "C" __typeof(duplocale) __duplocale;
extern "C" __typeof(uselocale) __uselocale;
#ifdef _GLIBCXX_USE_WCHAR_T
extern "C" __typeof(iswctype_l) __iswctype_l;
extern "C" __typeof(towlower_l) __towlower_l;
extern "C" __typeof(towupper_l) __towupper_l;
extern "C" __typeof(wcscoll_l) __wcscoll_l;
extern "C" __typeof(wcsftime_l) __wcsftime_l;
extern "C" __typeof(wcsxfrm_l) __wcsxfrm_l;
extern "C" __typeof(wctype_l) __wctype_l;
#endif
#endif // GLIBC 2.3 and later
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
struct Catalog_info
{
Catalog_info(messages_base::catalog __id, const char* __domain,
locale __loc)
: _M_id(__id), _M_domain(strdup(__domain)), _M_locale(__loc)
{ }
~Catalog_info()
{ free(_M_domain); }
messages_base::catalog _M_id;
char* _M_domain;
locale _M_locale;
private:
Catalog_info(const Catalog_info&);
Catalog_info&
operator=(const Catalog_info&);
};
class Catalogs
{
public:
Catalogs() : _M_catalog_counter(0) { }
~Catalogs();
messages_base::catalog
_M_add(const char* __domain, locale __l);
void
_M_erase(messages_base::catalog __c);
const Catalog_info*
_M_get(messages_base::catalog __c) const;
private:
mutable __gnu_cxx::__mutex _M_mutex;
messages_base::catalog _M_catalog_counter;
vector<Catalog_info*> _M_infos;
};
Catalogs&
get_catalogs();
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
|
Wednesday, 24 August 2016
Changing culture, not easy but the prize is huge!
Want to Change culture? Then change habits.
I get asked a lot, “how can I change the culture in my organisation?” This is probably because I’m obsessed by change in the workplace (see previous posts) and I studied cultural theory along with other things as part of my MA. In a nutshell I believe If you want to change the culture of an organisation you have to change its habits. That is the habitual behaviour of it’s individual people. I always reply that’s not an easy task.
It’s widely written that organisational culture is all about values, behaviours and actions of its staff. Often expressed as the unique social and psychological environment of the organisation’s members. History, technology, strategy, types of employees, management styles, national culture, vision, values, norms and systems all play a part in the creation of culture. Along with symbols, language, assumptions, beliefs that become habits! Phew!
Ravasi and Schulz (2006) described organisation culture as; “a set of shared assumptions that guide what happens in an organisation by defining appropriate behaviour for various situations”. Wow, that’s deep. What’s more staff teach these assumptions and behaviours to new members as a way of perceiving, thinking and feeling. The sum of this is an employee identity that affects how they identify with the organisation. In other words corporate culture.
That’s really profound, and it is reinforced daily so it’s hard to change, a bit like turning the Titanic. I’ve got an old copy of Charles B Handy’s seminal work Understanding Organisations. The first section chapter 7, deals with defining organisational culture in great detail and is still a fabulous read.
So how might we begin to change it?
First read this brilliant blog by Steve Chapman
I thought I might try and list some questions we could ask staff to simplify the process. And I’ve begun to list the areas that change makers need to address with a specific organisation in mind.
Question is where are we now? And where do we want to be? What are the values in that department at present and how do we want them to change? Why do we want to change? Break that down, what are the shared departmental assumptions? What are they based on? What do people do every day? How can we begin to change it? Where do we want to end? What do we want to start?
Although this article by Steve Chapman focuses on creativity, I believe it contains the essence of how to change culture. Ask difficult questions and prepare for things to break!
Set the scene, take 1
I’m imagining as I think of a specific department in a particular organisation.
I walk into the dept currently in my head. It has an air of formality. Presenteeism matters, what you’re producing doesn’t. It isn’t inviting or interesting to visitors it’s actually intimidating in its blandness. It’s full of perceived stuffy people dressed in the same uniform with their heads down. The hot desks, cleared every evening have zero personality. It doesn’t cross fertilise ideas with anyone outside and the people clearly don’t get out much. This is by design and is reinforced each day by shared habits and behaviours. and a possible shared vision of the rest of the organisation. Possibly world, Gosh, is there a shared ‘world view’ also prevalent here? I’m scared, I’ll run now before my formal meeting, I’m only there for a ten second slot, the rest will be irrelevant to me. Will anyone miss me, last time they were all comatose before my bit. They scoffed at my ideas.
If I sit for a while what behaviour do is see? Men in suits and ties, I was struck in Hamburg recently by the office uniform of middle aged German men, blue shirts beige slacks. What do I see here? Shirts, collars ties, pointy shoes. The women are less formal but not informal and indeed some follow the format. I observe People arrive early, they stay late. They sit in the same locations. the hot desk, open plan vibe encourages no personality of space. It’s quiet, diaries are full of formal back to back meetings with formal agendas. The language is formal and reflects the professional education of the staff members. There is a clear hierarchy. People come and go from meetings. They don’t share information.
Environment & silos of experts
There are so many things here where do I begin? Let’s start with the environment in that office and progress down to the individuals. The organisation shapes the environment of this department. This means it’s open plan and there are no collaborative spaces, you’re not even allowed to stick blue tack on the wall leave alone anything else.
Silo thanks to
People tend to sit within a set group. They can actually sit anywhere they choose but they group naturally. This is ok, and research extols the virtues of silos of experts. They share stuff, have great conversations and can be productive.The open plan hot desk scenario here leads to lack of personalisation. There is evidence that closed work spaces can be more productive. And personal adornment of those areas increases productivity. Essentially as the articles suggest, workspace needs to be flexible. Lets redesign it together to make it more user friendly, suitable for the work to be done and useful for other more collaborative work too.
Bump in and get out more
The other problem with the silo arrangement is that people don’t bump into other silos of experts even those who work in related but different fields. Many books describe the positive effects of bumping into each other. Walter Isaacson’s ‘Innovators’ is a fab book for understanding this. Steve Jobs designed the new HQ of Pixar so that people would bump into each other in the atrium. He designed the environment to make it happen. Knowing that great things would occur and they did.
Co working spaces take this further. (co work hubs in Devon) At the extremes the better ones actively encourage cross fertilisation of ideas. See Impact hubs and their success stories for examples of this. Essentially people should spend 70% of their time outside of their silo. Time to cross that bridge.
Question; how can we redesign the space for quiet silo working with like minded experts. But make this personal space just a safe haven?Question; how can we encourage staff get out seventy percent of their time to a co work space or other professional environment?
In a nutshell go gather pollen from the flowers and bring it back to the hive.
Buckminster Fuller
Whilst we’re at it, take those empty walls, ask who inspires the folks at work there and fill em with pictures. Apparently Ranulph Fiennes was inspired by pictures of explorers on the wall of his family home. Don’t let the images go stale, circulate the images to keep them fresh and put a short description underneath. The department in my head brings pictures of James Lovelock, Heath Robinson, Jony Ive, Mahatma Gandhi, Buckminster Fuller, Petra Kelly and many others to mind. But ask your people and let them bring variety. In a big organisation they could swop occasionally with other departments. On that subject some of their time could be spent in the other department silos. Go forth to shared spaces and communicate. get out more!
Environment done! Getting out more done! What about some personality
So we’ve shaken up the work place and the amount of time spent in it a bit. But we need to bring out the personalities a bit more too. What are we going to do with what we learn from the big outside? Will we discuss it at the end of our rigid formal meeting whilst everyone scoffs? Or will we clear a space in our diaries each day for some informal bumping of ideas?
According to research, 52 minutes is desired as the maximum productive time, but only if we have 17 minutes in between doing something completely off the wall. So let’s use that time for an upload together. Make it a bring and share, bring ideas, learn, read, show videos and put them all to the sword in a public forum. Discuss pros and cons, make it fun. Do this every day. Have expressive space, big whiteboards, pin up spaces etc. People talk about learning and development as though it’s something separate from your work. It should be part of your DNA to learn and take on new ideas and break down old assumptions and do it collectively.
Language and identity
thanks to
This upload forum described above also serves a different special purpose. It begins to attack the assumptions of agreement. It starts to change the dept language. It starts to erode ingrained values and beliefs. It starts to give people personal identities as they emerge from their silos. It can begin to shape how people self-identify. There are swathes of academic writing about identity and I bow to the research of e.g. David Campbell and Ziauddin Sardar. I cannot begin to open this Pandora’s box, but I will say that changing language to suggest activities rather than cultural themes is a good start. Say out loud; I’m an innovator, engineer, creative, environmentalist, maker, writer, photographer. These are positives. Move away from job titles, they’re a bit irrelevant and yesterday. Move away from descriptions like, team leader or manager these are equally unhelpful. Self identity around what you want to do might be nice place to start, e.g. Environmental champion, creative engineer etc. This should become default language, the way you introduce yourself in a speed dating session. A bit like your elevator pitch for yourself. Oh and watch this video it deals with shedding old identities better than I can.
As the language advances and the upload conversations will become more detailed, notions of who do I identify with can come in. Not in a negative way like I’m a facist and all my friends are white supremacists, hell No! More like I’m really into making things, I’m influenced by Michael Reynolds and Geoff ‘Earthship’ Starlington, I like the work of Jony Ive, I follow the philosophy of Buckminster Fuller and Hundertwasser, I listen to Curtis Mayfield and Megadeath. Suddenly each participant in upload develops a personality. Someone recently suggested a bring your personality to work day. Maybe that’s a possible start? Who influences you at work and why? Who influences or inspires you in life and why? What are their values and qualities you admire, have you worked this out? Do you carry this knowledge with you? Do you share it? Go share it now!
So the environment has changed, people are out more and the personalities they bring back begin to emerge now what?
How do we cultivate these changes further?
So identities are not fixed, remind people they can change their nationality, religion, beliefs, gender, sexuality, name, status, geography (urban/rural). All of these cross cutting themes can vary throughout your life! Oh yes they can and do! But try to see people without those labels, it’s really hard and takes practice but it’s worth it. Some organisations manage this, it’s worth taking a long look at them. Ask me for details.
Let’s develop some ideas about culture change a bit more. How are we going to move further together?
Well people can choose their identity and express it and they can choose their actions. They don’t have to conform to organisational assumptions. Move them further, ask them who they identify with? Characters from film or fiction, role models? heroes? Why ask them this? Because I suspect they are a great guide to where people get their ideas and possibly to where they think they’re going, or would like to go. Who influences you? Who do you aspire to be?
How do you want to be seen now, and how do you want to be remembered?
Now we have opened Pandora’s box, we are beginning to change things. People are attempting to express themselves within the new environment and new ideas are forming as a result of the getting out more.
How do we filter those ideas into the work that needs to be done?
Ask questions of each other and ourselves. Why am doing this work? Who else needs to know about it? (Not just the usual suspects our professional partners). Who is working on this stuff as well as me? Originality is very rare, someone is doing your project somewhere else, even fire was discovered in different parts of the world simultaneously. So go find out who you might be able to collaborate, share with, increase value of, learn from. Where shall I go to find out who’s doing this? Can I test it with someone completely different than me? What do I know? Why do I think I know it? What do I want to know? Who’s opinion do I currently value and why? Is that correct?
I’ll say it here and now; it is sharing information that is powerful not keeping it to yourself!
thanks to
Once we work together, we need to create a vision. At present we are here. Where do we want to be? What will it look like? How will we behave? Describe ourselves and the organisation? What will people see, hear, feel when they come to see us? Once you’ve built, collected, asked, advanced, changed the environment you work in. And the way you work, got out more, questioned yourself and others. The culture will begin to change and it will show.
Ponder this scary thought, you’ve changed the culture, collectively and individually. When you finally put your ideas up there, what does it feel like? Ask any artist, writer, film maker, songwriter. Very scary but really exciting. It will be challenging or beautiful but not passive!
So what about habits?
Question: What about habits what have they got to do with it? Habits become what we wear, where we work, how we describe things, what we eat, what we read, the cafe we drink our tea at, the tea we drink (coffee in my case can’t stand tea, was an avid Earl Grey drinker then I stopped and drank coffee instead) our work patterns, how we describe ourselves, how we relate to others. The things that shape the assumptions that lead to the culture of an organisation come down to habits.
Individual habits and they can change. They are the elements of a culture and they are a choice.
Some people say that they are part of our personalities. But if you vary habits and break patterns it can lead to unexpected benefits and adventures and enhanced wellbeing. Imagine the thrill of watching a different soap opera. Get into new characters in a book. Or read different news, possibly with widely varied or opposite views to the ones you habitually follow. Scary but enticing territory. I watched horror films for a while found them challenging and jarring. I went back to my safe zone of crime, but I never quite viewed it in the same way again. I really began to understand why I liked it so much more than horror.
Back to work and culture
Do you wear a suit every day? Or wear one occasionally? If you never do maybe you should. How about you never wear the same twice in two days. Perhaps people will enjoy a guess and wonder what you might wear next. Then go sit in a different place, pick a silo elsewhere. Ask them questions about or related to your work and theirs. People are flattered by questions. Organise a non-traditional meeting, read up on how to do it. Or ask me for help. Yes you can do all of these things in the same day, after all isn’t variety the spice of life?
Change your language, describe your role and yourself differently when asked. Invent a new persona at work, be who you really are. Present your work as you. Ask for critique in a constructive way, or combative if you dare! You’ll never be the same again. Programme your work in a pattern, 50 mins head down, 20 doing something radical. Go work elsewhere, invite others in! Mix your meetings up. Bring in outsiders (shock horror) Let the washing machine engineers meet the fashion designers and together they can design a new car. Read this brilliant article on collaborative culture by Rosie Manning Oh and just read more, its like learning and development only more enjoyable. here’s a great guide to how and why.
Set the scene, take 2
In my mind I walk into the dept, it’s a hive of activity, individuals work here. I know that because no two look alike. They’re in groups or silos huddled together hard at work. Another group are around a display board. They discuss an idea, it’s a challenge to get a word in. When I do I’m accepted, they listen to and record my contribution. The silos break out into a hive of activity. The meeting i attend is brisk, it has objectives and outcomes. People only come in when they’re needed. Not all of the orchestra plays at once! I take actions with deadlines so do others. There’s an acknowledgment we will complete them on time.
A walking meeting passes by deep in conversation. I notice staff have adorned the walls with interesting images. I ponder them whilst I drink my coffee. I go to a different dept and ask what their images are all about. For the next fifty minutes I write my next project overview. I take it out to the display board, colleagues and visitors gather to discuss it, not a suit or tie in sight. The odd pointy shoe here and there and some decent beards but I ignore that and view them as people. I record all of their views and ideas verbatim, they help gel and confirm some of mine. Some are radically different. I make a note to test them against my assumptions.
Borrowed Earthship diagram
I’m off now to work in the DeskLodge Bristol now (or any other co work space you’d like to imagine). I know it’s full of creatives today for a conference. I’m Going to stay for the evening discussions. I will show them my project, I’m scared but excited. Work will never be the same again. I get up excited to cycle in. I’ve got a picture of an Earthship in my bag I’m thinking about building. I want to know what people think, how they would improve it. Tomorrow I’ll work at the science park, see what they think of my latest project. Will it stand up to their scrutiny or will I need to rethink. it feels exciting when I put myself out there. I’m hoping for something innovative. if nothing else it’ll be a challenge, it may be beautiful.
If you want to change your organisation, change the culture. If you want to change the culture change the habits. If you want to make it more diverse, stop trying and change the above two.
NB. I’ve tagged some books and articles I’ve enjoyed, there’s a wealth of research done on this topic too great to mention here. This is simply a blog of my thoughts not an academic paper. Go read more it’s fun! If you want help doing things different ask me.
This blog is also on Medium:
Monday, 1 August 2016
Where are the future creatives? And what are we doing about it?
Only 1% of people on the internet are creators!
Creative tools past
Its an odd paradox that in an age where we have the most powerful creative tools in our hands most of us use them to do passive tasks. At best we might take a selfie, add a filter and post it in the ether. That is the endless stream of social media. yes we might well look back nostalgically at our efforts. But I suggest there are less and less people able and willing to make a living out of creating. Why is this?
First of all I guess the notion of jobs like photographer, artist, poet, writer, musician. Considered the creative roles appear diluted by digital technology and means of distribution. When I was a teenager if you wanted to take a photograph (my obsession back then), you had to and first save up for a decent camera. Mine was a Zenit E, followed by Canon AE and many more. Also the accessories as you gradually learned the trade of using different lenses for different reasons and flash in the dark etc. If you were a fanatic like me, you but a darkroom with a Durst enlarger. Struggled to create a space of total blackout where you could develop and enlarge your masterpieces. I was told that good print could last a 100 years or more. I wonder what digital archives will be around in 100 years?
Ingrained in that crazy slow learning curve was a desire to capture images that endured and pleased others. And master the techniques of presenting them. To exhibit was to bare your soul. The great and good came from far and wide to see, and if you were lucky purchase your efforts. You would number them to make them even more desirable. Oddly I've noticed a resurgence of people using film recently that might one day return to this situation. But I doubt it.
Like music and writing, the art of photography died with the digital camera. Music struggles on but the means of distribution have rendered earning a living as a musician almost impossible. Art is the last bastion. Struggling in its own way to stand out in the crowded space where social sharing and advertising increasingly co-exist. One in 11 jobs or 8.8 per cent of all UK jobs now falls within the creative economy, and one in six of all UK graduate jobs are also creative economy positionsThis is seen as good, but as work opportunities decline and the traditional notion of work disappears with the coming AI revolution. The percentage is going to have to be a lot bigger!
Part of developing and autonomous, think on your feet, adaptable workforce is going to be all about stimulating and encouraging creative skills beyond the odd selfie.
My self with Prisma - 5 mins of effort!
But how?
At the moment our education system and every other facet of society pushes people towards the traditional view of 9-5 treadmill jobs. The new breed of hamsters, apart from a small minority, seem happy to follow. Disruption is happening in many aspects of society, bitcoin, crowdfunding, crowdsourcing, AI, autonomous vehicles. But not in traditional education. According to many commentators it kills creativity. This is something we need to tackle quickly. Or we will hive our future creatives to mindless silos nose to the grind wheel.
The solution is opening things up, yes even schools and colleges. Oh the risks I hear you scream. But as long as we keep closed systems, closed institutions and closed thinking, we will not stimulate the 'autonomy economy' of future creatives.
My vision is that the best things happen when strange worlds meet. Co working hubs around the world are demonstrating this almost daily. what we need is to do this earlier, faster and cheaper to enable worlds to collide more often. Creative hubs, freely available to all are the answer. When I was a kid the library was my education, but they are no where near cool enough anymore. We need spaces that are the epitome of wow. Designed to attract and throw together the cleverest minds of all ages and social strata. No government will support this as this kind of autonomy terrifies them. It is for our generation, those who know how to make stuff, to provide them for the future.
Some light is starting to appear, we have hubs coming out of our ears in Exeter and conferences too. The problem is they are disparate and not in the centre. There is no one centrally placed Loci, I propose a quiet takeover and I have a target place! Watch this space...
|
/*
* Copyright (C) 2017-2021 Smirnov Vladimir [email protected]
* Source code licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 or in file COPYING-APACHE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.h
*/
#pragma once
#include <CoordinatorTypes.h>
#include <mutex>
#include <atomic>
namespace Wuild {
/**
* Balancer used to split request between several tool servers.
* Main goal: the request should gone to server with least load at this moment.
*
* To update client information, UpdateClient and SetClientActive is used.
*
* To recieve balancer most suitable client, call FindFreeClient.
* StartTask and FinishTask updates load cache.
* Get*Threads funcation used for overall statistics.
*/
class ToolBalancer {
public:
enum class ClientStatus
{
Added,
Skipped,
Updated
};
public:
ToolBalancer();
~ToolBalancer();
void SetRequiredTools(const StringVector& requiredToolIds);
void SetSessionId(int64_t sessionId);
ClientStatus UpdateClient(const ToolServerInfo& toolServer, size_t& index);
void SetClientActive(size_t index, bool isActive);
void SetClientCompatible(size_t index, bool isCompatible);
void SetServerSideLoad(size_t index, uint16_t load);
size_t FindFreeClient(const std::string& toolId) const;
void StartTask(size_t index);
void FinishTask(size_t index);
uint16_t GetTotalThreads() const { return m_totalRemoteThreads; }
uint16_t GetFreeThreads() const { return m_freeRemoteThreads; }
uint16_t GetUsedThreads() const { return m_usedThreads; }
bool IsAllChecked() const;
/// Used for tests.
std::vector<uint16_t> TestGetBusy() const;
protected:
struct ClientInfo {
ToolServerInfo m_toolServer;
bool m_checked = false;
bool m_active = false;
bool m_compatible = false;
uint16_t m_serverSideQueue = 0;
uint16_t m_serverSideQueuePrev = 0;
uint16_t m_serverSideQueueAvg = 0;
uint16_t m_busyMine = 0;
uint16_t m_busyOthers = 0;
uint16_t m_busyTotal = 0;
uint16_t m_busyByNetworkLoad = 0;
int64_t m_clientLoad = 0;
int m_eachTaskWeight = 32768; //TODO: priority? configaration?
void UpdateLoad(int64_t mySessionId);
};
protected:
void RecalcAvailable();
std::atomic<uint16_t> m_totalRemoteThreads{ 0 };
std::atomic<uint16_t> m_freeRemoteThreads{ 0 };
std::atomic<uint16_t> m_usedThreads{ 0 };
int64_t m_sessionId = 0;
std::deque<ClientInfo> m_clients;
StringVector m_requiredToolIds;
mutable std::mutex m_clientsMutex;
};
}
|
Talk:20.109(F12) Pre-Proposal: Engineering Viral Magnetic Nanoparticles for Magnetic Hyperthermic Cancer Therapy
- This is a brainstorming page.
You are very welcome to write any crazy / non-crazy / inventive / conventional / knowledgeable ideas or information you may have about our project.
Some key words: Magnetic Nanoparticles (MNP), Viruses, Magnetic Hyperthermia, Bioengineering
What is Magnetic Hyperthermia?
How it works?
Under an alternating magnetic field, MNP releases heat due to relaxation of magnetic moments (hysteresis). This can cause an increase in temperature to the range of 41C to 47C. Since tumor cells are more heat sensitive than normal cells, they will be killed by this thermal dissipation.
Here is an interesting tidbit from a paper I was reading: "In addition to the expected tumor cell death, hyperthermia treatment has also induced unexpected biological responses, such as tumor-specific immune responses as a result of heat-shock protein expression. These results suggest that hyperthermia is able to kill not only local tumors exposed to heat treatment, but also tumors at distant sites, including metastatic cancer cells." (Kobayashi)
- Clinical trials in prostate cancer
- Shows promising results when coupled with irradiation on breast cancer (mouse)
Current Limitations (This information will help us shape and define the problem.)
(1) To achieve the necessary rise in temperature with minimal dose of MNP.
- In other words, this means:
- High specific loss power / specific absorption rate (SLP) of the MNP.
- why is higher applied dosage bad? > leads to unnecessary heat dissipation
(2) Lack of knowledge about the metabolism, clearance, and toxicity of MNP.
Biomedical potentials of MNP
- Could be used as early detection for the following using MRI:
- Drug Delivery
- Cellular labeling and tissue targeting
- Purifying and separating cells and DNAs
- Transfection by magnetic nanoparticles
- Tissue repair
- Magnetic resonance imaging (MRI)
Types of Relevant Viruses
1. Tobacco Mosaic Virus (TMV)
- 18nmx300nm, helical
- Can withstand high temperatures up to 50C for 30mins (conventional hyperthermia involves heating up to 50C from an external source
- Safe for human consumption
- Mann group has active research on it
- 2130 molecules of coat protein
2. M13 Bacteriophage
- 6.6nmx880nm, helical (Length is too long - pose an issue in targeting cells)
- Lots of research done by the Belcher group, including attaching MNPs to M13 for imaging purposes
- We are familiar with the system
3. Cowpea chlorotic mottle virus (CCMV)
- 26nm, icosahedral
4. Cowpea mosaic virus (CPMV)
- 27nm, icosahedral
5. Brome mosaic virus (BMV)
- 28nm, icosahedral
6. Turnip yellow mosaic virus (TYMV)
- 30nm, icosahedral
Current Work in Viral MNP Attachment
Attachment of MNPs to M13 phage for in vivo imaging of prostate cancer
What we propose to do
See flowchart sketch.
- Identifying / Screening for appropriate virus vehicles and tumor-specific anchoring sequencse
- Developing / Engineering viral MNPs
- in vivo testing for efficacy of engineered vMNPs in mouse tumor cells.
We will start with using ferritin (Fe3O4) as the MNP.
Stage 1: Virus Hunt
- We need to investigate how the selected virus (likely one of the following: TMV, M13, CCMV, CPMV, BMV or TPMV) interacts with mammalian cells in vivo.
Stage 2: Screening for MNP binding site on virus
- We will start by using Fe3O4 as our MNP of interest. With this, a protein coat screen of the selected virus for a protein coat that can bind with our MNP is necessary.
Stage 3: Screening for tumor-specific sequence binding site on virus
- We need to do a protein coat or RNA screen of the virus for a region that can bind with a tumor-specific peptide sequence. If necessary, we might need to screen tumors for unique short sequences on their cell surfaces.
Stage 4: Virus engineering
- We can now engineer wild-type viruses using specific protein coats or RNA regions isolated in Stage 2 and 3 to produce the viral MNP of interest.
Stage 5: in vivo testing
- Perform an in vivo experiment by injecting the engineered viral MNPs into the circulatory system of mice that have developed tumors. By subjecting these mice to an alternating magnetic field under standard hyperthermia conditions and measuring the change in tumor size, we will be able to quantify the efficacy of using viral MNPs in magnetic hyperthermia.
- Experimenting with double layer MNP to increase response
- Target other cancerous cells
- Experiment with other types of viruses
Quantitative Goals (We can quantify with IC50 value)
- Currently, with the aid of 10Gy radiation, the hyperthermia treatment successfully accumulated less than 0.3mg Fe/g tissue. Dosage: 0.2mg Fe per gram of mouse. Say mouse is 25g, so 5mg total dosage injected. so 1% efficiency with the aid of radiation. (MNP sizes used: 70nm and 120nm; murine flank breast tumors were 150mm3)
From http://manalis-lab.mit.edu/publications/grover%20PNAS%202011.pdf, we estimated that a typical cell has an average density of 1.1g/mL. Since the murine flank breast tumors were 150mm3, and 0.25mg Fe/g of tumor was detected in the tumors, we can calculate that only a total of 0.0495mg of Fe is accumulated in the tumors. This gives a % efficacy of 1%.
- South Korean experiment: 75ug of MNPs were injected.
- From Belcher lab's paper, what is the % efficacy of using M13?
- "The actual rotations of the nanoparticles are disordered because the microviscosity of the local environment in cancer cells is not constant, and effective elasticity depends on the binding conditions between nanoparticles and membranes."
- but this is actually present because when treatment is done with individual MNPs, one side of the MNP is always bound to the targeted cell, so direction is never constant!
- Gupta AK, Naregalkar RR, Vaidya VD, and Gupta M. Recent advances on surface engineering of magnetic iron oxide nanoparticles and their biomedical applications. Future Medicine. 2007. 2(1), 23-39.
- Bakoglidis KD, Simeonidis K, Sakellari D, G. Stefanou, and Angelakeris M. Size-Dependent Mechanisms in AC Magnetic Hyperthermia Response of Iron-Oxide Nanoparticles. IEEE Transactions on Magnetics. 2012. 48:1320-1323.
- Great layman's way of explaining magnetic hyperthermia http://trialx.com/curetalk/2012/11/cancer-treatment-multifunctional-magnetic-nanoparticles-for-molecular-imaging-and-hyperthermia/
- A.J. Giustini, A.A. Petryk, S.M. Cassim, J.A. Tate, I. Baker, P.J. Hoopes. Magnetic nanoparticle hyperthermia in cancer treatment. Nano LIFE 2010; 01: 17.
- D. Ghosh, Y. Lee, S. Thomas, A. G. Kohli, D. S. Yun, A. M. Belcher, K. A. Kelly. M13-templated magnetic nanoparticles for targeted in vivo imaging of prostate cancer. Nat. Nanotechnol. 2012; 7 (10): 677–82.
- Add more references as deem appropriate
11/29 from Professor Angela Belcher:
- Look at Nature Nano Belcher lab paper
- Need to do very good characterization of materials using TEM, elemental analysis, etc.
|
//
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#ifndef _MGGEOMETRYFACTORY_H_
#define _MGGEOMETRYFACTORY_H_
class MgGeometryFactory;
template class MG_GEOMETRY_API Ptr<MgGeometryFactory>;
/// \defgroup MgGeometryFactory MgGeometryFactory
/// \ingroup Geometry_Module_classes
/// \{
/////////////////////////////////////////////////////////////////////
/// \brief
/// The MgGeometryFactory class is used to construct objects
/// whose classes are derived from MgGeometry.
///
/// \remarks
/// The starting point for the construction of the MgGeometry
/// objects is user-supplied numbers of type double or integer.
/// The lexical analyzer converts integers to doubles. The
/// numbers are passed to one of the CreateCoordinate????()
/// methods where ???? is one of XY, XYM, XYZ, or XYZM.
/// \n
/// The MgGeometryFactory methods do no spatial analysis. Errors
/// in the construction of the geometry objects are not detected
/// until some operation in the datastore requiring spatial
/// analysis is performed.
/// \n
/// The general rules for constructing geometry objects are as
/// follows:
/// <ul>
/// <li>add coordinates to a coordinate collection which defines
/// an MgLinearRing so that the first and last coordinates are
/// identical,</li>
/// <li>add coordinates to a coordinate collection which defines
/// an MgLinearRing to be used as an <b>exterior</b> ring in an
/// MgPolygon so that the direction of traversal is
/// counterclockwise,</li>
/// <li>add coordinates to a coordinate collection which defines
/// an MgLinearRing to be used as an <b>interior</b> ring in an
/// MgPolygon so that the direction of traversal is clockwise,</li>
/// <li>add MgCurveSegment objects (either MgArcSegment objects
/// or MgLinearSegment objects) to an MgCurveSegmentCollection
/// so that they are contiguous in the order added and so that
/// the last coordinate in an MgCurveSegment object is identical
/// to the first coordinate in the succeeding MgCurveSegment
/// object,</li>
/// <li>add MgCurveSegment objects (either MgArcSegment objects
/// or MgLinearSegment objects) to an MgCurveSegmentCollection
/// which defines an MgCurveRing to be used as an <b>exterior</b>
/// ring in an MgCurvePolygon so that the direction of traversal
/// is counterclockwise,</li>
/// <li>add MgCurveSegment objects (either MgArcSegment objects
/// or MgLinearSegment objects) to an MgCurveSegmentCollection
/// which defines an MgCurveRing to be used as an <b>interior</b>
/// ring in an MgCurvePolygon so that the direction of traversal
/// is clockwise.</li>
/// </ul>
/// With respect to the construction of linear and curve
/// polygons, the Autodesk Geometry Format (AGF) Binary
/// specification does not stipulate the direction of traversal
/// in a ring. However, some providers, for example, Oracle,
/// require that the direction of traversal be counterclockwise
/// in an exterior ring and clockwise in an interior ring.
/// \n
/// The following statements are represented in the graphic at
/// the bottom of this pane.
/// \n
/// MgCoordinate objects are used directly to create MgPoint
/// geometries and MgArcSegment geometry components.
/// \n
/// MgCoordinateCollection objects are used to create
/// MgLineString geometries, MgLinearRing geometry components and
/// MgLinearSegment geometry components.
/// \n
/// An MgPolygon geometry is constructed from an MgLinearRing
/// geometry component, which defines the polygon's external
/// boundary, and an optional MgLinearRingCollection of
/// MgLinearRing geometry components, which define "holes' in the
/// containing ring.
/// \n
/// An MgCurveSegmentCollection of MgLinearSegment objects and
/// MgArcSegment objects are used to create MgCurveString
/// geometries and MgCurveRing geometry components.
/// \n
/// An MgCurvePolygon geometry is constructed from an MgCurveRing
/// geometry component, which defines the curve polygon's
/// external boundary, and an optional MgCurveRingCollection of
/// MgCurveRing geometries, which define "holes" in the
/// containing ring.
/// \n
/// Each single geometry (point, line string, polygon, curve
/// string, and curve polygon) has a homogeneous multi-version.
/// For example, an MgMultiPoint geometry is composed of MgPoint
/// geometries. For each geometry type there is a helper
/// collection class used to construct the multi-version object.
/// \n
/// Finally an MgMultiGeometry object, which consists of a
/// heterogeneous collection of geometries, is constructed by
/// adding geometries to a helper collection class object and
/// passing that collection object to a constructor.
/// \n
/// \image html GeometryFactory.png
///
class MG_GEOMETRY_API MgGeometryFactory : public MgGuardDisposable
{
DECLARE_CLASSNAME(MgGeometryFactory)
PUBLISHED_API:
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgGeometryFactory object
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// MgGeometryFactory();
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// MgGeometryFactory();
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// MgGeometryFactory();
/// \htmlinclude SyntaxBottom.html
///
MgGeometryFactory();
////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XY, X = x, Y
/// = y.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXY(double x, double y);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXY(double x, double y);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXY(double x, double y);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXY(double x, double y);
/////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XYM, X = x, Y
/// = y, M = m.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYM(double x, double y, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYM(double x, double y, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYM(double x, double y, double m);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
/// \param m (double)
/// M value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXYM(double x, double y, double m);
/////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XYZ, X = x, Y
/// = y, Z = z.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZ(double x, double y, double z);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZ(double x, double y, double z);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZ(double x, double y, double z);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
/// \param z (double)
/// Z value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXYZ(double x, double y, double z);
////////////////////////////////////////////////////////////////
/// \brief
/// Creates an MgCoordinate object with Dimension = XYZM, X = x,
/// Y = y, Z = z, M = m.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZM(double x, double y, double z, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZM(double x, double y, double z, double m);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCoordinate CreateCoordinateXYZM(double x, double y, double z, double m);
/// \htmlinclude SyntaxBottom.html
///
/// \param x (double)
/// X value for the coordinate.
/// \param y (double)
/// Y value for the coordinate.
/// \param z (double)
/// Z value for the coordinate.
/// \param m (double)
/// M value for the coordinate.
///
/// \return
/// An initialized MgCoordinate instance.
///
virtual MgCoordinate* CreateCoordinateXYZM(double x, double y, double z, double m);
///////////////////////////////////////////////////////////////////////
/// \brief
/// Creates an arc segment from start, end, and control
/// coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgArcSegment CreateArcSegment(MgCoordinate start, MgCoordinate end, MgCoordinate control);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgArcSegment CreateArcSegment(MgCoordinate start, MgCoordinate end, MgCoordinate control);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgArcSegment CreateArcSegment(MgCoordinate start, MgCoordinate end, MgCoordinate control);
/// \htmlinclude SyntaxBottom.html
///
/// \param start (MgCoordinate)
/// The MgCoordinate that specifies the start point
/// of the arc.
/// \param end (MgCoordinate)
/// The MgCoordinate that specifies the end point
/// of the arc.
/// \param control (MgCoordinate)
/// The MgCoordinate that specifies the control
/// point of the arc.
///
/// \return
/// An instance of MgArcSegment.
///
virtual MgArcSegment* CreateArcSegment(MgCoordinate* start, MgCoordinate* end, MgCoordinate* control);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a linear segment from a collection of coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgLinearSegment CreateLinearSegment(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgLinearSegment CreateLinearSegment(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgLinearSegment CreateLinearSegment(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinates (MgCoordinateCollection)
/// An MgCoordinateCollection that specifies the coordinates of the linear
/// segment. The collection must contain at least two coordinates.
///
/// \return
/// An instance of MgLinearSegment.
///
virtual MgLinearSegment* CreateLinearSegment(MgCoordinateCollection* coordinates);
/////////////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a linear ring from a collection of coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgLinearRing CreateLinearRing(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgLinearRing CreateLinearRing(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgLinearRing CreateLinearRing(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinates (MgCoordinateCollection)
/// An MgCoordinateCollection that specifies the coordinates of the linear
/// ring. The collection must contain at least three coordinates.
///
/// \return
/// An instance of MgLinearRing.
///
virtual MgLinearRing* CreateLinearRing(MgCoordinateCollection* coordinates);
///////////////////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a curve ring from a collection of curve segments.
/// \remarks
/// The use of this method is illustrated in the MgCurvePolygon example code.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCurveRing CreateCurveRing(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCurveRing CreateCurveRing(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCurveRing CreateCurveRing(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
///
/// \param curveSegments (MgCurveSegmentCollection)
/// An MgCurveSegmentCollection that specifies the segments
/// of the curve ring. The segments in the collection must
/// form a closed shape. See the example php code for
/// details about the construction of the segments so that
/// the resulting shape is closed.
///
/// \return
/// An instance of MgCurveRing.
///
virtual MgCurveRing* CreateCurveRing(MgCurveSegmentCollection* curveSegments);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a point from a coordinate.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgPoint CreatePoint(MgCoordinate coordinate);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgPoint CreatePoint(MgCoordinate coordinate);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgPoint CreatePoint(MgCoordinate coordinate);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinate (MgCoordinate)
/// An MgCoordinate that specifies the location of this point.
///
/// \return
/// An instance of MgPoint.
///
virtual MgPoint* CreatePoint(MgCoordinate* coordinate);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a line string from a collection of coordinates.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgLineString CreateLineString(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgLineString CreateLineString(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgLineString CreateLineString(MgCoordinateCollection coordinates);
/// \htmlinclude SyntaxBottom.html
///
/// \param coordinates (MgCoordinateCollection)
/// An MgCoordinateCollection that specifies the coordinates of the line
/// string. The collection must contain at least two coordinates.
///
/// \return
/// An instance of MgLineString.
///
virtual MgLineString* CreateLineString(MgCoordinateCollection* coordinates);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a curve string from a collection of curve segments.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCurveString CreateCurveString(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCurveString CreateCurveString(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCurveString CreateCurveString(MgCurveSegmentCollection curveSegments);
/// \htmlinclude SyntaxBottom.html
///
/// \param curveSegments (MgCurveSegmentCollection)
/// An MgCurveSegmentCollection that specifies the segments of the
/// curve string. The collection must contain at least one segment.
///
/// \return
/// An instance of MgCurveString.
///
virtual MgCurveString* CreateCurveString(MgCurveSegmentCollection* curveSegments);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a polygon from an outer ring and a collection of inner rings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgPolygon CreatePolygon(MgLinearRing outerRing, MgLinearRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgPolygon CreatePolygon(MgLinearRing outerRing, MgLinearRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgPolygon CreatePolygon(MgLinearRing outerRing, MgLinearRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
///
/// \param outerRing (MgLinearRing)
/// An MgLinearRing that specifies the polygons outer boundary.
/// \param innerRings (MgLinearRingCollection)
/// An MgLinearRingCollection that specifies the polygons holes.
/// This parameter may be null.
///
/// \return
/// An instance of MgPolygon.
///
virtual MgPolygon* CreatePolygon(MgLinearRing* outerRing, MgLinearRingCollection* innerRings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a curve polygon from an outer ring and a collection of inner
/// rings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgCurvePolygon CreateCurvePolygon(MgCurveRing outerRing, MgCurveRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgCurvePolygon CreateCurvePolygon(MgCurveRing outerRing, MgCurveRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgCurvePolygon CreateCurvePolygon(MgCurveRing outerRing, MgCurveRingCollection innerRings);
/// \htmlinclude SyntaxBottom.html
///
/// \param outerRing (MgCurveRing)
/// An MgCurveRing that specifies the polygons outer boundary.
/// \param innerRings (MgCurveRingCollection)
/// An MgCurveRingCollection that specifies the polygons holes.
/// This parameter may be null.
///
/// \return
/// An instance of MgCurvePolygon.
///
virtual MgCurvePolygon* CreateCurvePolygon(MgCurveRing* outerRing, MgCurveRingCollection* innerRings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi point aggregate geometry from a collection of points.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiPoint CreateMultiPoint(MgPointCollection points);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiPoint CreateMultiPoint(MgPointCollection points);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiPoint CreateMultiPoint(MgPointCollection points);
/// \htmlinclude SyntaxBottom.html
///
/// \param points (MgPointCollection)
/// An MgGeometryCollection that specifies the points. All geometry
/// objects in this collection must be of type MgPoint.
///
/// \return
/// An instance of MgMultiPoint.
///
virtual MgMultiPoint* CreateMultiPoint(MgPointCollection* points);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi line string aggregate geometry from a collection of
/// line strings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiLineString CreateMultiLineString(MgLineStringCollection lineStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiLineString CreateMultiLineString(MgLineStringCollection lineStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiLineString CreateMultiLineString(MgLineStringCollection lineStrings);
/// \htmlinclude SyntaxBottom.html
///
/// \param lineStrings (MgLineStringCollection)
/// An MgGeometryCollection that specifies the line strings. All geometry
/// objects in this collection must be of type MgLineString.
///
/// \return
/// An instance of MgMultiLineString.
///
virtual MgMultiLineString* CreateMultiLineString(MgLineStringCollection* lineStrings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi curve string aggregate geometry from a collection of
/// curve strings.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiCurveString CreateMultiCurveString(MgCurveStringCollection curveStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiCurveString CreateMultiCurveString(MgCurveStringCollection curveStrings);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiCurveString CreateMultiCurveString(MgCurveStringCollection curveStrings);
/// \htmlinclude SyntaxBottom.html
///
/// \param curveStrings (MgCurveStringCollection)
/// An MgGeometryCollection that specifies the curve strings. All geometry
/// objects in this collection must be of type MgCurveString.
///
/// \return
/// An instance of MgMultiCurveString.
///
virtual MgMultiCurveString* CreateMultiCurveString(MgCurveStringCollection* curveStrings);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi polygon aggregate geometry from a collection of
/// polygons.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiPolygon CreateMultiPolygon(MgPolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiPolygon CreateMultiPolygon(MgPolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiPolygon CreateMultiPolygon(MgPolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
///
/// \param polygons (MgPolygonCollection)
/// An MgGeometryCollection that specifies the polygons. All geometry
/// objects in this collection must be of type MgPolygon.
///
/// \return
/// An instance of MgMultiPolygon.
///
virtual MgMultiPolygon* CreateMultiPolygon(MgPolygonCollection* polygons);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates a multi curve polygon aggregate geometry from a collection of
/// curve polygons.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiCurvePolygon CreateMultiCurvePolygon(MgCurvePolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiCurvePolygon CreateMultiCurvePolygon(MgCurvePolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiCurvePolygon CreateMultiCurvePolygon(MgCurvePolygonCollection polygons);
/// \htmlinclude SyntaxBottom.html
///
/// \param polygons (MgCurvePolygonCollection)
/// An MgGeometryCollection that specifies the curve polygons. All geometry
/// objects in this collection must be of type MgCurvePolygon.
///
/// \return
/// An instance of MgMultiCurvePolygon.
///
virtual MgMultiCurvePolygon* CreateMultiCurvePolygon(MgCurvePolygonCollection* polygons);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Creates an aggregate geometry from a collection of geometry objects.
///
/// <!-- Syntax in .Net, Java, and PHP -->
/// \htmlinclude DotNetSyntaxTop.html
/// virtual MgMultiGeometry CreateMultiGeometry(MgGeometryCollection geometries);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude JavaSyntaxTop.html
/// virtual MgMultiGeometry CreateMultiGeometry(MgGeometryCollection geometries);
/// \htmlinclude SyntaxBottom.html
/// \htmlinclude PHPSyntaxTop.html
/// virtual MgMultiGeometry CreateMultiGeometry(MgGeometryCollection geometries);
/// \htmlinclude SyntaxBottom.html
///
/// \param geometries (MgGeometryCollection)
/// An MgGeometryCollection that specifies the geometries.
///
/// \return
/// An instance of MgMultiGeometry.
///
virtual MgMultiGeometry* CreateMultiGeometry(MgGeometryCollection* geometries);
INTERNAL_API:
//////////////////////////////////////////////////////////////////
/// \brief
/// Get the unique identifier for the class
///
/// \return
/// Class Identifider.
///
virtual INT32 GetClassId();
//////////////////////////////////////////////////////////////////
/// \brief
/// Creates an empty geometry from its type identifier
///
/// \return
/// Geometry.
///
static MgGeometry* CreateGeometry(INT32 geomId);
protected:
//////////////////////////////////////////////
/// \brief
/// Dispose this object.
///
virtual void Dispose();
//////////////////////////////////////////////////////////////////
/// \brief
/// Initializes the factory
///
static bool InitializeGeometryFactory();
//////////////////////////////////////////////////////////////////
/// \brief
/// Empty geometry creation functions
///
static MgPoint* CreateEmptyPoint();
static MgLineString* CreateEmptyLineString();
static MgCurveString* CreateEmptyCurveString();
static MgPolygon* CreateEmptyPolygon();
static MgCurvePolygon* CreateEmptyCurvePolygon();
static MgMultiPoint* CreateEmptyMultiPoint();
static MgMultiLineString* CreateEmptyMultiLineString();
static MgMultiCurveString* CreateEmptyMultiCurveString();
static MgMultiPolygon* CreateEmptyMultiPolygon();
static MgMultiCurvePolygon* CreateEmptyMultiCurvePolygon();
static MgMultiGeometry* CreateEmptyMultiGeometry();
CLASS_ID:
static const INT32 m_cls_id = Geometry_GeometryFactory;
private:
static bool m_factoryInitialized;
};
/// \}
#endif //_MGGEOMETRYFACTORY_H_
|
We had a running joke in science ed that kids get so overexposed to discrepant events involving density and air pressure that they tend to try to explain anything and everything they don't understand with respect to science in terms of those two concepts. Why do we have seasons? Ummm... air pressure? Why did Dr. Smith use that particular research design? Ummm... density?
I think we need another catch-all explanation. I suggest index of refraction.
To simplify greatly, index of refraction describes the amount of bending a light ray will undergo as it passes from one medium to another (it's also related to the velocity of light in both media, but I do want to keep this simple). If the two media have significantly different indices, light passing from one to the other at an angle (not perpendicularly, in which case there is no bending) will be bent more than if indices of the two are similar. The first four data points are from Hyperphysics, the final one from Wikipedia... glass has a wide range of compositions and thus indices of refraction.
Water at 20 C: 1.33
Typical soda-lime glass: close to 1.5
Since glycerine and glass have similar IoR, light passing from one to the other isn't bent; as long as both are transparent and similarly colored, each will be effectively "invisible" against the other.
So, why does it rain? Umm... index of refraction?
A Bright Moon Impact
12 hours ago
|
#ifndef ___MESH_RENDERINFO__
#define ___MESH_RENDERINFO__
#include "Math.h"
class R_mesh;
enum AlphaTestTypes
{
ALPHA_OPAQUE = 0,
ALPHA_DISCARD,
ALPHA_BLEND
};
struct Mesh_RenderInfo
{
const R_mesh* origin = nullptr;
bool wired = false;
bool filled = false;
bool doubleSidedFaces = false;
bool renderNormals = false;
bool hasNormals = false;
bool hasUVs = false;
float4 meshColor = float4::zero;
float4 wiresColor = float4::zero;
unsigned int num_indices = 0;
unsigned int num_vertices = 0;
unsigned int indicesBuffer = 0;
unsigned int dataBuffer = 0;
unsigned int textureBuffer = 0;
AlphaTestTypes alphaType = AlphaTestTypes::ALPHA_OPAQUE;
int blendType = 0;
float alphaTest = 0.2f;
uint shader = 0;
float4x4 transform;
};
#endif // !___MESH_RENDERINFO__
|
By Justin Moyer
The Washington Post
— Defense Secretary Leon Panetta signed an order Thursday allowing women the same opportunities as men to serve in combat, including formerly off-limits assignments on attack submarines and in the Navy SEALs. Just two weeks before the announcement, researchers from San Diego's Naval Health Research Center published a study suggesting that some recent mothers deployed on the battlefield may be more prone to depression after seeing action.
"Women who deploy and report combat-associated exposures after childbirth are significantly more likely to screen positive for maternal depression than are women who did not deploy after childbirth," concluded the study, titled "Is Military Deployment a Risk Factor for Maternal Depression?" and appearing in the Journal of Women's Health. "It is also possible," the report noted, "that giving birth and leaving a young child, in addition to the experience of combat, contribute to postdeployment depression."
The study included eight co-authors, five of them associated with the Naval Health Research Center, a research and development laboratory within the Department of Defense. It was based on surveys of more than 1,600 women who "gave birth during active duty service."
Not all branches of the armed forces showed the same results. "Participants who served in the Army had an increased risk of maternal depression; Army service members tend to be deployed longer and more frequently than personnel serving in the Navy and Air Force," the study found.
Of course, you don't have to be a mom to experience depression on the front line. The report points out that "the increased rate of depression is primarily attributed to experiencing combat while deployed," not just to whether a solider is also a parent.
|
|Gallium metal is silver-white and melts at approximately body temperature (Wikipedia image).|
|Atomic Number:||31||Atomic Radius:||187 pm (Van der Waals)|
|Atomic Symbol:||Ga||Melting Point:||29.76 °C|
|Atomic Weight:||69.72||Boiling Point:||2204 °C|
|Electron Configuration:||[Ar]4s23d104p1||Oxidation States:||3|
From the Latin word Gallia, France; also from Latin, gallus, a translation of "Lecoq," a cock. Predicted and described by Mendeleev as ekaaluminum, and discovered spectroscopically by Lecoq de Boisbaudran in 1875, who in the same year obtained the free metal by electrolysis of a solution of the hydroxide in KOH.
Gallium is often found as a trace element in diaspore, sphalerite, germanite, bauxite, and coal. Some flue dusts from burning coal have been shown to contain as much 1.5 percent gallium.
It is one of four metals -- mercury, cesium, and rubidium -- which can be liquid near room temperature and, thus, can be used in high-temperature thermometers. It has one of the longest liquid ranges of any metal and has a low vapor pressure even at high temperatures.
There is a strong tendency for gallium to supercool below its freezing point. Therefore, seeding may be necessary to initiate solidification.
Ultra-pure gallium has a beautiful, silvery appearance, and the solid metal exhibits a conchoidal fracture similar to glass. The metal expands 3.1 percent on solidifying; therefore, it should not be stored in glass or metal containers, because they may break as the metal solidifies.
High-purity gallium is attacked only slowly by mineral acids.
Gallium wets glass or porcelain and forms a brilliant mirror when it is painted on glass. It is widely used in doping semiconductors and producing solid-state devices such as transistors.
Magnesium gallate containing divalent impurities, such as Mn+2, is finding use in commercial ultraviolet-activated powder phosphors. Gallium arsenide is capable of converting electricity directly into coherent light. Gallium readily alloys with most metals, and has been used as a component in low-melting alloys.
Its toxicity appears to be of a low order, but should be handled with care until more data is available.
|
Wednesday, April 30, 2014
Deciding to become a civic architectural systems theorist and visionary futurist, I recently changed my name to Buckminster Fugger and wrote a book called 'How to Enjoy Eating Alone and Other Dymaxion Visions'. My aim is to continue the great Buckminster Fuller's enterprise of designing and proposing efficient, fulfilling and, most importantly, imaginative new ways of living.
The following are some of the revolutionary concepts that you will find in my book...
A city with no streets and no roads (see image above) where you get around by climbing from building to building through windows and doors or jumping from roof to roof. This will entirely eradicate traffic congestion and pavement litter.
Huge coats you can live in made from water proof mattresses with lots of deep pockets where you store your belongings/children. When exhausted, you can just fall over and fall asleep. Each coat will be its own jurisdiction with laws decided upon by you and applying to you alone.
Balloon cities. Floating municipalities where the populations live off passing seagulls and other avian comestibles that they catch in nets.
Cities of air consisting of houses made out of air. Effectively, your belongings laid out in open spaces. Heating is provided by jumpers. Air conditioning is provided by taking the jumpers off. Protection from rain is achieved when the population takes to the skies on hang gliders and congregates beneath nimbus clouds, thus preventing possessions becoming water damaged.
Houses made out of human hair. We all have hair and we often cut it or it falls out. Why not use it as a construction material? Did you know that discarded human hair covers 98000 square miles of the Earth's surface? That's a lot of houses. Instead of being painted, hair houses will be combed. This will be done with large 'house combs'.
Spherical buildings, like balls, that will be tornado proof as they will just get rolled about the place instead of blown down. Occupants will be kept level when harnessed into interior gravitationally compensatory gyroscopes.
The Double Antwerp Decker. A new Antwerp that is an exact replica of the old Antwerp and placed right on top of it. This will give us twice the Antwerp we are currently accustomed to without taking up more of Belgium's space.
Skyscraper buildings made out of stacked minivans and inhabited solely by dogs that are fed via daily deliveries of chum fired upwards with catapults.
And finally, sky cats. These vicious feral cats will be dropped from the sky to land on top of corralled criminals as a new punitive measure that replaces prison.
That is all. To know more you will have to purchase my book but, in keeping with Bucky Fuller's avant-gardeism, my book is actually not a book at all but a bottled scent that you inhale. However, once you breathe it in you die, thus doing your bit for population reduction and avoiding the impending Malthusian catastrophe going forward.
Sunday, April 27, 2014
In no particular order…
It Must Not Live! It Cannot Die!
From Cygnus to Ceefax
A Quarter to Huh?
Return to Xalberemus
Xalberemus Victorius
Xalberemus Once More
Xalberemus Or Bust
Herbie Goes to Xalberemus
Xalberemus Destroyed
Xalberemus No More
Xalberemus Reborn
Go Fuck Yourself Xalberemus
When Telex Revolts!
Super Bomb in my Mouth!!!
Tyrolean Grey
The Desert Moons of L. Casei Immunitas
The Fartegium Conundrum
Star Farm – Livestock Us!!!
The Beast That Shouted Pardon At The Rear Of The World
The Chronicles of Arseworld
Clongriffin Heights
The Ska Planet
Last Rocket to Skasville
Come See, Come Ska!
Karganorak - Ravisher of Maidens!
Queen with a Thousand Tits
That Robot Has Tits!
Titbot 9000
An Omnibus of the Unthinkable
Unreadable Tales
Unspeakably Shite
I Have No Nose Yet I Must Smell!
I Have No Book Yet I Must Read!
I Cannot Write Yet I Must Sell!
Aldous Huxley's Flimpy the Robot Goose.
Wednesday, April 16, 2014
The other night I saw a fox sitting completely still in the middle of the road. Sodium streetlight spilled through tree branches and caused a nervous system to dance across the tarmac. There was a full moon above. A really really full moon. Fuck, that moon was full. Earlier, at dusk, I watched the city from a hilltop as it turned into a web of stars. The wind was just about cold enough to remind you that there is such a thing as cold and to remind you that you are warm.
The next day I woke up and so had the world, ahead of me. Birds were sending beautiful code. Clouds clumped and swirled and sent smoke signals beyond human ken. The burning ball of the sun sometimes showed itself but mainly hid. And the sea too, different to the day before or even the minute before or the second. Ever changing and never the same. It made the soaking sound of a stadium roar. Foamy fractals dissolved on its glistening shore.
And back inland, the flowers are coming. All different colors. All different sizes and shapes and permutations of those sizes and shapes and permutations of those again, an endless variety, endlessly. And if we're miserable it's because our heads are pointed at the wrong place. Not everything is a given but these things are guaranteed. These things are free. So much to see. Seriously, you'd never catch up. How could you ever leave?
Watch where you point your head. Please.
Sunday, April 13, 2014
We drove past the big shut down factory in the forest and my brother started talking. I couldn't hear him over the sound of the engine and with the wind coming through the broken window. As well as all that, I'm a bit deaf. I spend a lot of time faking that I know what's going on. My brother is one of the few people who knows this but he rarely takes it into consideration. I know that if I ask him to speak up I still won't be able to make out what he's saying. I also know that if I tell him I can't hear him he'll just keep talking anyway. So I just leave him keep talking. He seems to be enjoying it. He seems quite into whatever it is he's pretending I can hear. The only thing I think I hear him say is something about a billion euro. I decide that I'll ask him what he was talking about later, when it's quieter. When we've stopped for something to eat.
So, we stop for something to eat and it's quieter and I ask my brother what he was talking about.
'As we drove by the factory.'
'What factory?'
'The factory in the forest. The shut down place.'
My brother looks puzzled and shrugs.
'You said something about a billion euro.'
'I did?'
He still looks puzzled. He shrugs again. He says he can't remember.
'Well, you seemed pretty worked up about whatever it was.'
'Well sure, who wouldn't be?'
'How do you mean who wouldn't be? You don't even remember what you were talking about.'
'Well, you said I was talking about a billion euro, who wouldn't get worked up over that?'
I nod my head. 'I suppose', I say.
We finish eating in silence and then get back in the car. Once the engine is on and the wind is white noising through the broken window, my brother starts talking again. I watch him as he emotes. He's doing a lot of emoting. He's getting whatever it is off his chest. I can't hear a word he's saying but, you know, I'm glad I can be there for him.
Thursday, April 3, 2014
I'll never forget our Sunday adventure. Gazing at each another over macchiatos. Froth on your nose. 'Hey, let's do something.' Gliding through a lens flared afternoon on our fixies. Bon Iver on the soundtrack. 'Yeah, I feel that exact same way too.' The incline of your flannel hat. #CuteOverbite. Meeting Gustav and Francesca at the organic food market. He's getting back into puppeteering and she found this awesome Il Duce tee. We compare apps. We get toffee apples. You tell me about when you lived in Budapest and I tell you about my year in Brooklyn. 'I've been thinking about reading about physics.' We grab a taco and go see the new Spike Jonze. An Instagram sunset. A bench on the bank of the canal.
'I'm not sure I'm looking for something serious right now.'
'Me too, I'm like kind of like really busy and stuff.'
So it's an unremarkable goodbye that I'll write a remarkable song about and I'll perform it at Kabbáge and you say that you'll be there but I know that you won't and neither will I but I'll think about today all day tomorrow while I'm processing gypsies at the death camp.
|
From Oxford University Press:
There is a broad consensus among scholars that the idea of human rights was a product of the Enlightenment but that a self-conscious and broad-based human rights movement focused on international law only began after World War II. In this narrative, the nineteenth century's absence is conspicuous--few have considered that era seriously, much less written books on it. But as Jenny Martinez shows in this novel interpretation of the roots of human rights law, the foundation of the movement that we know today was a product of one of the nineteenth century's central moral causes: the movement to ban the international slave trade. Originating in England in the late eighteenth century, abolitionism achieved remarkable success over the course of the nineteenth century. Martinez focuses in particular on the international admiralty courts, which tried the crews of captured slave ships. The courts, which were based in the Caribbean, West Africa, Cape Town, and Brazil, helped free at least 80,000 Africans from captured slavers between 1807 and 1871. Here then, buried in the dusty archives of admiralty courts, ships' logs, and the British foreign office, are the foundations of contemporary human rights law: international courts targeting states and non-state transnational actors while working on behalf the world's most persecuted peoples--captured West Africans bound for the slave plantations of the Americas. Fueled by a powerful thesis and novel evidence, Martinez's work will reshape the fields of human rights history and international human rights law.
- Forces us to fundamentally rethink the origins of human rights activism
- Filled with fascinating stories of captured slave ship crews brought to trial across the Atlantic world in the nineteenth century
- Shows how the prosecution of the international slave trade was crucial to the development of modern international law
|
Researchers at UT Southwestern Medical Center have found that fluctuations in internal body temperature regulate the body's circadian rhythm, the 24-hour cycle that controls metabolism, sleep and other bodily functions.
A light-sensitive portion of the brain called the suprachiasmatic nucleus (SCN) remains the body's "master clock" that coordinates the daily cycle, but it does so indirectly, according to a study published by UT Southwestern researchers in the Oct. 15 issue of Science.
The SCN responds to light entering the eye, and so is sensitive to cycles of day and night. While light may be the trigger, the UT Southwestern researchers determined that the SCN transforms that information into neural signals that set the body's temperature. These cyclic fluctuations in temperature then set the timing of cells, and ultimately tissues and organs, to be active or inactive, the study showed.
Scientists have long known that body temperature fluctuates in warm-blooded animals throughout the day on a 24-hour, or circadian, rhythm, but the new study shows that temperature actually controls body cycles, said Dr. Joseph Takahashi, chairman of neuroscience at UT Southwestern and senior author of the study.
"Small changes in body temperature can send a powerful signal to the clocks in our bodies," said Dr. Takahashi, an investigator with the Howard Hughes Medical Institute. "It takes only a small change in internal body temperature to synchronize cellular 'clocks' throughout the body."
Daily changes in temperature span only a few degrees and stay within normal healthy ranges. This mechanism has nothing to do with fever or environmental temperature, Dr. Takahashi said.
This system might be a modification of an ancient circadian control system that first developed in other organisms, including cold-blooded animals, whose daily biological cycles are affected by external temperature changes, Dr. Takahashi said.
"Circadian rhythms in plants, simple organisms and cold-blooded animals are very sensitive to temperature, so it makes sense that over the course of evolution, this primordial mechanism could have been modified in warm-blooded animals," he said.
In the current study, the researchers focused on cultured mouse cells and tissues, and found that genes related to circadian functions were controlled by temperature fluctuations.
SCN cells were not temperature-sensitive, however. This finding makes sense, Dr. Takahashi said, because if the SCN, as the master control mechanism, responded to temperature cues, a disruptive feedback loop could result, he said.
Explore further: Now we know why old scizophrenia medicine works on antibiotics-resistant bacteria
|
If superparticles were to exist the decay would happen far more often. This test is one of the "golden" tests for supersymmetry and it is one that on the face of it this hugely popular theory among physicists has failed.
Prof Val Gibson, leader of the Cambridge LHCb team, said that the new result was "putting our supersymmetry theory colleagues in a spin".
The results are in fact completely in line with what one would expect from the Standard Model. There is already concern that the LHCb's sister detectors might have expected to have detected superparticles by now, yet none have been found so far.This certainly does not rule out SUSY, but it is getting to the same level as cold fusion if positive experimental result does not come soon.
|
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/gil.hpp>
#include <boost/mpl/vector.hpp>
#include <cassert>
#include <exception>
#include <iostream>
#include <vector>
using namespace boost::gil;
using namespace std;
void test_pixel_iterator()
{
boost::function_requires<Point2DConcept<point<int>>>();
boost::function_requires<MutablePixelIteratorConcept<bgr8_ptr_t> >();
boost::function_requires<MutablePixelIteratorConcept<cmyk8_planar_ptr_t> >();
boost::function_requires<PixelIteratorConcept<rgb8c_planar_step_ptr_t> >();
boost::function_requires<MutableStepIteratorConcept<rgb8_step_ptr_t> >();
boost::function_requires<MutablePixelLocatorConcept<rgb8_step_loc_t> >();
boost::function_requires<PixelLocatorConcept<rgb8c_planar_step_loc_t> >();
boost::function_requires<MutableStepIteratorConcept<cmyk8_planar_step_ptr_t> >();
boost::function_requires<StepIteratorConcept<gray8c_step_ptr_t> >();
boost::function_requires<MutablePixelLocatorConcept<memory_based_2d_locator<rgb8_step_ptr_t> > >();
typedef const bit_aligned_pixel_reference<std::uint8_t, boost::mpl::vector3_c<int,1,2,1>, bgr_layout_t, true> bgr121_ref_t;
typedef bit_aligned_pixel_iterator<bgr121_ref_t> bgr121_ptr_t;
boost::function_requires<MutablePixelIteratorConcept<bgr121_ptr_t> >();
boost::function_requires<PixelBasedConcept<bgr121_ptr_t> >();
boost::function_requires<MemoryBasedIteratorConcept<bgr121_ptr_t> >();
boost::function_requires<HasDynamicXStepTypeConcept<bgr121_ptr_t> >();
// TEST dynamic_step_t
BOOST_STATIC_ASSERT(( boost::is_same<cmyk16_step_ptr_t,dynamic_x_step_type<cmyk16_step_ptr_t>::type>::value ));
BOOST_STATIC_ASSERT(( boost::is_same<cmyk16_planar_step_ptr_t,dynamic_x_step_type<cmyk16_planar_ptr_t>::type>::value ));
BOOST_STATIC_ASSERT(( boost::is_same<iterator_type<uint8_t,gray_layout_t,false,false,false>::type,gray8c_ptr_t>::value ));
// TEST iterator_is_step
BOOST_STATIC_ASSERT(iterator_is_step< cmyk16_step_ptr_t >::value);
BOOST_STATIC_ASSERT(iterator_is_step< cmyk16_planar_step_ptr_t >::value);
BOOST_STATIC_ASSERT(!iterator_is_step< cmyk16_planar_ptr_t >::value);
typedef color_convert_deref_fn<rgb8c_ref_t, gray8_pixel_t> ccv_rgb_g_fn;
typedef color_convert_deref_fn<gray8c_ref_t, rgb8_pixel_t> ccv_g_rgb_fn;
gil_function_requires<PixelDereferenceAdaptorConcept<ccv_rgb_g_fn> >();
gil_function_requires<PixelDereferenceAdaptorConcept<deref_compose<ccv_rgb_g_fn,ccv_g_rgb_fn> > >();
typedef dereference_iterator_adaptor<rgb8_ptr_t, ccv_rgb_g_fn> rgb2gray_ptr;
BOOST_STATIC_ASSERT(!iterator_is_step< rgb2gray_ptr >::value);
typedef dynamic_x_step_type<rgb2gray_ptr>::type rgb2gray_step_ptr;
BOOST_STATIC_ASSERT(( boost::is_same< rgb2gray_step_ptr, dereference_iterator_adaptor<rgb8_step_ptr_t, ccv_rgb_g_fn> >::value));
make_step_iterator(rgb2gray_ptr(),2);
typedef dereference_iterator_adaptor<rgb8_step_ptr_t, ccv_rgb_g_fn> rgb2gray_step_ptr1;
BOOST_STATIC_ASSERT(iterator_is_step< rgb2gray_step_ptr1 >::value);
BOOST_STATIC_ASSERT(( boost::is_same< rgb2gray_step_ptr1, dynamic_x_step_type<rgb2gray_step_ptr1>::type >::value));
typedef memory_based_step_iterator<dereference_iterator_adaptor<rgb8_ptr_t, ccv_rgb_g_fn> > rgb2gray_step_ptr2;
BOOST_STATIC_ASSERT(iterator_is_step< rgb2gray_step_ptr2 >::value);
BOOST_STATIC_ASSERT(( boost::is_same< rgb2gray_step_ptr2, dynamic_x_step_type<rgb2gray_step_ptr2>::type >::value));
make_step_iterator(rgb2gray_step_ptr2(),2);
// bit_aligned iterators test
// Mutable reference to a BGR232 pixel
typedef const bit_aligned_pixel_reference<std::uint8_t, boost::mpl::vector3_c<unsigned,2,3,2>, bgr_layout_t, true> bgr232_ref_t;
// A mutable iterator over BGR232 pixels
typedef bit_aligned_pixel_iterator<bgr232_ref_t> bgr232_ptr_t;
// BGR232 pixel value. It is a packed_pixel of size 1 byte. (The last bit is unused)
typedef std::iterator_traits<bgr232_ptr_t>::value_type bgr232_pixel_t;
BOOST_STATIC_ASSERT((sizeof(bgr232_pixel_t)==1));
bgr232_pixel_t red(0,0,3); // = 0RRGGGBB, = 01100000
// a buffer of 7 bytes fits exactly 8 BGR232 pixels.
unsigned char pix_buffer[7];
std::fill(pix_buffer,pix_buffer+7,0);
bgr232_ptr_t pix_it(&pix_buffer[0],0); // start at bit 0 of the first pixel
for (int i=0; i<8; ++i) {
*pix_it++ = red;
}
// test cross byte pixel values - meaning when a pixel value is stretched over two bytes
typedef bit_aligned_image1_type< 3, gray_layout_t >::type gray3_image_t;
typedef gray3_image_t image_t;
typedef image_t::view_t view_t;
typedef view_t::reference ref_t;
typedef bit_aligned_pixel_iterator< ref_t > iterator_t;
std::vector< unsigned char > buf( 4 );
// bit pattern is: 1011 0110 0110 1101 1101 1011
// each byte is read right to left
buf[0] = 182;
buf[1] = 109;
buf[2] = 219;
iterator_t it( &buf[0], 0 );
ref_t p1 = *it; it++;
ref_t p2 = *it; it++;
ref_t p3 = *it; it++;
ref_t p4 = *it; it++;
ref_t p5 = *it; it++;
ref_t p6 = *it; it++;
ref_t p7 = *it; it++;
ref_t p8 = *it; it++;
unsigned char v1 = get_color( p1, gray_color_t() );
unsigned char v2 = get_color( p2, gray_color_t() );
unsigned char v3 = get_color( p3, gray_color_t() );
unsigned char v4 = get_color( p4, gray_color_t() );
unsigned char v5 = get_color( p5, gray_color_t() );
unsigned char v6 = get_color( p6, gray_color_t() );
unsigned char v7 = get_color( p7, gray_color_t() );
unsigned char v8 = get_color( p8, gray_color_t() );
// all values should be 110b ( 6 );
assert( v1 == 6 );
assert( v2 == 6 );
assert( v3 == 6 );
assert( v4 == 6 );
assert( v5 == 6 );
assert( v6 == 6 );
assert( v7 == 6 );
assert( v8 == 6 );
}
// TODO: Make better tests. Use some code from below.
/*
template <typename Pixel>
void invert_pixel1(Pixel& pix) {
at_c<0>(pix)=0;
}
template <typename T> inline void ignore_unused_variable_warning(const T&){}
void test_pixel_iterator() {
rgb8_pixel_t rgb8(1,2,3);
rgba8_pixel_t rgba8;
rgb8_ptr_t ptr1=&rgb8;
memunit_advance(ptr1, 3);
const rgb8_ptr_t ptr2=memunit_advanced(ptr1,10);
memunit_distance(ptr1,ptr2);
const rgb8_pixel_t& ref=memunit_advanced_ref(ptr1,10); ignore_unused_variable_warning(ref);
rgb8_planar_ptr_t planarPtr1(&rgb8);
rgb8_planar_ptr_t planarPtr2(&rgb8);
memunit_advance(planarPtr1,10);
memunit_distance(planarPtr1,planarPtr2);
rgb8_planar_ptr_t planarPtr3=memunit_advanced(planarPtr1,10);
// planarPtr2=&rgba8;
planar_pixel_reference<uint8_t&,rgb_t> pxl=*(planarPtr1+5);
rgb8_pixel_t pv2=pxl;
rgb8_pixel_t pv3=*(planarPtr1+5);
rgb8_pixel_t pv=planarPtr1[5];
assert(*(planarPtr1+5)==planarPtr1[5]);
rgb8_planar_ref_t planarRef=memunit_advanced_ref(planarPtr1,10);
rgb8_step_ptr_t stepIt(&rgb8,5);
stepIt++;
rgb8_step_ptr_t stepIt2=stepIt+10;
stepIt2=stepIt;
rgb8_step_ptr_t stepIt3(&rgb8,5);
rgb8_pixel_t& ref1=stepIt3[5];
// bool v=boost::is_POD<iterator_traits<memory_based_step_iterator<rgb8_ptr_t> >::value_type>::value;
// v=boost::is_POD<rgb8_pixel_t>::value;
// v=boost::is_POD<int>::value;
rgb8_step_ptr_t rgb8StepIt(ptr1, 10);
rgb8_step_ptr_t rgb8StepIt2=rgb8StepIt;
rgb8StepIt=rgb8StepIt2;
++rgb8StepIt;
rgb8_ref_t reff=*rgb8StepIt; ignore_unused_variable_warning(reff);
rgb8StepIt+=10;
std::ptrdiff_t dst=rgb8StepIt2-rgb8StepIt; ignore_unused_variable_warning(dst);
rgb8_pixel_t val1=ref1;
rgb8_ptr_t ptr=&ref1;
invert_pixel1(*planarPtr1);
// invert_pixel1(*ptr);
rgb8c_planar_ptr_t r8cpp;
// invert_pixel1(*r8cpp);
rgb8_pixel_t& val21=stepIt3[5];
rgb8_pixel_t val22=val21;
rgb8_pixel_t val2=stepIt3[5];
rgb8_ptr_t ptr11=&(stepIt3[5]); ignore_unused_variable_warning(ptr11);
rgb8_ptr_t ptr3=&*(stepIt3+5); ignore_unused_variable_warning(ptr3);
rgb8_step_ptr_t stepIt4(ptr,5);
++stepIt4;
rgb8_step_ptr_t stepIt5;
if (stepIt4==stepIt5) {
int st=0;ignore_unused_variable_warning(st);
}
iterator_from_2d<rgb8_loc_t> pix_img_it(rgb8_loc_t(ptr, 20), 5);
++pix_img_it;
pix_img_it+=10;
rgb8_pixel_t& refr=*pix_img_it;
refr=rgb8_pixel_t(1,2,3);
*pix_img_it=rgb8_pixel_t(1,2,3);
pix_img_it[3]=rgb8_pixel_t(1,2,3);
*(pix_img_it+3)=rgb8_pixel_t(1,2,3);
iterator_from_2d<rgb8c_loc_t> pix_img_it_c(rgb8c_loc_t(rgb8c_ptr_t(ptr),20), 5);
++pix_img_it_c;
pix_img_it_c+=10;
// *pix_img_it_c=rgb8_pixel_t(1,2,3); // error: assigning though const iterator
typedef iterator_from_2d<rgb8_loc_t>::difference_type dif_t;
dif_t dt=0;
std::ptrdiff_t tdt=dt; ignore_unused_variable_warning(tdt);
// memory_based_step_iterator<rgb8_pixel_t> stepIt3Err=stepIt+10; // error: non-const from const iterator
memory_based_2d_locator<rgb8_step_ptr_t> xy_locator(ptr,27);
xy_locator.x()++;
// memory_based_step_iterator<rgb8_pixel_t>& yit=xy_locator.y();
xy_locator.y()++;
xy_locator+=point<std::ptrdiff_t>(3,4);
// *xy_locator=(xy_locator(-1,0)+xy_locator(0,1))/2;
rgb8_pixel_t& rf=*xy_locator; ignore_unused_variable_warning(rf);
make_step_iterator(rgb8_ptr_t(),3);
make_step_iterator(rgb8_planar_ptr_t(),3);
make_step_iterator(rgb8_planar_step_ptr_t(),3);
// Test operator-> on planar ptrs
{
rgb8c_planar_ptr_t cp(&rgb8);
rgb8_planar_ptr_t p(&rgb8);
// get_color(p,red_t()) = get_color(cp,green_t()); // does not compile - cannot assign a non-const pointer to a const pointer. Otherwise you will be able to modify the value through it.
}
// xy_locator.y()++;
// dimensions to explore
//
// values, references, pointers
// color spaces (rgb,cmyk,gray)
// channel ordering (bgr vs rgb)
// planar vs interleaved
// Pixel POINTERS
// typedef const iterator_traits<rgb8_ptr_t>::pointer RGB8ConstPtr;
typedef const rgb8_ptr_t RGB8ConstPtr;
typedef const rgb8_planar_ptr_t RGB8ConstPlanarPtr;
// typedef const iterator_traits<rgb8_planar_ptr_t>::pointer RGB8ConstPlanarPtr;
// constructing from values, references and other pointers
RGB8ConstPtr rgb8_const_ptr=NULL; ignore_unused_variable_warning(rgb8_const_ptr);
rgb8_ptr_t rgb8ptr=&rgb8;
rgb8=bgr8_pixel_t(30,20,10);
rgb8_planar_ptr_t rgb8_pptr=&rgb8;
++rgb8_pptr;
rgb8_pptr--;
rgb8_pptr[0]=rgb8;
RGB8ConstPlanarPtr rgb8_const_planar_ptr=&rgb8;
rgb8c_planar_ptr_t r8c=&rgb8;
r8c=&rgb8;
rgb8_pptr=&rgb8;
// rgb8_const_planar_ptr=&rgb16p; // error: incompatible bit depth
// iterator_traits<CMYK8>::pointer cmyk8_ptr_t=&rgb8; // error: incompatible pointer type
RGB8ConstPtr rgb8_const_ptr_err=rgb8ptr; // const pointer from non-regular pointer
ignore_unused_variable_warning(rgb8_const_ptr_err);
// dereferencing pointers to obtain references
rgb8_ref_t rgb8ref_2=*rgb8ptr; ignore_unused_variable_warning(rgb8ref_2);
assert(rgb8ref_2==rgb8);
// RGB8Ref rgb8ref_2_err=*rgb8_const_planar_ptr; // error: non-const reference from const pointer
rgb8_planar_ref_t rgb8planarref_3=*rgb8_pptr; // planar reference from planar pointer
assert(rgb8planarref_3==rgb8);
// RGB8Ref rgb8ref_3=*rgb8_planar_ptr_t; // error: non-planar reference from planar pointer
const rgb8_pixel_t crgb8=rgb8;
*rgb8_pptr=rgb8;
*rgb8_pptr=crgb8;
memunit_advance(rgb8_pptr,3);
memunit_advance(rgb8_pptr,-3);
}
*/
int main()
{
try
{
test_pixel_iterator();
return EXIT_SUCCESS;
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (...)
{
return EXIT_FAILURE;
}
}
|
The Life & Times of Ulysses S. Grant
War Between the States
Ulysses S. Grant is best known for being the commander of the Union forces in the American Civil War. When war broke out, however, he was not even a member of the armed forces! Soon after the defeat at Fort Sumter, however, Grant was offered a position to train and recruit volunteers by the governor of Illinois, which he accepted. Grant was then appointed a field command after some pressure, and became a colonel of the 21st Illinois Infantry, a regiment notorious for its unruliness. After whipping them into shape, President Lincoln appointed Grant brigadier general of militia volunteers, which the general public would recognize as a one-star general.
After this success, Grant was moved to the important District of Southeast Missouri, close to the Confederate border. His original purpose, stationed in Cairo, Illinois, (close to Southeast Missouri) was to defend and divert Confederate forces; but that did not suit the aggressive Grant. He requested and received permission to go on the offensive. Grant swept into Confederate-controlled land, and took Forts Henry and Donelson, in the first large-scale Union victory of the Civil War. At Fort Donelson, Grant fractured Confederate lines that had repulsed Union attack just the day before; it was here that he demanded "no terms except unconditional and immediate surrender." This, due to his initials, earned him the famous nickname "Unconditional Surrender" Grant.
Capture of Fort Donelson
After Grant's success at Forts Henry and Donelson, Lincoln promoted him to major general (a two-star general). It was after this that Grant became a celebrity, something that would help him win the presidency in later years. In fact, after a picture was published of him smoking a cigar, fans sent him thousands of cigars---something that most likely led to his death of throat cancer at 63. Grant was given control of the Army of the Tennessee after his promotion, and moved his HQ to Savannah, Tennessee in 1862. It was in Tennessee that Grant fought the Battle of Shiloh, a surprise attack by Confederate forces on his army. Grant famously pushed off the Southern forces, but actually lost 3,000 more men than his Confederate counterpart. This heavy casualty list (13,047) shocked American citizens, and produced a large public outcry against Grant. This prompted his commanding officer to remove him from the lead position in the upcoming siege on Corinth, which nearly caused Grant to leave the Army. Luckily, William Tecumseh Sherman, a close friend and fierce general, convinced him to stay; when Grant's C.O. was called to be general-in-chief of the Union army, Grant was able to resume his position.
This left Grant free to stage the famous Siege of Vicksburg, Mississippi, the last Confederate stronghold on the Mississippi River. Grant relentlessly attacked the city, and when he won its surrender in July of 1863, he effectively cut the Confederacy in half on each side of the great river. The great victory at Vicksburg, unlike Shiloh, was accomplished with very minimal losses, and is still considered a brilliant example of military strategy. The long Vicksburg campaign cemented Lincoln's trust in Grant, and in March of 1864 the president gave Grant the rank of lieutenant general (a three-star general). Grant was the first to receive this honor since George Washington, and the post had been revived specifically for him.
Along with this promotion came overall command of all U.S. armies. The General Grant that people think of today was now a reality. He placed General William Tecumseh Sherman in control of the Western theater, and moved himself to Virginia to duel with his famous Confederate counterpart, General Robert E. Lee (pictured below).
Confederate General Robert E. Lee
Grant vs. Lee---Battle of the Century
The main goal of the war effort was now to destroy Robert E. Lee's Army of Northern Virginia, and to cut off the Confederacy's already limited railroad network. Grant and Lincoln devised the Overland Campaign to accomplish these two goals. The main gist of this plan was to have Grant take the main force of the Army against Lee in the east and drive towards Richmond, Virginia, while Sherman made his famous March to the Sea to take Georgia; at the same time, other generals would take key strategic points and railroads to choke off Confederate supplies and men. Grant was one of the first generals to comprehend the now essential art of total war, in which a country devotes all its resources to the war effort (something already practiced in Grant's day), and also realizes that striking against your opponent's economy and infrastructure can be just as important as winning battles (something not as widely used in the mid-1800s).
The Overland Campaign began in the spring of 1864, when Grant's Army of the Potomac marched towards Lee's Army of Northern Virginia, in order to provoke an attack. It worked. Grant fought in many battles, not just a couple major ones; he knew that he had to wear Lee so thin that he wouldn't have any more men to commit to battle. Engagements were fought in Spotsylvania, Cold Harbor, and other places, and the Union almost always had higher casualty lists---but they won the battles. Grant kept on going where other generals had decided to retreat because they didn't want to incur the costs. Grant would not let himself be driven away, which was the Confederacy's main goal. They could not defeat the Union Army, but they could fend it off---until they faced Grant.
The Overland Campaign led eventually to Petersburg, Virginia. Lee was trapped in Petersburg, but would not give it up. So began the Siege of Petersburg. Trenches were dug on both sides, and the Union attempted to cut off Confederate supply lines. Sherman's Georgia campaign was doing tremendously well, and all other aspects of the war seemed to come together for the Union.After months of siege, Lee finally abandoned the city, and Richmond soon after. He retreated to Appomattox Court House, where he surrendered to Grant on April 9, 1985 (pictured below).
Surrender at Appomattox
When Lincoln was assassinated five days after Appomattox, Grant was furious. Lincoln was one of the general's best friends, and he believed that the assassination was a Southern conspiracy that needed to be punished. When he discovered that it was not a wide conspiracy, he calmed down a little. Grant had the honor of being a pallbearer at Lincoln's funeral, where he cried openly while standing at attention.
Within a few months of Lincoln's death, Congress created the rank of General of the Army of the United States, which is the equivalent of a modern full four-star general (General of the Army of the United States would eventually become the five-star general, and a four-star general would be known as simply a general). President Johnson appointed Grant to the position the day it was created, and Grant was the overall commander of U.S. ground forces in the ensuing peacetime. His reign in the position would be short, however, as his celebrity status led to a wide demand for him to be president. This was to happen very soon after the war ended.
|
/*
* Copyright (C) 2018-2020 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
extern "C" {
#include <ia_css_program_group_data.h>
#include <ia_css_program_group_param.h>
#include <ia_css_psys_process_group.h>
#include <ia_css_psys_program_group_manifest.h>
#include <ia_css_psys_terminal.h>
#include <ia_css_psys_terminal_manifest.h>
#include <ia_css_terminal_manifest_types.h>
#include <ia_css_terminal_types.h>
#include <ia_isp_bxt.h>
#include <ia_isp_types.h>
#include <ia_p2p.h>
#include <ia_p2p_types.h>
#include <ia_pal_types_isp_ids_autogen.h>
#include <pg_control_init_framework.h>
}
#include <map>
#include <memory>
#include <vector>
#include "ia_tools/css_types.h"
#include "iutils/Errors.h"
#include "iutils/Utils.h"
#include "modules/ia_cipr/include/Utils.h"
#include "src/core/psysprocessor/PGUtils.h"
namespace icamera {
#define PSYS_MAX_KERNELS_PER_PG IA_CSS_KERNEL_BITMAP_BITS
/**
* \class IntelPGParam
*
* \brief This is a version P2P implementation which is used to encode parameter terminal
* and decode statistic terminal for PSYS pipeline.
*
* The call sequence as follows:
* 1. init();
* 2. prepare();
* 3. allocatePGBuffer() (optional);
* 4. setPGAndPrepareProgram();
* 5. getPayloadSizes(), and allocate payload buffers,
* allocatePayloads() is provided for that;
* 6. getFragmentDescriptors();
* 7. loop frame {
* updatePALAndEncode();
* decode();
* }
* 8. deinit();
*/
class IntelPGParam {
public:
explicit IntelPGParam(int pgId);
~IntelPGParam();
/**
* Use to init and config P2P handle.
*/
int init(ia_p2p_platform_t platform, const PgConfiguration& Pgconfiguration);
/**
* Query and save the requirement for each terminal, calculate the final kernel bitmap.
*/
int prepare(const ia_binary_data* ipuParameters, const ia_css_rbm_t* rbm,
ia_css_kernel_bitmap_t* bitmap, uint32_t* maxStatsSize = nullptr);
/**
* Allocate PG buffer for caller
*/
void* allocatePGBuffer(int pgSize);
/**
* Accept pg outside and init program_control_init terminal.
*/
int setPGAndPrepareProgram(ia_css_process_group_t* pg);
/**
* Allocate payload memory for terminals.
*/
int allocatePayloads(int payloadCount, ia_binary_data* payloads);
/**
* Update PAL and encode payload data for all terminals. Will skip inactive terminals.
*/
int updatePALAndEncode(const ia_binary_data* ipuParams, int payloadCount,
ia_binary_data* payloads);
/**
* Decode payload data for all related terminals.
*/
int decode(int payloadCount, ia_binary_data* payload, ia_binary_data* statistics);
/**
* Use to deinit P2P handle.
*/
void deinit();
/**
* Get fragment descriptors calculated according to PAL data
* Called after prepare().
*/
int getFragmentDescriptors(int descCount, ia_p2p_fragment_desc* descs);
/**
* Get payload size for all terminals, and return valid payloads number.
*/
int getPayloadSizes(int payloadCount, ia_binary_data* payloads);
private:
enum FragmentDataTerminalType {
FRAG_TERM_TYPE_INPUT = 0,
FRAG_TERM_TYPE_OUTPUT_START, // Mapping to data out terminal in order for all postgdc pgs.
FRAG_TERM_TYPE_DISPALY_OUTPUT = FRAG_TERM_TYPE_OUTPUT_START,
FRAG_TERM_TYPE_MAIN_OUTPUT,
FRAG_TERM_TYPE_PP_OUTPUT,
FRAG_TERM_TYPE_COUNT,
};
int mPgId;
int mTerminalCount;
PgFrameDesc mInputMainFrame;
PgFrameDesc mOutputMainFrame;
uint8_t mFragmentCount;
ia_p2p_fragment_desc* mFragmentDesc;
ia_p2p_fragment_configuration_t* mFragmentConfig;
// for pg fragment with new api:
// ia_p2p_calculate_fragments_rbm
// Instead of mFragmentDesc
ia_p2p_handle mP2pHandle;
ia_binary_data mP2pCacheBuffer;
ia_css_program_group_manifest_t* mPgManifest;
std::vector<int> mDisableDataTermials;
ia_css_process_group_t* mProcessGroup;
int mProgramControlInitTerminalIndex;
struct IpuPgTerminalKernelInfo {
IpuPgTerminalKernelInfo() {}
uint8_t id = 0;
uint8_t sections = 0;
uint32_t size = 0;
bool initialize = false;
};
struct IpuPgTerminaRequirements {
IpuPgTerminaRequirements() { kernelBitmap = ia_css_kernel_bitmap_clear(); }
ia_css_terminal_type_t type = IA_CSS_N_TERMINAL_TYPES;
uint32_t payloadSize = 0;
ia_css_kernel_bitmap_t kernelBitmap;
uint32_t sectionCount = 0;
IpuPgTerminalKernelInfo* kernelOrder = nullptr;
ia_p2p_fragment_desc* fragment_descs = nullptr;
// Use for program_control_init
uint32_t userParamSize;
std::unique_ptr<uint8_t[]> userParamAddress;
};
struct IpuPgRequirements {
IpuPgRequirements() { CLEAR(terminals); }
uint32_t terminalCount = 0;
IpuPgTerminaRequirements terminals[IPU_MAX_TERMINAL_COUNT];
};
struct KernelRequirement {
KernelRequirement() { mKernelBitmap = ia_css_kernel_bitmap_clear(); }
ia_p2p_terminal_requirements_t mSections[PSYS_MAX_KERNELS_PER_PG];
ia_p2p_payload_desc mPayloads[PSYS_MAX_KERNELS_PER_PG];
int mPayloadSize = 0;
ia_css_kernel_bitmap_t mKernelBitmap;
};
KernelRequirement mKernel;
IpuPgRequirements mPgReqs;
// Allocate them here, for sandboxing case (shared memory)
std::vector<ia_binary_data> mAllocatedPayloads;
void* mProcessGroupMemory;
private:
int getKernelIdByBitmap(ia_css_kernel_bitmap_t bitmap);
ia_css_kernel_bitmap_t getCachedTerminalKernelBitmap(
ia_css_param_terminal_manifest_t* manifest);
ia_css_kernel_bitmap_t getProgramTerminalKernelBitmap(
ia_css_program_terminal_manifest_t* manifest);
int disableZeroSizedTerminals(ia_css_kernel_bitmap_t* kernelBitmap);
css_err_t getKernelOrderForProgramTerm(ia_css_program_terminal_manifest_t* terminalManifest,
IpuPgTerminalKernelInfo* kernelOrder);
css_err_t getKernelOrderForParamCachedInTerm(ia_css_param_terminal_manifest_t* terminalManifest,
IpuPgTerminalKernelInfo* kernelOrder);
int8_t terminalEnumerateByType(IpuPgRequirements* reqs, ia_css_terminal_type_t terminalType,
uint8_t num);
int8_t terminalEnumerateByBitmap(IpuPgRequirements* reqs, ia_css_terminal_type_t terminal_type,
ia_css_kernel_bitmap_t bitmap);
bool isKernelIdInKernelOrder(IpuPgRequirements* reqs, int8_t termIndex, int kernelId,
uint8_t* orderedIndex);
uint32_t getKernelCountFromKernelOrder(IpuPgRequirements* reqs, int8_t termIndex, int kernelId);
void processTerminalKernelRequirements(IpuPgRequirements* reqs, int8_t termIndex,
ia_css_terminal_type_t terminalType, int kernelId);
css_err_t payloadSectionSizeSanityTest(ia_p2p_payload_desc* current, uint16_t kernelId,
uint8_t terminalIndex, uint32_t currentOffset,
size_t payloadSize);
int calcFragmentDescriptors(int fragmentCount, const PgFrameDesc& inputMainFrame,
const PgFrameDesc& outputMainFrame, const ia_css_rbm_t* rbm);
void dumpFragmentDesc(int fragmentCount);
int encodeTerminal(ia_css_terminal_t* terminal, ia_binary_data payload);
int decodeTerminal(ia_css_terminal_t* terminal, ia_binary_data payload);
int serializeDecodeCache(ia_binary_data* result);
void destroyPayloads();
void destroyPGBuffer();
DISALLOW_COPY_AND_ASSIGN(IntelPGParam);
};
} // namespace icamera
|
The New York Times is reporting today that the source of the worm (so advanced some thought it was alien weapon) was us. And it wasn't the first.
Let the Games Begin
There are wars that we know about, like the one in Afghanistan. And there are the ones we suspect, like the special forces operations taking part throughout the world. But it turns out there's another war, an invisible one, with programmers wielding code as vigorously as soldiers do their M16s. It's called operation Olympic Games, and it's been waged against Iran for nearly a decade.
Olympic Games began under the Bush administration, in 2006, reports the NYT. That's when a widely reported tour of Iran's Natanz nuclear plant made White House officials anxious enough to consider military action. Stop uranium enrichment at all cost, was the part line. But bombs are messy, and lead to more and bigger bombs; not ideal for a region that's already unstable.
An alternative presented itself:
The goal was to gain access to the Natanz plant's industrial computer controls. That required leaping the electronic moat that cut the Natanz plant off from the Internet - called the air gap, because it physically separates the facility from the outside world. The computer code would invade the specialized computers that command the centrifuges.
A blockade, then, not of supplies but of information. Lines of code infiltrating high command positions. This is how we fight now.
A Human Element
The new weapon took time and resources to develop. US called on help from Israel (see the NYT for the full, fascinating story of the collaboration). It resurrected some old P-1 centrifuges it had confiscated when Qaddafi gave up his nuclear ambitions, testing the delicate Stuxnet worm on its outdated technology to make sure that it worked. And then it headed straight for the real thing.
While Stuxnet may not have been discovered until 2010, but it was first deployed in 2008, when Iran found that its centrifuges began "spinning out of control." But how did it get there in the first place? Good old fashioned spies.
It's long been known that the US has people on the ground, undercover, in Iran; a dozen were sadly captured last year. Armed with thumb drives, they pumped Natanz's belly full of Stuxnet. It would wreak havoc with Iran's nuclear ambition for years.
Blown Cover
Throughout the last several years, the Obama administration has accelerated the attacks, ordering both more frequency and efficacy. As the NYT reports, it could be argued that what gave Stuxnet away is that it was too effective. Like King Kong throwing off its shackles in the theater and rampaging through Manhattan, Stuxnet escaped Natanz and began replicating itself. It seems that someone got a little overzealous:
"We think there was a modification done by the Israelis," one of the briefers told the president, "and we don't know if we were part of that activity."
Mr. Obama, according to officials in the room, asked a series of questions, fearful that the code could do damage outside the plant. The answers came back in hedged terms. Mr. Biden fumed. "It's got to be the Israelis," he said. "They went too far."
And so the plug was pulled.
The Battle Is Not the War
According to the NYT, while Stuxnet may be over, Olympic Games proceeds apace. We've used cyberweapons in other countries, and will continue to do so. Even now, massive spyware called Flame is hitting Iran—although it appears to predate the Bush initiative, and can't be traced back to the US.
It's not a one-sided fight, either. China has been notorious for engaging in cyber warfare with the US and others. And even before this report, it's been widely assumed that Stuxnet was America's baby. Iran will surely attempt to respond in kind. And the barrier to entry is so low—anyone can attack anyone, from anywhere, at any time—that we could well face threats from areas we'd never bothered to consider harmful.
Go read the full story at the NYT. It's a thrilling, in-depth look at our invisible war. And a blueprint, perhaps, for how we'll fight—and be fought—for decades to come. [NYT]
Photo credit: AP
|
/*
Title:
945. Minimum Increment to Make Array Unique
945. 使数组唯一的最小增量
Address:
https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique/
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
sort( A.begin(), A.end() );
int cnt = 0;
for ( int i = 1; i < (int)A.size(); ++i ) {
if ( A[i - 1] >= A[i] ) {
cnt += A[i - 1] - A[i] + 1;
A[i] = A[i - 1] + 1;
}
}
return cnt;
}
};
int main()
{
return 0;
}
|
Thursday, August 4, 2011
Walter Frederick Osborne - Dorothy and Irene Falkiner
signed u.l.: Walter Osborne
oil on canvas
150 by 114cm.; 59 by 45in.
ESTIMATE 500,000-700,000 GBP
Lot Sold: 580,500 GBP
Although better known for his genre paintings, landscapes and late impressionistic garden scenes, Walter Osborne was a superb portraitist, and practised as a portrait painter throughout his life. Amongst his oeuvre are many drawings and paintings, as well as watercolours and pastel studies of members of his family, relatives, children, and friends. He made a series of portraits of fellow artists such as Sarah Purser, Nathaniel Hone and John Hughes, and writers such as Stephen Gwynn and Walter Armstrong.
However, from the mid 1890s onwards much of Osborne's time was taken up by more formal portraits. Partly out of financial necessity, in the pursuit of his own career, and to support his own family, Osborne needed to gain portrait commissions. Even as early as 1892 Osborne made references to the portraits which he was working on. Many of his commissioned portraits of the late 1890s were formal studies of the Establishment and Irish Society: for example of governors, members of the legal profession, academics, the clergy, business people, and of society ladies and their
children. Some of these were purchased directly by the clients, and were never exhibited in public, while others, particularly the portraits of beautiful women and children, were shown at the Royal Hibernian Academy in Dublin, and the Royal Academy in London.
From the mid-1890s to the early twentieth century Osborne painted a series of society ladies and children dressed in their finery. These are amongst the most notable of all of his portraits including Portrait of a lady (Mrs. C. Litton
Falkiner seated at the piano)
Drawings and oil studies are extant of some of these portraits, indicating that Osborne planned and executed them carefully. In some of the portraits the mother and daughter are shown reading together, or there is music involved; while in several the sitter looks directly out at the viewer. In some of the pictures the woman is shown in similar three–quarter seated pose, an elegant dress floating down to her ankles. As the paintings include fine furniture, furnishings and sometimes a piano, it seems possible that Osborne painted the portraits in situ, in the sitters' homes rather than in his studio. Yet despite the potential formality of the occasion, Osborne creates a mood of intimacy. Some of the portraits may have been influenced by the likes of Reynolds, Whilstler and Orchardson, Valasquez and Goya but the closest affinities are with the portraits of Osborne's contemporary Sargent, who often painted mothers with daughters, sisters together, and children, in a brilliant and fluid manner demonstrated in works such as The Daughters of Edward Darley Boit (1882, Museum of Fine Arts, Boston).
The present portrait of Dorothy and Irene Falkiner was obviously commissioned by their parents Mr. and Mrs. C. Litton Falkiner (see fig.2). It was probably painted over the winter of 1899-1900, ready for exhibition in spring. The girls came
from an extremely distinguished Irish family. Their grandfather, Sir Frederick Falkiner (1831-1908), had been born in Borrisokane, Co. Tipperary and was called to the bar in 1852. In 1876, he was appointed Recorder in Dublin, and in 1880, elected to the King's Inns. He was also a leading member of the general synod of the church of Ireland. He was a compassionate man, concerned primarily with pursuing compensation for working men, who had been injured at work, and he became known as the 'poor man's judge' (R.H. Murray and Sinead Agnew, in Oxford Dictionary of
National Biography', Oxford 2004, Vol. 18, p984).
His second son Caesar Litton Falkiner (1863-1908), the girls' father, led a distinguished career as a barrister, politician, historian and writer. He was called to the Bar in Dublin in 1887 and was Assistant Legal Commissioner in the land Commission, 1897-1908. He became a member of the Royal Irish Academy in 1896, and was elected secretary in 1906. Among his publications were Studies in Irish History and Biography, 1901 and Essays relating to Ireland: biographical, historical and topographical, 1909, as well as the letters of Jonathan Swift. In 1982 Falkiner
married Henrietta May Deane, daughter of the brilliant architect Sir Thomas Newemham Deane (1828-1899) and Dorothy and Irene were born in the 1890s.
Osborne's portrait of them belongs firmly to his series of double portraits. It is striking in its depiction of the two sisters, and in the luxurious nature of their costumes. The figures are perfectly placed in the centre of the composition, one
seated on, one standing by, an ornate gilded seat. Osborne observes the pretty features and different expressions of the girls with sensitivity and sympathy. Both children look directly out at the viewer. The older girl, Dorothy, has clear
blue eyes, soft cheeks, rosy lips and flowing golden hair. The gentle face and pink cheeks of the younger girl, Irene, are visible beneath her bonnet. Her face is slightly lowered, her blue eyes looking up at us beneath her golden curls.
According to Hilary O'Kelly (lecturer in the History of Costume, National College of Art and Design, Dublin) the sisters were extremely lavishly dressed, even by the standards of society at the time, indicating their high status in society.
The sumptuous cream coloured material of the costumes, possibly of a Kashmir silk is subtly different in each girl, indicating the older and younger sister. Dorothy wears a frock and a double bow, one black and one white, tied under her chin. With her gorgeous flowing hair and striking black hat, somewhat in the Napoleonic style, O'Kelly believes that she was dressed to be presented to society.
Irene wears a long frock coat, and it is notable that she wears a white bonnet beneath her outer hood. She also seems to wear a black ribbon beneath her cream coloured bow and clutches a doll in her left hand. Both girls wear elegant black gloves, and hold muffs. The trimming around the girls' shoulders, and around the hood of the child, appears so light, that Hilary O'Kelly suggests that it is made of swans' down. There are pleasing echoes of Sargent, for example, the standing pose of the child touchingly recalls the girl in Beatrice Goelet , 1890, while the doll, and the gleaming shoes recall those in Sargent's masterly canvas The Daughters of Edward Darley Boit, 1882.
In spite of the opulence of the girls' costumes, the portrait is in no sense flashy or exhibitionistic. What Osborne conveys is a sense of tenderness and intimacy. In this it has kinship with a contemporary, but much more informal double portrait The Goldfish Bowl, which likewise features two girls. Although they are absorbed in watching the goldfish, rather than looking at the viewer, and their costumes are much more plain, the sitters are likewise set against a loosely painted brown interior, and Osborne conveys a similar mood of sympathy for the children.
As well as a portrait of the girls' mother Portrait of a lady (Mrs. C. Litton Falkiner seated at the piano (1902, National Gallery of Ireland, her pose seated at the piano closely recalling that of Sargent's Madam Ramon Subercaseaux, 1880-81), Osborne also painted the girls' grandfather, Sir Frederick Falkiner in 1903. Sir Frederick died at Funchal, Maderia in 1908, coincidentally the same year that his son C. Litton Falkiner died in a climbing accident at Chamonix in the Alps.
Julian Campbell
No comments:
|
Automatic projector calibration
[Johny Lee] sent in his(pdf) awesome projector calibration project. By adding embedding some optical fiber that feed into a set of USB connected light sensors, his groups software can determine the exact pixel position of each sensor. Once the positions are determined, the projected image can be dynamically adjusted to fix the screen. The technique can be used to stitch together multiple projectors, and even calibrate an image to project onto a three dimensional model. I know some home theater nuts that would love to have this system for calibrating their CRT projectors.
This is such an excellent project, that I want to give credit where it’s due – it was developed by [Johnny C. Lee], [Paul H. Dietz], [Dan Maynes-Aminzade], [Ramesh Raskar] and [Scott E. Hudson].
Be sure to check out the video demo after the break!
40 thoughts on “Automatic projector calibration
1. I wonder why nobody thought of this before… but the problem with the car demo is, that it still requires the geometry to be known beforehand in order to wrap the image correctly.
And how do they want to achieve “interactive” framerates? they have to project log2(width) + log2(height) stripes, which would require 500 projections/sec for VGA, if you refresh the geometry at 25Hz. One could use a special projector that projects the stripes in infrared and at the same time the image that’s for the user to see…
But wouldn’t it be easier and more flexible, at the expense of 1:1 pixel precision, to point a camera at the projection surface (from the users point of view). you could then project images that look flat from a certain viewpoint onto complex unknown surfaces… but I think that would solve another problem…
btw, the setup they use looks quite cheap, just hook up some sensors to the IO-ins of your favorite programmable USB-chip…
If I just had a projector :D
2. The only problem I see with this approach is that you loose a huge amount of the available number of pixels from the projector… He is using a screen that is about 6″ on a side in a field of view that is about 30 inches on a side, which is ‘wasting’ about 95% of the available pixels… When he turns the screen on its side it further complicates the problem because the screens footprint becomes more along the lines of 2″ by 6″, reducing the pixel utilisation to a meager 1%
Also, you still have to focus the projector onto the target, and your depth of field is still limited by the lens on your projector…
This could get really big when laser projectors (using moving mirror galvos to steer the beam) become affordable, as you can then adjust the field of view of the projector on the fly, and the images are always in focus.
Aside from that, that is an awesome setup. I envision some code to allow beryl/compiz (sorry windows/mac users) to have several small (or large for that matter) panels that can be mapped to an individual window. So you can drag/rotate/etc each of your windows on say a physical desk.
3. It must be possible to do the calibration in way less time.
Consider the projector has about a million pixels.
To uniquely identify each pixel, they must each be given a code about 20 bits (frames) long. The codes would be arranged so two adjacent pixels are different in only one frame. (basicly gray code with an extra dimension, so X and Y can be calculated simultaniously). That means positions can be calculated with only 20 frames, and with a 60Hz refresh rate it should only take a third of a second to identify a pixel (ie. 3Hz). That means it becomes practical to track moving objects using an IR projector (because you can do motion prediction and also you can presume the area certain pixels are in by their previous location, reducing the number of frames required to deduce a location). For fast-moving items, accuracy is also less important again reducing the number of frames.
I guess it would be possible to then track an item to about 10 Hz, which could have some interesting uses.
It would be possible to further speed up the process by using all 3 colour channels seperately and have detectors for all 3 colours on the ends of the fibers.
Another interesting ofshoot is it might be possible to do sub-pixel positions by measuring intensity.
4. Very impressive. Earlier today, I had an idea conveniently somewhat-relevant to the model car demo, cheap sort-of-invisibility:
Suppose a camera was added close to the projector, and the background was a random, inconsistent image, rather than a solid-gray one.
First, the camera takes a picture of the background and remembers it. Then the camera records the binary pattern, from which the offset relative to the projector can be determined; the background should not be a problem to calibration because a previously-recorded image may be used to filter out the graphical background noise.
Next, the still-flat-gray model car with the optical sensors is placed on the background. The calibration does its thing like in the demo so that the colors can be projected correctly onto it; however, this should also provide enough information to project a piece of the background over the car such that it becomes sort-of-invisible from the point of view of the view of the camera, or if multiple projector-cameras are used, sort-of-invisible from a single arbitrary point of view.
5. Love this post. I can’t help but dig up an older article from Technology Review (late ’04) that focused on one group’s work with hand held projectors, aiming to shrink them enough to replace/augment cellphone/PDA displays. Some of their tricks included adaptive projecting onto uneven surfaces, keeping a steady image despite moving the projector (so you could tilt and point the projector like a mouse/laser-pointer), and automatically unifying several projectors for an even larger image. So that was baseline already pretty cool. But they took it a bit further and got RFID tags involved that each had a photodiode sensor. They then ran a similar scanlines projection (like this project uses) across a scene, and identically they could exactly locate where the sensor was. Their working example was a storage shelf with different cardboard boxes and embedded tags + sensors, and they would project graphical information for each box onto the side of each box.
Now, having recently reformatted my lappy, I’m suddenly lacking the link to the online copy of the article. I’ve found a similar copy, but it lacks the images that went with each number. *grumble* Also, I’m not sure if this is related, but they seem to be doing very similar things: Ditto:
Although the original focused on what you could do with a palm sized (“pencil sized” they hoped) projector, I’d always been rather been intrigued with the RFID part. These days, we’ve got the multitouch demos and cameras tracking markers in realtime, but the light detector + projector combo still seems like a promising combination. Just wanted to share/connect this to some older research. (…and if they’re the same group, I’m going to go find a wall for my forehead.)
6. Neat stuff.
It gets better, a DMD can slam out binary frames at 14,300 Hz and the sequence is short (on the order of 20 frames) so you can get a fix in about 1.4 milliseconds and after you have an absolute fix you can use coding tricks to drop the number of frames to do relative tracking, I’d put it at about 8 frames with a periodic 20 frame burst to cancel out cumulative errors.
The actual reprojection is achieved by mapping the camera space to the projector space and fitting the point positions to identical virtual models. But it can get tricky without overdetermined sampling.
This also burns resolution like nobody’s business. The actual resolutions with a close up are pretty miserable. Lots of anti aliasing going on too.
Also check out this honest to goodness projector hack by the same guys:
7. Some more comments to add to the discussion:
1). For moving targets you don’t have to use the same search scheme as you already know roughly where the corners of the targers are (or were). You just need to be able to search those specific areas within a radius.
2). There is no reason why multiple targets could not be placed in projection view, once calibrated each could have a different image projected onto each of them.
3). The target screen are currently teathered to a compute, again not needed. The electronics could be fully self contained (not that difficult to code) and result sent to projector(s) system wirelessly (Bluetooth for example).
4). In the same manner that they use two projectors onto a wide target with 6 sensor, you could make a modular screen built from square panels where you just assemble the size screen you need and point a barrage of projectors at it to get some really (!!!) high resolutions.
A fantastically simple idea. Good hack!
8. Many CRT projectors have had this feature for many, many years and those of us who have set up CRT projectors more than once know that they are not as good as doing the setup manually.
The CRT projector system consists of about 5 different ways to focus the electron beam and 4 different ways to control optical focus, multiply that by 3 tubes and you have the number of settings that auto-convergence cannot fix.
Convergence (getting the 3 tubes to overlap) is about 10 settings pr. tube.
The tricky part is that several of these settings interoperate so several iterations are needed to get the perfect setup.
9. Embedded optical sensors seems somewhat complex. Wonder why they don’t use reflecting targets attached to the screen? Put a 2-d barcode on the target and pick up the reflected light with a single sensor at the projector to identify which target it is as well as the precise position. (Cube-corner retro-reflecting targets might help.)
10. This type of technology, using optical sensors to warp and blend projectors, is already commercially available from at least two companies. Iridas and 3D Perceptions. I’ve been using them to project on cylinders and spheres. However, they take about 30 seconds to auto-align and they are too expensive for everyday use. The speed of this is very impressive. If its being done with inexpensive hardware, thats equally impressive.
You can’t use reflecting targets because they would be visible to the viewer.
11. When I worked at IBM we had a system that would project onto multiple interactive surfaces using a projector and mirrors. The problem was always calibration. You’d mount the projector, motorized mirror, and position the surfaces to project onto and then calibrate. If anything got touched then you had to do the calibration all over again. This tech would make it so that all you had to do at the start was a very basic alignment and then the system could handle the calibration as needed.
The demo itself was very cool. We had a clothing store of the future set up for a major retailer and the projector could put a screen on the wall, on the floor, and on the jeans display depending on where the customer was. The jeans display was interactive so that you could point with your finger and it would show different options.
12. I think this is amazing but I don’t understand how it works. I have never seen a projector that has this sort of calibration via user-accessible menus. I mean, unless the team also re-wrote the projector code, I am stumped. I understand *how* the system works, I just don’t understand it’s able to tell the project to do anything other than zoom in and out, squeeze sides, or focus.
13. I really like the Hack-A-Day community because there is a high density of very smart people with an imagination that rivals or surpases that of the recognized research community.
The comments here about using high-speed DLP, infrared patterns, reflective markers, multiple surfaces, lost pixels are all completely spot on. Since this is my thesis work, some of these ideas have been addressed in my followup work. You can find that here (with more video!):
14. In the case of this demonstration, the calibration is not bing done in the projector. The video is passing through a computer first. The computer is processing the video and warping it to fit the projection surface. The projector is just being a dumb projector and not doing anything different.
15. impressive indeed – it is worth pointing out that this isn’t new research (UIST 2004) – MERL and CMU have done some pretty neat stuff in the past. as a followup, they had a publish in UIST 2005 where they built on this where they added the capability to move the display in real time and increased touch capabilities …
16. Currently, as far as I know, you can’t buy this software. If you were to check out you can request a copy of their callibration software, and from what I can tell, it is pretty similar to what Johnny was using for his callibration technique (which he worked with a few of the shader lamps people with).
I have tried to contact johnny directly through the e-mail on his website, but no luck so far. I want to try and use this callibration technique in a real-world, entertainment aspect.
Being a VJ, callibration is not really that important, but to be able to transform a stage into something that is immersive both for the audience, and the performers, this would be absolutely vital.
I certainly hope that research continues for this, and it someday, soon hopefully, becomes available to users.
17. i want to stack 2 projectors 3200 lumenes? what is the cheapest solution of software and hardware ? jhonny chun lee has good metods. Please is very imprtant for me can anyone help ? i had read three opcion: vioso wings , scalable displays, chung lee with sensors have anyone the software ? it is not for comercial use please help emergency story!
Leave a Reply
You are commenting using your account. Log Out / Change )
Twitter picture
Facebook photo
Google+ photo
Connecting to %s
|
#pragma once
#include <vector>
#include <istream>
#include "main/graphicsEditor.hpp"
#include "Interfaces/Window.hpp"
#include "ColorInput.hpp"
#include "ChoosenColor.hpp"
#include "TextInput.hpp"
class Palette : public Window {
private:
std::vector<ColorInput *> colors;
std::vector<TextInput *> textInputs;
ChoosenColor* m_choosenColor;
public:
Palette(int,int,int,int,const style_s *);
~Palette();
bool clicked(SDL_Event *) override;
bool hovered(SDL_Event *) override;
void draw(SDL_Surface *) override;
void addColorInput(int,int,int,int,const style_s *,Uint32,char *,ComponentName);
void addTextInput(int,int,int,int,const style_s *,char *,std::string,ComponentName);
void setChoosenColor(int,int,int,int,const style_s *,Uint32,char *,ComponentName);
ChoosenColor * getChoosenColor();
TextInput * getTextInput(size_t index);
};
|
Wednesday, October 26, 2011
critical responses to art
Last week in Interpretations class we read an article by two museum educators Danielle Rice and Philip Yenawine. Both are very well know in the field, yet have very different ways they teach art. I was very interested in Yenawine's technique to teach through critical response. Critical thinking is something that most schools are not incorporating into their lessons today because testing has taken over as the all-important aspect of public education (this is the conclusion we came to in class with the help of former and current public school teachers taking the class). That being said I think that art education is such a great way to incorporate critical thinking into academics.
Yenawine works with young children and asks them to say what they think about a work of art, what they see, tell a story, what does it mean. He asks questions and allows them to think critically about a work, but never intervenes. This got me thinking, is it responsible for an educator to allow someone to create their own interpretation of the art even if it is completely incorrect? While I think his ideas of critical thinking in education are amazing, I'm really not sure if that is the only way to do it. How can an educator allow a student to believe something completely incorrect about a work and not at least try to point them in the right direction? Coming from an art history background I believe that aspect is super important. While there may be several interpretations of what is going on in a work, wouldn't it be the responsibility of the educator to tell the student basic factual information in some way? or does this completely discourage critical thought if they find out they are wrong? This is really difficult stuff to think through!
1 comment:
1. i've always believed that an individual viewer's interpretation of a piece at any given moment is as valid as the 'correct' interpretation. for one thing, the experiences, perspectives, and ideas that the viewer brings will totally shape their view of an artwork, and each viewer's experience is totally unique. when you invalidate someone's reponse to an artwork, you push them away from wanting to engage with future works. bring them inot the conversation and let them have their own ideas, and we'll go from there. :)
|
When the world was still young, some 3 500 million years ago, molten rock forced its way through the earth's crust and solidified to form the spectacular granite outcrops where Pretoriuskop Rest Camp is now nestled. The impressive granite dome known as "Shabeni Hill" is not far from the camp, which is found in the south-western corner of the Kruger National Park. It is immediately apparent to any visitor that Pretoriuskop is unique as brilliant red trees adorn the camp, pre-dating the decision to make exclusive use of indigenous plants in laying out rest camp gardens. Nostalgia prompted an exception to the rule for Pretoriuskop, the Kruger National Park's oldest rest camp, and exotic flowering plants were allowed to stay, enhancing the strong sense of the past that is so pervasive.
Giving geographical context to places of interest in South Africa
|
Major Section: BREAK-REWRITE
Example: (brr@ :target) ; the term being rewritten (brr@ :unify-subst) ; the unifying substitutionwhere
General Form: (brr@ :symbol)
:symbolis one of the following keywords. Those marked with
*probably require an implementor's knowledge of the system to use effectively. They are supported but not well documented. More is said on this topic following the table.
:symbol (brr@ :symbol) ------- ---------------------In general
:target the term to be rewritten. This term is an instantiation of the left-hand side of the conclusion of the rewrite-rule being broken. This term is in translated form! Thus, if you are expecting (equal x nil) -- and your expectation is almost right -- you will see (equal x 'nil); similarly, instead of (cadr a) you will see (car (cdr a)). In translated forms, all constants are quoted (even nil, t, strings and numbers) and all macros are expanded.
:unify-subst the substitution that, when applied to :target, produces the left-hand side of the rule being broken. This substitution is an alist pairing variable symbols to translated (!) terms.
:wonp t or nil indicating whether the rune was successfully applied. (brr@ :wonp) returns nil if evaluated before :EVALing the rule.
:rewritten-rhs the result of successfully applying the rule or else nil if (brr@ :wonp) is nil. The result of successfully applying the rule is always a translated (!) term and is never nil.
:failure-reason some non-nil lisp object indicating why the rule was not applied or else nil. Before the rule is :EVALed, (brr@ :failure-reason) is nil. After :EVALing the rule, (brr@ :failure-reason) is nil if (brr@ :wonp) is t. Rather than document the various non-nil objects returned as the failure reason, we encourage you simply to evaluate (brr@ :failure-reason) in the contexts of interest. Alternatively, study the ACL2 function tilde-@- failure-reason-phrase.
:lemma * the rewrite rule being broken. For example, (access rewrite-rule (brr@ :lemma) :lhs) will return the left-hand side of the conclusion of the rule.
:type-alist * a display of the type-alist governing :target. Elements on the displayed list are of the form (term type), where term is a term and type describes information about term assumed to hold in the current context. The type-alist may be used to determine the current assumptions, e.g., whether A is a CONSP.
:ancestors * a stack of frames indicating the backchain history of the current context. The theorem prover is in the process of trying to establish each hypothesis in this stack. Thus, the negation of each hypothesis can be assumed false. Each frame also records the rules on behalf of which this backchaining is being done and the weight (function symbol count) of the hypothesis. All three items are involved in the heuristic for preventing infinite backchaining. Exception: Some frames are ``binding hypotheses'' (equal var term) or (equiv var (double-rewrite term)) that bind variable var to the result of rewriting term.
:gstack * the current goal stack. The gstack is maintained by rewrite and is the data structure printed as the current ``path.'' Thus, any information derivable from the :path brr command is derivable from gstack. For example, from gstack one might determine that the current term is the second hypothesis of a certain rewrite rule.
brr@-expressionsare used in break conditions, the expressions that determine whether interactive breaks occur when monitored runes are applied. See monitor. For example, you might want to break only those attempts in which one particular term is being rewritten or only those attempts in which the binding for the variable
ais known to be a
consp. Such conditions can be expressed using ACL2 system functions and the information provided by
brr@. Unfortunately, digging some of this information out of the internal data structures may be awkward or may, at least, require intimate knowledge of the system functions. But since conditional expressions may employ arbitrary functions and macros, we anticipate that a set of convenient primitives will gradually evolve within the ACL2 community. It is to encourage this evolution that
brr@provides access to the
|
Can a Game Help Low-Income Youth Get into College?: An Interview with Colleagology Games (Part One)
Today, the Collegeology Games project, a collaboration of the USC Rossier School of Education's Pullias Center for Higher Education and the USC School of Cinematic Arts' Game Innovation Lab, launched Mission: Admission, a Facebook game designed to help underserved students, often the first in their families to aspire to college, navigate the complicated process of applying for college and financial aid. (Full Disclosure: I am proud to be on the advisory board for the Colleageology Games Project.) The game's release comes as the application season opens for many American colleges and universities, including the University of Southern California.As described in the project's press release: "The game allows students to virtually experience the demands of the college application process and empowers them with the skills and knowledge they need to apply, get into and pay for college. Students guide their avatars through the process of meeting with college advisors, choosing the types of schools to apply to (including four-year, community and technical colleges), scheduling community service and sports activities, applying for scholarships and financial aid and requesting recommendation letters." The game is seen as a crisis intervention: cutbacks in budgets for education mean fewer and fewer high school students have access to college counselors -- the average ratio nation-wide stands at 459 students per conselor, and California's ration is 800 to 1. This shortage most dramatically effects low-income students who are more likely to be the first in their family to attend an institution of higher learning and thus lack the social capital in their immediate surroundings to help them make up for lack of help through their schools. By contrast, middle and upper-class parents are spending more and more money, helping their sons and daughters through SAT prep classes or getting special coaching to increase their chances of getting into the school of their choice.
Colleageology Games knows that games, in and of themselves, can not make up for these gross inequalities of access to information and mentorship, but the group does believe that spending time with the game can expose young players to core vocabulary and processes, help them think through issues of time management, and otherwise, get some of the foundations of the application process. They have found that those students who play the game more than once get a chance to improve on their performance and further rehearse these skills.
In honor of the game's launch, I asked Tracy Fullerton from USC's Game Innovation Lab and Zoe Corwin from the Pullias Center for Higher Education to talk about some of the research which went into this project.
Can you tell us something about the problems confronting low-income Americans as they think about preparing to apply for college? Have those issues grown better or worse in recent years? Why?
ZBC: Apart from an uneven playing field in the caliber of academic instruction afforded to students across schools, perhaps the most glaring problem in public high school education is access to high quality college guidance and support. The private college counseling industry – where parents pay top dollar for professionals to guide their children through the college application process – is a multi-million dollar industry. Students who can afford private college counseling services often attend schools with dedicated college counseling services and teachers who promote college readiness. Students from low-income communities are much more likely to attend schools with exorbitant guidance counselor ratios and limited college counseling resources.
This year, many of the low-income schools we work with in Los Angeles have had to cut college counseling positions due to budget cuts. As a consequence, low-income students with college aspirations are slipping through the cracks because they do not have anyone to assist them in filling out college and financial aid applications.
Bottom line: they don’t apply or they do apply but fail to fill out financial aid documents and housing applications and don’t enroll. College counselors serve as critical on-site champions for encouraging college aspirations and providing college-related support to students AND teacher advocates.
Why do you believe that games might provide an effect channel to help young people develop a deeper understand of the processes surrounding college application and financing?
TF: Games provide a safe space for exploring difficult to navigate systems – and the college application process is certainly a difficult to navigate system, especially the first time around, and given the importance of decisions made during this process it seems clear that giving students a way to gain experience with this system without having the weight of real world consequences on them can help them develop confidence and understanding of the strategies they’ll need to employ when they go through the process for real.
Tell us something about the process you use in developing these games. How have you sought feedback from the young people who will ultimately be most impacted by your project? What did you learn through this process about their understanding of college readiness? Do low income youth see college as a game they have any realistic chance of winning?
TF: In developing all of our games we reach out to players in our target group to help develop the game concepts and make sure they are addressing not only the needs of that group but also the sensibilities. For Application Crunch and Mission: Admission, this group consisted of high school students.
For both games, we created “junior design teams” – groups of about 15 students drawn from local high schools, who fit our target demographic. The students came to the Game Innovation Lab after school to learn about game design, and we learned about their hopes and concerns surrounding the college going process. We asked them to design games about the college application process and from those games, took away the kinds things that they want and need to understand about the process.
Some of the key things we learned from them is that they are concerned about time management – knowing where best to put their efforts in school. Also, they have fears about being able to afford college and a very limited understanding of their financial options.
Just making kids understand how important it is to fill out the FAFSA (Free Application for Federal Student Aid) is a key victory. It is one of the opportunities that is in both games, and we find that after playing once, the kids remind each other when they play again: “don’t forget to turn in your FAFSA!”
Your first game, Application Crunch, was a card game. Can you tell us something about the game’s mechanics and what it teaches its players?
TF: The first game was originally intended as a prototype for the digital game. We found that it played very well on its own, and that it served as an excellent intervention in places where computer access might be an issue. So, we developed the card game as a stand-alone product that is now available on Amazon and though our website.
The game is for 3-4 players who each take on the role of a college applicant. These roles are drawn randomly and range from the “Super Jock” to the “Misunderstood Artist.” Each character also has a family financial background that will affect their ability to pay for college.
The game centers on a set of deadlines that advance each round; these deadlines are for various colleges, scholarships and other opportunities. Players need to manage their time (in the form of actions) wisely to make sure their characters have “leveled up” in academics, extracurricular activities, and service to stand out when they apply to these deadlines.
The cards all have a kind of snarky tone to them that we picked up from the student design team. They know that this is serious information, but that doesn’t mean you can’t have fun with it.
One of the best features of this version of the game is the social play. Students tend to help each other with their strategies as they play, and even though there is a “winner” in the end, everyone who gets into school and can pay for it feels like they succeeded in the game. That kind of open discussion about how best to focus your time, to develop your character, it is a thinly veiled discussion about real world issues that the players are facing as they look to apply to college themselves.
You’ve found that students learn more when they play the game a second time. Why?
TF: If you think about your own experience in life, you probably look back and wish you’d done things a bit differently when you applied to college. Well, playing Application Crunch a second time is a lot like that. You take your learning from the first play through and apply it to the second.
In a sense, this is the entire point of developing a game like this: so that “playing” the admissions game the first time around in real life isn’t your first experience with it.
We find that the players come to their second game with confidence, a sense of what to expect in the deadlines they will face, the knowledge that things like FAFSA are out there, along with scholarships and other forms of financial aid. They know that they can set high aspirations for their characters—as long as they have safety schools. They understand the value of focusing deeply on one or two activities in school rather than spreading themselves thin, etc. In short, they feel a sense of ownership in their strategies about the application process. That knowledge and confidence raises their sense of efficacy around the real world process as well.
ZBC: When observing students play, I’ve been struck by their concentration when learning the rules the first time they play. They tend to collaborate throughout the whole play session and remain engaged for the duration of game play.
The second time they play I’ve noticed a trend. Usually they haven’t seen the game for a few weeks and when they enter the room, they voice enthusiasm about getting to play again. Then they start with upbeat banter: “I’m going to get into a Liberal Arts college this time!” Almost immediately they deal the cards and set up the game table.
Second time play is faster, more animated and a bit more competitive. After playing, students can articulate how their strategy changed from the first time and what they plan to do differently the next time they play.
As a researcher with the Pullias Center for Higher Education, Dr. Zoe Corwin has conducted research on college preparation programs and access to financial aid for underserved students, college pathways for foster youth, and the role of social media and games on postsecondary access and completion. She is co-editor of Preparing for College: Nine elements of effective outreach with SUNY Press and in addition to academic articles, has published several monographs designed for practitioners outlining effective college preparation strategies. Dr. Corwin is currently involved with the Collegeology Games project, collaborating with game designers to capitalize on game-based strategies and social media to engage students in college preparation, college application and financial aid processes.
Tracy Fullerton, M.F.A., is an experimental game designer, professor and director of the Game Innovation Lab at the USC School of Cinematic Arts where she holds the Electronic Arts Endowed Chair in Interactive Entertainment. The USC Game Innovation Lab is a design research center that has produced several of the most influential projects to be released in the emerging field of independent games, including games like Cloud, flOw, Darfur is Dying, The Misadventures of P.B. Winterbottom, and The Night Journey -- a collaboration with media artist Bill Viola. Tracy is also the author of “Game Design Workshop: A Playcentric Approach to Creating Innovative Games,” a design textbook in use at game programs worldwide. Prior to entering academia, she was a professional game designer and entrepreneur making games for companies including Microsoft, Sony, MTV, among many others.
|
Friday, April 27, 2012
Innovators aren't cynics
I was talking with a potential client who seemed cynical about innovation. In fact, most of our clients are both equally cynical and hopeful about innovation. They are cynical because innovation has often failed to deliver extravagant promises, and hopeful because innovation is one of the few tools that firms have to grow, to differentiate and to disrupt.
People are cynical about innovation because innovation often hasn't delivered what has been promised. But looking more closely at the reasons why uncovers some basic truths. One, many promises have been overstated, by people with a vested interest in promoting innovation. Yes, even us innovation consultants can get carried away, but often executives turn to innovation and make promises. Even politicians make promises about innovation. Yet those promises neglect some vital aspects. Often when executives or politicians promise great returns from innovation, they fail to support, fund, resource and sustain innovation. Blaming innovation for failing to deliver results when programs aren't adequately funded or resourced is like blaming your car for failing to start when you neglected to fill up.
Two, people are often cynical about innovation because they realize it is occasionally used as a scapegoat or "flavor of the month". Executives rush in, talk about innovation without intent to deploy anything, and then drop innovation to pick up another management credo to pronounce. Everyone realizes that innovation will be hard work, and everyone knows the differences between innovation as a talking point and innovation as a funded initiative supported by executives.
But there's a deeper point to made here about cynicism. We've learned, through books, through movies, through corporate examples, that business people lend a critical eye to everything. We business people are cynics by nature - looking for the challenge or failure in any product or service. Many businesses deliver products that HAVE to work - I want cynical engineers designing my bridges and airplanes. But cynicism is deadly to creative thinking and innovation.
Don't get me wrong - the best innovators, Jobs for example, are a masterful combination of wonder, empathy and cynicism. Wonder and empathy to imagine and create, cynicism to design, build and deliver. Edison, perhaps our first significant innovator, was devastated by the failure of his first invention, an automatic voting machine. He swore he would never again create a product that he didn't know if he could sell. But he obviously balanced his market cynicism with passion for experimentation and discovery. No cynic could attempt hundreds of experiments.
But what about the majority of us in business, in politics, in academia? We are notorious cynics, but we cannot afford to be. How many times have you said "I've seen this before" or "This didn't work the last time we tried it"? How many times have you turned a cynical eye on a new idea, not giving it the consideration it deserves? My favorite is "well, I've seen it all". No, sorry, you haven't. You can't possibly imagine all of the possibilities, and the disruption around the corner in your market will surprise and amaze you. Because someone with less cynicism and more wonder and optimism simply asked the question: why not?
Until you recognize that you haven't seen it all, that you can't even imagine all the opportunities, that cynicism is a set of blinders meant to keep you in line, you are definitely correct: you can't innovate. There is no more self-fulfilling prophecy than a cynic who boldly declares that he or she "can't innovate". They are exactly right, and self-reinforcing to boot. Get rid of your cynicism, approach innovation opportunities with a sense of wonder, enthusiasm, possibility. Yes, that means shedding your green eyeshades and corporate cynicism. Don't worry, we won't hold it against you.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 5:15 AM 1 comments
Wednesday, April 25, 2012
Getting Innovation Backwards
So I had lunch today with a friend who described another friend's innovation approach. It boiled down to "lets go generate a lot of ideas". The theory being that once they had a lot of ideas they'd find a valuable one that would be important and relevant. This approach always reminds me of the story of the little girl digging in the horse barn. Her father spots her and asks "why are you digging in that pile of horse manure?" (PG for mixed audiences). Her response? If there is all this manure here, there must be a pony in here too. Corporate innovators are often like the little girl, digging in a manure pile of ideas, convinced there's a pony there somewhere.
Far, far too many organizations, when given the chance to innovate, rush out to generate a bunch of ideas. There are several reasons they do this:
1. They are familiar with idea generation
2. It feels like they've accomplished something - a list of ideas
3. They now have a pile of stuff to wade through
4. They've been told that generating lots of ideas is important (and in context, it is)
5. Management wants to see ideas
What they are doing, basically, is generating ideas, searching for an answer. Which is exactly backwards. What they should do is identify an answer (significant opportunity or challenge) and then generate ideas (solutions).
But this seems counterproductive. Identifying answers - opportunities or challenges means taking time to research existing business challenges, prioritizing needs, understanding customer requirements. This doesn't seem like "innovation" and doesn't deliver quick ideas. So, after a month or two of following this path impatient management, not understanding the approach asks "where are the ideas?". So, far too many firms follow the first approach, since they think they understand the tools and know they need to deliver quickly.
But delivering poor, misaligned ideas quickly is just another way to deliver rapid failure. When your ideas aren't relevant or valuable, no matter how quickly you generate them, or if they fail to attract powerful sponsors or funding, who cares how quickly you generated them.
As with many things in life, received wisdom has it exactly backwards. Identifying the key challenges, understanding the links to strategic goals, deciphering customer needs leads to understanding the potential answer. Only then are you ready to generate ideas that matter. Or, as Einstein said "given an hour to solve a major problem I'd spend 55 minutes defining the problem and 5 minutes working on the solution". Once again, our approach is exactly backwards, which is why so many idea generation activities fail to deliver great solutions.
If you generate a lot of ideas without clear context or in answer to an important strategic question or need, you are simply shoveling the manure, looking for the pony that has already left the barn.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 5:03 AM 0 comments
Monday, April 23, 2012
The Wizard of Innovation
I've been thinking a lot about how the Wizard of Oz reflects so much about innovation. Not the story per se, but the setting and the characters and how they represent attributes or characteristics innovators must possess.
Take, for example, Dorothy's three key companions - the Scarecrow, the Cowardly Lion and the Tin Man. These three each personify a key trait that innovators must possess. The Scarecrow is looking for a brain. From an innovation perspective, we'll translate this as "insight" - the ability know what customer needs are unfolding and the willingness to learn new methods and approaches. The Cowardly Lion is looking for courage. Innovators must be courageous, to stand up to the challenges that they will face when trying to innovate, which bucks the business as usual mentality. The Tin Man was looking for a heart. Innovators need a big heart - a heart full of courage and commitment, but also a heart full of empathy. Anyone can dream up new ideas, but its only when you have empathy for the customer that you discover important needs. All of the characters who journey with Dorothy are capable of doing what they need to do, and discover their abilities in the journey. This is often true with innovators - people who don't think they are "creative" or who don't have the right status are often great innovators if they allow themselves to be.
Or, consider the Wizard, the man behind the curtain. The wizard is never presented until the very end, and is considered a very powerful force. When finally unmasked, he turns out to be much less powerful than he appeared. In the innovator's world, the Wizard correlates to the corporate culture. The culture is a seemingly powerful force, ephemeral but always present. But when a powerful innovator confronts a corporate culture with the right backing and the right ideas, the culture can be tamed.
Dorothy represents another facet of the innovator must possess - determination and focus. No matter what happens, Dorothy seeks to return home. She has a clear goal and pursues it regardless of the obstacles, regardless of the circumstances. She confronts all of these forces aligned against her, including the Wicked Witch, who personifies all of the nay-sayers, the status quoers, the let's leave well enough alone types. These people constantly confront an innovator, seeking to distract, delay and derail an innovation effort because they want to protect their products, their status or the existing status quo. No matter the obstacle, no matter how compelling Oz may seem, Dorothy stays true to her goals and convictions. So too must innovators have a clear goal and stay true to their convictions.
Innovators need bold ideas and clear thinking that come from an engaged brain, and bold actions and confidence, as well as empathy, that come from a big heart. They need courage to confront all that faces them in an existing business as usual culture. They need determination to face the faceless but seemingly powerful corporate culture and the slings and arrows thrown by the people who don't want change or are afraid of change.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 5:48 AM 1 comments
Tuesday, April 17, 2012
How to tell if you are an innovator
In a world of celebrity driven Twitter, "reality" shows and always on news, Andy Warhol was only partially right. We'll all be famous for 15 minutes. Unfortunately some people seem to get their 15 minutes over and over again for all the wrong reasons. Luckily for us, however, most innovators toil away from the spotlight. In fact many people who are innovators don't realize who and what they are.
Innovators are born and made. Innovators are people who have good ideas or sometimes just good insights. Innovators are people who aren't happy with the status quo, and are willing to do something about it. Herewith, seven factors that will tell you whether or not you are an innovator. Take the assessment, but know this: anyone can be an innovator. Read on and I'll tell you how.
1. Think a lot about the future. They wonder not about the next calamity, but what the future will be like and how they can impact the future. They wonder about emerging trends. They wonder what consumers will want next. Safety and security in today's world doesn't interest them. They are eager for what's next.
2. Aren't satisfied with the status quo. They are constantly trying to improve things - even things that don't seem to be broken. They want to know how to improve things, eliminate obstacles. As Shaw said, all progress is due to the unreasonable man, since reasonable people accept shortcomings.
3. Are empathetic. Innovators can get into other people's lives and shoes. They can virtually walk a mile in your moccasins. This doesn't necessarily mean they are "nice", just able to understand issues and challenges better than the average joe.
4. Are playful, in the best sense. By this I mean they are open to new experiences, are willing to test and prototype, and open to discovery.
5. Are stubborn and driven. If innovators don't have a stubborn streak, then their ideas won't progress, because many people will resist even good ideas initially. It's not easy advocating for a new idea. Innovators have to be committed to their ideas.
6. Are open to exchange of insights and ideas. While stubborn and driven, they understand that the best ideas are emergent and based on the kernal of good insights and ideas from a broad range of settings. They are willing to listen, to absorb and to incorporate inputs from a wide variety of sources.
7. Want to solve real problems. The difference between science fiction and innovation is that while innovators joke about jet backpacks, they want to solve real needs and offer real solutions. Some of those may be incremental in nature - the next product release and some may be disruptive - the next jet backpack. But only if the jet backpack solves a real, important, relevant need and is viable and adoptable.
So, how did you do? If the profile I've described feels right, you have all the proclivity to become an excellent innovator. Don't think you aren't creative enough or don't have enough time or energy. If this profile sounds like you, get moving. You are an innovator whether you like it or not.
If this doesn't sound like you, but you do want to innovate, the great news is this: nothing in this list can't be learned. These are a series of behaviors and perspectives that anyone can adopt. Stop telling yourself you aren't innovative. You weren't born with the gene, you build it from your experiences, interests and perspectives. Just exercise your attitude and become more open to the possibilities.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 9:01 AM 2 comments
Monday, April 16, 2012
Book Review: Beyond the Obvious
Over the years I've had a chance to interact with some really insightful innovators. I've been fortunate enough to meet and interact with individuals like Steve Shapiro, Paul Sloane, Paul Hobcraft, Alex Osterwalder and James Gardner. These individuals have all contributed to the pantheon of great innovation insights and writing. As have good friends and mentors like Tim Hurson, Gary Hamel and Peter Schwartz. The amount of material written on innovation is growing exponentially, but the amount of valuable material within that exponential growth is essentially flat.
That's why I was pleased to see Phil McKinney's new book, Beyond the Obvious, and have a chance to read it. McKinney, until recently, was the CTO for Hewlett-Packard and led a significant amount of innovation at H-P, and in roles prior to H-P. McKinney is unusual for a senior corporate executive, in that he has traditionally been very open with his thoughts, publishing a blog and a series of podcasts about innovation. So I looked forward to his book.
Beyond the Obvious, Killer questions that spark game-changing innovation, takes a new and unique approach to the challenges presented by innovation. Rather than present a specific methodology or toolset, McKinney starts at an almost philosophical position by asking questions. You have to like any management book that starts with a quote by Voltaire, rather than Drucker or Porter. Phil states early on that "the first step to freeing yourself to find innovations is to recognize that the knowledge you currently have is insufficient, and that you need to go out and discover new information that will lead you to new products or concepts". This is exceptionally important. Many organizations want to start from a position of certainty. They make statements rather than ask questions. Good innovators are naturally curious and willing to learn more. The best way to do this is to explore and ask questions. Yet asking questions is not in our corporate nature, unless we already know the answer.
Phil talks about challenging assumptions, getting beyond "business as usual". In Relentless Innovation I defined how powerful business as usual is, and what a barrier it can be to innovation activities. Phil describes business as usual as mental "handcuffs" that keep people locked into the way they've always worked. Questions break this cycle.
Phil also talks about "jolts" and weak signals - basically a way of talking about disruptions and spotting them by watching for trends. Jolts are disruptions but also opportunities for innovation.
In the final sections before diving more deeply into the killer questions he addresses the issue of corporate antibodies - those people and beliefs that stifle innovation. He addresses four kinds of corporate antibodies for innovation:
1. Ego
2. Fatigue (tried that before)
3. No risk ("no ROI", "no funds available")
4. Comfort ("don't rock the boat", "we've always done it this way")
These beliefs and innovation responses will be familiar to anyone who has attempted innovation.
In the next section of the book Phil defines his FIRE methodology: Focus, Ideation, Ranking and Execution. Basically a high level innovation methodology.
Focus is about making the right decisions - key questions: who (customer), what (product) and how (function). Phil argues too much emphasis is placed on customer and product, and not enough on function.
Ideation is about generating ideas based on key questions.
Ranking is, as its name suggests, ranking or prioritizing ideas, especially weeding out influence and bias
Execution described a gated funding system to advance good ideas while keeping costs and risks low.
Once the FIRE methodology is introduced, Phil shows how each step of the process is managed and governed by asking good questions. Who is your customer? What criteria do they use to select your product? Who is using it in unanticipated ways? What is your offering? and so forth. A lot of good questions to use to drive the ideation and ranking of your ideas.
Toward the end of the book Phil provides insights into how he runs innovation workshops and then provides a couple of very nice case studies where his Killer Questions approach has been used.
My Take:
Phil hits the nail on the head when he advocates approaching innovation from a discovery and questioning point of view. Far too often many firms attempt to start from certainty and move to certainty, rather than starting from questions and exploration. Phil's Killer Question approach is very helpful, using key questions and changing perspectives and assumptions. This is a methodology that can be used by individuals or by a large group.
Phil incorporates a lot of innovation best practice, including trend spotting and scenario planning, and even incorporates questions that begin to uncover customer needs that may be unclear or hidden. His advice on execution, using a gated funding model to keep costs and risks low, is in line with best practices.
There's much to take away from Killer Questions, especially the questions, but I think Phil's informal style is suitable only for people who are exceptionally skilled or confident in an innovation leadership role. I can easily see an innovation consultant leading a client through this process, or a very senior executive who buys into the questioning approach. There's not enough detail or definition to build an innovation capability or discipline based on what Phil has written. It would be difficult for a firm to adopt this model without strong facilitation, since there's little definition of the process.
Phil's Killer Questions and his questioning approach will definitely be adopted by many firms. I'll be incorporating some of his questions and his approach in our OVO innovation methodology. However, without a strong, confident innovation leader who can encourage people to question their assumptions and work within this approach, it may be difficult for some firms to replicate Phil's success.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 7:38 AM 0 comments
Friday, April 13, 2012
Looking to the past for ideas
Satchel Paige has been quoted as saying "never look back, someone may be gaining on you", but I think it's our natural proclivity to "look back". Looking back to our past is a way of reviewing and learning from our successes and mistakes. Further, history is concrete. We know what happened in the past, while everything that will happen, or could happen, in the future is still a mystery.
For another famous quote, Spinoza (or others, depending on your source) is attributed with "those who cannot learn from history are doomed to repeat it". I think that sentiment is true where human nature is concerned. We humans repeat the same mistakes in politics, in government and in personal affairs, often just in larger settings and with more significant consequences. Just as the Spanish Civil War was clearly a precursor and training ground for World War II, so to the Algerian war was to Viet Nam and eventually even into Afghanistan. And, as any historian can tell you, everyone who went into Afghanistan regretted it and left in less than noble terms. But does careful study of the past tell us about need for innovation in the future?
The question for executives and managers is: should I study the past, which is fixed and relatively unmoving, concrete and known for ideas? Or should I attempt to ascertain the future to find new ideas? Both approaches are full of promise and fraught with uncertainty.
Studying the past provides far greater clarity. We may not always understand the reasons WHY something happened, but we know WHAT happened. In our modern management circles, clarity of purpose often trumps insights about opportunities that are unclear. The problem with studying the past is that while ideas may be prevalent, and some even unexplored, the past is for the most part an open book. All the insights that may be there are available to anyone, so your insights had better be good, and further, you'd better be able to deploy new products or services based on insights gleaned from the past very quickly.
Studying the future is quite the opposite. There is no certainty or clarity once we look beyond a year or two, and, with the pace of change accelerating, attempting to forecast needs and wants five to ten years into the future is highly uncertain. We don't know the WHO or the WHAT or the WHY of future needs. But with careful thinking, aggregating weak signals into trends and excellent synthesis, we can begin to define more definitive patterns and shapes about the future, which can signal new needs and opportunities. These will NOT be definitive, so clarity and certainty won't be served, but those who are willing to risk the investments based on their careful studies will be rewarded.
In business, our first approach is always to look to history. Have we faced this issue before? Have we had a problem or initiative like this before? Can we relate this to something we've done in the past? The goal is to find existing patterns, reduce the problem to something in alignment with known approaches and move ahead. But many times historical patterns or knowledge aren't helpful or aren't in synch with future needs. We often don't have as much comfort looking to the future and finding solutions and alternatives as we do finding corollaries for problems in the past.
The choice, to me, is obvious. Far too often our teams are too comfortable looking to the past for answers, seeking clear and concrete needs in a past that is an open book, rather than looking ahead, harnessing the information that's available and making judgements based on the signals that are available. Not only are we doomed to repeat history, we are doomed to do so lacking knowledge, services and products that would have made life better if only we were willing to understand that most good ideas lie in the future, not the past.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 12:26 PM 0 comments
Monday, April 09, 2012
Innovation attitudes and success
Well, I'm back and feeling chipper after a nice trip to Istanbul to meet a potential partner and a week in Spain on R&R. After some relaxing days and digging out of email, it occurred to me that many of Stephen Covey's principles apply to innovation. Sharpening the saw equates to building skills through training. Important versus urgent defines innovation versus the day to day demands of business. But the one I want to focus on today is: start with the end in mind.
You see, there are three starting "attitudes" that define how companies begin an innovation effort. They are, in no particular order, fear, uncertainty and confidence. Where your team starts, matters. Because you need to start an innovation project with the end in mind.
Let's start with fear, which is where most innovation efforts begin. I'll call it "fear" since at least half of all innovation projects are started based on fear - the fear of falling behind a competitor, and are worked in fear - fear of failure, fear of new tools, fear of disrupting the status quo. In fact fear is probably the most prevalent of all attitudes when innovation is active. If fear is the starting point and fear is the dominant attitude during the effort, what's the likely result? Ideas that closely resemble the existing product portfolio, that don't ruffle feathers or cause any consternation. Fear is a limiting emotion, causing people who encounter fear to play it safe, or, often even worse, to become reckless. If you start from a position of fear, and fear overhangs your effort, innovation simply can't be successful.
Next is "uncertainty". Many firms start from a position or attitude of uncertainty. They are uncertain if innovation is necessary, uncertain about the tools and methods and uncertain about the best outcomes. When nothing is left to chance and everything is certain in business, only innovation is uncertain. Therefore, innovation is the outlier and by definition it is a variance to be eliminated rather than a path to be pursued. When you start in uncertainty and all tools, methods and outcomes are uncertain, your end result will be the same. Or, to quote another saying, when you don't know where you are going, any road can take you there. Uncertainty isn't necessarily limiting, it just creates confusion and aimlessness.
The final attitude is confidence. Firms with strong leadership, cultures that welcome innovation and people who have innovation skills start their innovation efforts confident of success, and are confident in their abilities to accelerate good ideas to market. Confidence is contagious and sweeps more people into its fold. It's almost unfair, actually, that confident innovators are gaining skills and capabilities at an ever increasing pace, while uncertain or fearful innovators are losing share, losing ground and falling further behind, which of course creates more uncertainty and more fear. Fear and uncertainty can create vicious cycles, while confidence creates a virtuous cycle.
What's really interesting is that most people understand this innately, even if they don't communicate it. Companies and teams that start with fear as a basis for innovation, or with uncertainty as the basis will almost always be unhappy with the results, regardless of the approach, regardless of the methodology or tool or software application, while firms that start in confidence will usually succeed regardless of the method, tool or approach. What gets in the way of confidence?
Not enough skills, not enough commitment, not enough simple belief that innovation can make a difference. It's the difference between "I'll believe it when I see it" or "I'll see it when I believe it". There's no magic to innovation. What's necessary is a set of skills, a clear goal, a commitment to working through a process and the ability to commercialize good ideas quickly. If your company has these characteristics and strong leadership to back it up, you can innovate from a position of confidence. Lacking these traits means you'll start from a position of fear or uncertainty, and will struggle to develop ideas that are valuable and meaningful.
Start with the end in mind. If you plan to be successful with an innovation effort, start confident in your goals, confident in your skills and confident that the systems and decision making processes will support you, or work to make them so. Otherwise, innovation is simply too difficult to do from a position of fear or uncertainty that you will struggle to succeed when starting from these attitudes.
AddThis Social Bookmark Button
posted by Jeffrey Phillips at 12:46 PM 0 comments
|
Hibiscus rosa-sinensis 'The Path'
Chinese Hibiscus, Tropical Hibiscus
Among the showiest flowering plants. Plants typically bear funnel-shaped blossoms, often with prominent stamens. The many species offer a wide range of flower colors.
Probably from tropical Asia; tropical hibiscus has been in cultivation for centuries, and is among the most flamboyant flowering shrubs. It reaches 30 ft. tall and 15 to 20 ft. wide in Hawaii, but more typical size on mainland is 8 to 15 ft. tall, 5 to 8 ft. wide. Glossy leaves vary somewhat in size and texture depending on variety. Growth habit may be dense and dwarfish or loose and open. Summer flowers are single or double, 4 to 8 in. wide. Colors range from white through pink to red, from yellow and apricot to orange. Individual flowers last only a day, but the plant blooms continuously.
Provide overhead protection where winter lows frequently drop below 30°F/-1°C. Where temperatures go much lower, grow in containers and shelter indoors over winter; or treat as annual, setting out fresh plants each spring. Hibiscus also makes a good houseplant.
This shrub requires excellent drainage; if necessary, improve soil for best drainage or set plants in raised beds or containers. Can be used as screen, espalier, or specimen. To develop good branch structure, prune poorly shaped young plants when you set them out in spring. To keep a mature plant growing vigorously, prune out about a third of old wood in early spring. Pinching out tips of stems in spring and summer increases flower production.All varieties susceptible to aphids. There are thousands of selections.'The Path'
Gorgeous, ruffled, single, buttercup yellow flowers with a bright pink center on a bushy, upright shrub that grows 6–8 ft. tall, 4–5 ft. wide.
Large, frilly, single, bright orange flowers with white central eye edged in red. Strong-growing, erec...
Double golden flowers with petals that shade to carmine orange toward base. Plant is bushy and upright...
This 6–8 ft.-tall variety has big, single, soft pink flowers.
|
/*
* Copyright (c) 2011 Daisuke Okanohara
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above Copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above Copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*/
#ifndef REDSVD_UTIL_HPP__
#define REDSVD_UTIL_HPP__
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <vector>
#include "Eigen/Sparse"
#include "Eigen/Dense"
#include "Eigen/Eigenvalues"
namespace REDSVD {
typedef Eigen::SparseMatrix<float, Eigen::RowMajor> SMatrixXf;
typedef std::vector<std::pair<int, float> > fv_t;
class Util{
public:
static void convertFV2Mat(const std::vector<fv_t>& fvs, SMatrixXf& A);
static void sampleGaussianMat(Eigen::MatrixXf& x);
static void processGramSchmidt(Eigen::MatrixXf& mat);
static double getSec();
private:
static void sampleTwoGaussian(float& f1, float& f2);
};
}
#endif // REDSVD_UTIL_HPP_
|
#include "SDL_Timer.h"
#include "simple_logger.h"
#include "spikes.h"
#include "entity.h"
int p = 0;
void deathball_think(Entity* self);
void deathball_ontouch(Entity* self, Entity* other);
Entity* deathball_new(Vector3D position)
{
Entity* ent = NULL;
ent = entity_new();
if (!ent)
{
slog("UGH OHHHH, no player for you!");
return NULL;
}
ent->model = gf3d_model_load("cube");
ent->scale = vector3d(0.1, 0.1, 0.1);
ent->position = position;
ent->touch = deathball_ontouch;
ent->think = deathball_think;
gfc_matrix_scale(ent->modelMat, ent->scale);
ent->radius = 0.05;
return ent;
}
void deathball_think(Entity* self) {
{
switch (p) {
case 0:
if (self->position.x > .9) {
p = 1;
break;
}
self->position.x += .01;
break;
case 1:
if (self->position.x < -.9) {
p = 0;
break;
}
self->position.x -= .01;
break;
}
}
}
void deathball_ontouch(Entity* self, Entity* other) {
other->health -= 1;
slog("healthy");
}
|
#pragma once
#include <string>
#include <vector>
namespace common
{
class CmdLineArgs
{
public:
CmdLineArgs(std::vector<std::string> const & arguments);
bool shouldForceWindowedMode() const { return forceWindowedMode; };
bool shouldUseDebugMode() const { return debugMode; };
std::string modificationName() const;
private:
void parseArguments(std::vector<std::string> const & arguments);
std::string parseStringParameter(std::vector<std::string> const & arguments, unsigned & i) const;
private:
static std::string const defaultModification;
bool forceWindowedMode;
bool debugMode;
std::string customModification;
};
} // namespace common
|
Power walking has several advantages. First of all, it is probably the safest form of sport available and can be practiced by anyone, anywhere, at any time, without the need for a complex equipment, only a training suit and some sports shoes. It can be incorporated into any program, even if you work a lot of hours a day or not, even if you have done sports or not, even if you are young or old, it is safe even for people with various diseases and pregnant women after a medical check , of course. It is a form of movement that, unlike running, has a very low impact on the joints, protects the knees and especially does not expose the heart to a great deal of stress.
For power walking to have an effect, the training regime must be serious. Do not confuse the stroll through the shops or even the leisure walks for a sport. Ala is not sports, it’s relaxation. Sessions of about 40 minutes a day of fast walking are recommended, sessions that are not interrupted by anything (frequent stops, obstacles, intersections, etc.). It’s a great workout for those who want to lose weight because it involves a lower heart rate, somewhere in the “fat burn” zone, roughly between 60-70 percent of the heart’s capacity. In this zone the body will burn predominantly adipose tissue and very little muscle (what we want when we want to lose weight). And if you ask why we do not want to burn muscle and ideas like “but I do not want to be muscular” pop in your head, I will briefly say two things: 1. Muscles are the ones that maintain a high metabolism, meaning high calorie burns, that is, burning the cheescake you ate faster. 2. It is difficult to gain muscles! Extremely, especially as we women do not have testosterone. But about this more details in another post.
The idea is to maintain a constant speed and to have a relevant indicator, it is very simple to look after the limit between walking and running. That is, to go fast enough to be at the point where you would normally start running. The longer you keep the pace constant, the better (that is, the more fat we burn). I suppose it makes no sense to explain how important it is to properly hydrate and to have a proper nutrition. After training, the body will release endorphins and you will feel much better. It would be good for the training to be completed with a 5-10 minutes of stretching, which plays a vital role in preventing injuries and a good muscle development.
Such a training helps you to get into shape, especially if you have been sedentary or have not practiced sports for a long time and burn more calories than jogging would, making it harder to walk at a faster speed, than running at a lower speed.
Think that this type of training is being practiced by bodybuilders, at the end of the weight training, somewhere around 20-30 minutes, to burn the last traces of fat on the muscles. If you try this kind of training, let me know! And of course, any questions you have, I’m here!
Go, go, go!
Your Internet Best friend
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2009 Greenplum, Inc.
//
// @filename:
// CExpressionTest.cpp
//
// @doc:
// Test for CExpression
//---------------------------------------------------------------------------
#include "unittest/gpopt/operators/CExpressionTest.h"
#include "gpos/error/CAutoTrace.h"
#include "gpos/io/COstreamString.h"
#include "gpos/string/CWStringDynamic.h"
#include "gpopt/base/CCTEReq.h"
#include "gpopt/base/CDrvdPropCtxtPlan.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/engine/CEngine.h"
#include "gpopt/eval/CConstExprEvaluatorDefault.h"
#include "gpopt/mdcache/CAutoMDAccessor.h"
#include "gpopt/metadata/CIndexDescriptor.h"
#include "gpopt/operators/CLogicalBitmapTableGet.h"
#include "gpopt/operators/CLogicalDynamicGetBase.h"
#include "gpopt/operators/CLogicalInnerJoin.h"
#include "gpopt/operators/CLogicalLeftAntiSemiJoin.h"
#include "gpopt/operators/CLogicalLeftAntiSemiJoinNotIn.h"
#include "gpopt/operators/CLogicalLeftOuterJoin.h"
#include "gpopt/operators/CLogicalLeftSemiJoin.h"
#include "gpopt/operators/CLogicalUnion.h"
#include "gpopt/operators/CScalarBitmapBoolOp.h"
#include "gpopt/operators/CScalarBitmapIndexProbe.h"
#include "naucrates/base/CDatumInt8GPDB.h"
#include "naucrates/md/CMDIdGPDB.h"
#include "naucrates/md/IMDScalarOp.h"
#include "unittest/base.h"
#include "unittest/gpopt/CTestUtils.h"
using namespace gpos;
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest
//
// @doc:
// Create required properties which are empty, except for required column set, given by 'pcrs'.
// Caller takes ownership of returned pointer.
//
//---------------------------------------------------------------------------
CReqdPropPlan *
CExpressionTest::PrppCreateRequiredProperties(CMemoryPool *mp, CColRefSet *pcrs)
{
COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp);
CDistributionSpec *pds = GPOS_NEW(mp)
CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster);
CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec(
CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion);
CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy);
CEnfdDistribution *ped =
GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmSatisfy);
CEnfdRewindability *per =
GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy);
CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp);
return GPOS_NEW(mp) CReqdPropPlan(pcrs, peo, ped, per, pcter);
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest
//
// @doc:
// Creates a logical GroupBy and a Get as its child. The columns in the
// Get follow the format wszColNameFormat.
// Caller takes ownership of returned pointer.
//
//---------------------------------------------------------------------------
CExpression *
CExpressionTest::PexprCreateGbyWithColumnFormat(CMemoryPool *mp,
const WCHAR *wszColNameFormat)
{
CWStringConst strRelName(GPOS_WSZ_LIT("Rel1"));
CMDIdGPDB *rel_mdid = GPOS_NEW(mp) CMDIdGPDB(GPOPT_TEST_REL_OID1, 1, 1);
CTableDescriptor *ptabdesc = CTestUtils::PtabdescPlainWithColNameFormat(
mp, 3, rel_mdid, wszColNameFormat, CName(&strRelName), false);
CWStringConst strRelAlias(GPOS_WSZ_LIT("Rel1"));
CExpression *pexprGet =
CTestUtils::PexprLogicalGet(mp, ptabdesc, &strRelAlias);
return CTestUtils::PexprLogicalGbAggWithInput(mp, pexprGet);
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest
//
// @doc:
// Unittest for expressions
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest()
{
CUnittest rgut[] = {
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_SimpleOps),
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_Union),
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_BitmapGet),
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_Const),
#ifdef GPOS_DEBUG
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_ComparisonTypes),
#endif // GPOS_DEBUG
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_FValidPlan),
GPOS_UNITTEST_FUNC(
CExpressionTest::EresUnittest_FValidPlan_InvalidOrder),
GPOS_UNITTEST_FUNC(
CExpressionTest::EresUnittest_FValidPlan_InvalidDistribution),
GPOS_UNITTEST_FUNC(
CExpressionTest::EresUnittest_FValidPlan_InvalidRewindability),
GPOS_UNITTEST_FUNC(
CExpressionTest::EresUnittest_FValidPlan_InvalidCTEs),
#ifdef GPOS_DEBUG
GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_FValidPlanError),
#endif // GPOS_DEBUG
GPOS_UNITTEST_FUNC(EresUnittest_ReqdCols),
#ifdef GPOS_DEBUG
GPOS_UNITTEST_FUNC_ASSERT(CExpressionTest::EresUnittest_InvalidSetOp),
#endif // GPOS_DEBUG
};
return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_SimpleOps
//
// @doc:
// Basic tree builder test
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_SimpleOps()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
typedef CExpression *(*Pfpexpr)(CMemoryPool *);
Pfpexpr rgpf[] = {
CTestUtils::PexprLogicalGet,
CTestUtils::PexprLogicalExternalGet,
CTestUtils::PexprLogicalGetPartitioned,
CTestUtils::PexprLogicalSelect,
CTestUtils::PexprLogicalSelectCmpToConst,
CTestUtils::PexprLogicalSelectArrayCmp,
CTestUtils::PexprLogicalSelectPartitioned,
CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>,
CTestUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>,
CTestUtils::PexprLogicalJoin<CLogicalLeftSemiJoin>,
CTestUtils::PexprLogicalJoin<CLogicalLeftAntiSemiJoin>,
CTestUtils::PexprLogicalJoin<CLogicalLeftAntiSemiJoinNotIn>,
CTestUtils::PexprLogicalGbAgg,
CTestUtils::PexprLogicalGbAggOverJoin,
CTestUtils::PexprLogicalGbAggWithSum,
CTestUtils::PexprLogicalLimit,
CTestUtils::PexprLogicalNAryJoin,
CTestUtils::PexprLogicalProject,
CTestUtils::PexprConstTableGet5,
CTestUtils::PexprLogicalDynamicGet,
CTestUtils::PexprLogicalSequence,
CTestUtils::PexprLogicalTVFTwoArgs,
CTestUtils::PexprLogicalAssert,
PexprComplexJoinTree};
#ifdef GPOS_DEBUG
// misestimation risk for the roots of the plans in rgpf
ULONG rgulRisk[] = {1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 6};
#endif // GPOS_DEBUG
for (ULONG i = 0; i < GPOS_ARRAY_SIZE(rgpf); i++)
{
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
// generate simple expression
CExpression *pexpr = rgpf[i](mp);
CLogicalGet *popGet = dynamic_cast<CLogicalGet *>(pexpr->Pop());
CLogicalDynamicGetBase *popDynGet =
dynamic_cast<CLogicalDynamicGetBase *>(pexpr->Pop());
CColRefArray *colrefs = nullptr;
if (nullptr != popGet)
{
colrefs = popGet->PdrgpcrOutput();
}
else if (nullptr != popDynGet)
{
colrefs = popDynGet->PdrgpcrOutput();
}
if (nullptr != colrefs)
{
for (ULONG ul = 0; ul < colrefs->Size(); ul++)
{
(*colrefs)[ul]->MarkAsUsed();
}
}
// self-match
GPOS_ASSERT(pexpr->FMatchDebug(pexpr));
// debug print
CWStringDynamic str(mp, GPOS_WSZ_LIT("\n"));
COstreamString oss(&str);
oss << "EXPR:" << std::endl << *pexpr << std::endl;
GPOS_TRACE(str.GetBuffer());
str.Reset();
#ifdef GPOS_DEBUG
oss << std::endl << "DERIVED PROPS:" << std::endl;
GPOS_TRACE(str.GetBuffer());
str.Reset();
pexpr->DbgPrint();
// copy expression
CColRef *pcrOld = pexpr->DeriveOutputColumns()->PcrAny();
CColRef *new_colref =
COptCtxt::PoctxtFromTLS()->Pcf()->PcrCreate(pcrOld);
UlongToColRefMap *colref_mapping = GPOS_NEW(mp) UlongToColRefMap(mp);
BOOL result = colref_mapping->Insert(GPOS_NEW(mp) ULONG(pcrOld->Id()),
new_colref);
GPOS_ASSERT(result);
CExpression *pexprCopy = pexpr->PexprCopyWithRemappedColumns(
mp, colref_mapping, true /*must_exist*/);
colref_mapping->Release();
oss << std::endl
<< "COPIED EXPRESSION (AFTER MAPPING " << *pcrOld << " TO "
<< *new_colref << "):" << std::endl;
GPOS_TRACE(str.GetBuffer());
str.Reset();
pexprCopy->DbgPrint();
pexprCopy->Release();
// derive stats on expression
CReqdPropRelational *prprel =
GPOS_NEW(mp) CReqdPropRelational(GPOS_NEW(mp) CColRefSet(mp));
IStatisticsArray *stats_ctxt = GPOS_NEW(mp) IStatisticsArray(mp);
IStatistics *stats = pexpr->PstatsDerive(prprel, stats_ctxt);
GPOS_ASSERT(nullptr != stats);
oss << "Expected risk: " << rgulRisk[i] << std::endl;
oss << std::endl << "STATS:" << *stats << std::endl;
GPOS_TRACE(str.GetBuffer());
GPOS_ASSERT(rgulRisk[i] == stats->StatsEstimationRisk());
prprel->Release();
stats_ctxt->Release();
#endif // GPOS_DEBUG
// cleanup
pexpr->Release();
}
return GPOS_OK;
}
//---------------------------------------------------------------------------
// CExpressionTest::EresUnittest_Union
//
// @doc:
// Basic tree builder test w/ Unions
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_Union()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
// build union tree of depth 2
CExpression *pexpr = CTestUtils::PexprLogicalUnion(mp, 2);
// debug print
CWStringDynamic str(mp);
COstreamString oss(&str);
pexpr->OsPrint(oss);
GPOS_TRACE(str.GetBuffer());
// derive properties on expression
(void) pexpr->PdpDerive();
#ifdef GPOS_DEBUG
CReqdPropRelational *prprel =
GPOS_NEW(mp) CReqdPropRelational(GPOS_NEW(mp) CColRefSet(mp));
IStatisticsArray *stats_ctxt = GPOS_NEW(mp) IStatisticsArray(mp);
IStatistics *stats = pexpr->PstatsDerive(prprel, stats_ctxt);
GPOS_ASSERT(nullptr != stats);
// We expect a risk of 3 because every Union increments the risk.
GPOS_ASSERT(3 == stats->StatsEstimationRisk());
stats_ctxt->Release();
prprel->Release();
#endif // GPOS_DEBUG
// cleanup
pexpr->Release();
return GPOS_OK;
}
//---------------------------------------------------------------------------
// CExpressionTest::EresUnittest_BitmapScan
//
// @doc:
// Basic tree builder test with bitmap index and table get.
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_BitmapGet()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
CWStringConst strRelName(GPOS_WSZ_LIT("MyTable"));
CWStringConst strRelAlias(GPOS_WSZ_LIT("T"));
CMDIdGPDB *rel_mdid = GPOS_NEW(mp) CMDIdGPDB(GPOPT_MDCACHE_TEST_OID, 1, 1);
const WCHAR *wszColNameFormat = GPOS_WSZ_LIT("column_%04d");
CTableDescriptor *ptabdesc = CTestUtils::PtabdescPlainWithColNameFormat(
mp, 3, rel_mdid, wszColNameFormat, CName(&strRelName), false);
// get the index associated with the table
const IMDRelation *pmdrel = mda.RetrieveRel(ptabdesc->MDId());
GPOS_ASSERT(0 < pmdrel->IndexCount());
// create an index descriptor
IMDId *pmdidIndex = pmdrel->IndexMDidAt(0 /*pos*/);
const IMDIndex *pmdindex = mda.RetrieveIndex(pmdidIndex);
CColumnFactory *col_factory = COptCtxt::PoctxtFromTLS()->Pcf();
const ULONG num_cols = pmdrel->ColumnCount();
GPOS_ASSERT(2 < num_cols);
// create an index on the first column
const IMDColumn *pmdcol = pmdrel->GetMdCol(0);
const IMDType *pmdtype = mda.RetrieveType(pmdcol->MdidType());
CColRef *pcrFirst = col_factory->PcrCreate(pmdtype, pmdcol->TypeModifier());
CExpression *pexprIndexCond = CUtils::PexprScalarEqCmp(
mp, pcrFirst, CUtils::PexprScalarConstInt4(mp, 20 /*val*/));
CMDIdGPDB *mdid = GPOS_NEW(mp) CMDIdGPDB(CMDIdGPDB::m_mdid_unknown);
CIndexDescriptor *pindexdesc =
CIndexDescriptor::Pindexdesc(mp, ptabdesc, pmdindex);
CExpression *pexprBitmapIndex = GPOS_NEW(mp) CExpression(
mp, GPOS_NEW(mp) CScalarBitmapIndexProbe(mp, pindexdesc, mdid),
pexprIndexCond);
CColRefArray *pdrgpcrTable = GPOS_NEW(mp) CColRefArray(mp);
for (ULONG ul = 0; ul < num_cols; ++ul)
{
const IMDColumn *pmdcol = pmdrel->GetMdCol(ul);
const IMDType *pmdtype = mda.RetrieveType(pmdcol->MdidType());
CColRef *colref =
col_factory->PcrCreate(pmdtype, pmdcol->TypeModifier());
pdrgpcrTable->Append(colref);
}
CExpression *pexprTableCond = CUtils::PexprScalarEqCmp(
mp, pcrFirst, CUtils::PexprScalarConstInt4(mp, 20 /*val*/));
CExpression *pexprBitmapTableGet = GPOS_NEW(mp) CExpression(
mp,
GPOS_NEW(mp) CLogicalBitmapTableGet(
mp, ptabdesc,
gpos::ulong_max, // pgexprOrigin
GPOS_NEW(mp) CName(mp, CName(&strRelAlias)), pdrgpcrTable),
pexprTableCond, pexprBitmapIndex);
// debug print
CWStringDynamic str(mp);
COstreamString oss(&str);
pexprBitmapTableGet->OsPrint(oss);
CWStringConst strExpectedDebugPrint(GPOS_WSZ_LIT(
"+--CLogicalBitmapTableGet , Table Name: (\"MyTable\"), Columns: [\"ColRef_0001\" (1), \"ColRef_0002\" (2), \"ColRef_0003\" (3)]\n"
" |--CScalarCmp (=)\n"
" | |--CScalarIdent \"ColRef_0000\" (0)\n"
" | +--CScalarConst (20)\n"
" +--CScalarBitmapIndexProbe Bitmap Index Name: (\"T_a\")\n"
" +--CScalarCmp (=)\n"
" |--CScalarIdent \"ColRef_0000\" (0)\n"
" +--CScalarConst (20)\n"));
GPOS_ASSERT(str.Equals(&strExpectedDebugPrint));
// derive properties on expression
(void) pexprBitmapTableGet->PdpDerive();
// test matching of bitmap index probe expressions
CMDIdGPDB *pmdid2 = GPOS_NEW(mp) CMDIdGPDB(CMDIdGPDB::m_mdid_unknown);
CIndexDescriptor *pindexdesc2 =
CIndexDescriptor::Pindexdesc(mp, ptabdesc, pmdindex);
CExpression *pexprIndexCond2 = CUtils::PexprScalarEqCmp(
mp, pcrFirst, CUtils::PexprScalarConstInt4(mp, 20 /*val*/));
CExpression *pexprBitmapIndex2 = GPOS_NEW(mp) CExpression(
mp, GPOS_NEW(mp) CScalarBitmapIndexProbe(mp, pindexdesc2, pmdid2),
pexprIndexCond2);
CWStringDynamic strIndex2(mp);
COstreamString ossIndex2(&strIndex2);
pexprBitmapIndex2->OsPrint(ossIndex2);
CWStringConst strExpectedDebugPrintIndex2(GPOS_WSZ_LIT(
// clang-format off
"+--CScalarBitmapIndexProbe Bitmap Index Name: (\"T_a\")\n"
" +--CScalarCmp (=)\n"
" |--CScalarIdent \"ColRef_0000\" (0)\n"
" +--CScalarConst (20)\n"
// clang-format on
));
GPOS_ASSERT(strIndex2.Equals(&strExpectedDebugPrintIndex2));
GPOS_ASSERT(pexprBitmapIndex2->Matches(pexprBitmapIndex));
mdid->AddRef();
pexprBitmapIndex->AddRef();
pexprBitmapIndex2->AddRef();
CExpression *pexprBitmapBoolOp1 = GPOS_NEW(mp) CExpression(
mp,
GPOS_NEW(mp)
CScalarBitmapBoolOp(mp, CScalarBitmapBoolOp::EbitmapboolAnd, mdid),
pexprBitmapIndex, pexprBitmapIndex2);
mdid->AddRef();
pexprBitmapIndex->AddRef();
CExpression *pexprBitmapBoolOp2 = GPOS_NEW(mp) CExpression(
mp,
GPOS_NEW(mp)
CScalarBitmapBoolOp(mp, CScalarBitmapBoolOp::EbitmapboolAnd, mdid),
pexprBitmapIndex, pexprBitmapIndex2);
GPOS_ASSERT(pexprBitmapBoolOp2->Matches(pexprBitmapBoolOp1));
// cleanup
pexprBitmapBoolOp2->Release();
pexprBitmapBoolOp1->Release();
pexprBitmapTableGet->Release();
return GPOS_OK;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_Const
//
// @doc:
// Test of scalar constant expressions
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_Const()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
BOOL value = true;
CExpression *pexprTrue = CUtils::PexprScalarConstBool(mp, value);
value = false;
CExpression *pexprFalse = CUtils::PexprScalarConstBool(mp, value);
ULONG ulVal = 123456;
CExpression *pexprUl = CUtils::PexprScalarConstInt4(mp, ulVal);
CExpression *pexprUl2nd = CUtils::PexprScalarConstInt4(mp, ulVal);
ulVal = 1;
CExpression *pexprUlOne = CUtils::PexprScalarConstInt4(mp, ulVal);
CWStringDynamic str(mp);
COstreamString oss(&str);
oss << std::endl;
pexprTrue->OsPrint(oss);
pexprFalse->OsPrint(oss);
pexprUl->OsPrint(oss);
pexprUl2nd->OsPrint(oss);
pexprUlOne->OsPrint(oss);
#ifdef GPOS_DEBUG
CScalarConst *pscalarconstTrue = CScalarConst::PopConvert(pexprTrue->Pop());
CScalarConst *pscalarconstFalse =
CScalarConst::PopConvert(pexprFalse->Pop());
CScalarConst *pscalarconstUl = CScalarConst::PopConvert(pexprUl->Pop());
CScalarConst *pscalarconstUl2nd =
CScalarConst::PopConvert(pexprUl2nd->Pop());
CScalarConst *pscalarconstUlOne =
CScalarConst::PopConvert(pexprUlOne->Pop());
#endif // GPOS_DEBUG
GPOS_ASSERT(pscalarconstUl->HashValue() == pscalarconstUl2nd->HashValue());
GPOS_ASSERT(!pscalarconstTrue->Matches(pscalarconstFalse));
GPOS_ASSERT(!pscalarconstTrue->Matches(pscalarconstUlOne));
pexprTrue->Release();
pexprFalse->Release();
pexprUl->Release();
pexprUl2nd->Release();
pexprUlOne->Release();
GPOS_TRACE(str.GetBuffer());
return GPOS_OK;
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_ComparisonTypes
//
// @doc:
// Test of scalar comparison types
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_ComparisonTypes()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache());
mda.RegisterProvider(CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
const IMDType *pmdtype = mda.PtMDType<IMDTypeInt4>();
GPOS_ASSERT(
IMDType::EcmptEq ==
CUtils::ParseCmpType(pmdtype->GetMdidForCmpType(IMDType::EcmptEq)));
GPOS_ASSERT(
IMDType::EcmptL ==
CUtils::ParseCmpType(pmdtype->GetMdidForCmpType(IMDType::EcmptL)));
GPOS_ASSERT(
IMDType::EcmptG ==
CUtils::ParseCmpType(pmdtype->GetMdidForCmpType(IMDType::EcmptG)));
const IMDScalarOp *pmdscopEq =
mda.RetrieveScOp(pmdtype->GetMdidForCmpType(IMDType::EcmptEq));
const IMDScalarOp *pmdscopLT =
mda.RetrieveScOp(pmdtype->GetMdidForCmpType(IMDType::EcmptL));
const IMDScalarOp *pmdscopGT =
mda.RetrieveScOp(pmdtype->GetMdidForCmpType(IMDType::EcmptG));
GPOS_ASSERT(IMDType::EcmptNEq ==
CUtils::ParseCmpType(pmdscopEq->GetInverseOpMdid()));
GPOS_ASSERT(IMDType::EcmptLEq ==
CUtils::ParseCmpType(pmdscopGT->GetInverseOpMdid()));
GPOS_ASSERT(IMDType::EcmptGEq ==
CUtils::ParseCmpType(pmdscopLT->GetInverseOpMdid()));
return GPOS_OK;
}
#endif // GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::SetupPlanForFValidPlanTest
//
// @doc:
// Helper function for the FValidPlan tests
//
//---------------------------------------------------------------------------
void
CExpressionTest::SetupPlanForFValidPlanTest(CMemoryPool *mp,
CExpression **ppexprGby,
CColRefSet **ppcrs,
CExpression **ppexprPlan,
CReqdPropPlan **pprpp)
{
*ppexprGby =
PexprCreateGbyWithColumnFormat(mp, GPOS_WSZ_LIT("Test Column%d"));
// Create a column requirement using the first output column of the group by.
CColRefSet *pcrsGby = (*ppexprGby)->DeriveOutputColumns();
*ppcrs = GPOS_NEW(mp) CColRefSet(mp);
(*ppcrs)->Include(pcrsGby->PcrFirst());
*pprpp = PrppCreateRequiredProperties(mp, *ppcrs);
CExpressionHandle exprhdl(mp);
exprhdl.Attach(*ppexprGby);
exprhdl.InitReqdProps(*pprpp);
// Optimize the logical plan under default required properties, which are always satisfied.
CEngine eng(mp);
CAutoP<CQueryContext> pqc;
pqc = CTestUtils::PqcGenerate(mp, *ppexprGby);
eng.Init(pqc.Value(), nullptr /*search_stage_array*/);
eng.Optimize();
*ppexprPlan = eng.PexprExtractPlan();
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_FValidPlan
//
// @doc:
// Test for CExpression::FValidPlan
// Test now just very basic cases. More complex cases are covered by minidump tests
// in CEnumeratorTest.
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_FValidPlan()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
const IMDType *pmdtype = mda.PtMDType<IMDTypeInt4>();
// Create a group-by with a get child. Properties required contain one of the columns in the group by.
// Test that the plan is valid.
{
CExpression *pexprGby = nullptr;
CColRefSet *pcrs = nullptr;
CExpression *pexprPlan = nullptr;
CReqdPropPlan *prpp = nullptr;
SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp);
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
// Test that prpp is actually satisfied.
GPOS_ASSERT(pexprPlan->FValidPlan(prpp, pdpctxtplan));
pdpctxtplan->Release();
pexprPlan->Release();
prpp->Release();
pexprGby->Release();
}
// Create a group-by with a get child. Properties required contain one column that doesn't exist.
// Test that the plan is NOT valid.
{
CExpression *pexprGby =
PexprCreateGbyWithColumnFormat(mp, GPOS_WSZ_LIT("Test Column%d"));
(void) pexprGby->PdpDerive();
CColRefSet *pcrsInvalid = GPOS_NEW(mp) CColRefSet(mp);
CColumnFactory *col_factory = COptCtxt::PoctxtFromTLS()->Pcf();
// Creating the column reference with the column factory ensures that it's a brand new column.
CColRef *pcrComputed =
col_factory->PcrCreate(pmdtype, default_type_modifier);
pcrsInvalid->Include(pcrComputed);
CReqdPropPlan *prpp = PrppCreateRequiredProperties(mp, pcrsInvalid);
CExpressionHandle exprhdl(mp);
exprhdl.Attach(pexprGby);
exprhdl.InitReqdProps(prpp);
// Optimize the logical plan, but under default required properties, which are always satisfied.
CEngine eng(mp);
CAutoP<CQueryContext> pqc;
pqc = CTestUtils::PqcGenerate(mp, pexprGby);
eng.Init(pqc.Value(), nullptr /*search_stage_array*/);
eng.Optimize();
CExpression *pexprPlan = eng.PexprExtractPlan();
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
// Test that prpp is actually unsatisfied.
GPOS_ASSERT(!pexprPlan->FValidPlan(prpp, pdpctxtplan));
pdpctxtplan->Release();
pexprPlan->Release();
prpp->Release();
pexprGby->Release();
}
return GPOS_OK;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_FValidPlan_InvalidOrder
//
// @doc:
// Test for CExpression::FValidPlan with incompatible order properties
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_FValidPlan_InvalidOrder()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
CExpression *pexprGby = nullptr;
CColRefSet *pcrs = nullptr;
CExpression *pexprPlan = nullptr;
CReqdPropPlan *prpp = nullptr;
SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp);
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
// Create similar requirements, but
// add an order requirement using a couple of output columns of a Get
CExpression *pexprGet = CTestUtils::PexprLogicalGet(mp);
CColRefSet *pcrsGet = pexprGet->DeriveOutputColumns();
CColRefSet *pcrsGetCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrsGet);
CColRefArray *pdrgpcrGet = pcrsGetCopy->Pdrgpcr(mp);
GPOS_ASSERT(2 <= pdrgpcrGet->Size());
COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp);
const IMDType *pmdtypeint4 = mda.PtMDType<IMDTypeInt4>();
IMDId *pmdidInt4LT = pmdtypeint4->GetMdidForCmpType(IMDType::EcmptL);
pmdidInt4LT->AddRef();
pos->Append(pmdidInt4LT, (*pdrgpcrGet)[1], COrderSpec::EntFirst);
CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy);
CDistributionSpec *pds = GPOS_NEW(mp)
CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster);
CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec(
CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion);
CEnfdDistribution *ped =
GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact);
CEnfdRewindability *per =
GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy);
CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp);
CReqdPropPlan *prppIncompatibleOrder =
GPOS_NEW(mp) CReqdPropPlan(pcrsGetCopy, peo, ped, per, pcter);
// Test that the plan is not valid.
GPOS_ASSERT(!pexprPlan->FValidPlan(prppIncompatibleOrder, pdpctxtplan));
pdpctxtplan->Release();
prppIncompatibleOrder->Release();
pdrgpcrGet->Release();
prpp->Release();
pexprGet->Release();
pexprPlan->Release();
pexprGby->Release();
return GPOS_OK;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_FValidPlan_InvalidDistribution
//
// @doc:
// Test for CExpression::FValidPlan with incompatible distribution properties
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_FValidPlan_InvalidDistribution()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
CExpression *pexprGby = nullptr;
CColRefSet *pcrs = nullptr;
CExpression *pexprPlan = nullptr;
CReqdPropPlan *prpp = nullptr;
SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp);
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp);
CDistributionSpec *pds = GPOS_NEW(mp) CDistributionSpecRandom();
CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec(
CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion);
CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy);
CEnfdDistribution *ped =
GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact);
CEnfdRewindability *per =
GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy);
CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp);
CColRefSet *pcrsCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrs);
CReqdPropPlan *prppIncompatibleDistribution =
GPOS_NEW(mp) CReqdPropPlan(pcrsCopy, peo, ped, per, pcter);
// Test that the plan is not valid.
GPOS_ASSERT(
!pexprPlan->FValidPlan(prppIncompatibleDistribution, pdpctxtplan));
pdpctxtplan->Release();
pexprPlan->Release();
prppIncompatibleDistribution->Release();
prpp->Release();
pexprGby->Release();
return GPOS_OK;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_FValidPlan_InvalidRewindability
//
// @doc:
// Test for CExpression::FValidPlan with incompatible rewindability properties
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_FValidPlan_InvalidRewindability()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
CExpression *pexprGby = nullptr;
CColRefSet *pcrs = nullptr;
CExpression *pexprPlan = nullptr;
CReqdPropPlan *prpp = nullptr;
SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp);
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp);
CDistributionSpec *pds = GPOS_NEW(mp)
CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster);
CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec(
CRewindabilitySpec::ErtRewindable, CRewindabilitySpec::EmhtNoMotion);
CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy);
CEnfdDistribution *ped =
GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact);
CEnfdRewindability *per =
GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy);
CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp);
CColRefSet *pcrsCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrs);
CReqdPropPlan *prppIncompatibleRewindability =
GPOS_NEW(mp) CReqdPropPlan(pcrsCopy, peo, ped, per, pcter);
// Test that the plan is not valid.
GPOS_ASSERT(
!pexprPlan->FValidPlan(prppIncompatibleRewindability, pdpctxtplan));
pdpctxtplan->Release();
pexprPlan->Release();
prppIncompatibleRewindability->Release();
prpp->Release();
pexprGby->Release();
return GPOS_OK;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_FValidPlan_InvalidCTEs
//
// @doc:
// Test for CExpression::FValidPlan with incompatible CTE properties
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_FValidPlan_InvalidCTEs()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
CExpression *pexprGby = nullptr;
CColRefSet *pcrs = nullptr;
CExpression *pexprPlan = nullptr;
CReqdPropPlan *prpp = nullptr;
SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp);
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp);
CDistributionSpec *pds = GPOS_NEW(mp)
CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster);
CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec(
CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion);
CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy);
CEnfdDistribution *ped =
GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact);
CEnfdRewindability *per =
GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy);
CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp);
ULONG ulCTEId = 0;
CExpression *pexprProducer =
CTestUtils::PexprLogicalCTEProducerOverSelect(mp, ulCTEId);
CDrvdPropPlan *pdpplan = CDrvdPropPlan::Pdpplan(pexprPlan->PdpDerive());
pdpplan->AddRef();
pcter->Insert(ulCTEId, CCTEMap::EctProducer /*ect*/, true /*fRequired*/,
pdpplan);
CColRefSet *pcrsCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrs);
CReqdPropPlan *prppIncompatibleCTE =
GPOS_NEW(mp) CReqdPropPlan(pcrsCopy, peo, ped, per, pcter);
// Test that the plan is not valid.
GPOS_ASSERT(!pexprPlan->FValidPlan(prppIncompatibleCTE, pdpctxtplan));
pdpctxtplan->Release();
pexprPlan->Release();
prppIncompatibleCTE->Release();
prpp->Release();
pexprGby->Release();
pexprProducer->Release();
return GPOS_OK;
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_FValidPlanError
//
// @doc:
// Tests that CExpression::FValidPlan fails with an assert exception in debug mode
// for bad input.
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_FValidPlanError()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */
CTestUtils::GetCostModel(mp));
const IMDType *pmdtype = mda.PtMDType<IMDTypeInt4>();
GPOS_RESULT eres = GPOS_OK;
// Test that in debug mode GPOS_ASSERT fails for non-physical expressions.
{
CColRefSet *pcrsInvalid = GPOS_NEW(mp) CColRefSet(mp);
CColumnFactory *col_factory = COptCtxt::PoctxtFromTLS()->Pcf();
CColRef *pcrComputed =
col_factory->PcrCreate(pmdtype, default_type_modifier);
pcrsInvalid->Include(pcrComputed);
CReqdPropPlan *prpp = PrppCreateRequiredProperties(mp, pcrsInvalid);
IDatum *datum = GPOS_NEW(mp) gpnaucrates::CDatumInt8GPDB(
CTestUtils::m_sysidDefault, 1 /*val*/, false /*is_null*/);
CExpression *pexpr =
GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CScalarConst(mp, datum));
CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp);
GPOS_TRY
{
// FValidPlan should fail for expressions which are not physical.
if (!pexpr->FValidPlan(prpp, pdpctxtplan))
{
eres = GPOS_FAILED;
}
pdpctxtplan->Release();
}
GPOS_CATCH_EX(ex)
{
pdpctxtplan->Release();
if (!GPOS_MATCH_EX(ex, CException::ExmaSystem,
CException::ExmiAssert))
{
GPOS_RETHROW(ex);
}
else
{
GPOS_RESET_EX;
}
}
GPOS_CATCH_END;
pexpr->Release();
prpp->Release();
}
return eres;
}
#endif // GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresCheckCachedReqdCols
//
// @doc:
// Helper for checking cached required columns
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresCheckCachedReqdCols(CMemoryPool *mp, CExpression *pexpr,
CReqdPropPlan *prppInput)
{
if (pexpr->Pop()->FScalar())
{
// scalar operators have no required columns
return GPOS_OK;
}
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != prppInput);
CExpressionHandle exprhdl(mp);
exprhdl.Attach(pexpr);
// init required properties of expression
exprhdl.InitReqdProps(prppInput);
// create array of child derived properties
CDrvdPropArray *pdrgpdp = GPOS_NEW(mp) CDrvdPropArray(mp);
GPOS_RESULT eres = GPOS_OK;
const ULONG arity = pexpr->Arity();
for (ULONG ul = 0; GPOS_OK == eres && ul < arity; ul++)
{
CExpression *pexprChild = (*pexpr)[ul];
if (pexprChild->Pop()->FScalar())
{
continue;
}
GPOS_ASSERT(nullptr != pexprChild->Prpp());
// extract cached required columns of the n-th child
CColRefSet *pcrsChildReqd = pexprChild->Prpp()->PcrsRequired();
// compute required columns of the n-th child
exprhdl.ComputeChildReqdCols(ul, pdrgpdp);
// check if cached columns pointer is the same as computed columns pointer,
// if this is not the case, then we have re-computed the same set of columns and test should fail
if (pcrsChildReqd != exprhdl.Prpp(ul)->PcrsRequired())
{
CAutoTrace at(mp);
at.Os() << "\nExpression: \n" << *pexprChild;
at.Os() << "\nCached cols: " << pcrsChildReqd << " : "
<< *pcrsChildReqd;
at.Os() << "\nComputed cols: " << exprhdl.Prpp(ul)->PcrsRequired()
<< " : " << *exprhdl.Prpp(ul)->PcrsRequired();
eres = GPOS_FAILED;
continue;
}
// call the function recursively for child expression
GPOS_RESULT eres =
EresCheckCachedReqdCols(mp, pexprChild, exprhdl.Prpp(ul));
if (GPOS_FAILED == eres)
{
eres = GPOS_FAILED;
continue;
}
// add plan props of current child to derived props array
CDrvdProp *pdp = pexprChild->PdpDerive();
pdp->AddRef();
pdrgpdp->Append(pdp);
}
pdrgpdp->Release();
return eres;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresComputeReqdCols
//
// @doc:
// Helper for testing required column computation
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresComputeReqdCols(const CHAR *szFilePath)
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// reset metadata cache
CMDCache::Reset();
// set up MD providers
CMDProviderMemory *pmdp = GPOS_NEW(mp) CMDProviderMemory(mp, szFilePath);
GPOS_CHECK_ABORT;
GPOS_RESULT eres = GPOS_FAILED;
{
CAutoMDAccessor amda(mp, pmdp, CTestUtils::m_sysidDefault);
CAutoOptCtxt aoc(mp, amda.Pmda(), nullptr,
/* pceeval */ CTestUtils::GetCostModel(mp));
// read query expression
CExpression *pexpr = CTestUtils::PexprReadQuery(mp, szFilePath);
// optimize query
CEngine eng(mp);
CQueryContext *pqc = CTestUtils::PqcGenerate(mp, pexpr);
eng.Init(pqc, nullptr /*search_stage_array*/);
eng.Optimize();
// extract plan and decorate it with required columns
CExpression *pexprPlan = eng.PexprExtractPlan();
// attempt computing required columns again --
// we make sure that we reuse cached required columns at each operator
eres = EresCheckCachedReqdCols(mp, pexprPlan, pqc->Prpp());
pexpr->Release();
pexprPlan->Release();
GPOS_DELETE(pqc);
}
return eres;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_ReqdCols
//
// @doc:
// Test for required columns computation
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_ReqdCols()
{
const CHAR *rgszTests[] = {
"../data/dxl/tpch/q1.mdp",
"../data/dxl/tpch/q3.mdp",
"../data/dxl/expressiontests/WinFunc-OuterRef-Partition-Query.xml",
"../data/dxl/expressiontests/WinFunc-OuterRef-Partition-Order-Query.xml",
};
GPOS_RESULT eres = GPOS_OK;
for (ULONG ul = 0; GPOS_OK == eres && ul < GPOS_ARRAY_SIZE(rgszTests); ul++)
{
const CHAR *szFilePath = rgszTests[ul];
eres = EresComputeReqdCols(szFilePath);
}
return eres;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::EresUnittest_InvalidSetOp
//
// @doc:
// Test for invalid SetOp expression,
// SetOp is expected to have no outer references in input columns,
// when an outer reference needs to be fed to SetOp as input, we must
// project it first and feed the projected column into SetOp
//
// For example, this is an invalid SetOp expression since it consumes
// an outer reference from inner child
//
// +--CLogicalUnion [Output: "col0" (0)], [Input: ("col0" (0)), ("col6" (6))]
// |--CLogicalGet ("T1"), Columns: ["col0" (0)]
// +--CLogicalGet ("T2"), Columns: ["col3" (3)]
//
//
// the valid expression should looks like this:
//
// +--CLogicalUnion [Output: "col0" (0)], [Input: ("col0" (0)), ("col7" (7))]
// |--CLogicalGet ("T1"), Columns: ["col0" (0)]
// +--CLogicalProject
// |--CLogicalGet ("T2"), Columns: ["col3" (3)]
// +--CScalarProjectList
// +--CScalarProjectElement "col7" (7)
// +--CScalarIdent "col6" (6)
//
//
//---------------------------------------------------------------------------
GPOS_RESULT
CExpressionTest::EresUnittest_InvalidSetOp()
{
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
// Setup an MD cache with a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
{
CAutoOptCtxt aoc(mp, &mda, nullptr /* pceeval */,
CTestUtils::GetCostModel(mp));
// create two different Get expressions
CWStringConst strName1(GPOS_WSZ_LIT("T1"));
CMDIdGPDB *pmdid1 = GPOS_NEW(mp) CMDIdGPDB(GPOPT_TEST_REL_OID1, 1, 1);
CTableDescriptor *ptabdesc1 =
CTestUtils::PtabdescCreate(mp, 3, pmdid1, CName(&strName1));
CWStringConst strAlias1(GPOS_WSZ_LIT("T1Alias"));
CExpression *pexprGet1 =
CTestUtils::PexprLogicalGet(mp, ptabdesc1, &strAlias1);
CColRefSet *pcrsOutput1 = pexprGet1->DeriveOutputColumns();
CWStringConst strName2(GPOS_WSZ_LIT("T2"));
CMDIdGPDB *pmdid2 = GPOS_NEW(mp) CMDIdGPDB(GPOPT_TEST_REL_OID2, 1, 1);
CTableDescriptor *ptabdesc2 =
CTestUtils::PtabdescCreate(mp, 3, pmdid2, CName(&strName2));
CWStringConst strAlias2(GPOS_WSZ_LIT("T2Alias"));
CExpression *pexprGet2 =
CTestUtils::PexprLogicalGet(mp, ptabdesc2, &strAlias2);
// create output columns of SetOp from output columns of first Get expression
CColRefArray *pdrgpcrOutput = GPOS_NEW(mp) CColRefArray(mp);
pdrgpcrOutput->Append(pcrsOutput1->PcrFirst());
// create input columns of SetOp while including an outer reference in inner child
CColRef2dArray *pdrgpdrgpcrInput = GPOS_NEW(mp) CColRef2dArray(mp);
CColRefArray *pdrgpcr1 = GPOS_NEW(mp) CColRefArray(mp);
pdrgpcr1->Append(pcrsOutput1->PcrFirst());
pdrgpdrgpcrInput->Append(pdrgpcr1);
CColRefArray *pdrgpcr2 = GPOS_NEW(mp) CColRefArray(mp);
CColRef *pcrOuterRef = COptCtxt::PoctxtFromTLS()->Pcf()->PcrCreate(
pcrsOutput1->PcrFirst());
pdrgpcr2->Append(pcrOuterRef);
pdrgpdrgpcrInput->Append(pdrgpcr2);
// create invalid SetOp expression
CLogicalUnion *pop =
GPOS_NEW(mp) CLogicalUnion(mp, pdrgpcrOutput, pdrgpdrgpcrInput);
CExpression *pexprSetOp =
GPOS_NEW(mp) CExpression(mp, pop, pexprGet1, pexprGet2);
{
CAutoTrace at(mp);
at.Os() << "\nInvalid SetOp Expression: \n" << *pexprSetOp;
}
// deriving relational properties must fail
(void) pexprSetOp->PdpDerive();
pexprSetOp->Release();
}
return GPOS_FAILED;
}
//---------------------------------------------------------------------------
// @function:
// CExpressionTest::PexprComplexJoinTree
//
// @doc:
// Return an expression with several joins
//
//---------------------------------------------------------------------------
CExpression *
CExpressionTest::PexprComplexJoinTree(CMemoryPool *mp)
{
// The plan will have this shape
//
// +--CLogicalInnerJoin
// |--CLogicalUnion
// | |--CLogicalLeftOuterJoin
// | | |--CLogicalInnerJoin
// | | | |--CLogicalGet
// | | | +--CLogicalSelect
// | | +--CLogicalInnerJoin
// | | |--CLogicalGet
// | | +--CLogicalDynamicGet
// | +--CLogicalLeftOuterJoin
// | |--CLogicalGet
// | +--CLogicalGet
// +--CLogicalInnerJoin
// |--CLogicalGet
// +--CLogicalSelect
CExpression *pexprInnerJoin1 =
CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>(
mp, CTestUtils::PexprLogicalGet(mp),
CTestUtils::PexprLogicalSelect(mp));
CExpression *pexprJoinIndex =
CTestUtils::PexprLogicalJoinWithPartitionedAndIndexedInnerChild(mp);
CExpression *pexprLeftJoin =
CTestUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>(mp, pexprInnerJoin1,
pexprJoinIndex);
CExpression *pexprOuterJoin =
CTestUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>(mp);
CExpression *pexprInnerJoin4 =
CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>(mp, pexprLeftJoin,
pexprOuterJoin);
CExpression *pexprInnerJoin5 =
CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>(
mp, CTestUtils::PexprLogicalGet(mp),
CTestUtils::PexprLogicalSelect(mp));
CExpression *pexprTopJoin = CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>(
mp, pexprInnerJoin4, pexprInnerJoin5);
return pexprTopJoin;
}
// EOF
|
Outside of the academic environment, a harsh and seemingly ever-growing debate has appeared, concerning how mass media distorts the political agenda. Few would argue with the notion that the institutions of the mass media are important to contemporary politics. In the transition to liberal democratic politics in the Soviet Union and Eastern Europe the media was a key battleground. In the West, elections increasingly focus around television, with the emphasis on spin and marketing. Democratic politics places emphasis on the mass media as a site for democratic demand and the formation of “public opinion”. The media are seen to empower citizens, and subject government to restraint and redress. Yet the media are not just neutral observers but are political actors themselves. The interaction of mass communication and political actors — politicians, interest groups, strategists, and others who play important roles — in the political process is apparent. Under this framework, the American political arena can be characterized as a dynamic environment in which communication, particularly journalism in all its forms, substantially influences and is influenced by it.
According to the theory of democracy, people rule. The pluralism of different political parties provides the people with “alternatives,” and if and when one party loses their confidence, they can support another. The democratic principle of “government of the people, by the people, and for the people” would be nice if it were all so simple. But in a medium-to-large modern state things are not quite like that. Today, several elements contribute to the shaping of the public’s political discourse, including the goals and success of public relations and advertising strategies used by politically engaged individuals and the rising influence of new media technologies such as the Internet.
A naive assumption of liberal democracy is that citizens have adequate knowledge of political events. But how do citizens acquire the information and knowledge necessary for them to use their votes other than by blind guesswork? They cannot possibly witness everything that is happening on the national scene, still less at the level of world events. The vast majority are not students of politics. They don’t really know what is happening, and even if they did they would need guidance as to how to interpret what they knew. Since the early twentieth century this has been fulfilled through the mass media. Few today in United States can say that they do not have access to at least one form of the mass media, yet political knowledge is remarkably low. Although political information is available through the proliferation of mass media, different critics support that events are shaped and packaged, frames are constructed by politicians and news casters, and ownership influences between political actors and the media provide important short hand cues to how to interpret and understand the news.
One must not forget another interesting fact about the media. Their political influence extends far beyond newspaper reports and articles of a direct political nature, or television programs connected with current affairs that bear upon politics. In a much more subtle way, they can influence people’s thought patterns by other means, like “goodwill” stories, pages dealing with entertainment and popular culture, movies, TV “soaps”, “educational” programs. All these types of information form human values, concepts of good and evil, right and wrong, sense and nonsense, what is “fashionable” and “unfashionable,” and what is “acceptable” and “unacceptable”. These human value systems, in turn, shape people’s attitude to political issues, influence how they vote and therefore determine who holds political power.
|
Working with the MEAN stack: Application setup
In this tutorial I will convert the app I wrote using AngularJS to make it use the MEAN stack. Don’t worry, there’s nothing mean about the MEAN stack.
The MEAN stack is a pure JavaScript stack containing:
• MongoDB: MongoDB is a NoSQL database allowing you to store JSON (actually BSON) documents and query them. This is a great database when going for pure JavaScript applications because it’s easy to put the same object structure that you’re working with, inside the database.
• Express: Express is a web framework that runs on Node.js. A “web” framework may sound a bit vague, but it is actually that. It allows you to serve static content, it allows you to route certain requests to execute certain logic (great for RESTful webservices) and so on.
• AngularJS: I probably don’t have to explain this one to you, but AngularJS is a client-side Model-View-Controller framework by Google.
• Node.js: I mentioned it already that we’re going to use Node.js (because we’re going to use Express), but Node.js is a JavaScript platform, quite popular nowadays. In this tutorial we will use it as our server-side platform.
Before starting with the application, you obviously need to install the MEAN stack. If you followed some of my other tutorials, you probably already used Node.js and npm to use Bower. If you didn’t install Node.js yet, you can get it from
By installing Node.js you install two things; first of all it will install Node.js (obviously), and second it will also install the Node.js package manager called npm.
Verify that the installation was successful by using the command:
node version
nodejs version
And to check if npm was installed, use:
npm version
The second step is to install MongoDB, which you can download from To check if the installation was successful, use:
mongod version
Setting up our application
The first step is that we’re going to setup our application. Start a new project and add the following folders:
• client: This folder will contain our client-side application using AngularJS. This content will be served by Express.
• config: This folder will contain configuration used to run our application. Things like a connection URL and the port we will run on can be setup here. It’s a good idea to centralize this information for when you want to dpeloy the app on a cloud based environment.
• server: This folder will contain our server-side logic to serve the client and to provide a RESTful webservice.
We’re also going to add some files. First of all we’re going to create our Node.js application by creating a file called app.js. Node.js also comes with a packaage manager called NPM.
To load our dependencies, we will have to define a file called package.json, which will define our application and the dependencies we have.
In our app the file will contain:
1. {
2. “name”: “mean-song-rate”,
3. “version”: “0.0.1”,
4. “dependencies”: {
5. “mongoose”: “~3.6.14”,
6. “express”: “~3.3.4”
7. }
8. }
I already explained what we’re going to do with Express. Mongoose on the other hand is a Node.js framework used to communicate with MongoDB. It provides a sweet API where you use models to add/update/retrieve and read your data.
For the client-side part of our application, I’m going to start of where we left in my previous tutorial. I’m not going into detail about AngularJS controllers, services or directives in this tutorial. If you’re interested in that, I suggest reading my introduction tutorial series to AngularJS.
What we do need is the code of the application, which you can find on Github ( Put all the code in the client folder, except bower.json and .bowerrc which you can put in the root folder.
Now open up .bowerrc and change the directory to:
1. {
2. “directory”: “client/libs”,
3. “json”: “bower.json”
4. }
This is obviously necessary because we moved our Bower configuration one level up (to the parent folder).
Now open bower.json and add the dependency angular-resource, for example:
1. {
3. “version”: “0.0.1”,
4. “dependencies”: {
5. “angular”: “1.2.15”,
6. “angular-resource”: “1.2.15”,
7. “bootstrap”: “3.1.1”,
8. “lodash”: “2.4.1”,
9. “underscore.string”: “2.3.3”,
10. “font-awesome”: “4.0.3”
11. }
12. }
Angular-resource is a part of the AngularJS framework and provides an easy way to integrate with your RESTful webservices.
Also note that I changed the name in the bower configuration.
The next part is the configuration. Open the config folder and add the following files:
• config.js: This file will contain our main configuration including port number and database URL.
• db.js: This file will contain the Mongoose configuration to connect to our MongoDB instance.
• express.js: This file will contain the configuration used for Express.js like on which port it has to un, which context will be used to serve our client application and which context will be used to provide our RESTful webservices.
• routes.js: Finally we will also use the routing pattern to setup which URL is bound to which logic in our controller.
The serverside logic will not be too complicated. We’re going to add two folders here called controllersand models.
In the controllers folder we will add our RESTful webservice controller, called rest.js. In the models folder we will add our model, a file called Song.js.
Writing your Node.js app
Now all files are ready, so let’s start by writing our application. I’m going to start with the boring stuff first, namely the configuration part.
Let’s open up config.js and add the following code:
1. var env = process.env.NODE_ENV || ‘development’;
2. var config = {
3. port: 3000,
4. db: ‘mongodb://localhost/songs’,
5. host: ‘localhost’
6. };
7. module.exports = config;
On the first line we’re retrieving a system variable called NODE_ENV. This is not really important in our app, but if you want to deploy this on a cloud environment like IBM BlueMix or if you want to host this on multiple environments, you might be interested in this. For every environment you choose another value forNODE_ENV, which will allow you to use something like:
1. if (env === “production”) {
2. config.db = ‘mongodb://my.production.server/songs’;
3. }
So, on the next lines we can see our configuration which contains:
• port: The port our application will run on
• db: The MongoDB connection string
• host: The hostname the application will run on
And finally we make sure that this module returns config, so when another module calls it, it gets the configuration object. You can do this by using module.exports.
The next configuration file is db.js. Similar to config.js we will configure Mongoose and return the configuration by using module.exports, for example:
1. var mongoose = require(‘mongoose’);
2. module.exports = function(config) {
3. mongoose.connect(config.db);
4. var db = mongoose.connection;
5. db.on(‘error’, function() {
6. throw new Error(‘Unable to connect to database at ‘ + config.db);
7. });
8. };
So, here we’re using the configuration object we made in our previous module and use it to connect to MongoDB using Mongoose.
The configuration itself is passed as an argument to this module, I will show you how that works later.
Then the next configuration file is express.js, similar to db.js it will configure our application based upon the configuration from config.js.
1. var express = require(‘express’);
2. module.exports = function(app, config) {
3. app.configure(function () {
4. app.use(express.compress());
5. app.set(‘port’, config.port);
6. app.use(express.logger(‘dev’));
7. app.use(express.bodyParser());
8. app.use(express.methodOverride());
10. app.use(‘/api’, app.router);
11. app.use(‘/’, express.static(__dirname + “/../client”));
12. });
13. };
So, what happens here is that this module accepts two parameters, app which is an application object initialized by Express and second we have config which is our configuration object which we’re going to need to know the port we’re going to run on.
So, let’s talk about each line more into detail. The first two lines of configuration are pretty easy, the first line makes sure that our files are compressed using the GZIP protocol and the second line says which port we’re going to use.
The third line (app.use(express.logger('dev')); makes sure that we’re going to log all requests of both our RESTful webservice as the static files that are served.
The next two lines are important for our RESTful webservice In our RESTful webservice we’re going to use the post body to add or update the objects. To do that we need to enable the express.bodyParser()) on our application.
The express.methodOverride() on the other hand allows us to use PUT and DELETE requests, which we will use to update and delete our objects in our RESTful webservice.
Then finally we configure our app to use /api to serve our RESTful webservice and / to provide the static files from the client folder.
The last configuration file is routes.js and this is probably the easiest one. In this configuration file we will define which REST endpoint is mapped to which method in our controller.
1. var rest = require(‘../server/controllers/rest’);
2. module.exports = function(app){
3. // find all songs route
4. app.get(‘/songs’, rest.findAll);
6. // find one song route
7. app.get(‘/songs/:id’, rest.findOne);
9. // Add song route
10.‘/songs’, rest.add);
12. // Update song route
13. app.put(‘/songs/:id’, rest.update);
15. // Delete song route
16. app.del(‘/songs/:id’, rest.remove);
17. };
As you can see here, we’re using several endpoints here:
• GET /songs: This will be used to retrieve all songs in our database
• GET /songs/:id: The :id is a placeholder for the real ID of a song. Which means that we’re going to use this to retrieve a single song from our database.
• POST /songs: This method will be used to add a new song to the list. The song itself will be provided as JSON in the post body of the request.
• PUT /songs/:id: This method will be used to update a song by its ID. The updated song itself will be provided in the request body, just like adding new songs.
• DELETE /songs/:id: This method will be used to delete a song by its ID.
At the first lien you can see how we import our REST controller in the configuration file by usingrequire('../server/controllers/rest').
The main application
Before actually writing our application we have to write the “glue” that keeps all modules together. Our main module (app.js) will import the configuration files to make sure our app is properly started.
The code itself is not that complex, as it’s sole purpose is to load other modules (like our configuration).
So, first of all we’re going to import all modules that we need by using the require() function:
1. var express = require(‘express’), mongoose = require(‘mongoose’), fs = require(‘fs’), http = require(‘http’),
2. config = require(‘./config/config’), root = __dirname, app = express(), server = null;
Most of these modules are known by now. Only fs and http are new modules. These are standard modules of Node.js, so that’s why you won’t find them in package.json.
The names of the modules already explain what they do:
• fs: Provides functions to access the file system
• http: Allows you to create a HTTP web server
Then the next step is that we’re going to configure Mongoose by using db.js:
1. require(‘./config/db’)(config);
As you can see here, we’re importing the module and immediately after it we’re executing the function and providing the config argument.
The next part is a bit more complex. To dynamically load all our models, we’re going to list all files in the models directory and add all modules that are inside that folder.
We can do that by writing:
1. var modelsPath = __dirname + ‘/server/models’;
2. fs.readdirSync(modelsPath).forEach(function (file) {
3. if (file.indexOf(‘.js’) >= 0) {
4. require(modelsPath + ‘/’ + file);
5. }
6. });
Now we only have the express and route configuration file left, which we’re going to load by writing:
1. require(‘./config/express’)(app, config);
2. require(‘./config/routes’)(app);
And finally we need to start the webserver itself, which we will do by adding:
1. var server = http.createServer(app);
2. server.listen(config.port,;
3. console.log(‘App started on port ‘ + config.port);
This is everything we have to do to make our application work. In the next part I’m going to explain how we’re going to create the MVC application using Express and how we’re going to tweak the AngularJS application to make it work with our new RESTful webservice.
IT Consultant with a passion for JavaScript. Experienced in the Spring Framework and various JavaScript frameworks.
Share This:
Leave a Reply
|
/*
Copyright (c) 2016, 2021, Alden Torres
Copyright (c) 2017, Steven Siloti
Copyright (c) 2017-2021, Arvid Norberg
All rights reserved.
You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/
#include "libtorrent/kademlia/dht_state.hpp"
#include <libtorrent/bdecode.hpp>
#include <libtorrent/aux_/socket_io.hpp>
namespace libtorrent::dht {
node_ids_t extract_node_ids(bdecode_node const& e, string_view key)
{
if (e.type() != bdecode_node::dict_t) return node_ids_t();
node_ids_t ret;
// first look for an old-style nid
auto const old_nid = e.dict_find_string_value(key);
if (old_nid.size() == 20)
{
ret.emplace_back(address(), node_id(old_nid));
return ret;
}
auto const nids = e.dict_find_list(key);
if (!nids) return ret;
for (int i = 0; i < nids.list_size(); i++)
{
bdecode_node nid = nids.list_at(i);
if (nid.type() != bdecode_node::string_t) continue;
if (nid.string_length() < 20) continue;
char const* in = nid.string_ptr();
node_id id(in);
in += id.size();
address addr;
if (nid.string_length() == 24)
addr = aux::read_v4_address(in);
else if (nid.string_length() == 36)
addr = aux::read_v6_address(in);
else
continue;
ret.emplace_back(addr, id);
}
return ret;
}
namespace {
entry save_nodes(std::vector<udp::endpoint> const& nodes)
{
entry ret(entry::list_t);
entry::list_type& list = ret.list();
for (auto const& ep : nodes)
{
std::string node;
std::back_insert_iterator<std::string> out(node);
aux::write_endpoint(ep, out);
list.emplace_back(node);
}
return ret;
}
} // anonymous namespace
void dht_state::clear()
{
nids.clear();
nids.shrink_to_fit();
nodes.clear();
nodes.shrink_to_fit();
nodes6.clear();
nodes6.shrink_to_fit();
}
dht_state read_dht_state(bdecode_node const& e)
{
dht_state ret;
if (e.type() != bdecode_node::dict_t) return ret;
ret.nids = extract_node_ids(e, "node-id");
if (bdecode_node const nodes = e.dict_find_list("nodes"))
ret.nodes = aux::read_endpoint_list<udp::endpoint>(nodes);
if (bdecode_node const nodes = e.dict_find_list("nodes6"))
ret.nodes6 = aux::read_endpoint_list<udp::endpoint>(nodes);
return ret;
}
entry save_dht_state(dht_state const& state)
{
entry ret(entry::dictionary_t);
auto& nids = ret["node-id"].list();
for (auto const& n : state.nids)
{
std::string nid;
std::copy(n.second.begin(), n.second.end(), std::back_inserter(nid));
aux::write_address(n.first, std::back_inserter(nid));
nids.emplace_back(std::move(nid));
}
entry const nodes = save_nodes(state.nodes);
if (!nodes.list().empty()) ret["nodes"] = nodes;
entry const nodes6 = save_nodes(state.nodes6);
if (!nodes6.list().empty()) ret["nodes6"] = nodes6;
return ret;
}
}
|
Taking Play Seriously
By ROBIN MARANTZ HENIG
Published: February 17, 2008
On a drizzly Tuesday night in late January, 200 people came out to hear a psychiatrist talk rhapsodically about play -- not just the intense, joyous play of children, but play for all people, at all ages, at all times. (All species too; the lecture featured touching photos of a polar bear and a husky engaging playfully at a snowy outpost in northern Canada.) Stuart Brown, president of the National Institute for Play, was speaking at the New York Public Library's main branch on 42nd Street. He created the institute in 1996, after more than 20 years of psychiatric practice and research persuaded him of the dangerous long-term consequences of play deprivation. In a sold-out talk at the library, he and Krista Tippett, host of the public-radio program ''Speaking of Faith,'' discussed the biological and spiritual underpinnings of play. Brown called play part of the ''developmental sequencing of becoming a human primate. If you look at what produces learning and memory and well-being, play is as fundamental as any other aspect of life, including sleep and dreams.''
The message seemed to resonate with audience members, who asked anxious questions about what seemed to be the loss of play in their children's lives. Their concern came, no doubt, from the recent deluge of eulogies to play . Educators fret that school officials are hacking away at recess to make room for an increasingly crammed curriculum. Psychologists complain that overscheduled kids have no time left for the real business of childhood: idle, creative, unstructured free play. Public health officials link insufficient playtime to a rise in childhood obesity. Parents bemoan the fact that kids don't play the way they themselves did -- or think they did. And everyone seems to worry that without the chance to play stickball or hopscotch out on the street, to play with dolls on the kitchen floor or climb trees in the woods, today's children are missing out on something essential.
The success of ''The Dangerous Book for Boys'' -- which has been on the best-seller list for the last nine months -- and its step-by-step instructions for activities like folding paper airplanes is testament to the generalized longing for play's good old days. So were the questions after Stuart Brown's library talk; one woman asked how her children will learn trust, empathy and social skills when their most frequent playing is done online. Brown told her that while video games do have some play value, a true sense of ''interpersonal nuance'' can be achieved only by a child who is engaging all five senses by playing in the three-dimensional world.
This is part of a larger conversation Americans are having about play. Parents bobble between a nostalgia-infused yearning for their children to play and fear that time spent playing is time lost to more practical pursuits. Alarming headlines about U.S. students falling behind other countries in science and math, combined with the ever-more-intense competition to get kids into college, make parents rush to sign up their children for piano lessons and test-prep courses instead of just leaving them to improvise on their own; playtime versus r?m?uilding.
Discussions about play force us to reckon with our underlying ideas about childhood, sex differences, creativity and success. Do boys play differently than girls? Are children being damaged by staring at computer screens and video games? Are they missing something when fantasy play is populated with characters from Hollywood's imagination and not their own? Most of these issues are too vast to be addressed by a single field of study (let alone a magazine article). But the growing science of play does have much to add to the conversation. Armed with research grounded in evolutionary biology and experimental neuroscience, some scientists have shown themselves eager -- at times perhaps a little too eager -- to promote a scientific argument for play. They have spent the past few decades learning how and why play evolved in animals, generating insights that can inform our understanding of its evolution in humans too. They are studying, from an evolutionary perspective, to what extent play is a luxury that can be dispensed with when there are too many other competing claims on the growing brain, and to what extent it is central to how that brain grows in the first place.
Scientists who study play, in animals and humans alike, are developing a consensus view that play is something more than a way for restless kids to work off steam; more than a way for chubby kids to burn off calories; more than a frivolous luxury. Play, in their view, is a central part of neurological growth and development -- one important way that children build complex, skilled, responsive, socially adept and cognitively flexible brains.
Their work still leaves some questions unanswered, including questions about play's darker, more ambiguous side: is there really an evolutionary or developmental need for dangerous games, say, or for the meanness and hurt feelings that seem to attend so much child's play? Answering these and other questions could help us understand what might be lost if children play less.
|
Financial Accounting - CH 1 & 2
|Four Principal Activities of Business Firms:|| 1.Establishing goals and strategies|
|What are the 2 sources Financing comes from?|| 1. Owners|
|Investments are made in the following:|| 1. Land, buildings, equipment|
2. Patents, licenses, contractual rights
3. Stock and bonds of other organizations
5. Accounts Receivable
|What are the 4 areas for conducting operations?|| 1. Purchasing|
|What are the 4 commonly used conventions in financial statements?|| 1. The accounting period|
2. The number of reporting periods
3. The monetary amounts
4. The terminology and level of detail in the financial statements
|Common Financial Reporting Conventions, Accounting Period||The length of time covered by the financial statements. (The most common interval for external reporting is the fiscal year).|
|Common Financial Reporting Conventions, Number of reporting periods||The number of reporting periods included in a given financial statement presentation, Both U.S. GAAP and IFRS require firms to include results for multiple reporting periods in each report.|
|Common Financial Reporting Conventions, Monetary amounts||This includes measuring units, like thousands, millions, or billions, and the currency, such as dollars ($), euros (€), or Swedish kronor (SEK)|
|Common Financial Reporting Conventions, Terminology and level of detail in the financial statements||U.S. GAAP and IFRS contain broad guidance on what the financial statements must contain, but neither system completely specifies the level of detail or the names of accounts. Therefore, some variation occurs.|
|Characteristics of a Balance Sheet||A Balance Sheet:|
1. is also known as a statement of financial position;
2. provides information at a point in time;
3. lists the firm's assets, liabilities, and shareholders' equity and provides totals and subtotals; and
4. can be represented as the Basic Accounting Equation.
Assets = Liabilities + Shareholders' Equity
|Accounting Equation Components|| 1. Assets|
3. Share Holder's Equity
|Assets|| Assets are economic resources with the potential to provide future economic benefits to a firm. |
Examples: Cash, Accounts Receivable, Inventories, Buildings, Equipment, intangible assets (like Patents)
|Liabilities|| Liabilities are creditors' claims for funds, usually because they have provided funds, or goods and services, to the firm.|
Examples: Accounts Payable, Unearned Income, Notes Payable, Buildings, Accrued Salaries
|Shareholders' Equity|| Shareholders' Equity shows the amounts of funds owners have provided and, in parallel, their claims on the assets of a firm. |
Examples: Common Stock, Contributed Capital, Retained Earnings
|What are the separate sections on a Balance Sheet (Balance sheet classification)||1. Current assets represent assets that a firm expects to turn into cash, or sell, or consume within approximately one year from the date of the balance sheet (i.e., accounts receivable and inventory).|
2. Current liabilities represent obligations a firm expects to pay within one year (i.e., accounts payable and salaries payable).
3. Non-current assets are typically held and used for several years (i.e., land, buildings, equipment, patents, long-term security investments).
4. Noncurrent liabilities and shareholders' equity are sources of funds where the supplier of funds does not expect to receive them all back within the next year.
|Income Statement||1. Sometimes called the statement of profit and loss by firms applying IFRS|
2. Provides information on profitability
3. May use the terms net income, earnings, and profit interchangeably
4. Reports amounts for a period of time
5. Typically one year
6. Is represented by the Basic Income Equation:
Net Income = Revenues - Expenses
|Revenues||(also known as sales, sales revenue, or turnover, a term used by some firms reporting under IFRS) measure the inflows of assets (or reductions in liabilities) from selling goods and providing services to customers.|
|Expenses||measure the outflow of assets (or increases in liabilities) used in generating revenues.|
|Relationship between the Balance Sheet and the Income Statement|| 1. The income statement links the balance sheet at the beginning of the period with the balance sheet at the end of the period.|
2. Retained Earnings is increased by net income and decreased by dividends.
|Statement of Cash Flows|| The statement of cash flows (also called the|
cash flow statement) reports information about
cash generated from or used by:
2. investing, and
3. financing activities during specified time periods.
The statement of cash flows shows where the firm obtains or generates cash and where it spends or uses cash.
|Classification of Cash Flows|| 1. Operations: |
cash from customers less cash paid in carrying out the firm's operating activities
cash paid to acquire noncurrent assets less amounts from any sale of noncurrent assets
cash from issues of long-term debt or new capital less dividends
|Inflows and Outflows of Cash|
|The Relationship of the Statement of Cash Flows to the Balance Sheet and Income Statement||-The statement of cash flows explains the change in cash between the beginning and the end of the period, and separately displays the changes in cash from operating, investing, and financing activities.|
-In addition to sources and uses of cash, the statement of cash flows shows the relationship between net income and cash flow from operations.
|Statement of Shareholders' Equity||This statement displays components of shareholders' equity, including common shares and retained earnings, and changes in those components.|
|Other Items in Annual Reports||Financial reports provide additional explanatory material in the schedules and notes to the financial statements.|
|Who are the 4 main groups of people involved with the Financial Reporting Process|| 1. Managers and governing boards of reporting entities.|
2. Accounting standard setters
and regulatory bodies.
3. Independent external auditors.
4. Users of financial statements.
|What is the Securities and Exchange Commission (SEC)?||An agency of the federal government, that has the legal authority to set acceptable accounting standards and enforce securities laws.|
|What is the Financial Accounting Standards Board (FASB)?||a private-sector body comprising five voting members, to whom the SEC has delegated most tasks of U.S. financial accounting standard-setting.|
|GAAP||1. Common terminology includes the pronouncements of the FASB (and its predecessors) in the compilation of accounting rules, procedures, and practices known as generally accepted accounting principles (GAAP).|
2. Recently, the FASB launched its codification project which organizes all of U.S GAAP by topic (for example, revenues), eliminates duplications, and corrects inconsistencies.
|FASB board members make standard-setting decisions guided by a conceptual framework that addresses:|| 1. Objectives of financial reporting.|
2. Qualitative characteristics of accounting information including the relevance, reliability, and comparability of data.
3. Elements of the financial statements.
4. Recognition and measurement issues.
|Sarbanes-Oxley Act of 2002.|| Concerns over the quality of financial reporting have led, and continue to lead, to government initiatives in the United States.|
Sarbanes-Oxley Act of 2002 established the Public Company Accounting Oversight Board (PCAOB), which is responsible for monitoring the quality of audits of SEC registrants.
|International Financial Reporting Standards (IFRS)||-The International Accounting Standards Board (IASB) is an independent accounting standard-setting entity with 14 voting members from a number of countries. Standards set by the IASB are International Financial Reporting Standards (IFRS).|
-The FASB and IASB Boards are working toward converging their standards, based on an agreement reached in 2002 and updated since then.
|Auditor's Opinion||Firms whose common stock is publicly traded are required to get an opinion by an independent auditor who:|
1.Assesses the effectiveness of the firm's internal control system for measuring and reporting business transactions
2.Assesses whether the financial statements and notes present fairly a firm's financial position, results of operations, and cash flows in accordance with generally accepted accounting principles
|Basic Accounting Conventions and Concepts||1. Materiality is the qualitative concept that financial reports need not include items that are so small as to be meaningless to users of the reports.|
2. The accounting period convention refers to the uniform length of accounting reporting periods.
3. Interim reports are often prepared for periods shorter than a year. However, preparing interim reports does not eliminate the need to prepare an annual report.
|Cash vs. Accrual Accounting||Cash basis|
A firm measures performance from selling goods and providing services as it receives cash from customers and makes cash expenditures to providers of goods and services.
A firm recognizes revenue when it sells goods or renders services and recognizes expenses in the period when the firm recognizes the revenues that the costs helped produce.
|What Is an Account? How Do You Name Accounts?||-An account represents an amount on a line of a balance sheet or income statement (i.e., cash, accounts receivable, etc.).|
-There is not a master list to define these accounts since they are customized to fit each specific business's needs.
-Accountants typically follow a conventional naming system for accounts, which increases communication.
|What Accounts Make up the Typical Balance Sheet?|
|Current assets and current liabilities (Balance Sheet Classifications)||Receipt or payment of assets that the firm expects will occur within one year or one operating cycle.|
|Noncurrent assets and noncurrent liabilities (Balance Sheet Classifications)||Firm expects to collect or pay these more than one year after the balance sheet date.|
|Duality Effects of the Balance Sheet Equation (Assets = Liabilites + Shareholders' Equity)||Any single event or transaction will have one of the following four effects or some combination of these effects:|
1.INCREASE an asset and INCREASE either a liability or shareholders' equity.
2.DECREASE an asset and DECREASE either a liability or shareholders' equity.
3.INCREASE one asset and DECREASE another asset.
4.INCREASE one liability or shareholders' equity and DECREASE another liability or shareholders' equity.
A T-account is a device or convention for organizing and accumulating the accounting entries of transactions that affect an individual account, such as Cash, Accounts Receivable, Bonds Payable, or Additional Paid-in Capital.
|T-Account Conventions: Assets|
|T-Account Conventions: Liabilities|
|T-Account Conventions: Shareholders' Equity|
|Debit vs. Credit|
While T-accounts are useful to help analyze how individual transactions flow and accumulate within various accounts, journal entries formalize the reasoning that supports the transaction.
The attached standardized format indicates the accounts and amounts, with debits on the first line and credits (indented) on the second line:
| Revenue or Sales:|
(Common Income Statement Terms)
|Assets received in exchange for goods sold and services rendered.|
| Cost of Goods Sold:|
(Common Income Statement Terms)
|The cost of products sold.|
| Selling, General, and Administrative (SG&A):|
(Common Income Statement Terms)
|Costs incurred to sell products/services as well as costs of administration.|
| Research and Development (R&D) Expense:|
(Common Income Statement Terms)
|Costs incurred to create/develop new products, processes, and services.|
| Interest Income:|
(Common Income Statement Terms)
|Income earned on amounts lent to others or from investments in interest-yielding securities.|
|Unique Relationships Exist Between the Balance Sheet and the Income Statement|
|Important Account Differences||1. Balance sheet accounts are permanent accounts in the sense that they remain open, with nonzero balances, at the end of the reporting period.|
2. In contrast, income statement accounts are temporary accounts in the sense that they start a period with a zero balance, accumulate information during the reporting period, and have a zero balance at the end of the reporting period.
|The Financial Statement Relationships can be summarized as:|
-After preparing the end-of-period income statement, the accountant transfers the balance in each temporary revenue and expense account to the Retained Earnings account.
-This procedure is called closing the revenue and expense accounts. After transferring to Retained Earnings, each revenue and expense account is ready to begin the next period with a zero balance.
|Expense and Revenue Transactions|
|Dividend Declaration and Payment|
|Issues of Capital Stock|
|Posting||1. After each transaction is recognized by a journal entry, the information is transferred in the accounting system via an activity known as posting.|
2. The balance sheet ledger accounts (or permanent accounts) where these are posted begin each period with a balance equal to the ending balance of the previous period.
3.The income statement ledger accounts (or temporary accounts) have zero beginning balances.
|Adjusting Entries|| There are some journal entries that are not triggered by a transaction or exchange.|
-Rather, journal entries known as adjusting entries, result from the passage of time at the end of an accounting period or are used to correct errors (more commonly known as correcting entries).
|Four Basic Types of Adjusting Entries|| 1.Unearned Revenues|
|Closing Process||1. After adjusting and correcting entries are made, the income statement can be prepared.|
2. Once completed, it is time to transfer the balance in each temporary revenue and expense account to the Retained Earnings account. This is known as the closing process.
3. Each revenue account is reduced to zero by debiting it and each expense account is reduced to zero by crediting it.
4. The offset account—Retained Earnings—is credited for the amount of total revenues and debited for the amount of total expenses.
5. Thus, the balance of ending Retained Earnings for a period shows the difference between total revenues and total expenses.
|Preparation of the Balance Sheet||1. After the closing process is completed, the accounts with nonzero balances are all balance sheet accounts.|
2. We can use these accounts to prepare the balance sheet as at the end of the period.
3. The Retained Earnings account will appear with all other balance sheet accounts and now reflects the cumulative effect of transactions affecting that account.
|Final Step in Preparing Financial Statements: The Cash Flow Statement||1. The statement of cash flows describes the sources and uses of cash during a period and classifies them into operating, investing, and financing activities.|
2. It provides a detailed explanation for the change in the balance of the Cash account during that period.
3. Two approaches can be used to prepare this statement: Direct and Indirect
|
// <snippet10>
#using <remotable.dll>
using namespace System;
using namespace System::Runtime::Remoting;
int main()
{
// Set up a remoting client.
RemotingConfiguration::Configure( "Client.config" );
// Call a method on a remote object.
Remotable ^ remoteObject = gcnew Remotable;
Console::WriteLine( remoteObject->GetCount() );
}
// </snippet10>
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/rekognition/model/ProjectDescription.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Rekognition
{
namespace Model
{
ProjectDescription::ProjectDescription() :
m_projectArnHasBeenSet(false),
m_creationTimestampHasBeenSet(false),
m_status(ProjectStatus::NOT_SET),
m_statusHasBeenSet(false)
{
}
ProjectDescription::ProjectDescription(JsonView jsonValue) :
m_projectArnHasBeenSet(false),
m_creationTimestampHasBeenSet(false),
m_status(ProjectStatus::NOT_SET),
m_statusHasBeenSet(false)
{
*this = jsonValue;
}
ProjectDescription& ProjectDescription::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("ProjectArn"))
{
m_projectArn = jsonValue.GetString("ProjectArn");
m_projectArnHasBeenSet = true;
}
if(jsonValue.ValueExists("CreationTimestamp"))
{
m_creationTimestamp = jsonValue.GetDouble("CreationTimestamp");
m_creationTimestampHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = ProjectStatusMapper::GetProjectStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
return *this;
}
JsonValue ProjectDescription::Jsonize() const
{
JsonValue payload;
if(m_projectArnHasBeenSet)
{
payload.WithString("ProjectArn", m_projectArn);
}
if(m_creationTimestampHasBeenSet)
{
payload.WithDouble("CreationTimestamp", m_creationTimestamp.SecondsWithMSPrecision());
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", ProjectStatusMapper::GetNameForProjectStatus(m_status));
}
return payload;
}
} // namespace Model
} // namespace Rekognition
} // namespace Aws
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2019, Perry L Miller IV
// All rights reserved.
// MIT License: https://opensource.org/licenses/mit-license.html
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Test the math functions.
//
////////////////////////////////////////////////////////////////////////////////
#include "Usul/Math/Functions.h"
#include "Usul/Math/Vector2.h"
#include "catch2/catch.hpp"
#include <sstream>
#include <iomanip>
// Pythagorean triples.
// http://mathworld.wolfram.com/PythagoreanTriple.html
const unsigned int numPythagoreanTriples = 4;
const unsigned char pythagoreanTriples[numPythagoreanTriples][4] = {
{ 3, 4, 5 },
{ 5, 12, 13 },
{ 8, 15, 17 },
{ 7, 24, 25 }
};
////////////////////////////////////////////////////////////////////////////////
//
// Helper function to check the length.
//
////////////////////////////////////////////////////////////////////////////////
template < class ScalarType > inline void checkLength (
ScalarType v0, ScalarType v1, ScalarType len )
{
typedef typename Usul::Math::Vector2 < ScalarType > VectorType;
REQUIRE ( len == Usul::Math::length ( VectorType ( v0, v1 ) ) );
}
////////////////////////////////////////////////////////////////////////////////
//
// Helper function to check the angle between two vectors.
//
////////////////////////////////////////////////////////////////////////////////
template < class VectorType >
inline void testAngle ( const VectorType &a, const VectorType &b,
const typename VectorType::value_type &expected, unsigned int numDecimals )
{
REQUIRE ( expected == Usul::Math::trunc ( Usul::Math::radToDeg ( Usul::Math::angle ( a, b ) ), numDecimals ) );
}
////////////////////////////////////////////////////////////////////////////////
//
// Test the math functions.
//
////////////////////////////////////////////////////////////////////////////////
#ifdef __GNUC__
TEMPLATE_TEST_CASE ( "Vector2 template math functions with all primitive types", "",
int, long, ( unsigned int ), ( unsigned long ),
float, double, ( long double ) )
#else
TEMPLATE_TEST_CASE ( "Vector2 template math functions with all primitive types", "",
char, short, ( unsigned char ), ( unsigned short ),
int, long, ( unsigned int ), ( unsigned long ),
float, double, ( long double ) )
#endif
{
typedef typename Usul::Math::Vector2 < TestType > VectorType;
SECTION ( "Default constructor works" )
{
const VectorType a;
REQUIRE ( 0 == a[0] );
REQUIRE ( 0 == a[1] );
}
SECTION ( "Constructor that takes 3 values works" )
{
const VectorType a ( 1, 2 );
REQUIRE ( 1 == a[0] );
REQUIRE ( 2 == a[1] );
}
SECTION ( "Constructor that takes an array works" )
{
const VectorType a ( { 1, 2 } );
REQUIRE ( 1 == a[0] );
REQUIRE ( 2 == a[1] );
}
SECTION ( "Default copy constructor works" )
{
VectorType a ( 1, 2 );
const VectorType b ( a ); // Copy constructor.
// Should be the same.
REQUIRE ( a[0] == b[0] );
REQUIRE ( a[1] == b[1] );
// Is it different memory?
a[0] = 4; // Changing one value.
REQUIRE ( 4 == a[0] ); // It should be different.
REQUIRE ( 1 == b[0] ); // It should be original value.
}
SECTION ( "Can call a function for all values" )
{
unsigned int count = 0;
Usul::Math::each ( VectorType ( 1, 2 ), [&] ( TestType value )
{
++count;
// Need the static cast here to satisfy strict warnings.
// Not making count a TestType because I want to make sure
// a reliable interger type is being incremented.
REQUIRE ( ( static_cast < TestType > ( count ) ) == value );
} );
REQUIRE ( VectorType::SIZE == count );
}
SECTION ( "Equal vectors are equal" )
{
REQUIRE ( true == Usul::Math::equal ( VectorType ( 1, 2 ), VectorType ( 1, 2 ) ) );
}
SECTION ( "Different vectors are not equal" )
{
VectorType a ( 1, 2 );
REQUIRE ( false == Usul::Math::equal ( a, VectorType ( 3, 2 ) ) );
REQUIRE ( false == Usul::Math::equal ( a, VectorType ( 1, 3 ) ) );
REQUIRE ( false == Usul::Math::equal ( a, VectorType ( 4, 5 ) ) );
}
SECTION ( "Can scale a vector" )
{
const VectorType a ( 1, 2 );
const TestType scale ( static_cast < TestType > ( 10 ) );
VectorType b;
Usul::Math::scale ( a, scale, b );
REQUIRE ( 10 == b[0] );
REQUIRE ( 20 == b[1] );
const VectorType c = Usul::Math::scale ( a, scale );
REQUIRE ( 10 == c[0] );
REQUIRE ( 20 == c[1] );
}
SECTION ( "Assigning is making a copy" )
{
VectorType a ( 1, 2 );
VectorType b;
b = a; // Assignment operator.
// Should be the same.
REQUIRE ( a[0] == b[0] );
REQUIRE ( a[1] == b[1] );
// Is it different memory?
a[0] = 4; // Changing one value.
REQUIRE ( 4 == a[0] ); // It should be different.
REQUIRE ( 1 == b[0] ); // It should be original value.
}
SECTION ( "Setter functions work" )
{
VectorType a;
REQUIRE ( 0 == a[0] );
REQUIRE ( 0 == a[1] );
a.set ( VectorType ( 1, 2 ) );
REQUIRE ( 1 == a[0] );
REQUIRE ( 2 == a[1] );
a.set ( { 4, 5 } );
REQUIRE ( 4 == a[0] );
REQUIRE ( 5 == a[1] );
a.set ( 7, 8 );
REQUIRE ( 7 == a[0] );
REQUIRE ( 8 == a[1] );
}
SECTION ( "Can add two vectors" )
{
const VectorType a ( 1, 2 );
const VectorType b ( 4, 5 );
VectorType c;
Usul::Math::add ( a, b, c );
REQUIRE ( 5 == c[0] );
REQUIRE ( 7 == c[1] );
const VectorType d = Usul::Math::add ( a, b );
REQUIRE ( 5 == d[0] );
REQUIRE ( 7 == d[1] );
const VectorType e = a + b;
REQUIRE ( 5 == e[0] );
REQUIRE ( 7 == e[1] );
}
SECTION ( "Can subtract two vectors" )
{
const VectorType a ( 4, 5 );
const VectorType b ( 1, 2 );
VectorType c;
Usul::Math::subtract ( a, b, c );
REQUIRE ( 3 == c[0] );
REQUIRE ( 3 == c[1] );
const VectorType d = Usul::Math::subtract ( a, b );
REQUIRE ( 3 == d[0] );
REQUIRE ( 3 == d[1] );
const VectorType e = a - b;
REQUIRE ( 3 == e[0] );
REQUIRE ( 3 == e[1] );
}
SECTION ( "Can scale a vector" )
{
const VectorType a ( 1, 2 );
const TestType scale ( static_cast < TestType> ( 10 ) );
VectorType b;
Usul::Math::scale ( a, scale, b );
REQUIRE ( 10 == b[0] );
REQUIRE ( 20 == b[1] );
const VectorType c = Usul::Math::scale ( a, scale );
REQUIRE ( 10 == c[0] );
REQUIRE ( 20 == c[1] );
const VectorType d = a * scale;
REQUIRE ( 10 == d[0] );
REQUIRE ( 20 == d[1] );
}
SECTION ( "Can get the dot product" )
{
REQUIRE ( 11 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( 3, 4 ) ) );
REQUIRE ( 14 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( 4, 5 ) ) );
REQUIRE ( 17 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( 5, 6 ) ) );
}
SECTION ( "Can get the distance squared between two points" )
{
REQUIRE ( 8 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 2, 2 ) ) );
REQUIRE ( 18 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 3, 3 ) ) );
REQUIRE ( 18 == Usul::Math::distanceSquared ( VectorType ( 1, 2 ), VectorType ( 4, 5 ) ) );
REQUIRE ( 32 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 4, 4 ) ) );
REQUIRE ( 50 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 5, 5 ) ) );
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Test the math functions.
//
////////////////////////////////////////////////////////////////////////////////
#ifdef __GNUC__
TEMPLATE_TEST_CASE ( "Vector2 template math functions with signed primitive types", "",
int, long, float, double, ( long double ) )
#else
TEMPLATE_TEST_CASE ( "Vector2 template math functions with signed primitive types", "",
short,
int, long, float, double, ( long double ) )
#endif
{
typedef typename Usul::Math::Vector2 < TestType > VectorType;
SECTION ( "Can get the absolute value of a vector" )
{
const VectorType a ( 1, 2 );
const VectorType b ( -1, -2 );
REQUIRE ( false == Usul::Math::equal ( a, b ) );
REQUIRE ( true == Usul::Math::equal ( a, Usul::Math::absolute ( b ) ) );
}
SECTION ( "Can get the dot product" )
{
REQUIRE ( -11 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( -3, -4 ) ) );
REQUIRE ( -14 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( -4, -5 ) ) );
REQUIRE ( -17 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( -5, -6 ) ) );
}
SECTION ( "Can get the distance squared between two points" )
{
REQUIRE ( 18 == Usul::Math::distanceSquared(VectorType ( -1, -1 ), VectorType ( 2, 2 ) ) );
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Test the math functions.
//
////////////////////////////////////////////////////////////////////////////////
TEMPLATE_TEST_CASE ( "Vector2 template math functions with floating point types", "",
float, double, ( long double ) )
{
typedef typename Usul::Math::Vector2 < TestType > VectorType;
SECTION ( "Can get the length" )
{
checkLength < TestType > ( 3, 4, 5 );
checkLength < TestType > ( 5, 12, 13 );
checkLength < TestType > ( 8, 15, 17 );
checkLength < TestType > ( 7, 24, 25 );
}
SECTION ( "Can get the length of pythagorean quadruples" )
{
// Test all pythagorean quadruples.
for ( unsigned int i = 0; i < numPythagoreanTriples; ++i )
{
const auto q = pythagoreanTriples[i];
checkLength (
static_cast < TestType > ( q[0] ),
static_cast < TestType > ( q[1] ),
static_cast < TestType > ( q[2] )
);
}
}
SECTION ( "Can normalize" )
{
// They are almost never exact so we have to convert to a string to compare.
auto isUnitLength = [] ( const VectorType &v )
{
const TestType len = Usul::Math::length ( v );
std::ostringstream s;
s << len;
REQUIRE ( "1" == s.str() );
};
// Test all pythagorean quadruples.
for ( unsigned int i = 0; i < numPythagoreanTriples; ++i )
{
const auto q = pythagoreanTriples[i];
const VectorType a (
static_cast < TestType > ( q[0] ),
static_cast < TestType > ( q[1] )
);
const TestType len = static_cast < TestType > ( q[2] );
REQUIRE ( len == Usul::Math::length ( a ) );
// We want the original length.
VectorType b;
TestType originalLength = 0;
Usul::Math::normalize ( a, b, &originalLength );
REQUIRE ( len == originalLength );
isUnitLength ( b );
// We do not want the original length.
VectorType c;
Usul::Math::normalize ( a, c );
isUnitLength ( c );
// We want a new vector.
const VectorType d = Usul::Math::normalize ( a );
REQUIRE ( len == Usul::Math::length ( a ) );
isUnitLength ( d );
}
}
SECTION ( "Can get the distance between two points" )
{
const VectorType a ( 1, 2 );
const VectorType b ( 3, 4 );
// Got the answer from here using "distance between two points":
// https://www.wolframalpha.com
const std::string expected ( "2.82843" );
// We need the answer with only so many decimals.
std::ostringstream answer;
answer << std::fixed << std::setprecision ( 5 )
<< Usul::Math::distance ( a, b );
REQUIRE ( expected == answer.str() );
}
}
TEST_CASE ( "Angle between two vectors" )
{
SECTION ( "Can get the angle between two vectors of floats" )
{
typedef float TestType;
typedef typename Usul::Math::Vector2 < TestType > VectorType;
testAngle ( VectorType ( 5, 24 ), VectorType ( 1, 3 ),
static_cast < TestType > ( 6.6666 ), 4 );
}
SECTION ( "Can get the angle between two vectors of doubles" )
{
typedef double TestType;
typedef typename Usul::Math::Vector2 < TestType > VectorType;
testAngle ( VectorType ( 5, 24 ), VectorType ( 1, 3 ),
static_cast < TestType > ( 6.66665989 ), 8 );
}
// SECTION ( "Can get the angle between two vectors of long doubles" )
// {
// typedef long double TestType;
// typedef typename Usul::Math::Vector2 < TestType > VectorType;
//
// // Why doesn't this one work?
// testAngle ( VectorType ( 5, 24 ), VectorType ( 1, 3 ),
// static_cast < TestType > ( 6.66665989 ), 8 );
// }
}
|
#ifndef __GSTL_SAMPLER_UPDATER_SAMPLER_H__
#define __GSTL_SAMPLER_UPDATER_SAMPLER_H__
/** Updater_sampler is a model of concept Sampler.
* An Updater_sampler first updates the ccdf before sampling it.
* The update can be local, ie dependent on the geovalue where
* the sampling is performed.
* \c local_cdf_updater is a model of BinaryFunction that has the
* following signature:
* cdf_type binary_function( const geovalue&, const cdf_type& ).
* \c sampler is a model of concept Sampler.
*/
template <class BinaryFunction, class Sampler_>
class Updater_sampler {
public:
Updater_sampler( BinaryFunction local_cdf_updater,
Sampler_& sampler )
: local_cdf_updater_( local_cdf_updater ),
sampler_( sampler ) {
}
int operator() ( typename BinaryFunction::first_argument& g,
const typename BinaryFunction::second_argument& cdf ) {
return sampler_( g, local_cdf_updater_( g, cdf ) );
}
private:
BinaryFunction local_cdf_updater_;
Sampler_ sampler_;
};
#endif
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/imagebuilder/Imagebuilder_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace imagebuilder
{
namespace Model
{
/**
* <p>Identifies an Amazon EC2 launch template to use for a specific
* account.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/LaunchTemplateConfiguration">AWS
* API Reference</a></p>
*/
class AWS_IMAGEBUILDER_API LaunchTemplateConfiguration
{
public:
LaunchTemplateConfiguration();
LaunchTemplateConfiguration(Aws::Utils::Json::JsonView jsonValue);
LaunchTemplateConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline const Aws::String& GetLaunchTemplateId() const{ return m_launchTemplateId; }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline bool LaunchTemplateIdHasBeenSet() const { return m_launchTemplateIdHasBeenSet; }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline void SetLaunchTemplateId(const Aws::String& value) { m_launchTemplateIdHasBeenSet = true; m_launchTemplateId = value; }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline void SetLaunchTemplateId(Aws::String&& value) { m_launchTemplateIdHasBeenSet = true; m_launchTemplateId = std::move(value); }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline void SetLaunchTemplateId(const char* value) { m_launchTemplateIdHasBeenSet = true; m_launchTemplateId.assign(value); }
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline LaunchTemplateConfiguration& WithLaunchTemplateId(const Aws::String& value) { SetLaunchTemplateId(value); return *this;}
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline LaunchTemplateConfiguration& WithLaunchTemplateId(Aws::String&& value) { SetLaunchTemplateId(std::move(value)); return *this;}
/**
* <p>Identifies the Amazon EC2 launch template to use.</p>
*/
inline LaunchTemplateConfiguration& WithLaunchTemplateId(const char* value) { SetLaunchTemplateId(value); return *this;}
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline const Aws::String& GetAccountId() const{ return m_accountId; }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline bool AccountIdHasBeenSet() const { return m_accountIdHasBeenSet; }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline void SetAccountId(const Aws::String& value) { m_accountIdHasBeenSet = true; m_accountId = value; }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline void SetAccountId(Aws::String&& value) { m_accountIdHasBeenSet = true; m_accountId = std::move(value); }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline void SetAccountId(const char* value) { m_accountIdHasBeenSet = true; m_accountId.assign(value); }
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline LaunchTemplateConfiguration& WithAccountId(const Aws::String& value) { SetAccountId(value); return *this;}
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline LaunchTemplateConfiguration& WithAccountId(Aws::String&& value) { SetAccountId(std::move(value)); return *this;}
/**
* <p>The account ID that this configuration applies to.</p>
*/
inline LaunchTemplateConfiguration& WithAccountId(const char* value) { SetAccountId(value); return *this;}
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline bool GetSetDefaultVersion() const{ return m_setDefaultVersion; }
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline bool SetDefaultVersionHasBeenSet() const { return m_setDefaultVersionHasBeenSet; }
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline void SetSetDefaultVersion(bool value) { m_setDefaultVersionHasBeenSet = true; m_setDefaultVersion = value; }
/**
* <p>Set the specified Amazon EC2 launch template as the default launch template
* for the specified account.</p>
*/
inline LaunchTemplateConfiguration& WithSetDefaultVersion(bool value) { SetSetDefaultVersion(value); return *this;}
private:
Aws::String m_launchTemplateId;
bool m_launchTemplateIdHasBeenSet;
Aws::String m_accountId;
bool m_accountIdHasBeenSet;
bool m_setDefaultVersion;
bool m_setDefaultVersionHasBeenSet;
};
} // namespace Model
} // namespace imagebuilder
} // namespace Aws
|
What is an estimate?
“An 'Estimate' is a computer-generated approximation of a property's market value calculated by means of the Automated Value Model (AVM). As such, an Estimate is calculated on the basis of:
- Publicly available tax assessment records for the property
- Recent sale prices of comparable properties in the same area
There are many additional factors that determine a property's actual market value, including its condition, house style, layout, special features, quality of workmanship, and so on. For this reason, an Estimate should not be viewed as an appraisal, but rather as an approximate basis for making comparisons, and as a starting point for further inquiry. A REALTOR® who specializes in the given area will be able to provide a more accurate valuation based upon current market trends, as well as specific property and neighborhood characteristics.”
In some parts of the country, Realtor.com does not have access to public records data or the available estimates are not considered accurate. In these instances, the company does not display an estimated value.
|
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "../executor_for_test.h"
#include "../test_include.h"
#include "operators/im2sequence_op.h"
int main() {
paddle_mobile::Loader<paddle_mobile::CPU> loader;
auto program = loader.Load(g_ocr_recg);
PADDLE_MOBILE_ENFORCE(program.originProgram != nullptr,
"program file read fail");
Executor4Test<paddle_mobile::CPU,
paddle_mobile::operators::ReluOp<paddle_mobile::CPU, float>>
executor(program, "im2sequence");
// 1. input_tensors;
vector<Tensor> input_tensors;
Tensor input1;
auto input1_data = CreateInput<float>(&input1, {2, 2, 3, 3}, -1, 1);
input_tensors.push_back(input1);
// 2. input_names
vector<string> input_names({
"conv2d_19.tmp_1",
});
// 3. output_names
vector<string> output_names({"im2sequence_0.tmp_0"});
// 4. out_dims;
vector<DDim> out_ddims;
auto out_ddim = paddle_mobile::framework::make_ddim({8, 9});
out_ddims.push_back(out_ddim);
auto output = executor.Predict<LoDTensor>(input_tensors, input_names,
output_names, out_ddims);
auto output0_data = output[0]->data<float>();
for (int j = 0; j < input_tensors[0].numel(); ++j) {
DLOG << " value of input: " << input1_data[j];
}
for (int j = 0; j < output[0]->numel(); ++j) {
DLOG << " value of output: " << output0_data[j];
}
return 0;
}
|
/*
* Copyright (c) 2014 - 2015, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <utils/constants.h>
#include <utils/debug.h>
#include "display_base.h"
#include "hw_info_interface.h"
#define __CLASS__ "DisplayBase"
namespace sdm {
// TODO(user): Have a single structure handle carries all the interface pointers and variables.
DisplayBase::DisplayBase(DisplayType display_type, DisplayEventHandler *event_handler,
HWDeviceType hw_device_type, BufferSyncHandler *buffer_sync_handler,
CompManager *comp_manager, RotatorInterface *rotator_intf,
HWInfoInterface *hw_info_intf)
: display_type_(display_type), event_handler_(event_handler), hw_device_type_(hw_device_type),
buffer_sync_handler_(buffer_sync_handler), comp_manager_(comp_manager),
rotator_intf_(rotator_intf), state_(kStateOff), hw_device_(0), display_comp_ctx_(0),
display_attributes_(NULL), num_modes_(0), active_mode_index_(0), pending_commit_(false),
vsync_enable_(false), underscan_supported_(false), max_mixer_stages_(0),
hw_info_intf_(hw_info_intf), color_mgr_(NULL) {
}
DisplayError DisplayBase::Init() {
DisplayError error = kErrorNone;
hw_panel_info_ = HWPanelInfo();
hw_intf_->GetHWPanelInfo(&hw_panel_info_);
error = hw_intf_->GetNumDisplayAttributes(&num_modes_);
if (error != kErrorNone) {
goto CleanupOnError;
}
display_attributes_ = new HWDisplayAttributes[num_modes_];
if (!display_attributes_) {
error = kErrorMemory;
goto CleanupOnError;
}
for (uint32_t i = 0; i < num_modes_; i++) {
error = hw_intf_->GetDisplayAttributes(&display_attributes_[i], i);
if (error != kErrorNone) {
goto CleanupOnError;
}
}
active_mode_index_ = GetBestConfig();
error = hw_intf_->SetDisplayAttributes(active_mode_index_);
if (error != kErrorNone) {
goto CleanupOnError;
}
error = comp_manager_->RegisterDisplay(display_type_, display_attributes_[active_mode_index_],
hw_panel_info_, &display_comp_ctx_);
if (error != kErrorNone) {
goto CleanupOnError;
}
if (rotator_intf_) {
error = rotator_intf_->RegisterDisplay(display_type_, &display_rotator_ctx_);
if (error != kErrorNone) {
goto CleanupOnError;
}
}
if (hw_info_intf_) {
HWResourceInfo hw_resource_info = HWResourceInfo();
hw_info_intf_->GetHWResourceInfo(&hw_resource_info);
int max_mixer_stages = hw_resource_info.num_blending_stages;
int property_value = Debug::GetMaxPipesPerMixer(display_type_);
if (property_value >= 0) {
max_mixer_stages = MIN(UINT32(property_value), hw_resource_info.num_blending_stages);
}
DisplayBase::SetMaxMixerStages(max_mixer_stages);
}
color_mgr_ = ColorManagerProxy::CreateColorManagerProxy(display_type_, hw_intf_,
display_attributes_[active_mode_index_], hw_panel_info_);
if (!color_mgr_) {
DLOGW("Unable to create ColorManagerProxy for display = %d", display_type_);
}
return kErrorNone;
CleanupOnError:
if (display_comp_ctx_) {
comp_manager_->UnregisterDisplay(display_comp_ctx_);
}
if (display_attributes_) {
delete[] display_attributes_;
display_attributes_ = NULL;
}
hw_intf_->Close();
return error;
}
DisplayError DisplayBase::Deinit() {
if (rotator_intf_) {
rotator_intf_->UnregisterDisplay(display_rotator_ctx_);
}
if (color_mgr_) {
delete color_mgr_;
color_mgr_ = NULL;
}
comp_manager_->UnregisterDisplay(display_comp_ctx_);
if (display_attributes_) {
delete[] display_attributes_;
display_attributes_ = NULL;
}
hw_intf_->Close();
return kErrorNone;
}
DisplayError DisplayBase::Prepare(LayerStack *layer_stack) {
DisplayError error = kErrorNone;
if (!layer_stack) {
return kErrorParameters;
}
pending_commit_ = false;
if (state_ == kStateOn) {
// Clean hw layers for reuse.
hw_layers_.info = HWLayersInfo();
hw_layers_.info.stack = layer_stack;
hw_layers_.output_compression = 1.0f;
comp_manager_->PrePrepare(display_comp_ctx_, &hw_layers_);
while (true) {
error = comp_manager_->Prepare(display_comp_ctx_, &hw_layers_);
if (error != kErrorNone) {
break;
}
if (IsRotationRequired(&hw_layers_)) {
if (!rotator_intf_) {
continue;
}
error = rotator_intf_->Prepare(display_rotator_ctx_, &hw_layers_);
} else {
// Release all the previous rotator sessions.
if (rotator_intf_) {
error = rotator_intf_->Purge(display_rotator_ctx_, &hw_layers_);
}
}
if (error == kErrorNone) {
error = hw_intf_->Validate(&hw_layers_);
if (error == kErrorNone) {
// Strategy is successful now, wait for Commit().
pending_commit_ = true;
break;
}
}
}
comp_manager_->PostPrepare(display_comp_ctx_, &hw_layers_);
} else {
return kErrorNotSupported;
}
return error;
}
DisplayError DisplayBase::Commit(LayerStack *layer_stack) {
DisplayError error = kErrorNone;
if (!layer_stack) {
return kErrorParameters;
}
if (state_ != kStateOn) {
return kErrorNotSupported;
}
if (!pending_commit_) {
DLOGE("Commit: Corresponding Prepare() is not called for display = %d", display_type_);
return kErrorUndefined;
}
pending_commit_ = false;
// Layer stack attributes has changed, need to Reconfigure, currently in use for Hybrid Comp
if (layer_stack->flags.attributes_changed) {
error = comp_manager_->ReConfigure(display_comp_ctx_, &hw_layers_);
if (error != kErrorNone) {
return error;
}
error = hw_intf_->Validate(&hw_layers_);
if (error != kErrorNone) {
return error;
}
}
if (rotator_intf_ && IsRotationRequired(&hw_layers_)) {
error = rotator_intf_->Commit(display_rotator_ctx_, &hw_layers_);
if (error != kErrorNone) {
return error;
}
}
// check if feature list cache is dirty and pending.
// If dirty, need program to hardware blocks.
if (color_mgr_)
error = color_mgr_->Commit();
if (error != kErrorNone) { // won't affect this execution path.
DLOGW("ColorManager::Commit(...) isn't working");
}
error = hw_intf_->Commit(&hw_layers_);
if (error != kErrorNone) {
return error;
}
if (rotator_intf_ && IsRotationRequired(&hw_layers_)) {
error = rotator_intf_->PostCommit(display_rotator_ctx_, &hw_layers_);
if (error != kErrorNone) {
return error;
}
}
error = comp_manager_->PostCommit(display_comp_ctx_, &hw_layers_);
if (error != kErrorNone) {
return error;
}
return kErrorNone;
}
DisplayError DisplayBase::Flush() {
DisplayError error = kErrorNone;
if (state_ != kStateOn) {
return kErrorNone;
}
hw_layers_.info.count = 0;
error = hw_intf_->Flush();
if (error == kErrorNone) {
comp_manager_->Purge(display_comp_ctx_);
pending_commit_ = false;
} else {
DLOGV("Failed to flush device.");
}
return error;
}
DisplayError DisplayBase::GetDisplayState(DisplayState *state) {
if (!state) {
return kErrorParameters;
}
*state = state_;
return kErrorNone;
}
DisplayError DisplayBase::GetNumVariableInfoConfigs(uint32_t *count) {
if (!count) {
return kErrorParameters;
}
*count = num_modes_;
return kErrorNone;
}
DisplayError DisplayBase::GetConfig(DisplayConfigFixedInfo *fixed_info) {
if (!fixed_info) {
return kErrorParameters;
}
return kErrorNone;
}
DisplayError DisplayBase::GetConfig(uint32_t index, DisplayConfigVariableInfo *variable_info) {
if (!variable_info || index >= num_modes_) {
return kErrorParameters;
}
*variable_info = display_attributes_[index];
return kErrorNone;
}
DisplayError DisplayBase::GetActiveConfig(uint32_t *index) {
if (!index) {
return kErrorParameters;
}
*index = active_mode_index_;
return kErrorNone;
}
DisplayError DisplayBase::GetVSyncState(bool *enabled) {
if (!enabled) {
return kErrorParameters;
}
return kErrorNone;
}
bool DisplayBase::IsUnderscanSupported() {
return underscan_supported_;
}
DisplayError DisplayBase::SetDisplayState(DisplayState state) {
DisplayError error = kErrorNone;
DLOGI("Set state = %d, display %d", state, display_type_);
if (state == state_) {
DLOGI("Same state transition is requested.");
return kErrorNone;
}
switch (state) {
case kStateOff:
hw_layers_.info.count = 0;
error = hw_intf_->Flush();
if (error == kErrorNone) {
comp_manager_->Purge(display_comp_ctx_);
error = hw_intf_->PowerOff();
}
break;
case kStateOn:
error = hw_intf_->PowerOn();
break;
case kStateDoze:
error = hw_intf_->Doze();
break;
case kStateDozeSuspend:
error = hw_intf_->DozeSuspend();
break;
case kStateStandby:
error = hw_intf_->Standby();
break;
default:
DLOGE("Spurious state = %d transition requested.", state);
break;
}
if (error == kErrorNone) {
state_ = state;
}
return error;
}
DisplayError DisplayBase::SetActiveConfig(uint32_t index) {
DisplayError error = kErrorNone;
if (index >= num_modes_) {
return kErrorParameters;
}
error = hw_intf_->SetDisplayAttributes(index);
if (error != kErrorNone) {
return error;
}
active_mode_index_ = index;
if (display_comp_ctx_) {
comp_manager_->UnregisterDisplay(display_comp_ctx_);
}
error = comp_manager_->RegisterDisplay(display_type_, display_attributes_[index], hw_panel_info_,
&display_comp_ctx_);
return error;
}
DisplayError DisplayBase::SetMaxMixerStages(uint32_t max_mixer_stages) {
DisplayError error = kErrorNone;
if (comp_manager_) {
error = comp_manager_->SetMaxMixerStages(display_comp_ctx_, max_mixer_stages);
if (error == kErrorNone) {
max_mixer_stages_ = max_mixer_stages;
}
}
return error;
}
DisplayError DisplayBase::SetDisplayMode(uint32_t mode) {
return kErrorNotSupported;
}
DisplayError DisplayBase::IsScalingValid(const LayerRect &crop, const LayerRect &dst,
bool rotate90) {
return comp_manager_->ValidateScaling(crop, dst, rotate90);
}
void DisplayBase::AppendDump(char *buffer, uint32_t length) {
DumpImpl::AppendString(buffer, length, "\n-----------------------");
DumpImpl::AppendString(buffer, length, "\ndevice type: %u", display_type_);
DumpImpl::AppendString(buffer, length, "\nstate: %u, vsync on: %u, max. mixer stages: %u",
state_, INT(vsync_enable_), max_mixer_stages_);
DumpImpl::AppendString(buffer, length, "\nnum configs: %u, active config index: %u",
num_modes_, active_mode_index_);
DisplayConfigVariableInfo &info = display_attributes_[active_mode_index_];
DumpImpl::AppendString(buffer, length, "\nres:%u x %u, dpi:%.2f x %.2f, fps:%.2f,"
"vsync period: %u", info.x_pixels, info.y_pixels, info.x_dpi,
info.y_dpi, info.fps, info.vsync_period_ns);
DumpImpl::AppendString(buffer, length, "\n");
uint32_t num_layers = 0;
uint32_t num_hw_layers = 0;
if (hw_layers_.info.stack) {
num_layers = hw_layers_.info.stack->layer_count;
num_hw_layers = hw_layers_.info.count;
}
if (num_hw_layers == 0) {
DumpImpl::AppendString(buffer, length, "\nNo hardware layers programmed");
return;
}
HWLayersInfo &layer_info = hw_layers_.info;
LayerRect &l_roi = layer_info.left_partial_update;
LayerRect &r_roi = layer_info.right_partial_update;
DumpImpl::AppendString(buffer, length, "\nROI(L T R B) : LEFT(%d %d %d %d), RIGHT(%d %d %d %d)",
INT(l_roi.left), INT(l_roi.top), INT(l_roi.right), INT(l_roi.bottom),
INT(r_roi.left), INT(r_roi.top), INT(r_roi.right), INT(r_roi.bottom));
const char *header = "\n| Idx | Comp Type | Split | WB | Pipe | W x H | Format | Src Rect (L T R B) | Dst Rect (L T R B) | Z | Flags | Deci(HxV) |"; //NOLINT
const char *newline = "\n|-----|-------------|--------|----|-------|-------------|--------------------|---------------------|---------------------|----|------------|-----------|"; //NOLINT
const char *format = "\n| %3s | %11s " "| %6s " "| %2s | 0x%03x | %4d x %4d | %18s " "| %4d %4d %4d %4d " "| %4d %4d %4d %4d " "| %2s | %10s " "| %9s |"; //NOLINT
DumpImpl::AppendString(buffer, length, "\n");
DumpImpl::AppendString(buffer, length, newline);
DumpImpl::AppendString(buffer, length, header);
DumpImpl::AppendString(buffer, length, newline);
for (uint32_t i = 0; i < num_hw_layers; i++) {
uint32_t layer_index = hw_layers_.info.index[i];
Layer &layer = hw_layers_.info.stack->layers[layer_index];
LayerBuffer *input_buffer = layer.input_buffer;
HWLayerConfig &layer_config = hw_layers_.config[i];
HWRotatorSession &hw_rotator_session = layer_config.hw_rotator_session;
char idx[8] = { 0 };
const char *comp_type = GetName(layer.composition);
const char *buffer_format = GetName(input_buffer->format);
const char *rotate_split[2] = { "Rot-L", "Rot-R" };
const char *comp_split[2] = { "Comp-L", "Comp-R" };
snprintf(idx, sizeof(idx), "%d", layer_index);
for (uint32_t count = 0; count < hw_rotator_session.hw_block_count; count++) {
char writeback_id[8];
HWRotateInfo &rotate = hw_rotator_session.hw_rotate_info[count];
LayerRect &src_roi = rotate.src_roi;
LayerRect &dst_roi = rotate.dst_roi;
snprintf(writeback_id, sizeof(writeback_id), "%d", rotate.writeback_id);
DumpImpl::AppendString(buffer, length, format, idx, comp_type, rotate_split[count],
writeback_id, rotate.pipe_id, input_buffer->width,
input_buffer->height, buffer_format, INT(src_roi.left),
INT(src_roi.top), INT(src_roi.right), INT(src_roi.bottom),
INT(dst_roi.left), INT(dst_roi.top), INT(dst_roi.right),
INT(dst_roi.bottom), "-", "- ", "- ");
// print the below only once per layer block, fill with spaces for rest.
idx[0] = 0;
comp_type = "";
}
if (hw_rotator_session.hw_block_count > 0) {
input_buffer = &hw_rotator_session.output_buffer;
buffer_format = GetName(input_buffer->format);
}
for (uint32_t count = 0; count < 2; count++) {
char decimation[16];
char flags[16];
char z_order[8];
HWPipeInfo &pipe = (count == 0) ? layer_config.left_pipe : layer_config.right_pipe;
if (!pipe.valid) {
continue;
}
LayerRect &src_roi = pipe.src_roi;
LayerRect &dst_roi = pipe.dst_roi;
snprintf(z_order, sizeof(z_order), "%d", pipe.z_order);
snprintf(flags, sizeof(flags), "0x%08x", layer.flags.flags);
snprintf(decimation, sizeof(decimation), "%3d x %3d", pipe.horizontal_decimation,
pipe.vertical_decimation);
DumpImpl::AppendString(buffer, length, format, idx, comp_type, comp_split[count],
"-", pipe.pipe_id, input_buffer->width, input_buffer->height,
buffer_format, INT(src_roi.left), INT(src_roi.top),
INT(src_roi.right), INT(src_roi.bottom), INT(dst_roi.left),
INT(dst_roi.top), INT(dst_roi.right), INT(dst_roi.bottom),
z_order, flags, decimation);
// print the below only once per layer block, fill with spaces for rest.
idx[0] = 0;
comp_type = "";
}
DumpImpl::AppendString(buffer, length, newline);
}
}
int DisplayBase::GetBestConfig() {
return (num_modes_ == 1) ? 0 : -1;
}
bool DisplayBase::IsRotationRequired(HWLayers *hw_layers) {
HWLayersInfo &layer_info = hw_layers->info;
for (uint32_t i = 0; i < layer_info.count; i++) {
Layer& layer = layer_info.stack->layers[layer_info.index[i]];
HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session;
if (hw_rotator_session->hw_block_count) {
return true;
}
}
return false;
}
const char * DisplayBase::GetName(const LayerComposition &composition) {
switch (composition) {
case kCompositionGPU: return "GPU";
case kCompositionSDE: return "SDE";
case kCompositionHybrid: return "HYBRID";
case kCompositionBlit: return "BLIT";
case kCompositionGPUTarget: return "GPU_TARGET";
case kCompositionBlitTarget: return "BLIT_TARGET";
default: return "UNKNOWN";
}
}
const char * DisplayBase::GetName(const LayerBufferFormat &format) {
switch (format) {
case kFormatARGB8888: return "ARGB_8888";
case kFormatRGBA8888: return "RGBA_8888";
case kFormatBGRA8888: return "BGRA_8888";
case kFormatXRGB8888: return "XRGB_8888";
case kFormatRGBX8888: return "RGBX_8888";
case kFormatBGRX8888: return "BGRX_8888";
case kFormatRGBA5551: return "RGBA_5551";
case kFormatRGBA4444: return "RGBA_4444";
case kFormatRGB888: return "RGB_888";
case kFormatBGR888: return "BGR_888";
case kFormatRGB565: return "RGB_565";
case kFormatRGBA8888Ubwc: return "RGBA_8888_UBWC";
case kFormatRGBX8888Ubwc: return "RGBX_8888_UBWC";
case kFormatRGB565Ubwc: return "RGB_565_UBWC";
case kFormatYCbCr420Planar: return "Y_CB_CR_420";
case kFormatYCrCb420Planar: return "Y_CR_CB_420";
case kFormatYCbCr420SemiPlanar: return "Y_CBCR_420";
case kFormatYCrCb420SemiPlanar: return "Y_CRCB_420";
case kFormatYCbCr420SemiPlanarVenus: return "Y_CBCR_420_VENUS";
case kFormatYCbCr422H1V2SemiPlanar: return "Y_CBCR_422_H1V2";
case kFormatYCrCb422H1V2SemiPlanar: return "Y_CRCB_422_H1V2";
case kFormatYCbCr422H2V1SemiPlanar: return "Y_CBCR_422_H2V1";
case kFormatYCrCb422H2V1SemiPlanar: return "Y_CRCB_422_H2V2";
case kFormatYCbCr420SPVenusUbwc: return "Y_CBCR_420_VENUS_UBWC";
case kFormatYCbCr422H2V1Packed: return "YCBYCR_422_H2V1";
default: return "UNKNOWN";
}
}
DisplayError DisplayBase::ColorSVCRequestRoute(const PPDisplayAPIPayload &in_payload,
PPDisplayAPIPayload *out_payload,
PPPendingParams *pending_action) {
if (color_mgr_)
return color_mgr_->ColorSVCRequestRoute(in_payload, out_payload, pending_action);
else
return kErrorParameters;
}
DisplayError DisplayBase::ApplyDefaultDisplayMode() {
if (color_mgr_)
return color_mgr_->ApplyDefaultDisplayMode();
else
return kErrorParameters;
}
} // namespace sdm
|
By Roger Fox
I doubt the Keystone project is even a real long term goal by TransCanada,. Certainly in the big picture Keystone is only a single chapter in a much larger book. If you read this diary you will risk information overload, you will be offered numerous disparate data points that at first glance may seem unconnected. You will need to digest all the information offered, and then analyze.
Crude is is classified by the American Petroleum Institute (API) into light, medium, heavy and extra heavy crudes, by API gravity. If its API gravity is greater than 10, it is lighter and floats on water; if less than 10, it is heavier and sinks. The Albert Tar Sands contain crudes of API 10 or less that is called Extra heavy or Bitumen. Heavy oil is defined as having an API gravity below 22.3, Medium oil is defined as having an API gravity between 22.3 °API and 31.1 °API, Light crude oil is defined as having an API gravity higher than 31.1.
At a production rate of 3 million barells a day the tar sands can last for 170 years. This would also mean a hole in the ground visible from orbit.
The Keystone pipeline is only one of a couple of handfuls of pipeline proposals over the last decade in the Western US, Canada and Alaska.
Alaskan nat gas is largely unexploited, and is used locally on the North Slope. Its estimated that 70 trillion cubic feet of nat gas can be found in Alaska, a lot of it in the North Slope area. There are at least 3 major proposals for nat gas pipelines from the North Slope area and the adjacent Mackenzie River Delta in Canada. 2 of these projects point right at Alberta.
TransCanada and Exxon Mobil are partnered in the Alaska gas pipeline proposal that will directly link nat gas production in the North Slope of ALaska thru Alberta to the US mid west. This project may be the same as the Denali proposal, and was reintroduced to theSenate in Feb, of 2011. There also at least 2 variations. Additionally there is the Dempster Lateral.
-> Next page: Follow the routes south
|
Join us!
...... Less of YOU
The Less of Me Store
...... Twitter
Follow us on Twitter
...... Less of Me Blog
Join us on Facebook!
in Ebook format!
...... style7
Tips on managing Stalls/Gains
I was just out looking for some other blogs to read to see what other people might have for recipes... While out, I found this site which had a particular post that I thought you'd be interested in.
Here's part of the post:
Tips on Managing Stalls/Gains
1. Watch what you’re eating; you should have a food journal and you might find patterns of foods that cause you not to lose, or to lose fantastically. A lot of people have had problems losing with tomatoes and oranges (but some people have no problem at all). Every body is different and you need to monitor your own body and see what works (and doesn’t work) for you.
2. Make sure you are drinking enough water (at least 2 liters a day).
3. Those that have held true to the diet and not cheated, have been rewarded with a large weight reduction when it finally drops. You will usually resume your previous average loss before the stall.
4. Each time you stall, take your measurements; you have probably lost inches (remember it is called Pounds and INCHES).
5. You could gain some weight and not have cheated, depending on your menses, ovulation, and hormones. Almost all of us have seen the scale go up due to water retention, etc.
6. If you eat more salt in the food you prepare, and your body isn't used to that sodium level, your blood volume will increase to handle the extra salt, which will translate into a gain because you're retaining water to boost that blood volume. In other words, watch your salt intake.
7. Remember what Simeons said about losing. You lose fat from the body cells but the cells do not disappear at the same time. The cell structure is still present for two to three days while the body breaks down the cellulose and fills the cell with water in order to release it (through urine). Once the fat cell is removed, the scale will drop.
8. Sensitivity/allergies to foods (like lemons) may cause weight stalls. Listen to your body. The guru is you!
9. Pay attention to weight gains, they usually signify a mishap in the protocol, like not drinking enough water, eating too many/too few calories, too much salt, or (inadvertently) eating foods not allowed on the protocol.
10. Be careful, spices have calories. As long as the serving size listed has less than 5 calories, the company can list 0 calories (even though it may actually have 4). Usually spices and seasonings use 1/4 of a teaspoon as their serving size, so BE CAREFUL...4 calories in 1/4 teaspoon = 16 calories in 1 teaspoon. Account for every calorie, no matter how miniscule it may seem. Here is an exact calorie count per TABLESPOON of various spices:
1TB Onion Powder =22.54 calories
1TB Garlic Powder =27.91 calories
1TB Chili Powder =23.55 calories
1TB Paprika =19.94 calories
1TB Poltry Season =11.36 calories
1TB Oregano =13.77 calories
1 comment:
1. I woke up this morning freaking out!! I gained more than 3lbs!!!! I was just about to say forget it to this crazy diet and just go on a food bender today.....this post helped me stay focused and remember that I need to be more aware of the calories. I still get a bit frustrated that as little as we eat that 100 calories either way makes that much difference. I won't give up on this and will see it through to the end. Thanks for all the great information you post on here, it really helps.
Related Posts with Thumbnails
|
A risk factor is something that increases your likelihood of getting a disease or condition.
It is possible to develop melanoma with or without the risk factors listed below. However, the more risk factors you have, the greater your likelihood of developing melanoma. If you have a number of risk factors, ask your doctor what you can do to reduce your risk.
Risk factors for melanoma include:
The occurrence of melanoma has been linked with exposure to ultraviolet (UV) radiation. Therefore, exposing your skin to UV rays from the sun or tanning lamps increases your odds of developing melanoma. People who live in sunny climates are exposed to more sunlight. People who live at high altitudes, where the sunlight is strongest, are exposed to more UV radiation. Blistering sunburns, even as a child, also increase the risk of developing melanoma.
Having melanoma once increases your risk of developing it again.
Having many moles or large moles increases your risk of melanoma. Also, irregular moles are more likely to turn into melanoma than normal moles. Irregular moles are characterized by:
- Being larger than normal moles
- Being variable in color
- Having irregular borders
- Any pigmented spot in the nail beds
- Changing in size and/or shape
Most melanomas are diagnosed in young adults and older adults.
Family members of people with melanoma are at greater risk of developing the disease than people with no family history of the disease. People with a disease called xeroderma pigmentosa (XP) are at a very increased risk of developing melanoma. This rare disease does not allow patients to repair sun-damaged DNA, therefore any sun exposure will result in damage and mutations that become melanomatous. It is not unusual for these people to develop hundreds of melanomas on their skin. Similarly, people with hereditary dysplastic nevus syndrome or familial atypical multiple mole melanoma (FAMMM) syndrome are also at increased risk for developing melanoma.
Caucasians are more likely than black, Hispanic and Asian people to develop melanoma.
Most people who develop melanoma tend to burn rather than tan when exposed to sunlight. These people tend to have fair skin, freckles, red or blonde hair, or blue-colored eyes.
- Reviewer: Brian Randall, MD
- Review Date: 04/2013 -
- Update Date: 04/08/2013 -
|
W hy is it important for scientists to contribute to science education?
Our nation has failed to meet important educational challenges, and our children are ill prepared to respond to the demands of today?s world. Results of the Third International Mathematics and Science Study ( TIMSS )--and its successor, TIMSS-R--show that the relatively strong international performance of U.S. 4th graders successively deteriorates across 8th- and 12th-grade cohorts. Related studies indicate that U.S. PreK-12 curricula lack coherence, depth, and continuity and cover too many topics superficially. By high school, unacceptably low numbers of students show motivation or interest in enrolling in physics (only one-quarter of all students) or chemistry (only one-half).
We are rapidly approaching universal participation at the postsecondary level, but we still have critical science, technology, engineering, and mathematics (STEM) workforce needs and too few teachers who have studied science or mathematics. Science and engineering degrees as a percentage of the degrees conferred each year have remained relatively constant at about 5%. In this group, women and minorities are gravely underrepresented.
The consequences of these conditions are serious. The U.S. Department of Labor estimates that 60% of the new jobs being created in our economy today will require technological literacy, yet only 22% of the young people entering the job market now actually possess those skills. By 2010, all jobs will require some form of technological literacy, and 80% of those jobs haven?t even been created yet. We must prepare our students for a world that we ourselves cannot completely anticipate. This will require the active involvement of scientists and engineers.
How is NSF seeking to encourage scientists to work on educational issues?
The NSF Strategic Plan includes two relevant goals: to develop "a diverse, internationally competitive, and globally engaged workforce of scientists, engineers, and well-prepared citizens" and to support "discovery across the frontiers of science and engineering, connected to learning, innovation, and service to society." To realize both of these goals, our nation?s scientists and engineers must care about the educational implications of their work and explore educational issues as seriously and knowledgeably as they do their research questions. The phrase "integration of research and education" conveys two ideas. First, good research generates an educational asset, and we must effectively use that asset. Second, we need to encourage more scientists and engineers to pursue research careers that focus on teaching and learning within their own disciplines.
All proposals submitted to NSF for funding must address two merit criteria: intellectual merit and broader impacts.
In everyday terms, our approach to evaluating the broader impact of proposals is built on the philosophy that scientists and engineers should pay attention to teaching and value it, and that their institutions should recognize, support, and reward faculty, as well as researchers in government and industry, who take their role as educators seriously and approach instruction as a scholarly act. We think of education very broadly, including formal education (K-graduate and postdoctoral study) and informal education (efforts to promote public understanding of science and research outside the traditional educational environment).
What does it mean to take education seriously and explore it knowledgeably?
Any scholarly approach to education must be intentional, be based on a valid body of knowledge, and be rigorously assessed. That is, our approach to educational questions must be a scholarly act. NSF actively invests in educational reform and models that encourage scientists and engineers to improve curriculum, teaching, and learning in science and mathematics at all levels of the educational system from elementary school to graduate study and postdoctoral work.
We recognize that to interest faculty and practicing scientists and engineers in education, we must support research that generates convincing evidence that changing how we approach the teaching of science and mathematics will pay off in better learning and deeper interest in these fields.
Here are a few of the most recent efforts to stimulate interest in education that might be of interest to Next Wave readers. (For more information, go to the NSF Education and Human Resources directorate's Web site .)
The GK-12 program supports fellowships and training to enable STEM graduate students and advanced undergraduates to serve in K-12 schools as resources in STEM content and applications. Outcomes include improved communication and teaching skills for the Fellows, increased content knowledge for preK-12 teachers, enriched preK-12 student learning, and stronger partnerships between higher education and local schools.
The Centers for Learning and Teaching ( CLT ) program is a "comprehensive, research-based effort that addresses critical issues and national needs of the STEM instructional workforce across the entire spectrum of formal and informal education." The goal of the CLT program is to support the development of new approaches to the assessment of learning, research on learning within the disciplines, the design and development of effective curricular materials, and research-based approaches to instruction--and through this work to increase the number of people who do research on education in the STEM fields. This year (FY 02) we are launching some prototype higher education centers to reform teaching and learning in our nation's colleges and universities through a mix of research, faculty development and exploration of instructional practices that can promote learning. Like other NSF efforts, the Centers incorporate a balanced strategy of attention to people, ideas and tools. We hope to encourage more science and engineering faculty to work on educational issues in both K-12 and in postsecondary education.
If you are interested in these issues and want to pursue graduate or postdoctoral study, or want to develop a research agenda on learning in STEM fields, find the location and goals of the currently funded centers and also check later this summer to find out which higher education CLT prototypes are funded.
The following solicitations all involve the integration of research and education as well as attention to broadening participation in STEM careers:
The Science, Technology, Engineering, and Mathematics Talent Expansion Program ( STEP ) program seeks to increase the number of students (U.S. citizens or permanent residents) pursuing and receiving associate or baccalaureate degrees in established or emerging fields within STEM.
The Faculty Early Career Development ( CAREER ) program recognizes and supports the early career development activities of those teacher-scholars who are most likely to become the academic leaders of the 21st century.
The Course, Curriculum, and Laboratory Improvement (CCLI) program seeks to improve the quality of STEM education for all students and targets activities affecting learning environments, course content, curricula, and educational practices. CCLI offers three tracks: educational materials development , national dissemination , and adaptation and implementation .
The Integrative Graduate Education and Research Training ( IGERT ) program addresses the challenges of preparing Ph.D. scientists and engineers with the multidisciplinary backgrounds and the technical, professional, and personal skills needed for the career demands of the future.
The Vertical Integration of Research and Education in the Mathematical Sciences ( VIGRE ) program supports institutions with Ph.D.-granting departments in the mathematical sciences in carrying out innovative educational programs, at all levels, that are integrated with the department?s research activities.
The Increasing the Participation and Advancement of Women in Academic Science and Engineering Careers (ADVANCE) program seeks to increase the participation of women in the scientific and engineering workforce through the increased representation and advancement of women in academic science and engineering careers.
The Science, Technology, Engineering and Mathematics Teacher Preparation ( STEMTP ) program involves partnerships among STEM and education faculty working with preK-12 schools to develop exemplary preK-12 teacher education models that will improve the science and mathematics preparation of future teachers.
The Noyce Scholarship Supplements program supports scholarships and stipends for STEM majors and STEM professionals seeking to become preK-12 teachers.
The views expressed are those of the authors and do not necessarily reflect those of the National Science Foundation.
|
Saturday, August 20, 2016
Book review: INVISIBLE MONSTERS by Chuck Palahniuk
Because beauty is power the way money is power the way a loaded gun is power.
Palahniuk is best known for Fight Club, a manly book about guys beating each other up and feeling more alive because of it. Invisible Monsters is his second novel, and unlike the macho air of Fight Club, here is another world of (also ruthless and brutal) the modeling industry, plastic surgery, sex change, and getting rid of your past.
The novel's narrator and protagonist is a fashion model who was shot in the jaw. She is saved by a transgender Brandy Alexander, body full of operations and drugs, as she embarks on a new life wandering around with her ex-boyfriend and taking revenge against her former model frenemy. Here we get a lot of angst about beauty and ugliness. The narrator realizes that her face, no matter how scary and horrible now, is also a kind of power.
My favorite moral lesson from this book, though, is getting rid of the past and focusing instead on the future and all its possibilities.
The main character looks like this:
"Your perception is all fucked up. All you can talk about is trash that's already happened. You can't base your life on the past or the present. You have to tell me about your future."
"When you understand, is that what you're telling is just a story. It isn't happening anymore. When you realize the story you're telling is just words, when you can just crumble it up and throw your past in the trashcan, then we'll figure out who you're going to be."
"It's because we're so trapped in our culture, in the being of being human on this planet with the brains we have, and the same two arms and two legs everybody has. We're so trapped that any way we could imagine to escape would be just another part of the trap. Anything we want, we're trained to want."
"Times like this, it helps to think of yourself as a sofa or a newspaper, something made by a lot of other people but not made to last forever. It helps to know you're not any more responsible for how you look than a car is. You're a product just as much. A product of a product of a product. The people who design cars, they're products. Your parents are products. Their parents were products. Your teachers, products. The minister in your church, another product. The best way is not to fight it, just go. Don't be trying all the time to fix things. What you run from only stays with you longer. When you fight something, you only make it stronger. Whatever you're thinking, a million other folks are thinking. Whatever you do, they're doing, and none of you is responsible. All of you is a cooperative effort."
No comments:
Post a Comment
|
#include "min_cg_old.h"
#include <stdlib.h>
using namespace MAPP_NS;
/*--------------------------------------------
constructor
--------------------------------------------*/
MinCGOld::MinCGOld(type0 __e_tol,
bool(&__H_dof)[__dim__][__dim__],bool __affine,type0 __max_dx,LineSearch* __ls):
Min(__e_tol,__H_dof,__affine,__max_dx,__ls),
atoms(NULL),
ff(NULL),
xprt(NULL)
{
}
/*--------------------------------------------
destructor
--------------------------------------------*/
MinCGOld::~MinCGOld()
{
atoms=NULL;
ff=NULL;
}
/*--------------------------------------------
--------------------------------------------*/
type0 MinCGOld::calc_ndofs()
{
return 0.0;
}
/*--------------------------------------------
--------------------------------------------*/
void MinCGOld::force_calc()
{
ff->derivative();
if(chng_box)
Algebra::DoLT<__dim__>::func([this](int i,int j){f.A[i][j]=H_dof[i][j] ? f.A[i][j]:0.0;});
}
/*--------------------------------------------
--------------------------------------------*/
void MinCGOld::prep()
{
x_d=h;
if(!chng_box) return;
const int natms_lcl=atoms->natms_lcl;
type0* xvec=x0.vecs[0]->begin();
type0* hvec=h.vecs[0]->begin();
type0* x_dvec=x_d.vecs[0]->begin();
Algebra::MLT_mul_MLT(atoms->H,h.A,x_d.A);
if(affine)
{
for(int iatm=0;iatm<natms_lcl;iatm++,xvec+=__dim__,x_dvec+=__dim__)
Algebra::V_mul_MLT(xvec,h.A,x_dvec);
}
else
{
for(int iatm=0;iatm<natms_lcl;iatm++,xvec+=__dim__,x_dvec+=__dim__,hvec+=__dim__)
Algebra::V_mul_MLT_add_in(xvec,h.A,x_dvec);
}
}
/*--------------------------------------------
init before a run
--------------------------------------------*/
void MinCGOld::init()
{
x.~VecTens();
new (&x) VecTens<type0,1>(atoms,chng_box,atoms->H,atoms->x);
f.~VecTens();
new (&f) VecTens<type0,1>(atoms,chng_box,ff->F_H,ff->f);
h.~VecTens();
new (&h) VecTens<type0,1>(atoms,chng_box,__dim__);
x0.~VecTens();
new (&x0) VecTens<type0,1>(atoms,chng_box,__dim__);
x_d.~VecTens();
new (&x_d) VecTens<type0,1>(atoms,chng_box,__dim__);
f0.~VecTens();
new (&f0) VecTens<type0,1>(atoms,chng_box,__dim__);
dynamic=new DynamicMD(atoms,ff,chng_box,{},{atoms->x_dof,h.vecs[0],x0.vecs[0],x_d.vecs[0],f0.vecs[0]},{atoms->x_d});
dynamic->init();
if(xprt)
{
try
{
xprt->atoms=atoms;
xprt->init();
}
catch(std::string& err_msg)
{
fin();
throw err_msg;
}
}
}
#ifdef POTFIT
/*--------------------------------------------
init before a run
--------------------------------------------*/
void MinCGOld::init(vec* ext_vec_0)
{
x.~VecTens();
new (&x) VecTens<type0,1>(atoms,chng_box,atoms->H,atoms->x);
f.~VecTens();
new (&f) VecTens<type0,1>(atoms,chng_box,ff->F_H,ff->f);
h.~VecTens();
new (&h) VecTens<type0,1>(atoms,chng_box,__dim__);
x0.~VecTens();
new (&x0) VecTens<type0,1>(atoms,chng_box,__dim__);
x_d.~VecTens();
new (&x_d) VecTens<type0,1>(atoms,chng_box,__dim__);
f0.~VecTens();
new (&f0) VecTens<type0,1>(atoms,chng_box,__dim__);
dynamic=new DynamicMD(atoms,ff,chng_box,{},{atoms->x_dof,h.vecs[0],x0.vecs[0],x_d.vecs[0],f0.vecs[0],
ext_vec_0
},{atoms->x_d});
dynamic->init();
if(xprt)
{
try
{
xprt->atoms=atoms;
xprt->init();
}
catch(std::string& err_msg)
{
fin();
throw err_msg;
}
}
}
#endif
/*--------------------------------------------
finishing minimization
--------------------------------------------*/
void MinCGOld::fin()
{
if(xprt)
{
xprt->fin();
xprt->atoms=NULL;
}
dynamic->fin();
delete dynamic;
dynamic=NULL;
f0.~VecTens();
x_d.~VecTens();
x0.~VecTens();
h.~VecTens();
f.~VecTens();
x.~VecTens();
}
/*--------------------------------------------
ff_test
--------------------------------------------*/
#include "random.h"
void MinCGOld::ff_test(int seed,type0 __max_dx,type0 __max_st,int __n_desc)
{
bool __chng_box=chng_box;
chng_box=true;
bool __H_dof[__dim__][__dim__];
Algebra::V_eq<__dim__*__dim__>(&H_dof[0][0],&__H_dof[0][0]);
Algebra::DoLT<__dim__>::func([this](int i,int j)
{H_dof[i][j]=H_dof[j][i]=true;});
x.~VecTens();
new (&x) VecTens<type0,1>(atoms,chng_box,atoms->H,atoms->x);
f.~VecTens();
new (&f) VecTens<type0,1>(atoms,chng_box,ff->F_H,ff->f);
h.~VecTens();
new (&h) VecTens<type0,1>(atoms,chng_box,__dim__);
x0.~VecTens();
new (&x0) VecTens<type0,1>(atoms,chng_box,__dim__);
x_d.~VecTens();
new (&x_d) VecTens<type0,1>(atoms,chng_box,__dim__);
dynamic=new DynamicMD(atoms,ff,chng_box,{},{atoms->x_dof,h.vecs[0],x0.vecs[0],x_d.vecs[0]},{atoms->x_d});
dynamic->init();
/* creating random h*/
Random rand(seed+atoms->comm_rank);
int natms_lcl=atoms->natms_lcl;
type0* __h=h.vecs[0]->begin();
for(int i=0;i<__dim__*natms_lcl;i++)
__h[i]=(2.0*rand.uniform()-1.0)*__max_dx;
Algebra::DoLT<__dim__>::func([this,&rand,&__max_st](int i,int j)
{h.A[i][j]=(2.0*rand.uniform()-1.0)*__max_st;});
x0=x;
force_calc();
f_h=f*h;
prep();
type0 alpha=0.0;
type0 dalpha=1.0/static_cast<type0>(__n_desc);
type0 u0=F(alpha);
type0 du=0.0;
type0 du_alpha=0.0;
ThermoDynamics thermo(12,"alpha",alpha,"delta_U",du,"dU*alpha",du_alpha);
thermo.init();
for(int i=0;i<__n_desc+1;i++)
{
du=F(alpha)-u0;
du_alpha=-alpha*f_h;
thermo.print(i);
alpha+=dalpha;
}
thermo.fin();
dynamic->fin();
delete dynamic;
dynamic=NULL;
x_d.~VecTens();
x0.~VecTens();
h.~VecTens();
f.~VecTens();
x.~VecTens();
Algebra::V_eq<__dim__*__dim__>(&__H_dof[0][0],&H_dof[0][0]);
chng_box=__chng_box;
}
/*--------------------------------------------
min
--------------------------------------------*/
void MinCGOld::run(int nsteps)
{
if(dynamic_cast<LineSearchGoldenSection*>(ls))
return run(dynamic_cast<LineSearchGoldenSection*>(ls),nsteps);
if(dynamic_cast<LineSearchBrent*>(ls))
return run(dynamic_cast<LineSearchBrent*>(ls),nsteps);
if(dynamic_cast<LineSearchBackTrack*>(ls))
return run(dynamic_cast<LineSearchBackTrack*>(ls),nsteps);
}
/*--------------------------------------------
--------------------------------------------*/
type0 MinCGOld::F(type0 alpha)
{
x=x0+alpha*x_d;
if(chng_box)
atoms->update_H();
dynamic->update<true>();
return ff->value();
}
/*--------------------------------------------
inner product of f and h
--------------------------------------------*/
type0 MinCGOld::dF(type0 alpha,type0& drev)
{
x=x0+alpha*x_d;
if(chng_box)
atoms->update_H();
dynamic->update<true>();
force_calc();
drev=-(f*h);
return atoms->pe;
}
/*--------------------------------------------
find maximum h
lets find the next sensible number
x=x_0+h*alpha
(x-x0)/alpha=sqrt(eps)/alpha
--------------------------------------------*/
void MinCGOld::ls_prep(type0& dfa,type0& h_norm,type0& max_a)
{
h_norm=h*h;
dfa=-f_h;
if(h_norm==0.0)
{
max_a=0.0;
dfa=0.0;
return;
}
if(dfa>=0.0)
{
max_a=0.0;
dfa=1.0;
return;
}
h_norm=sqrt(h_norm);
type0 max_x_d_lcl=0.0;
type0 max_x_d;
type0* x_dvec=x_d.vecs[0]->begin();
const int n=atoms->natms_lcl*__dim__;
for(int i=0;i<n;i++)
max_x_d_lcl=MAX(max_x_d_lcl,fabs(x_dvec[i]));
MPI_Allreduce(&max_x_d_lcl,&max_x_d,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world);
max_a=fabs(max_dx/max_x_d);
}
/*--------------------------------------------
reset to initial position
--------------------------------------------*/
void MinCGOld::F_reset()
{
x=x0;
if(chng_box) atoms->update_H();
dynamic->update<true>();
}
/*------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------*/
PyObject* MinCGOld::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds)
{
Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0));
PyObject* self=reinterpret_cast<PyObject*>(__self);
return self;
}
/*--------------------------------------------
--------------------------------------------*/
int MinCGOld::__init__(PyObject* self,PyObject* args,PyObject* kwds)
{
FuncAPI<type0,symm<bool[__dim__][__dim__]>,bool,type0,OP<LineSearch>> f("__init__",{"e_tol","H_dof","affine","max_dx","ls"});
f.noptionals=5;
f.logics<0>()[0]=VLogics("ge",0.0);
f.logics<3>()[0]=VLogics("gt",0.0);
//set the defualts
f.val<0>()=sqrt(std::numeric_limits<type0>::epsilon());
for(int i=0;i<__dim__;i++) for(int j=0;j<__dim__;j++)f.val<1>()[i][j]=false;
f.val<2>()=false;
f.val<3>()=1.0;
PyObject* empty_tuple=PyTuple_New(0);
PyObject* empty_dict=PyDict_New();
PyObject* __ls=LineSearchBackTrack::__new__(&LineSearchBackTrack::TypeObject,empty_tuple,empty_dict);
LineSearchBackTrack::__init__(__ls,empty_tuple,empty_dict);
Py_DECREF(empty_dict);
Py_DECREF(empty_tuple);
f.val<4>().ob=__ls;
if(f(args,kwds)==-1) return -1;
Object* __self=reinterpret_cast<Object*>(self);
Py_INCREF(f.val<4>().ob);
__self->ls=reinterpret_cast<LineSearch::Object*>(f.val<4>().ob);
__self->min=new MinCGOld(f.val<0>(),f.val<1>(),f.val<2>(),f.val<3>(),&(__self->ls->ls));
__self->xprt=NULL;
return 0;
}
/*--------------------------------------------
--------------------------------------------*/
PyObject* MinCGOld::__alloc__(PyTypeObject* type,Py_ssize_t)
{
Object* __self=new Object;
Py_TYPE(__self)=type;
Py_REFCNT(__self)=1;
__self->min=NULL;
__self->ls=NULL;
__self->xprt=NULL;
return reinterpret_cast<PyObject*>(__self);
}
/*--------------------------------------------
--------------------------------------------*/
void MinCGOld::__dealloc__(PyObject* self)
{
Object* __self=reinterpret_cast<Object*>(self);
delete __self->min;
__self->min=NULL;
if(__self->ls) Py_DECREF(__self->ls);
__self->ls=NULL;
if(__self->xprt) Py_DECREF(__self->xprt);
__self->xprt=NULL;
delete __self;
}
/*--------------------------------------------*/
PyTypeObject MinCGOld::TypeObject={PyObject_HEAD_INIT(NULL)};
/*--------------------------------------------*/
int MinCGOld::setup_tp()
{
TypeObject.tp_name="mapp4py.md.min_cg";
TypeObject.tp_doc=R"---(
__init__(e_tol=1.0e-8,H_dof=[[False],[False,False],[False,False,False]],affine=False,max_dx=1.0,ls=mapp4py.ls_bt())
CG minimization algorithm
Parameters
----------
e_tol : double
Energy tolerance criterion for stopping minimization
H_dof : symm<bool[dim][dim]>
Unitcell degrees of freedom during minimization, here dim is the dimension of simulation
affine : bool
If set to True atomic displacements would be affine
max_dx : double
Maximum displacement of any atom in one step of minimization
ls : mapp4py.ls
Line search method
Notes
-----
Cojugate Gradient (CG) algorithm for minimization, see :cite:`press_numerical_2007`.
References
----------
.. bibliography:: ../refs.bib
:filter: docname in docnames
:style: unsrt
)---";
TypeObject.tp_flags=Py_TPFLAGS_DEFAULT;
TypeObject.tp_basicsize=sizeof(Object);
TypeObject.tp_new=__new__;
TypeObject.tp_init=__init__;
TypeObject.tp_alloc=__alloc__;
TypeObject.tp_dealloc=__dealloc__;
setup_tp_methods();
TypeObject.tp_methods=methods;
setup_tp_getset();
TypeObject.tp_getset=getset;
int ichk=PyType_Ready(&TypeObject);
if(ichk<0) return ichk;
Py_INCREF(&TypeObject);
/*
this is a shitty hack since python does not have a slot
for __init__, __new__, __call__, and etc. they use
a wrapper_desriptor with a default doc here I change it
*/
GET_WRAPPER_DOC(TypeObject,__init__)=NULL;
return ichk;
}
/*--------------------------------------------*/
PyGetSetDef MinCGOld::getset[]=EmptyPyGetSetDef(8);
/*--------------------------------------------*/
void MinCGOld::setup_tp_getset()
{
getset_e_tol(getset[0]);
getset_H_dof(getset[1]);
getset_affine(getset[2]);
getset_max_dx(getset[3]);
getset_ls(getset[4]);
getset_ntally(getset[5]);
getset_export(getset[6]);
}
/*--------------------------------------------*/
PyMethodDef MinCGOld::methods[]=EmptyPyMethodDef(3);
/*--------------------------------------------*/
void MinCGOld::setup_tp_methods()
{
ml_run(methods[0]);
ml_ff_test(methods[1]);
}
/*--------------------------------------------
--------------------------------------------*/
void MinCGOld::getset_export(PyGetSetDef& getset)
{
getset.name=(char*)"export";
getset.doc=(char*)R"---(
(mapp4py.md.export) export object
Export object to record the snapshots of the system while minimizing
)---";
getset.get=[](PyObject* self,void*)->PyObject*
{
ExportMD::Object* xprt=reinterpret_cast<Object*>(self)->xprt;
if(!xprt) Py_RETURN_NONE;
Py_INCREF(xprt);
return reinterpret_cast<PyObject*>(xprt);
};
getset.set=[](PyObject* self,PyObject* op,void*)->int
{
VarAPI<OP<ExportMD>> xprt("export");
int ichk=xprt.set(op);
if(ichk==-1) return -1;
if(reinterpret_cast<Object*>(self)->xprt) Py_DECREF(reinterpret_cast<Object*>(self)->xprt);
Py_INCREF(xprt.val.ob);
reinterpret_cast<Object*>(self)->xprt=reinterpret_cast<ExportMD::Object*>(xprt.val.ob);
return 0;
};
}
/*--------------------------------------------
--------------------------------------------*/
void MinCGOld::ml_run(PyMethodDef& tp_methods)
{
tp_methods.ml_flags=METH_VARARGS | METH_KEYWORDS;
tp_methods.ml_name="run";
tp_methods.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)(
[](PyObject* self,PyObject* args,PyObject* kwds)->PyObject*
{
Object* __self=reinterpret_cast<Object*>(self);
FuncAPI<OP<AtomsMD>,int> f("run",{"atoms","max_nsteps"});
f.logics<1>()[0]=VLogics("ge",0);
if(f(args,kwds)) return NULL;
AtomsMD* __atoms=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->atoms;
ForceFieldMD* __ff=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->ff;
ExportMD* __xprt=__self->xprt==NULL ? NULL:__self->xprt->xprt;
try
{
__self->min->pre_run_chk(__atoms,__ff);
}
catch(std::string& err_msg)
{
PyErr_SetString(PyExc_TypeError,err_msg.c_str());
return NULL;
}
__self->min->atoms=__atoms;
__self->min->ff=__ff;
__self->min->xprt=__xprt;
try
{
__self->min->init();
}
catch(std::string& err_msg)
{
__self->min->xprt=NULL;
__self->min->ff=NULL;
__self->min->atoms=NULL;
PyErr_SetString(PyExc_TypeError,err_msg.c_str());
return NULL;
}
__self->min->run(f.val<1>());
__self->min->fin();
__self->min->xprt=NULL;
__self->min->ff=NULL;
__self->min->atoms=NULL;
Py_RETURN_NONE;
});
tp_methods.ml_doc=(char*)R"---(
run(atoms,max_nsteps)
Execute minimization
This method starts the energy minimization for a given atoms object and maximum number of steps.
Parameters
----------
atoms : mapp4py.md.atoms
System of interest
max_nsteps : int
Maximum number of steps to achieve energy minimization
Returns
-------
None
)---";
}
/*--------------------------------------------
--------------------------------------------*/
void MinCGOld::ml_ff_test(PyMethodDef& tp_methods)
{
tp_methods.ml_flags=METH_VARARGS | METH_KEYWORDS;
tp_methods.ml_name="ff_test";
tp_methods.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)(
[](PyObject* self,PyObject* args,PyObject* kwds)->PyObject*
{
Object* __self=reinterpret_cast<Object*>(self);
FuncAPI<OP<AtomsMD>,int,type0,type0,int> f("ff_test",{"atoms","seed","max_dx","max_strain","N"});
f.logics<1>()[0]=VLogics("ge",0);
f.logics<2>()[0]=VLogics("ge",0.0);
f.logics<3>()[0]=VLogics("ge",0.0);
f.logics<4>()[0]=VLogics("gt",0);
if(f(args,kwds)) return NULL;
AtomsMD* __atoms=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->atoms;
ForceFieldMD* __ff=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->ff;
__self->min->atoms=__atoms;
__self->min->ff=__ff;
__self->min->ff_test(f.val<1>(),f.val<2>(),f.val<3>(),f.val<4>());
__self->min->ff=NULL;
__self->min->atoms=NULL;
Py_RETURN_NONE;
});
tp_methods.ml_doc=(char*)R"---(
ff_test,(atoms,seed,max_dx,max_strain,N)
for the purpose of testing
Parameters
----------
atoms : mapp4py.md.atoms
System of interest
max_nsteps : int
Maximum number of steps to achieve energy minimization
Returns
-------
None
)---";
}
|
Hershey, PA : Information Science Reference, c2009.
xxi, 417 p. : ill. ; 29 cm.
"Premier reference source"--Cover.
Includes bibliographical references (p. 362-407) and index.
Now established as an effective tool in the instructional process, multimedia has penetrated educational systems at almost every level of study. In their quest to maximize educational outcomes and identify best practices, multimedia researchers are now expanding their examinations to extend towards the cognitive functionality of multimedia."Cognitive Effects of Multimedia Learning" identifies the role and function of multimedia in learning through a collection of research studies focusing on cognitive functionality. An advanced collection of critical theories and practices, this much needed contribution to the research is an essential holding for academic libraries, and will benefit researchers, practitioners and students in basic and applied fields ranging from education to cognitive sciences. (source: Nielsen Book Data)
|
Senin, 22 Juli 2013
Why Children Need A Character Education?
Character building is essential approach for building nation. In essence, the development of a child is to develop a true understanding of how this world works, learn "rules of the game" every aspect in this world. Children will grow into personal character when can grow in the range of characteristic
There are 3 Ways to Educate Children Character:
1. Change the environment, doing character education by laying out rules and consequences at school and at home.
2. Provide knowledge, provide knowledge on how to do the behavior that hoped to appear in their days and applied.
3. Controlling emotions, human emotions are in control of 88% of human life. If able to touch the emotions and provide accurate information so that information will be settled in his life.
The story of a corrupt racket
I found this interesting story at
Perhaps all of us can learn from these story.
A young boy accidentally destroy his father's racket. Because of fear, she hid the racket under the bed in his room.
Every time his father entered the room, her fear. He accidentally sat down on the bed, worried father raised beds later found that he rusakkan racket. That's why he is always trying to move the racket that he rusakkan to another as often as possible, in hopes father will not be able to find it.
So far everything is always able to be treated successfully. Faults remain hermetically sealed in front of his father. However, as long as it did not calm him. Every moment of guilt arise and judge. Wherever he went, his heart was always drawn to the racket that the father he never rusakkan.
The more often he moved his racket rusakkan, he is getting restless, because it means the little place that allows it to hide the broken racket. In ketertekanannya, he finally took the damaged racquet, bring it in his right hand, then went to his father with fear.
Having been in front of his father, he said as he showed the destruction racket, "father, forgive me for damaging racquets father, I am ready to be punished."
Heard of her son, the father leaned over and said, "son, father already knew all of that from last week, just waiting for your father to have the courage to admit it. Now the father was about to say to you that the father forgive you. "
The last sentence of the father actually make the child feel relieved and free. Admit mistakes is the beginning of a great deed, and to account for the error is a step towards happiness.
Jumat, 19 Juli 2013
Meerkat and Grebe : Two Signs of Love for a Child
In a vast steppes, a set of Meerkat (Ind.: Mongoose) is preparing to return to the nest. By evening, a fox crept toward the nest. Knowing this, the parent Meerkat immediately put the body in the nest entrance. He was ready to fight to protect her children. The next morning, the battle scars overnight with wolves force the meerkat’s parent last breath.
In another hemisphere, a pair of birds building nests near Grebe lake inhabited by crocodiles. Once when the crocodile was very hungry, Grebe chicks are still too weak to be crocodile’s food. Parent birds know it and immediately pretended hurt to distract the crocodile. Seeing other larger dining, the crocodile follow where the mother bird away. As she shuffled like a mortally wounded, the parent birds Grebe risking his life so that the crocodile away from her children.
Two stories above is not a fictional story.
Grebe bird and meerkats are just 2 of the many creatures of God given instinct of compassion. There are many other creatures that God showed his affection with a variety of ways. Especially humans, which was given the mandate as the inheritors of the earth, the absolute has the affectionate nature. Without it, the position as the leader in the face of the earth will only bring misfortune.
When young, Grebe chicks feed her mother found hairs or feathers of his own. It is intended that these feathers form a filter in the stomach chicks, which would prevent the entry of fish spines into the digestive tract.
When we were kids, our parents are very careful with what we eat. When we are sick, we are the ones that most parents worry about the condition of our bodies. They think very best education that will be given to us. With all the sacrifices they made, how should we reply?
There's no way we give back what they have given. But as a child, our obedience, our devotion, respect, attention, and affection we do, are the things that will make them happy to have us as their sons and daughters. (Aan)
Languages and Civilizations
Long before Cesare Bollugia ambitious to unite Spain, Naples, and Rome, the Abbasid Caliphate had been in control of Western civilization in Europe. Yes, Andalusia in the 7th century AD has been the center of civilization with Cordoba as one of the prominent cities. At this time, in Spain, Christians are immersed into what is known as the Mozarabic Culture (Dr. Hamid Fahmi Zarkasyi). Islam is the dominant culture that may have contributed greatly to the birth of a new view of life in the West.
Prior to the 7th century, Western civilization has indeed been inherited from the Greeks and Romans. However, sophisticated Muslim worldview and more rich knowledge of what is contained in the Latin world, has given stimulus to the rise of the ideology, intellectuality, and imagination of medieval European society.
Then, in the 10th century AD, wheel rolling back civilization. Rotating steady and strengthen the Christian army ambition to return to the glory which he inherited from Roman civilization, while continuing to enrich the heritage of world civilization with Islam: aspiration and enthusiasm for life.
Transfer the live of view
Civilization is formed when the constituent elements that include factors accumulate material and immaterial in such a way in a short time. And indeed, the forerunner of the wheels of civilization from the time of the Abbasid Caliphate to Christian Europe has been going on since the Islamic civilization reached its glory. Of course, just as the Ibn Khaldun: "When a people have reached the point of civilization, then nobody could awaited addition to its destruction" (Mujahideen Muhayyan).
When Islamic civilization that reached its peak, western aspirations of Muslims to enrich their worldview.
Lives of the people with intellectual and sophisticated view of life in the shade of the Islamic civilization, which is felt and seen by the European through and visit their diplomatic relations, has given rise to the embryo changes. And these embryos develop when the people of Europe realize that they can absorb the aspirations and spirit of Muslim life by transferring and assimilating the books of philosophy and Islamic science. In addition to stories and poems were transmitted orally, many Muslim scientific works translated by the West. This enthusiasm is so great-monastery to monastery Europe, especially Santa Marie de Rippol, on the 12th and 13th century AD manuscript has storage space for a large number of Muslims to their scientific work translated. Thus, they can explore science contained in the libraries of Islam. In fact, for the smooth running of the translation process, the kings of Europe established a school for translators in Toledo, just after Christian forces recaptured the city in 1085 AD
So no wonder, if the works of medieval European scientists could not be separated from the works of translation from Arabic.Historians note that the development of Western Europe in the mid 13th century is a combination of elements, called Greco-Arabic-Latin. In other words, the mastery of the language that characterizes the works of philosophy and science of the time, has opened the gates of the intellect and the western way of life, and make the people of Europe, once again, as the ruler of Western civilization, which is more rich in scientific works andconcepts of the Islamic worldview.
Once again, "just" because of the language ...
Language, forming the arms of civilization
History of a civilization begins when the language has evolved its constituent communities. Archaeologists itself establish that history began when society has known writings. It refers to the written evidence is found. Interim period before the written evidence is categorized as prehistoric. And writing, is evidence that language comprehension is a growing community.
Language, according to Muhayyan Mujahideen, a form born of the workings of the brain, which is thought. The brainchild of a variety of shapes.
Some are born as art, philosophy, mathematics, astronomy, and so on. The birth of the results of this thinking help humanity understand the moral values, religion, the universe, including his true identity. Because art is the language of our feelings and thoughts. Philosophy is the language of the deepest values of life and living. Mathematics is the language of symbols for objects and events around us. Similarly astronomy, is a language that helps us understand the universe, as well as our identity.
So the development indicates the rise of the language of a people.
This evolving mindset, enables man to actualize themselves in such a way as to develop the immaterial factors such as rules, moral values and beliefs (religion). Immaterial factors, supported by material factors such as geological factors, geographical, and economic, accumulate to form a civilization.Because it's no wonder, when the only developed nation that bahasanyalah, which is able to form a human existence, called civilization.
Generating Islamic civilization
Mastery over the language does have an important role for the formation of a civilization. Therefore, it is not possible to revive the language of a civilization that had drowned.
Ibn Khaldun defines civilization as the pinnacle of cultural achievement ladder.
And a spokesman for culture, language becomes a very powerful tool for spreading the culture of the speakers of the language. When languages have made the culture of a nation into a global culture, the culture of the nation will color the joints civilization.
But the Islamic civilization, not just a collection of culture.Civilization is built upon the apostles ”millah” worldview that contains the potential to blow up its constituent humans.
Muslims need to unite immediately languages, and raised the height of the glory of civilization with language. To that end, efforts to unify the language of the policy must be followed up with efforts to speak.
During the cold war, the Soviet Union and the United States in a world polarized into the motor block west and a block east.
But in reality, the Soviet Union was not able to put the Russian language equal to English in the international arena. So that American popular culture over popular culture coloring origin of civilization than the Soviet Union. History also indicates the failure of the Japanese and German military during World War II as a result of the absence of the policy language. So the Japanese or German culture does not contribute significantly in the coloring of civilization.
Now, it was time for Muslims to dye civilization again.
Because the Muslim worldview that rests on the Quran, should be the entity of human civilization. In order for civilization, become truly civilized. (Aan)
This is one of my article that published in "buletin Integral" a few years ago. After re-read it, I found interesting to publish it in my blog. How is your opinion about it content?
Sabtu, 13 Juli 2013
Club for everygirl who likes writing
After talking left and right, never thought, it turns out quite a few friends "excited" by the idea of establishing a school-based Talent. Just how? As a result, this idea should be the way somehow. Because this is not just an idea, but a dream. So, as a first step we will make the club first. Talent-based school is a school for developing talent and interest, so the classes are in the form of clubs.There are writing club, diva club, animation club, etc. Well, because the cost of the device and to establish schools quite complicated and large, then we set up the club first. It's like building a dream home, which is preceded by arranging bricks one by one. Clubs that want to set up the first time was writing club. This is due to the establishment of school-based talent is fronted by people equally like writing. In addition, the establishment of capital was also not so great. Well, after writing club, then other clubs will surely also soon stand. This is a writing club targets schoolgirls. Club members will be divided into teams to complete the project. We are also looking for a publisher to accept the results of the project will be. What if the publisher does not accept? then we publish the results of the project will be independent. So, for the schoolgirls aged 15 years and over who are interested in realizing the dream in the field of writing, better join this club. It's free. Want it???
Talent-based School
What it was like going to school with our way? We learn what we really like and need. For example, I love to write. Then the school will host a book-making project, or a novel, or other. Each time the teaching and learning process, which we are doing is trying to complete the project. The Report is the result of our posts have been published.
Or as I like the culinary arts. Someday want to be a culinary professional artist. Then the school will bring experts in the field to teach. Each meeting we make a work of culinary art different.For example, today the theme is chocolate, fruit mix next meeting, the next meeting different again. At the end of the school year, the exam form of culinary art exhibition, then we get certificate of diploma culinary professional artist. So, we can use the certificate to apply for work in the gallery or school or corporate pastry / cake culinary artist in need of services. Exciting right !
If I love photography, so I would join a photography class. Each meeting we learn to take pictures with different themes. During the meeting, we automatically learn how to set up the lighting, take a right angle, and all about cameras, ranging from its history to the development of the camera. In the end, the science of photography we can get it deeply. Then at the end of the school year, the evaluation of learning is in the form of an international photo exhibition. Sure is cool!
What about I like sports, football for example. Of course I’ll follow football class. In football class, the students are trained in the discipline to be a professional player. In addition there are certain times interspersed lessons on personality. Sports athletes nowadays it's that close to the entertainment world. So it's important to be a decent athlete sale. Well, the school organizes regular events match as well, but to follow the games of football clubs outside school. The football graders must compete for a chance to play in international clubs. Well, of course the school have to facilitated it.
And other talents, such as singing. The Report is the album of their work. Who love animation, the report is animated movie they’ve made. School will facilitate to distribute the work of his students to the broadcasting world. And so on ...
If school is in this way, both students and teachers certainly do not stress, because they learn and teach appropriate field of their interest and obtained knowledge that is certainly needed when they grow up and work in the field, right?
Wanna go to school in a school like this? Or would like to teach in a school like this? Let’s make!
Senin, 01 Juli 2013
Klub buat yang suka nulis
Setelah bicara kiri-kanan, nggak nyangka, ternyata beberapa teman cukup "excited" dengan ide pendirian Talent based school. Cuma caranya gimana? Alhasil, ide ini harus bisa jalan bagaimanapun caranya. Karena ini bukan sekedar ide, tapi impian.
Jadi, sebagai langkah awal kita akan bikin klub dulu. Talent based school adalah sekolah berbasis bakat, jadi kelas-kelasnya berupa klub-klub. Ada writing club, diva club, animasi club, de el el. Nah, karena perangkat dan biaya untuk mendirikan sekolah cukup rumit dan besar, maka kita dirikan klub dulu. Ini seperti membangun sebuah rumah impian, yang diawali dengan menata batu bata satu demi satu. Klub yang mau didirikan pertama kali adalah writing club. Ini karena pendirian talent based school ini digawangi oleh orang-orang yang sama-sama suka nulis. Selain itu, modal pendiriannya juga tidak begitu besar. Nah, setelah writing club, maka club-club lainnya juga pasti akan segera berdiri.
Target writing club ini adalah siswi-siswi SMU (muslimah) mulai dari kelas 1. Anggota club akan dibagi menjadi beberapa tim untuk menyelesaikan proyek bukunya. Kita juga sedang mencari penerbit untuk menerima hasil proyek nantinya. Bagaimana jika penerbit tidak menerima? maka hasil proyek akan kita terbitkan secara indie.
So, buat para remaja muslimah usia 15 tahun ke atas yang berminat mewujudkan impian di bidang tulis-menulis, lebih baik ikut klub ini. Kan gratis. Mau???
|
Classroom Activities for Teaching Sedimentary GeologyThis collection of teaching materials allows for the sharing of ideas and activities within the community of geoscience teachers. Do you have a favorite teaching activity you'd like to share? Please help us expand this collection by contributing your own teaching materials.
Subject: Sedimentary Geology
Results 1 - 4 of 4 matches
Chemical and Physical Weathering Field and Lab Experiment: Development and Testing of Hypotheses part of Activities
Lisa Greer, Washington and Lee University
This exercise combines an integrated field and laboratory experiment with a significant scientific writing assignment to address chemical and physical weathering processes via hypothesis development, experimental ...
Demystifying the Equations of Sedimentary Geology part of Activities
Larry Lemke, Wayne State University
This activity includes three strategies to help students develop a deeper comfort level and stronger intuitive sense for understanding mathematical expressions commonly encountered in sedimentary geology. Each can ...
Digital Sandstone Tutorial part of Activities
Kitty Milliken, University of Texas at Austin, The
The Tutorial Petrographic Image Atlas is designed to give students more exposure to petrographic features than they can get during organized laboratory periods.
Red rock and concretion models from Earth to Mars: Teaching diagenesis part of Activities
Margie Chan, University of Utah
This activity teaches students concepts of terrestrial diagenesis (cementation, fluid flow, porosity and permeability, concretions) and encourages them to apply those concepts to new or unknown settings, including ...
|
#include "macros.h"
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include "Mat.h"
#include "KeyPoint.h"
#include "DescriptorMatch.h"
#ifndef __FF_DESCRIPTORMATCHING_H__
#define __FF_DESCRIPTORMATCHING_H__
class DescriptorMatching : public Nan::ObjectWrap {
public:
static NAN_MODULE_INIT(Init);
static NAN_METHOD(MatchFlannBased);
static NAN_METHOD(MatchBruteForce);
static NAN_METHOD(MatchBruteForceL1);
static NAN_METHOD(MatchBruteForceHamming);
static NAN_METHOD(MatchBruteForceHammingLut);
static NAN_METHOD(MatchBruteForceSL2);
static NAN_METHOD(MatchFlannBasedAsync);
static NAN_METHOD(MatchBruteForceAsync);
static NAN_METHOD(MatchBruteForceL1Async);
static NAN_METHOD(MatchBruteForceHammingAsync);
static NAN_METHOD(MatchBruteForceHammingLutAsync);
static NAN_METHOD(MatchBruteForceSL2Async);
#if CV_VERSION_MINOR < 2
static void match(Nan::NAN_METHOD_ARGS_TYPE info, std::string matcherType);
static void matchAsync(Nan::NAN_METHOD_ARGS_TYPE info, std::string matcherType);
#else
static void match(Nan::NAN_METHOD_ARGS_TYPE info, int matcherType);
static void matchAsync(Nan::NAN_METHOD_ARGS_TYPE info, int matcherType);
#endif
struct MatchContext {
public:
cv::Ptr<cv::DescriptorMatcher> matcher;
cv::Mat descFrom;
cv::Mat descTo;
std::vector<cv::DMatch> dmatches;
const char* execute() {
matcher->match(descFrom, descTo, dmatches);
return "";
}
FF_VAL getReturnValue() {
FF_ARR jsMatches = FF_NEW_ARRAY(dmatches.size());
uint i = 0;
for (auto dmatch : dmatches) {
FF_OBJ jsMatch = FF_NEW_INSTANCE(DescriptorMatch::constructor);
FF_UNWRAP(jsMatch, DescriptorMatch)->dmatch = dmatch;
jsMatches->Set(i++, jsMatch);
}
return jsMatches;
}
};
};
#endif
|
- Exam wrappers. As David Thompson describes the process, "exam wrappers required students to reflect on their performance before and after seeing their graded tests." The first four questions, completed just prior to receiving their graded test, asked students to report the time they spent preparing for the test, their methods of preparation, and their predicted test grade. After reviewing their graded test, students completed the final three reflection questions, including a categorization of test mistakes and a list of changes to implement in preparation for the next test. Thompson then collected and made copies of the wrappers returned them to the students several days later, reminding them to consider what they planned to do differently or the same in preparation for the upcoming test. Thompson reports that each reflection exercise required only 8-10 minutes of class time. Clara Hardy and others also describes uses exam wrappers.
- Reading Reflections. As Karl Wirth writes, reading reflections, effectively outlined by David Bressoud (2008), are designed to address some of the challenges students face with college-level reading assignments. Students submit online reading reflections (e.g., using Moodle or Blackboard) after completing each reading assignment and before coming to class. In each reflection, students summarize the important concepts of the reading and describe what was interesting, surprising, or confusing to them. The reading reflections not only encourage students to read regularly before class, but they also promote content mastery and foster student development of monitoring, self-evaluation, and reflection skills. For the instructor, reading reflections facilitate "just-in-time" teaching and provide invaluable insights into student thinking and learning. According to Wirth, expert readers are skilled at using a wide range of strategies during all phases of reading (e.g., setting goals for learning, monitoring comprehension during reading, checking comprehension, and self-reflection), but most college instruction simply assumes the mastery of such metacognitive skills.
- Knowledge surveys. Many members of the group were influenced by Karl Wirth's work on "knowledge surveys" as a central strategy for helping students think about their thinking. Knowledge surveys involve simple self-reports from students about their knowledge of course concepts and content. In knowledge surveys, students are presented with different facets of course content and are asked to indicate whether they know the answer, know some of the answer, or don't know the answer. Faculty can use these reports to gauge how confident students feel in their understanding of course material at the beginning or end of a course, before exams or papers, or even as graduating seniors or alumni.
Kristin Bonnie's report relates how her students completed a short knowledge survey (6-12 questions) online (via Google forms) on the material covered in class that week. Rather than providing the answer to each question, students indicated their confidence in their ability to answer the question correctly (I know; I think I know; I don't know). Students received a small amount of credit for completing the knowledge survey. She used the information to review material that students seemed to struggle with. In addition, a subset of these questions appeared on their exam – the knowledge survey therefore served as a review sheet.Wirth notes that the surveys need not take much class time and can be administered via paper or the web. The surveys can be significant for clarifying course objectives, structure, and design. For students, knowledge surveys achieve several purposes: they help make clear course objectives and expectations, are useful as study guides, can serve as a formative assessment tool, and, perhaps most critically, aid in their development of self-assessment and metacognitive skills. For instructors, the surveys help them assess learning gains, instructional practices, and course design.
|
Sunday, April 13, 2008
Loaded words and contested terms
You can imagine that as an English professor I believe that words matter, that language matters. And that what you call things matters quite a bit. Take, for example, my preference for using "Asian American" to refer to people of Asian ancestry/descent rather than "Oriental." It's actually not just my preference; a whole movement in the late 1960s was formed, in part, around wanting to affirm the place of Asians in America and to dismiss the notion of people as objects (because remember: only rugs are Oriental).
Two of my most recent posts have touched on the issue of loaded words and contested terms. The April 11 post about the use of the term "Concentration Camp" to talk about where Japanese Americans were detained during WWII has sparked some interest from another blog, "Is That Legal?," where Eric Muller (remember Professor Muller? I gave a plug for his excellent book American Inquisition: The Hunt for Japanese American Disloyalty during World War II) provides more nuanced examination for thinking through the use of the term "concentration camp"--particularly its charged nature and yet why it IS an accurate term to describe the situation of Japanese Americans during WWII--click here for the link to "Is That Legal?"
[If you are reading this Eric, thanks for plugging my post/blog on your blog--I'm honored!]
And in the April 12 post asking when Asian immigrants become Asian Americans, a commenter and fellow blogger, John B. of "Domestic Issue," began an interesting exchange with another commenter about the use of the phrase "miscegenation."
Now, I don't know if any of you were reading my blog this summer, but that exact phrase came up in my August 2 post relating a racist comment made to me by a woman about purity and Asian Canadians. I said in the post: "That word has such a controversial connotation--rooted in a history of race baiting." This is the history of the word:
Originally coined in 1863, the word first appeared on a hoax pamphlet entitled “Miscegenation: The Theory of the Blending of the Races, Applied to the American White Man and Negro.” Conceived by two New York journalists, David Goodman Croly and George Wakeman, the pamphlet was an attempt to depict the Republican party explicitly as proponents of inter-racial marriage and implicitly with the propagation of mixed-race children. By doing so, the hope was that voters would reject President Lincoln in his re-election campaign, for the man who supported the emancipation proclamation was also obviously in favor of promoting not only equality of the races but inter-mixing as well. Thus from its inception, miscegenation was a word linked with political propaganda and fear mongering for the purposes of supporting segregation and defying racial equality
[taken from a talk I gave five years ago at Southern U.]
So here's the question for you, dear readers: Can loaded words and contested terms be rehabilitated? Can they escape, in the case of "concentration camp" the tragic and overwrought associations with one of the worst genocides of the 20th century? Can we use a term, like "miscegenation" to simply mean "inter-racial" without invoking its etymological roots in race baiting and its historic use as a word associated with negativity, rancor, and hatred (because whenever "miscegenation" was invoked in the mid to late 20th century it was usually done in the context of "anti-miscegenation" laws, ie: laws prohibiting inter-racial marriage, or white racist Southerners invoking the fear of "miscegenation" as a rationale for school segregation.
I suppose a few more questions to consider are:
*Why is this loaded word or contested term being used in current, contemporary usage?
*What is the purpose of this rehabilitation?
*Who is trying to use this term and for what purpose?
*Is there another term that is as accurate/precise in its meaning as the contested term? Why is it important to use the contested term rather than the less loaded word?
I'd love to hear from anyone out there with an opinion...anyone???
CVT said...
I'm still waiting to read John B.'s explanation before I go too far into this, but here's my quick off-the-cuff take:
I think there are definitely terms that can be used, instead. I think the easiest is "interracial" with a relevant descriptor attached to it (i.e. "interracial marriage," "interracial sex," or whatever). If that sounds a bit awkward, "cross-cultural" could suffice. I don't know. "Miscegenation" just feels along the lines of "Oriental" to me. Certainly not along the lines of major ethnic slurs, but not feeling good, either. More of the - "do people REALLY still say that?" - than the other kind of reaction.
And - if people are going to try to reclaim the term, then I would say that it's got to be the people the term is referring to do so. Nobody would even think about "re-claiming" the N-word FOR black people, so it would have to be a group of mixed folks that took on "miscegenation" for me to sit well with it.
That said, I don't know John B.'s explanation yet, so there might be more to it than I am aware . . .
Charlotte said...
The "n-word" also came to mind for me when I read this post. Still controversial, but it has most certainly been rehabilitated, at least by some of the population against whom it was used.
I brought this topic up in the classroom when I taught with Emily Bernard's "Teaching the N-Word," and the generational/racial differences with the answers was amazing.
Usage does change with time and context, but it's always important to acknowledge the word's history, and how you are attempting to redefine it, and why.
On another note: I was looking at makeup online, and some line, I forget which, offered mineral powder in "golden oriental." I couldn't believe it.
Were they really able to sell this product with that marketing? Were consumers ok with that? That is a problem for me.
John B. said...
Jennifer (and cvt), I'll have a post up tonight (probably late) and post the link to it here.
Thanks again for these questions: they get to the very essence of some claims I want to make about how racial admixture is depicted and discussed in art and literature throughout the Americas, and dialogue about them will certainly be helpful for my work.
John B. said...
Later than I had intended, but here is my post.
Genepool said...
The nice thing about America is that whatever term we decide is appropriate today will likely be exchanged for something else down the road.
"Miscegenation" basically means the same thing as "Interracial" with only time and peoples perception of its descriptive intent to really differentiate the two words.
"Crippled" and "Handicapped" are similar examples. I am almost positive that in my lifetime that we will see other seemingly innocuous words replaced as individuals and groups decide they are inappropriate, for whatever reason.
I'm not saying I approve or disapprove of the word "miscegenation" because before reading your post I had honestly never even heard the term used. I'm just saying for all that these usages matter to people now they will likely, over time, be reevaluated and replaced. Which is, in my opinion, pretty damn funny.
baby221 said...
I really don't think you can save miscegenation, but if it were to happen at all it would have to come out of a movement of mixed-race folk as cvt suggested. The lgbt movement has reclaimed queer and dyke, some women are in the process of reclaiming bitch and slut. I guess it could happen, but I'm not sure it's a word I'd ever use because it just rubs me the wrong way. I'm a much bigger fan of interracial and/or interethnic.
Jennifer said...
I appreciate everyone who left comments on this topic, because I think this continues to be a vexed subject and I appreciate the thoughtfulness to which everyone approached this subject.
I've just posted a lengthy comment on John B.'s blog, so if you're curious, I'd go to "Domestic Issue" for a continuation of the "miscegenation" usage there.
What I will say in this space is that I agree with both CVT and Baby221--I don't believe, personally as well as professionally, that "miscegenation" is a word that can escape its etymological roots and consistent negative/pejorative usage. And if one were to undertake such a project, it would have to be a mass movement coming from inter-racial couples or from mixed-race people.
But I suppose, more to the point, I remain unconvinced for trying to rehabilitate it for common usage in the 21st century. I do think that John B., in his own academic project, SHOULD use this word and SHOULD investigate "miscegenation" and its use as a concept and tool of the state and cultural apparatus--I think any historic project that is looking at inter-racial relationships in the 17th-19th centuries would be remiss in not referring to "miscegenation" since that's the terminology that was in use during that time period.
But in the late 20th C and 21st century, I don't see a place for "miscegenation" as a word to simply refer to "inter-racial" couples.
And I would disagree with Genepool that inter-racial and miscegenation are inter-changable--they really aren't. I don't see "inter-racial" as simply a more "pc" or 21st century version of miscegenation. I'm not sure when "inter-racial" came into the American lexicon, but I think it makes a HUGE differece that the word "miscegenation" had such distinctly "American" roots in racism and politics--and that it was a phrase almost always associated with things that were negative--anti-miscegenation, agitating against miscegenation--miscegenation as a way to quickly malign someone and to suggest that miscegenated people were a blight on the American society. It is a word that is so filled with a history of racism and race hatred--a word we should remember was employed skillfully by segregationists--that to my mind, it's negative history can't be forgotten, and actually shouldn't be forgotten.
[she steps off soapbox now]
The last thing I'll leave you with is directed to Charlotte:
"REALLY??? Golden Oriental???"
UGH. If you find the name of the makeup company, Charlotte, I'd love to know.
John B. said...
Just a quick thank-you, first of all, for your very thorough and thoughtful response over at my place. You've given me much to think about that, in a couple of days, I'll have some time to address properly.
The earliest use of "interracial" according to the OED is from 1888--as an adjective for the substantive "conflict." The earliest use given for that word used within a sexual context--"interracial couple"--is 1972(!). More research required, of course, but I wonder if "interracial" was adopted as a response to Loving vs. Virginia's finding that anti-miscegenation laws were unconstitutional.
Shoot. This is far more compelling than the papers I have to grade, but duties call. Still: thanks again for this discussion.
|
#pragma once
#include "PR_Config.h"
namespace PR {
class RayStream;
class HitStream;
class BoundingBox;
struct Ray;
struct HitEntry;
/// An archive is a containerlike object with a bounding box. A scene is a special case of an archive
class PR_LIB_CORE IArchive {
public:
/// Traces a stream of rays and produces a stream of hits
virtual void traceRays(RayStream& rays, HitStream& hits) const = 0;
/// Traces a single ray and returns true if something was hit. Information about the hit are updated if a hit was found
virtual bool traceSingleRay(const Ray& ray, HitEntry& entry) const = 0;
/// Traces a single ray and returns true if something lays within the given distance
virtual bool traceShadowRay(const Ray& ray, float distance = PR_INF) const = 0;
/// Bounding box containing all elements inside in world coordinates.
virtual BoundingBox boundingBox() const = 0;
};
} // namespace PR
|
A Euro theory
f it were not for the euro, Germany’s trade balance would have caused a revaluation of the Mark, which would automatically have reduced the exchange rates of the other "European currencies", thus favouring them on international markets. The single currency was not created to stimulate exports and improve productivity.
In fact, for the first time, the then President of the European Economic Community, Roy Jenkins, proposed a common currency which, however, was also based on a common budget, equal to 10% of the sum of all Member States’ GDPs.
Initially the Euro was based on the "optimum currency area" theory developed by the Canadian economist, Robert Mundell, in 1961. It also rested on the fact that an economy open to international trade always tends to a low exchange rate.
Furthermore, as assumed by Mundell’s group of economists, in a highly diversified national economy the exogenous shock is always very limited.
This would lead a country open to trade and with a diversified economy to accept, in principle, a currency common to other countries.
Provided, however, that there is flexibility on the capital and labour markets and that its economy is very diversified and open to international trade.
However, to what extent can an economy be "diversified"? Does excess of diversification not lead - as natural - to a different and sometimes negative gain margin between products?
In Mundell’s model, the national currencies were described by the economic theory as simple barriers to international trade, as well as limits to productivity and finally obstacles blocking commercial transactions.
At that time, Jacques Delors and Romano Prodi theorized that - rebus sic stantibus - with the mere introduction of the Euro, the European economy would grow 1-1.5% per year.
Later Perrson and Nitsch proved that the econometric model used for those predictions was wrong, while other academics and experts studied the influence of the European monetary union on international trade.
Once again the analyses carried out on macroeconomic data demonstrated that the assessment of the benefits resulting from the single currency had been greatly exaggerated.
Obviously, for political purposes, economics is not so much a "sad science", but rather rhetoric used to convey political and social messages and choices.
According to these more realistic models, the monetary union was responsible only for a 4.7-6.3% increase in foreign trade, while the most pessimistic forecasts of the first analyses on the Euro-induced growth pointed to a 20% or even a 200-300% increase in international trade.
We have always known that economics is ideology in disguise.
In other words, the Euro does not change international trade transactions, but rather tends to change competitive pricing.
Furthermore, there is no factual evidence of a stable structural difference between foreign trade and exchange rate.
Moreover, according to the International Monetary Fund, a 10% decline of the exchange rate leads to a 1.5% average increase of GDP.
Yet another demonstration of how a healthy and sound devaluation is good for international trade.
The persistently "high" single currency has also hampered recovery in the Eurozone countries, while other European countries, such as Sweden, could quickly rebuild their economy.
This implies that the Euro could do nothing to avoid the crisis, except in Germany, where the per capita GDP has been growing incessantly since 1999.
As to investment in fixed assets, only France, Belgium and Finland have been successful.
Portugal and Greece have fallen to the levels of fixed capital investment of the 1980s, while per capita fixed capital investment (housing, infrastructure, roads, railways, airports, machinery, etc.) has levelled off since 1999.
With the Euro introduction, investment in infrastructure was put to an end.
Furthermore, as repeatedly noted, the crisis of the single currency and of the Eurozone began with Greece’s tragic situation.
Greece is worth almost 3% of the Eurozone GDP and the banking crisis following tension in Greece, at first, and later in Spain, Germany and Italy, cannot be solved with the EU banking union, but only with the action of individual governments.
The signal to international markets is clear: if the Euro is hit with a speculative action, the Eurozone individual countries shall try to solve it, with their limited resources.
With its crisis Greece has later demonstrated that monetary and credit tensions in each country of the single monetary area are never supported by the rest of the Eurozone - as would happen in any real monetary union - but the country in trouble is blamed for being "spendthrift". The result is that the other Eurozone countries buy the assets of the nation in crisis below cost.
In fact, the single currency works only in really federal States, such as India or the United States, where the internal market and financial networks are wide and can manage the income gap between the various regions of the country.
If we were to support the economies of Italy, Greece, Spain and Portugal, the cost of recovery for these four countries would be 260 billion euro per year for ten years.
Hence the issue does not lie in Germany being wicked, but in the fact that the Euro has been conceived and designed badly and leads to crisis the countries which do not adjust their domestic economy to a structurally and unreasonably overvalued currency.
And in these cases, monetary expansion combined with economic "austerity" does not solve the problems.
Public spending and discretionary spending, as well as wages and salaries and, in some respects, even profits are now regulated by the Solidarity Pacts of 2011, in addition to the Treaty on Stability, Coordination and Governance signed in 2012.
They are inter-European agreements prohibiting the redistribution of funds within the EU. They were signed upon German pressure and it is worth recalling that Germany cannot objectively take upon itself the cost for restructuring Southern countries’ debt.
Indeed, we could devalue the Euro.
Nevertheless the relations between the Eurozone members would not change and Germany would gain even more from a devalued Euro.
Therefore the only way then to change the exchange rate between the various countries of the single currency is not to devalue the Euro, which is based on fixed exchange rates established ne varietur in 1999, but just leave the Euro area.
Furthermore, considering the differences of economic integration in the Eurozone, if the single currency were devalued, the least integrated country, namely France, would gain much more than the others.
It is worth making clear that it would be a gain at the expense of the Euro Mediterranean countries.
It would be tantamount to go back with the Euro to the old gold standard of the 1930s, with the Euro: either it is fully dissolved or you decide to leave.
In this sense, the single currency is a severe loss of economic flexibility in the relationship between inflation, productivity and public debt.
Relations between macroeconomic values which can be manipulated for the better only in a national context, given that the EU still records very significant micro and macroeconomic differences.
It should be noted that the impasse resulting from the gold standard led to the Great Depression after the 1929 crisis.
At the beginning of the Great Depression, Germany and Great Britain tried an internal devaluation, but in these cases, if there is a fixed monetary standard, devaluation only means domestic deflation.
Considering price rigidity, unchanged financial costs and the money supply restriction, any policy of this kind finally makes both politics and society unmanageable.
What about leaving the single currency?
Meanwhile, it is worth recalling that, in international financial law, what matters is not the lender’s nationality, but rather the law applicable to the contract.
If, for example, the debt were regulated by French law, regardless of the parties’ nationality, the payment should be made in the French national currency.
Moreover, statistics throughout the single currency EU tells us that the private debt would not be affected by the transition to the new Franc, Lira, Peseta, etc.
According to the studies of the Bank for International Settlements, which has already analysed these issues, the cost to be borne by EU countries for leaving the single currency would be approximately 5 billion euros - a figure that can be easily managed by everybody.
Hence, after the end of the Euro, the EU countries could appreciate or devalue their currencies, by offering competitive prices and thus recreating precisely those competitive advantages which had been basically removed by the single currency.
In this way the German Mark would surely appreciate as against the Lira and the Peseta, thus favouring the Southern countries’ currencies and making the huge German trade surplus disappear, as if by magic.
Probably this is the best prospect and the best way forward.
Giancarlo Elia Valori
Advisory Board Co-chair Honoris Causa
MD Newsletter
|
Sesame Street
Plot The Count's Australian friend
Air date May 4, 1994
Season Season 25 (1993-1994)
Sponsors I, O, 2
Picture Segment Description
SCENE 1 An exhausted letter carrier delivers six bags of mail from Australia to The Count at Hooper's Store. He explains to Mr. Handford that they all come from one of his oldest and dearest friends, Matilda. Each piece of mail tells him she'll be visiting today and to meet her at the bus stop at 10 o'clock.
Cartoon A map of Australia morphs into the shape of animals that are found there.
Artist: Fred Garbers
(EKA: Episode 3021)
Film "We have a nice school"... with ducks.
(First: Episode 3144)
Cartoon A cat catches a TELEPHONE and eats it.
Artists: The Hubleys
(EKA: Episode 0172)
Muppets Monty sings "Watermelons and Cheese," the improper way to answer the phone.
(EKA: Episode 3214)
Animation Kids narrate how a Navajo blanket is weaved.
(EKA: Episode 3006)
Cartoon Gerald's dog Sparky likes to pretend he's an alligator.
(EKA: Episode 1563)
SCENE 2 Big Bird wonders why the Count is waiting at the bus stop and he's filled in. The Count counts the passing buses, until one stops and an elderly woman steps off. She's not Matilda, but has a message from her - she'll call the Hooper's Store phone at 11.
Animation Counting to 10 (Chinese imagery)
(EKA: Episode 3217)
(First: Episode 3193)
Cartoon "In My Book" (sung by Jerry Nelson)
(EKA: Episode 3018)
Cast Maria as Charlie Chaplin -Long, Longer, Longest
(EKA: Episode 1460)
Cartoon At the Pride Day Ceremony, Donald is waiting to describe his proudest accomplishment, and is initially unsure of himself next to other impressive students. He finally proudly acclaims his achievement, tying his shoes all by himself.
Artist: John Korty
(EKA: Episode 2254)
SCENE 3 The Count waits at the phone, when a construction worker needs to use it. She agrees to wait, until he starts counting the rings instead of answering. Mr. Handford angrily hands him the phone and Matilda responds, telling him she will be there soon. The Count uses Mr. Handford's watch to count the seconds.
Cartoon Counting to 10
Artist: Keith Haring
(EKA: Episode 3104)
Film People go under, over, through and around a hoop. (Luis voice-over)
(First: Episode 3140)
Animation I / i candles
(EKA: Episode 3107)
Muppets Grover sings "I Stand Up Straight and Tall" while using some fast cutting camera trickery.
(EKA: Episode 0926)
Cartoon Speech Balloon: I for Island.
(EKA: Episode 0340)
Muppets Telly Monster demonstrates "Fast" and "Slow" to Cookie Monster by using a plate of cookies. To demonstrate slow, Telly eats one of the cookies in slow bites. After finishing eating, he asks Cookie Monster to eat a cookie slowly. Cookie Monster gives it a try, but ends up gobbling all the cookies on the plate. Telly considers it to be fast rather than slow, but Cookie Monster says it was slow in his opinion.
(EKA: Episode 2226)
SCENE 4 Matilda finally arrives at Hooper's and the two friends share a "Hello," before saying goodbye immediately after. The Count explains to a confused Big Bird and Mr. Handford that he and Matilda were the best of friends, but as kids she and her family moved to Melbourne. Since then, they've gotten back together 103 times, counting each "hello" as a precious moment. They know that the sooner they say "goodbye," the sooner they can say "hello" again. They begin counting the different ways to say goodbye.
Cartoon A girl narrates a poem about the sad time when her goldfish died.
Artist: Bruce Cayard
(EKA: Episode 2228)
(EKA: Episode 0729)
Cartoon What if I looked like George Washington...
(EKA: Episode 2257)
Song Joe Raposo sings "I Believe in Little Things."
(EKA: Episode 2485)
Animation Fans reveal the letter O.
(EKA: Episode 3021)
Muppets / Celebrity "That's the Letter O"
(EKA: Episode 3066)
Cartoon O for open, off, owl, ocean
(EKA: Episode 3091)
Muppets Oscar reads Irvine the story of "Snow Grouch."
(First: Episode 2630)
Cartoon A man tells a confused boy that he saw a bird on a tree, with both of their thoughts appearing on the screen.
(EKA: Episode 0814)
Film A man and a little girl perform small aerobic workouts.
(EKA: Episode 1845)
Song Holy cow, it's number 2!
(First: Episode 3193)
Muppets Game Show: The How Many Game??
Guy Smiley tells The Two-Headed Monster to find two things in 30 seconds. They bring one bowling ball, four sheep and three cows, all of which don't count. Suddenly, they realize they have two heads, which means they win! Little Bo Peep appears looking for her sheep, a train appears out of nowhere, and the scene ends in chaos.
(EKA: Episode 2503)
Film The McDouble twins display pairs of things.
(EKA: Episode 3217)
Cartoon The secret drawing is a mailman.
(EKA: Episode 0265)
SCENE 5 The Count finishes writing a letter for the letter carrier to bring to Matilda. She's relieved it's only a single letter, but faints when the Count shows her six more bags. The Count begins listing things he can count while he waits for the mail to reach Matilda, and Matilda announces the sponsors (in voice-over).
Previous episode: Next episode:
Episode 3252 Episode 3254
Ad blocker interference detected!
|
#pragma once
#include <unordered_map>
#include <ostream>
#include <vector>
using namespace std;
class SparseVector
{
private:
unordered_map<int, double> values;
public:
SparseVector(void)
{}
SparseVector(unordered_map<int, double> val): values(val)
{}
unordered_map<int, double>::iterator begin()
{
return values.begin();
}
unordered_map<int, double>::iterator end()
{
return values.end();
}
unordered_map<int, double>::const_iterator cbegin() const
{
return values.cbegin();
}
unordered_map<int, double>::const_iterator cend() const
{
return values.cend();
}
int size()
{
return values.size();
}
double& operator[](int key)
{
return values[key];
}
double operator[](int key) const
{
return values.count(key) ? values.at(key): 0;
}
const SparseVector& operator*= (double other)
{
for(auto it = values.begin(); it != values.end(); it++)
values[(*it).first] = other * (*it).second;
return *this;
}
const SparseVector& operator+= (const SparseVector& other)
{
for(auto it = other.values.begin(); it != other.values.end(); it++)
values[(*it).first] += (*it).second;
return *this;
}
const SparseVector& operator-= (const SparseVector& other)
{
for(auto it = other.values.begin(); it != other.values.end(); it++)
values[(*it).first] -= (*it).second;
return *this;
}
SparseVector operator* (double other) const
{
SparseVector result(values);
return result *= other;
}
SparseVector operator+ (const SparseVector& other) const
{
SparseVector result(values);
return (result += other);
}
SparseVector operator- (const SparseVector& other) const
{
SparseVector result(values);
return (result -= other);
}
template <class TVector>
double dot(const TVector& other) const
{
double sum = 0.0;
for(auto it = values.begin(); it != this->values.end(); it++)
{
int key = (*it).first;
sum += other[key] * (*it).second;
}
return sum;
}
double sum() const
{
double sum = 0.0;
for(auto it = values.begin(); it != this->values.end(); it++)
sum += (*it).second;
return sum;
}
void clear()
{
values.clear();
}
double lengthSquared() const
{
double sum = 0.0;
for(auto it = values.begin(); it != this->values.end(); it++)
sum += (*it).second * (*it).second;
return sum;
}
~SparseVector(void)
{
}
};
ostream& operator<<(ostream& out, SparseVector &v);
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef GEODE_SECURITY_TYPEDEFS_H_
#define GEODE_SECURITY_TYPEDEFS_H_
#include "config.h"
#ifdef _LINUX
_Pragma("GCC system_header")
#endif
#include <vector>
#include <string>
#include <algorithm>
namespace apache {
namespace geode {
namespace client {
namespace testframework {
namespace security {
typedef enum {
ID_NONE = 1,
ID_DUMMY = 2,
ID_LDAP = 3,
ID_PKI = 4,
ID_NOOP = 5,
ID_DUMMY2 = 6,
ID_DUMMY3 = 7
} ID;
typedef enum {
READER_ROLE = 1,
WRITER_ROLE = 2,
QUERY_ROLE = 3,
ADMIN_ROLE = 4,
NO_ROLE = 5
} ROLES;
typedef enum {
OP_GET = 0,
OP_CREATE = 1,
OP_UPDATE = 2,
OP_DESTROY = 3,
OP_INVALIDATE = 4,
OP_REGISTER_INTEREST = 5,
OP_UNREGISTER_INTEREST = 6,
OP_CONTAINS_KEY = 7,
OP_KEY_SET = 8,
OP_QUERY = 9,
OP_REGISTER_CQ = 10,
OP_REGION_CLEAR = 11,
OP_REGION_CREATE = 12,
OP_REGION_DESTROY = 13,
OP_GETALL = 14,
OP_PUTALL = 15,
OP_EXECUTE_FUNCTION = 16,
OP_END = 17
} OperationCode;
typedef std::vector<std::string> stringList;
typedef std::vector<std::string> opCodeStrs;
typedef std::vector<OperationCode> opCodeList;
typedef std::vector<std::string> PerClientList;
typedef std::vector<std::string> readerList;
typedef std::vector<std::string> writerList;
typedef std::vector<std::string> adminList;
typedef std::vector<std::string> queryList;
const opCodeStrs::value_type opCodeStrArr[] = {"get",
"create",
"update",
"destroy",
"invalidate",
"register_interest",
"unregister_interest",
"contains_key",
"key_set",
"query",
"register_cq",
"region_clear",
"region_create",
"region_destroy",
"get_all",
"put_all",
"execute_function",
"end"};
static OperationCode strToOpCode(std::string& opCodeStr) {
static opCodeStrs allOpCodes(
opCodeStrArr,
opCodeStrArr + sizeof opCodeStrArr / sizeof *opCodeStrArr);
opCodeStrs::iterator it =
std::find(allOpCodes.begin(), allOpCodes.end(), opCodeStr);
OperationCode retCode = OP_END;
if (it != allOpCodes.end()) {
retCode = static_cast<OperationCode>(it - allOpCodes.begin());
if (allOpCodes[retCode] != opCodeStr) {
retCode = OP_END;
}
}
return retCode;
}
/* for future use
static std::string opCodeToStr(OperationCode op) {
static opCodeStrs allOpCodes(opCodeStrArr, opCodeStrArr + sizeof
opCodeStrArr / sizeof *opCodeStrArr);
return std::string(allOpCodes[ op ]);
}
*/
} // namespace security
} // namespace testframework
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_SECURITY_TYPEDEFS_H_
|
Excerpts for Thames : The Biography
The River as Fact
It has a length of 215 miles, and is navigable for 191 miles. It is the longest river in England but not in Britain, where the Severn is longer by approximately 5 miles. Nevertheless it must be the shortest river in the world to acquire such a famous history. The Amazon and the Mississippi cover almost 4,000 miles, and the Yangtze almost 3,500 miles; but none of them has arrested the attention of the world in the manner of the Thames.
It runs along the borders of nine English counties, thus reaffirming its identity as a boundary and as a defence. It divides Wiltshire from Gloucestershire, and Oxfordshire from Berkshire; as it pursues its way it divides Surrey from Middlesex (or Greater London as it is inelegantly known) and Kent from Essex. It is also a border of Buckinghamshire. It guarded these once tribal lands in the distant past, and will preserve them into the imaginable future.
There are 134 bridges along the length of the Thames, and forty-four locks above Teddington. There are approximately twenty major tributaries still flowing into the main river, while others such as the Fleet have now disappeared under the ground. Its "basin," the area from which it derives its water from rain and other natural forces, covers an area of some 5,264 square miles. And then there are the springs, many of them in the woods or close to the streams beside the Thames. There is one in the wood below Sinodun Hills in Oxfordshire, for example, which has been described as an "everlasting spring" always fresh and always renewed.
The average flow of the river at Teddington, chosen because it marks the place where the tidal and non-tidal waters touch, has been calculated at 1,145 millions of gallons (5,205 millions of litres) each day or approximately 2,000 cubic feet (56.6 cubic metres) per second. The current moves at a velocity between 1Ú2 and 23Ú4 miles per hour. The main thrust of the river flow is known to hydrologists as the "thalweg"; it does not move in a straight and forward line but, mingling with the inner flow and the variegated flow of the surface and bottom waters, takes the form of a spiral or helix. More than 95 per cent of the river's energy is lost in turbulence and friction.
The direction of the flow of the Thames is therefore quixotic. It might be assumed that it would move eastwards, but it defies any simple prediction. It flows north-west above Henley and at Teddington, west above Abingdon, south from Cookham and north above Marlow and Kingston. This has to do with the variegated curves of the river. It does not meander like the Euphrates, where according to Herodotus the voyager came upon the same village three times on three separate days, but it is circuitous. It specialises in loops. It will take the riparian traveller two or three times as long to cover the same distance as a companion on the high road. So the Thames teaches you to take time, and to view the world from a different vantage.
The average "fall" or decline of the river from its beginning to its end is approximately 17 to 21 inches (432 to 533 mm) per mile. It follows gravity, and seeks out perpetually the simplest way to the sea. It falls some 600 feet (183 m) from source to sea, with a relatively precipitous decline of 300 feet (91.5 m) in the first 9 miles; it falls 100 (30.4 m) more in the next 11 miles, with a lower average for the rest of its course. Yet averages may not be so important. They mask the changeability and idiosyncrasy of the Thames. The mean width of the river is given as 1,000 feet (305 m), and a mean depth of 30 feet (9 m); but the width varies from 1 or 2 feet (0.3 to 0.6 m) at Trewsbury to 51Ú2 miles at the Nore.
The tide, in the words of Tennyson, is that which "moving seems asleep, too full for sound and foam." On its flood inward it can promise benefit or danger; on its ebb seaward it suggests separation or adventure. It is one general movement but it comprises a thousand different streams and eddies; there are opposing streams, and high water is not necessarily the same thing as high tide. The water will sometimes begin to fall before the tide is over. The average speed of the tide lies between 1 and 3 knots (1.15 and 3.45 miles per hour), but at times of very high flow it can reach 7 knots (8 miles per hour). At London Bridge the flood tide runs for almost six hours, while the ebb tide endures for six hours and thirty minutes. The tides are much higher now than at other times in the history of the Thames. There can now be a difference of some 24 feet (7.3 m) between high and low tides, although the average rise in the area of London Bridge is between 15 and 22 feet (4.5 and 6.7 m). In the period of the Roman occupation, it was a little over 3 feet (0.9 m). The high tide, in other words, has risen greatly over a period of two thousand years.
The reason is simple. The south-east of England is sinking slowly into the water at the rate of approximately 12 inches (305 mm) per century. In 4000 BC the land beside the Thames was 46 feet (14 m) higher than it is now, and in 3000 BC it was some 31 feet (9.4 m) higher. When this is combined with the water issuing from the dissolution of the polar ice-caps, the tides moving up the lower reaches of the Thames are increasing at a rate of 2 feet (0.6 m) per century. That is why the recently erected Thames Barrier will not provide protection enough, and another barrier is being proposed.
The tide of course changes in relation to the alignment of earth, moon and sun. Every two weeks the high "spring" tides reach their maximum two days after a full moon, while the low "neap" tides occur at the time of the half-moon. The highest tides occur at the times of equinox; this is the period of maximum danger for those who live and work by the river. The spring tides of late autumn and early spring are also hazardous. It is no wonder that the earliest people by the Thames venerated and propitiated the river.
The general riverscape of the Thames is varied without being in any sense spectacular, the paraphernalia of life ancient and modern clustering around its banks. It is in large part now a domesticated river, having been tamed and controlled by many generations. It is in that sense a piece of artifice, with some of its landscape deliberately planned to blend with the course of the water. It would be possible to write the history of the Thames as a history of a work of art.
It is a work still in slow progress. The Thames has taken the same course for ten thousand years, after it had been nudged southward by the glaciation of the last ice age. The British and Roman earthworks by the Sinodun Hills still border the river, as they did two thousand years before. Given the destructive power of the moving waters, this is a remarkable fact. Its level has varied over the millennia--there is a sudden and unexpected rise at the time of the Anglo-Saxon settlement, for example--and the discovery of submerged forests testifies to incidents of overwhelming flood. Its appearance has of course also altered, having only recently taken the form of a relatively deep and narrow channel, but its persistence and identity through time are an aspect of its power.
Yet of course every stretch has its own character and atmosphere, and every zone has its own history. Out of oppositions comes energy, out of contrasts beauty. There is the overwhelming difference of water within it, varying from the pure freshwater of the source through the brackish zone of estuarial water to the salty water in proximity to the sea. Given the eddies of the current, in fact, there is rather more salt by the Essex shore than by the Kentish shore. There are manifest differences between the riverine landscapes of Lechlade and of Battersea, of Henley and of Gravesend; the upriver calm is in marked contrast to the turbulence of the long stretches known as River of London and then London River. After New Bridge the river becomes wider and deeper, in anticipation of its change.
The rural landscape itself changes from flat to wooded in rapid succession, and there is a great alteration in the nature of the river from the cultivated fields of Dorchester to the thick woods of Cliveden. From Godstow the river becomes a place of recreation, breezy and jaunty with the skiffs and the punts, the sports in Port Meadow and the picnic parties on the banks by Binsey. But then by some change of light it becomes dark green, surrounded by vegetation like a jungle river; and then the traveller begins to see the dwellings of Oxford, and the river changes again. Oxford is a pivotal point. From there you can look upward and consider the quiet source; or you can look downstream and contemplate the coming immensity of London.
In the reaches before Lechlade the water makes its way through isolated pastures; at Wapping and Rotherhithe the dwellings seem to drop into it, as if overwhelmed by numbers. The elements of rusticity and urbanity are nourished equally by the Thames. That is why parts of the river induce calm and forgetfulness, and others provoke anxiety and despair. It is the river of dreams, but it is also the river of suicide. It has been called liquid history because within itself it dissolves and carries all epochs and generations. They ebb and flow like water.
The River as Metaphor
The river runs through the language, and we speak of its influence in every conceivable context. It is employed to characterise life and death, time and destiny; it is used as a metaphor for continuity and dissolution, for intimacy and transitoriness, for art and history, for poetry itself. In The Principles of Psychology (1890) William James first coined the phrase "stream of consciousness" in which "every definite image of the mind is steeped . . . in the free water that flows around it." Thus "it flows" like the river itself. Yet the river is also a token of the unconscious, with its suggestion of depth and invisible life.
The river is a symbol of eternity, in its unending cycle of movement and change. It is one of the few such symbols that can readily be understood, or appreciated, and in the continuing stream the mind or soul can begin to contemplate its own possible immortality.
In the poetry of John Denham's "Cooper's Hill" (1642), the Thames is a metaphor for human life. How slight its beginning, how confident its continuing course, how ineluctable its destination within the great ocean:
Hasting to pay his tribute to the sea,
Like mortal life to meet eternity.
The poetry of the Thames has always emphasised its affiliations with human purpose and with human realities. So the personality of the river changes in the course of its journey from the purity of its origins to the broad reaches of the commercial world. The river in its infancy is undefiled, innocent and clear. By the time it is closely pent in by the city, it has become dank and foul, defiled by greed and speculation. In this regress it is the paradigm of human life and of human history. Yet the river has one great advantage over its metaphoric companions. It returns to its source, and its corruption can be reversed. That is why baptism was once instinctively associated with the river. The Thames has been an emblem of redemption and of renewal, of the hope of escaping from time itself.
When Wordsworth observed the river at low tide, with the vista of the "mighty heart" of London "lying still," he used the imagery of human circulation. It is the image of the river as blood, pulsing through the veins and arteries of its terrain, without which the life of London would seize up. Sir Walter Raleigh, contemplating the Thames from the walk by his cell in the Tower, remarked that the "blood which disperseth itself by the branches or veins through all the body, may be resembled to these waters which are carried by brooks and rivers overall the earth." He wrote his History of the World (1610) from his prison cell, and was deeply imbued with the current of the Thames as a model of human destiny. It has been used as the symbol for the unfolding of events in time, and carries the burden of past events upon its back. For Raleigh the freight of time grew ever more complex and wearisome as it proceeded from its source; human life had become darker and deeper, less pure and more susceptible to the tides of affairs. There was one difference Raleigh noticed in his history, when he declared that "for this tide of man's life, after it once turneth and declineth, ever runneth with a perpetual ebb and falling stream, but never floweth again."
The Thames has also been understood as a mirror of morality. The bending rushes and the yielding willows afford lessons in humility and forbearance; the humble weeds along its banks have been praised for their lowliness and absence of ostentation. And who has ventured upon the river without learning the value of patience, of endurance, and of vigilance? John Denham makes the Thames the subject of native discourse in a further sense:
Though deep, yet clear; though gentle, yet not dull;
Strong without rage; without o'erflowing, full.
This suggests that the river represents an English measure, an aesthetic harmony to be sought or wished for, but in the same breath Denham seems to be adverting to some emblem of Englishness itself. The Thames is a metaphor for the country through which it runs. It is modest and moderate, calm and resourceful; it is powerful without being fierce. It is not flamboyantly impressive. It is large without being too vast. It eschews extremes. It weaves its own course without artificial diversions or interventions. It is useful for all manner of purposes. It is a practical river.
When Robert Menzies, an erstwhile Australian prime minister, was taken to Runnymede he was moved to comment upon the "secret springs" of the "slow English character." This identification of the land with the people, the characteristics of the earth and water with the temperament of their inhabitants, remains a poignant one. There is an inward and intimate association between the river and those who live beside it, even if that association cannot readily be understood.
From the Hardcover edition.
|
/*
矩陣快速冪
*/
#include <iostream>
#include <vector>
using namespace std;
int mod;
class matrix {
public:
vector<vector<long long>> mat;
matrix(vector<vector<long long>>& d) {
mat = d;
}
matrix(int a, int b, int c, int d) {
mat = vector<vector<long long>>(2, vector<long long>(2, 0));
mat[0][0] = a;
mat[0][1] = b;
mat[1][0] = c;
mat[1][1] = d;
}
matrix operator*(const matrix& other) {
vector<vector<long long>> temp(2, vector<long long>(2, 0));
temp[0][0] = (mat[0][0] * other.mat[0][0] % mod + mat[0][1] * other.mat[1][0] % mod) % mod;
temp[0][1] = (mat[0][0] * other.mat[0][1] % mod + mat[0][1] * other.mat[1][1] % mod) % mod;
temp[1][0] = (mat[1][0] * other.mat[0][0] % mod + mat[1][1] * other.mat[1][0] % mod) % mod;
temp[1][1] = (mat[1][0] * other.mat[0][1] % mod + mat[1][1] * other.mat[1][1] % mod) % mod;
return matrix(temp);
}
matrix operator^(int exp) {
matrix ret(1, 0, 0, 1);
while (exp) {
if (exp & 1)
ret = ret * *this;
*this = *this * *this;
exp >>= 1;
}
return ret;
}
};
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int n, m;
while (cin >> n >> m) {
if (n == 0)
cout << "0\n";
else {
mod = 1 << m;
cout << ((matrix(1, 1, 1, 0) ^ (n - 1)) * matrix(1, 1, 1, 1)).mat[1][1] << "\n";
}
}
}
|
/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(){
int T;
// Number of test cases
cin >> T;
while(T--){
string s;
// String to read
int n;
// n-th permutation to find
cin >> s >> n;
sort(s.begin(), s.end());
// Sort the string so all possible permutations can be found
for(int k = 0; k < n; k++){
// Go up to the n-th permutation
next_permutation(s.begin(), s.end());
}
// THIS IS VERY EXPENSIVE IN COMPUTATIONS BECAUSE IT CALCULATES EVERY
// LEXICOGRAPHICALLY INCREASING PERMUTATION OF THE ORIGINAL STRING UP
// TO THE DESIRED TARGED PERMUTATION, WHICH COULD BE 20! PERMUTATIONS
// LATER! For that check out H_newperm.cpp, which lays out how to more
// or less in much more less computations calculate the target permut-
// tation directly, without going over all its previous ones.
cout << s << endl;
}
}
|
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em
// with input from rmf_traffic_msgs:msg/ConvexShape.idl
// generated code does not contain a copyright notice
#ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__CONVEX_SHAPE__STRUCT_HPP_
#define RMF_TRAFFIC_MSGS__MSG__DETAIL__CONVEX_SHAPE__STRUCT_HPP_
#include <rosidl_runtime_cpp/bounded_vector.hpp>
#include <rosidl_runtime_cpp/message_initialization.hpp>
#include <algorithm>
#include <array>
#include <memory>
#include <string>
#include <vector>
#ifndef _WIN32
# define DEPRECATED__rmf_traffic_msgs__msg__ConvexShape __attribute__((deprecated))
#else
# define DEPRECATED__rmf_traffic_msgs__msg__ConvexShape __declspec(deprecated)
#endif
namespace rmf_traffic_msgs
{
namespace msg
{
// message struct
template<class ContainerAllocator>
struct ConvexShape_
{
using Type = ConvexShape_<ContainerAllocator>;
explicit ConvexShape_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL)
{
if (rosidl_runtime_cpp::MessageInitialization::ALL == _init ||
rosidl_runtime_cpp::MessageInitialization::ZERO == _init)
{
this->type = 0;
this->index = 0;
}
}
explicit ConvexShape_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL)
{
(void)_alloc;
if (rosidl_runtime_cpp::MessageInitialization::ALL == _init ||
rosidl_runtime_cpp::MessageInitialization::ZERO == _init)
{
this->type = 0;
this->index = 0;
}
}
// field types and members
using _type_type =
uint8_t;
_type_type type;
using _index_type =
uint8_t;
_index_type index;
// setters for named parameter idiom
Type & set__type(
const uint8_t & _arg)
{
this->type = _arg;
return *this;
}
Type & set__index(
const uint8_t & _arg)
{
this->index = _arg;
return *this;
}
// constant declarations
static constexpr uint8_t NONE =
0u;
static constexpr uint8_t BOX =
1u;
static constexpr uint8_t CIRCLE =
2u;
// pointer types
using RawPtr =
rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> *;
using ConstRawPtr =
const rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> *;
using SharedPtr =
std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>;
using ConstSharedPtr =
std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const>;
template<typename Deleter = std::default_delete<
rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>>
using UniquePtrWithDeleter =
std::unique_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>, Deleter>;
using UniquePtr = UniquePtrWithDeleter<>;
template<typename Deleter = std::default_delete<
rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>>
using ConstUniquePtrWithDeleter =
std::unique_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const, Deleter>;
using ConstUniquePtr = ConstUniquePtrWithDeleter<>;
using WeakPtr =
std::weak_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>;
using ConstWeakPtr =
std::weak_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const>;
// pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead
// NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly
typedef DEPRECATED__rmf_traffic_msgs__msg__ConvexShape
std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>
Ptr;
typedef DEPRECATED__rmf_traffic_msgs__msg__ConvexShape
std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const>
ConstPtr;
// comparison operators
bool operator==(const ConvexShape_ & other) const
{
if (this->type != other.type) {
return false;
}
if (this->index != other.index) {
return false;
}
return true;
}
bool operator!=(const ConvexShape_ & other) const
{
return !this->operator==(other);
}
}; // struct ConvexShape_
// alias to use template instance with default allocator
using ConvexShape =
rmf_traffic_msgs::msg::ConvexShape_<std::allocator<void>>;
// constant definitions
template<typename ContainerAllocator>
constexpr uint8_t ConvexShape_<ContainerAllocator>::NONE;
template<typename ContainerAllocator>
constexpr uint8_t ConvexShape_<ContainerAllocator>::BOX;
template<typename ContainerAllocator>
constexpr uint8_t ConvexShape_<ContainerAllocator>::CIRCLE;
} // namespace msg
} // namespace rmf_traffic_msgs
#endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__CONVEX_SHAPE__STRUCT_HPP_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.