content
stringlengths
7
2.61M
/*************************************************************************** * Copyright 2015-2019 Kieker Project (http://kieker-monitoring.net) * * 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. ***************************************************************************/ package kieker.diagnosis.frontend.tab.statistics.composite; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableDoubleValue; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.control.ProgressBar; import javafx.scene.control.TitledPane; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import javafx.util.Pair; public final class StatisticsMemoryUsageBar extends TitledPane { private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( StatisticsMemoryUsageBar.class.getName( ) ); private final ObjectProperty<Pair<Long, Long>> memoryUsage = new SimpleObjectProperty<>( new Pair<>( 0L, 0L ) ); public StatisticsMemoryUsageBar( ) { createControl( ); startUpdateThread( ); } private void createControl( ) { setText( RESOURCE_BUNDLE.getString( "memoryUsage" ) ); setCollapsible( false ); setContent( createStackPane( ) ); } private StackPane createStackPane( ) { final StackPane stackPane = new StackPane( ); stackPane.getChildren( ).add( createProgressBar( ) ); stackPane.getChildren( ).add( createProgressText( ) ); return stackPane; } private Node createProgressBar( ) { final ProgressBar progressBar = new ProgressBar( ); progressBar.setMaxWidth( Double.POSITIVE_INFINITY ); progressBar.setPrefHeight( 30 ); final ObservableDoubleValue observable = Bindings.createDoubleBinding( ( ) -> 1.0 * memoryUsage.get( ).getKey( ) / memoryUsage.get( ).getValue( ), memoryUsage ); progressBar.progressProperty( ).bind( observable ); return progressBar; } private Node createProgressText( ) { final Text progressText = new Text( ); final ObservableValue<String> observable = Bindings.createStringBinding( ( ) -> String.format( "%d / %d [MB]", memoryUsage.get( ).getKey( ), memoryUsage.get( ).getValue( ) ), memoryUsage ); progressText.textProperty( ).bind( observable ); return progressText; } private void startUpdateThread( ) { final Thread thread = new Thread( ( ) -> { while ( !Thread.interrupted( ) ) { final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean( ); final long usedHeap = memoryMXBean.getHeapMemoryUsage( ).getUsed( ) / 1024 / 1024; final long committedHeap = memoryMXBean.getHeapMemoryUsage( ).getCommitted( ) / 1024 / 1024; Platform.runLater( ( ) -> memoryUsage.set( new Pair<>( usedHeap, committedHeap ) ) ); try { Thread.sleep( 2500 ); } catch ( final InterruptedException ex ) { Thread.currentThread( ).interrupt( ); } } } ); thread.setDaemon( true ); thread.setName( "Statistics Memory Refresh Thread" ); thread.start( ); } }
His reasoning: There’s a giant hole in the market for a computer bigger than an iPhone, smaller than an iMac, and meant to be used in a relaxed position and location, rather than typed at full-speed at a desk or on a handset. Moreover, Arrington’s coverage of startups and gadget makers convinced him that, despite his zero experience as a gadget maker, he could design a tablet, hire a company to build it, and then sell it through deals with big-box retailers and online stores. The computer, named the Crunchpad, was scheduled to ship in time for Black Friday / Cyber Monday shoppers two weeks ago. It would have been a great tale of how a journalist proved his own claims for the new rules of entrepreneurialism. But at the last minute, Arrington posted on TechCrunch a claim that the production contractor, Fusion Garage — a 12 person company set up in Silicon Valley in February — had told him without warning that they and their investors had decided to sell the product themselves. Arrington, according to email he posted from Fusion Garage CEO Chandrasekar Rathakrishnan, would be pushed aside into a marketing / evangelism role. The Crunchpad was dead, he said. Since Fusion Garage and Arrington’s Crunchpad business co-owned the intellectual property for the device, the gadget would surely never ship to customers. Rathakrishnan also criticized Arrington’s Internet-celebrity approach to talking up the Crunchpad before its launch. “Publishing pictures of an unfinished product on a blog … is not a recipe for success,” he said. In Rathakrishnan’s version of the story, Arrington spent his time blowing hot air about what he was going to do, while Fusion Garage did all the work to finish the design and build the product. Enough gossip, let’s skip to the product: It’s been renamed JooJoo — the URL is thejoojoo.com. It’ll cost $499, it works over Wi-Fi only, and Rathakrishnan says the formal launch will be this week. He’s giving a video demo right now: “It has the graphic power to deliver full HD video on the go.” It will also have built-in e-book capabilities, he said. “We don’t boot to an operating system,” he said. “We boot directly to the Internet.” The operating system under the hood is a Unix variant. Pre-orders will be available beginning this Friday, December 11th. Fusion Garage will also announce a new round of funding, on top of the $3 million the company has already raised from unnamed investors. For now, JooJoo is one of those “it remains to be seen” stories. Will Arrington stop Fusion Garage? Will the two parties reconcile in the interest of making some money and not ending as the Internet’s latest FAIL tale? And if so, will enough customers spend five hundred bucks on one? Or will Apple debut its rumored tablet Mac and eat everyone’s lunch? For at least the rest of this week, JooJoo speculation and rumor-mongering will be a news beat all to itself.
In 1979, psychologist Ellen Langer and her students carefully refurbished an old monastery in Peterborough, New Hampshire, to resemble a place that would have existed two decades earlier. They invited a group of elderly men in their late 70s and early 80s to spend a week with them and live as they did in 1959, “a time when an IBM computer filled a whole room and panty hose had just been introduced to U.S. women,” Langer wrote. Her idea was to return the men, at least in their minds, to a time when they were younger and healthier—and to see if it had physiological consequences. Every day Langer and her students met with the men to discuss “current” events. They talked about the first United States satellite launch, Fidel Castro entering Havana after his march across Cuba, and the Baltimore Colts winning the NFL championship game. They discussed “current” books: Ian Fleming’s Goldfinger and Leon Uris’ Exodus. They watched Ed Sullivan and Jack Benny and Jackie Gleason on a black-and-white TV, listened to Nat King Cole on the radio, and saw Marilyn Monroe in Some Like It Hot. Everything was transporting the men back to 1959. When Langer studied the men after a week of such sensory and mindful immersion in the past, she found that their memory, vision, hearing, and even physical strength had improved. She compared the traits to those of a control group of men, who had also spent a week in a retreat. The control group, however, had been told the experiment was about reminiscing. They were not told to live as if it were 1959. The first group, in a very objective sense, seemed younger. The team took photographs of the men before and after the experiment, and people who knew nothing about the study said the men looked younger in the after-pictures, says Langer, who today is a professor of psychology at Harvard University. Clockwise: Robert Riger / Getty Images; Wikipedia; Wikipedia; Luis Korda/ Wikipedia; Wikipedia; Wikipedia Langer’s experiment was a tantalizing demonstration that our chronological age based on our birthdate is a misleading indicator of aging. Langer, of course, was tackling the role of the mind in how old we feel and act. Since her study, others have taken a more objective look at the aging body. The goal is to determine an individual’s “biological age,” a term that aims to capture the body’s physiological development and decline with time, and predict, with reasonable accuracy, the risks of disease and death. As scientists have worked to pinpoint a person’s biological age, they have learned that organs and tissues often age differently, making it difficult to reduce biological age to a single number. They have also made a discovery that echoes Langer’s work. How old we feel—our subjective age—can influence how we age. Where age is concerned, the pages torn off a calendar do not tell the whole story. While we intuitively know what it means to grow old, precise definitions of aging haven’t been easy to come by. In 1956, British gerontologist and author Alex Comfort (later famous for writing The Joy of Sex) memorably defined senescence as “a decrease in viability and an increase in vulnerability.” Any given individual, he wrote, would die from “randomly distributed causes.” Evolutionary biologists think of aging as something that reduces our ability to survive and reproduce because of “internal physiological deterioration.” Such deterioration, in turn, can be understood in terms of cellular functions: The older the cells in an organ, the more likely they are to stop dividing and die, or develop mutations that lead to cancer. This leads us to the idea that our bodies may have a true biological age. The road to determining that age, though, has not been a straight one. One approach is to look for so-called biomarkers of aging, something that’s changing in the body and can be used as a predictor of the likelihood of being struck by age-related diseases or of how much longer one has left to live. An obvious set of biomarkers could be attributes like blood pressure or body weight. Both tend to go up as the body ages. But they are unreliable. Blood pressure can be affected by medication and body weight depends on lifestyle and diet, and there are people who certainly don’t gain weight as they age. Where age is concerned, the pages torn off calendar do not tell the whole story. In the 1990s, one promising biomarker stood out: stretches of DNA called telomeres. They appear at the ends of chromosomes, serving as caps that protect the chromosomes from fraying. Telomeres have often been likened to the plastic tips that similarly protect shoelaces. It turns out that telomeres themselves get shorter and shorter each time a cell divides. And when the telomere shortens beyond a point, the cell dies. There’s a strong relationship between telomere length and health and diseases, such as cancer and atherosclerosis. But despite a range of studies trying to find such a link, it’s been hard to make the case for telomeres as accurate biomarkers of aging. In 2013, Anne Newman, director of the Center for Aging and Population Health at the University of Pittsburgh, and her student Jason Sanders reviewed the existing literature on telomeres and concluded that “if telomere length is a biomarker of human aging, it is a weak biomarker with poor predictive accuracy.” “Twenty years ago, people had high hopes that telomere length could actually explain aging, as in biological aging. There was a hope that it would be the root cause of aging,” says Steve Horvath, a geneticist and biostatistician at the University of California, Los Angeles. “Now we know that that’s simply not the case. In the last 10 to 15 years, people realized that there must be other mechanisms that play an important role in aging.” Attention shifted to how fast stem cells are being depleted in the body, or the efficacy of mitochondria (the organelles inside our cells that produce the energy needed for cells to function). Horvath scoured the data for reliable markers, looking at, for example, levels of gene expression for any strong correlations to aging. He found none. But that didn’t mean there weren’t reliable biomarkers. There was one set of data Horvath had been studiously avoiding. This had to do with DNA methylation, a process cells use to switch off genes. Methylation mainly involves the addition of a so-called methyl group to cytosine, one of the four main bases that make up strands of DNA. Because DNA methylation does not alter the core genetic sequence, but rather modifies gene expression externally, the process is called epigenetics. Courtesy of Steve Horvath Horvath didn’t think that epigenetics would have anything to do with aging. “I had data sitting there and I would not really touch them, because I thought there was no meaning in it anyway,” he says. But some time in 2009, Horvath gave in and analyzed a dataset of methylation levels at 27,000 locations on the human genome—an analysis “you can do in an hour,” he says. Nothing in his 10 years of analyzing genomic datasets had prepared him for the results. “I had never seen anything like it,” he says. “It’s a cliché, but it really was a smoking gun.” Because their minds were taken back to a time when they were younger, their bodies went back too. After a few more years of “labor intensive” work, Horvath identified 353 special sites on the human genome that were present in cells in every tissue and organ. Horvath developed an algorithm that used the methylation levels at these 353 sites—regardless of the cell type—to establish an epigenetic clock. His algorithm took into account that in some of these 353 sites, the methylation levels decreased with age, while in others they increased. In 2013, Horvath published the results of his analysis of 8,000 samples taken from 51 types of healthy tissue and cells, and the conclusions were striking. When he calculated a single number for the biological age of the person based on the weighted average of the methylation levels at the 353 sites, he found that this number correlated well with the chronological age of the person (it was off by less than 3.6 years in 50 percent of the people—a far better correlation than has been obtained for any other biomarker). He also discovered that for middle-aged people and older, the epigenetic clock starts slowing down or speeding up—providing a way of telling whether someone is aging faster or slower than the calendar suggests. Despite the correlation, Horvath says that biological age, rather than being for the whole body, is better applied to specific tissues and organs, whether it’s bone, blood, heart, lungs, muscles, or even the brain. The difference between the biological age and chronological age can be negative, zero, or positive. A negative deviation means that the tissue or organ is younger than expected; a zero indicates that the tissue is aging normally; and a positive deviation means the tissue or organ is older. Data show that different tissues can age at different rates. In general, diseases speed up the epigenetic clock, and this is particularly striking in patients with Down’s syndrome or in those infected with HIV. In both cases, the tissues tend to age faster than normal. For instance, the blood and brain tissue in those infected with HIV show accelerated aging. Obesity causes the liver to age faster. And studies of people who died of Alzheimer’s disease show that the prefrontal cortex undergoes accelerated aging. Horvath also analyzed 6,000 samples of cancerous tissue and found that the epigenetic clock was ticking much faster in such cases, showing that the tissue had aged significantly more than the chronological age. Despite this wealth of data, there is a gaping hole in our understanding of this striking correlation between methylation markers and biological age. “The biggest weakness of the epigenetic clock is that we just don’t understand the precise molecular mechanism behind it,” says Horvath. His speculation—and he stresses it’s just speculation—is that the epigenetic clock is related to what he calls the “epigenetic maintenance system,” molecular and enzymatic processes that maintain the epigenome and protect it from damage. “I feel that these markers are a footprint of that mechanism,” says Horvath. But “why is it so accurate? What pathway relates to it? That’s the biggest challenge right now,” he adds. Even without understanding exactly how and why it works, the epigenetic clock gives researchers a tool to test the efficacy of anti-aging interventions that can potentially slow aging. “It’d be very exciting to develop a therapy that allows us to reset the epigenetic clock,” says Horvath. While Horvath is thinking about hormonal treatments, Langer’s work with elderly men at the monastery in New Hampshire suggests that we can use the power of our mind to influence the body. Langer didn’t publish her results in a scientific journal in 1979. At the time, she didn’t have the resources to do a thorough study for the leading journals. “When you run a retreat over the course of five days, it’s very hard to control for everything,” Langer says. “Also, I didn’t have the funds to have, for instance, a vacationing control group. I could have published it in a second-rate journal, but I didn’t see any point to that. I wanted to get the information out there and I wrote it first in a book for Oxford University Press, so it was reviewed.” Also, her argument that mind and body are one was potentially a little too path-breaking for the journals. “I think they were unlikely to buy the theoretical part of it,” she says. “The findings, improving vision and hearing in an elderly population, were so unusual that they were not going to rush to publish and stick their necks out.” Since then, Langer has pursued the mind-body connection and its effects on physiology and aging in rigorous studies that have been published in numerous scientific journals and books. Traditionally, the mind-body problem refers to the difficulty of explaining how our ostensibly non-material mental states can affect the material body (clearly seen in the placebo effect). To Langer, the mind and body are one. “Wherever you put the mind you are necessarily putting the body,” she says. So Langer began asking if subjective mental states could influence something as objective as the levels of blood sugar in patients with Type 2 diabetes. The 46 subjects in her study, all suffering from Type 2 diabetes, were asked to play computer games for 90 minutes. On their desk was a clock. They were asked to switch games every 15 minutes. The twist in the study was that for one-third of the subjects, the clock was ticking slower than real time, for one-third it was going faster, and for the last third, the clock was keeping real time. Most of us are slaves to our chronological age. “The question we were asking was would blood sugar level follow real or perceived time,” says Langer. “And the answer is perceived time.” This was a striking illustration of psychological processes—in this case the subjective perception of time—influencing metabolic processes in the body that control the level of blood sugar. Although Langer did not explore a connection between the mind and epigenetic changes, other studies suggest such a link. In 2013, Richard Davidson of the University of Wisconsin at Madison and his colleagues reported that even one day of mindfulness meditation can impact the expression of genes. In their study, 19 experienced meditators were studied before and after a full day of intensive meditation. For control, the researchers similarly studied a group of 21 people who engaged in a full day of leisure. At the end of the day, the meditators showed lowered levels of activity of inflammatory genes—exactly the kind of effect seen when one takes anti-inflammatory drugs. The study also showed lowered activity of genes that are involved in epigenetically controlling expressions of other genes. The state of one’s mind, it seems, can have an epigenetic effect. Such studies taken together provide clues as to why the week-long retreat in New Hampshire reversed some of the age-related attributes in elderly men. Because their minds were taken back to a time when they were younger, their bodies too went back to that earlier time, bringing about some of the physiological changes that resulted in improved hearing or grip strength. But it’s important to point out that biological aging is an inexorable process—and there comes a time when no amount of thinking positive thoughts can halt aging. If body and mind are one and the same—as Langer suggests—then an aging body and aging mind go hand-in-hand, limiting our ability to influence physiological decline with psychological deftness. Still, Langer thinks that how we age has a lot to do with our perceptions of what aging means—often reinforced by culture and society. “Whether it’s about aging or anything else, if you are surrounded by people who have certain expectations for you, you tend to meet those expectations, positive or negative,” says Langer. Related Articles The Wisdom of the Aging Brain Tantalizing evidence suggests that brain activity shifts to increase wisdom as we age. Anil Ananthaswamy Yes, Life in the Fast Lane Kills You New insights into mitochondria reveal how life expends energy. Philip Ball MARCH 2017 What Good Is Grandma? The growing role of grandparents in raising children is right in line with human biology. David P. Barash Most of us are slaves to our chronological age, behaving, as the saying goes, age-appropriately. For example, young people often take steps to recover from a minor injury, whereas someone in their 80s may accept the pain that comes with the injury and be less proactive in addressing the problem. “Many people, because of societal expectations, all too often say, ‘Well, what do you expect, as you get older you fall apart,’ ” says Langer. “So, they don’t do the things to make themselves better, and it becomes a self-fulfilling prophecy.” It’s this perception of one’s age, or subjective age, that interests Antonio Terracciano, a psychologist and gerontologist at Florida State University College of Medicine. Horvath’s work shows that biological age is correlated with diseases. Can one say the same thing about subjective age? People’s perception of their own age can differ markedly from person to person. People between the ages of 40 and 80, for example, tend to think they are younger. People who are 60 may say that they feel like they are 50 or 55, or sometimes even 45. Rarely will they say they feel older. However, people in their 20s often perceive their age to be the same as their chronological age, and may say they feel somewhat older. Terracciano and colleagues have found that subjective age correlates with certain physiological markers of aging, such as grip strength, walking speed, lung capacity, and even the levels of C-reactive protein in the blood, an indication of inflammation in the body. The younger you feel you are, the better are these indicators of age and health: You walk faster, have better grip strength and lung capacity, and less inflammation. Subjective age affects cognition and is an indicator of the likelihood of developing dementia. Terracciano and colleagues looked at data collected from 5,748 people aged 65 or older. The subjects’ cognitive abilities were evaluated to establish a baseline and they were then followed for a period of up to four years. The subjects were also asked about how old they felt at each instance. The researchers found that those who had a higher subjective age to start with were more likely to develop cognitive impairments and even dementia. These correlation studies have limitations, however. For example, it’s possible that physically active people, who have better walking speed and lung capacity, and lower levels of C-reactive protein in their blood, naturally feel younger. How can one establish that our subjective age influences physiology and not the other way around? That’s exactly what Yannick Stephan of the University of Grenoble in France and colleagues tried to find out. They recruited 49 adults, aged between 52 and 91, and divided them into an experimental and control group. Both groups were first asked their subjective age—how old they felt as opposed to their chronological age—and tested for grip strength to establish a baseline. The experimental group was told they had done better than 80 percent of people their age. The control group received no feedback. After this experimental manipulation, both groups were tested again for grip strength and asked about how old they felt. The experimental group reported feeling, on average, younger than their baseline subjective age. No such change was seen in the control group. Also, the experimental group showed an increase in grip strength, while the grip strength of the control decreased somewhat. These correlations do not necessarily mean that feeling young causes better health. Terracciano’s next step is to correlate subjective age with quantitative biological markers of age. While no study has yet been done to find associations between the newly developed epigenetic markers and subjective age, Terracciano is keen to see if there are strong correlations. Still, the message seems to be that our chronological age really is just a number. “If people think that because they are getting older they cannot do things, or cut their social ties, or incorporate this negative view which limits their life, that can be really detrimental,” says Terracciano. “Fighting those negative attitudes, challenging yourself, keeping an open mind, being engaged socially, can absolutely have a positive impact.”
<filename>src/Components/Authentication/Validators.tsx<gh_stars>0 import Yup from "yup" export const email = Yup.string() .email("Please enter a valid email.") .required("Please enter a valid email.") const name = Yup.string().required("Name is required.") const password = Yup.string() .required("<PASSWORD>") .min(8, "Your password must be at least 8 characters") const loginPassword = Yup.string().required("<PASSWORD>") const otpAttempt = Yup.string().required("Enter a code") const accepted_terms_of_service = Yup.boolean() .required("You must agree to our terms to continue.") .oneOf([true]) export const SignUpValidator = Yup.object().shape({ name, email, password: Yup.string() .required("<PASSWORD>") .min(8, "Password must be at least 8 characters."), accepted_terms_of_service, }) export const ForgotPasswordValidator = Yup.object().shape({ email }) export const LoginValidator = Yup.object().shape({ email, password: Yup.string().required("Password <PASSWORD>."), }) export const MobileSignUpValidator = { email: Yup.object().shape({ email, accepted_terms_of_service }), name: Yup.object().shape({ name }), password: Yup.object().shape({ password }), } export const MobileLoginValidator = { email: Yup.object().shape({ email }), password: Yup.object().shape({ password: <PASSWORD> }), otpAttempt: Yup.object().shape({ otp_attempt: otpAttempt }), }
def update_storage_policy(session, policy_id, full_description, gb_per_month_cost, return_type=None): path = '/api/zios/policies/{0}.json'.format(policy_id) body_values = {'full_description': full_description, 'gb_per_month_cost': gb_per_month_cost} return session.put_api(path=path, body=body_values, return_type=return_type)
Google and social media have been in the headlines. So has Bitcoin. Tech guru and conservative economist George Gilder now brings the two together in a fascinating and pertinent way. According to a very recent WellsFargo/Gallup poll, about 2% of American investors — defined as people with more than $10,000 in stocks, bonds or mutual funds — own some bitcoin. Less than 1% are planning to buy any soon. Yet about one in four investors are intrigued. You may be one of them. I am the senior counselor to the Chamber of Digital Commerce, the world’s largest trade association which represents the blockchain industry. George Gilder serves on the advisory board of the Chamber of Digital Commerce and we’ve been professional colleagues, on and off, for decades. As such, I was privileged to read his new book, Life After Google: The Fall of Big Data and The Rise of the Blockchain Economy, thrice: twice in manuscript and again in hardcover. I rarely read a book once, much less three times, and reread twice it out of pleasure not duty. The blockchain — the virtual “stuff” of which bitcoin was the pioneering (and remains the preeminent) version — is one of the hottest technologies in the world right now. It’s also one of the most controversial. Gilder, for those space travelers recently returned from the long trip to Proxima Centauri, is one of the leading public intellectuals of our era. He wrote what Dr. Arthur Laffer, co-architect of Supply-Side economics, called “the bible of the Reagan Revolution,” the million-selling book Wealth and Poverty. Gilder was the living author most quoted in his speeches by President Reagan. Since Reagan was the president who, in following the Kemp/Mundell/Laffer/Gilder recipe, set the course for multiplying world’s wealth by something like a (nominal) factor of seven, bringing over a billion people worldwide out of dire poverty in the process, Gilder is obviously a consequential public intellectual. Nor was George Gilder a one-hit wonder. He went on to write a series of books on technology that propelled him to nearly legendary status. He flew high and moved markets with the Gilder Technology Report… until the Fed busted the dotcom boom. That implosion did not, however, undermine his prophetic qualities. In 1990, I picked up a book by George Gilder called “Life After Television.” It changed my life. It caused me to imagine technology that could move so fast that our industry might be gone in a decade or two. Most of the people where I worked couldn’t see that. They bet on the past. Because of George’s book, I bet on the future and left to start my own business. It was one of the hardest decisions of my life, but I’ve never looked back. George predicted a world where traditional network television programming ended because of computers, digital video and fiber optics. You can still call that box in your house a TV, but the TV business as we knew it in those days is gone. We didn’t have the words to describe all the inventions George talked about back then like “teleputers” and “channels of information.” But today we know them as iPhones and the web. The internet, mobile and streaming revolutions happened just as George predicted. Watching George’s predictions happen, living through them and building my business around them, I learned that the cycle of innovation doesn’t stop after TV. Surviving the next revolution means connecting the dots early and trusting your instincts when things are about to change. Never one to rest on his laurels Gilder now moves us from Life After Television to Life After Google to make an even bolder prophecy. (Spoiler alert: imagine the Web in 3D virtual reality. Now… read on.) Gilder, an old pro at this, also authored Microcosm (a defining book about the semiconductor industry), Telecosm (a cult classic about fiber optics), and The Silicon Eye, among others. Computer chips and flat panel displays revolutionized our lives (as the stuff of the MacBook Pro on which I compose this review and, likely, the screen on which you read it). Fiber optics also revolutionized our lives (as the Web, on which I researched and submitted it, and infinite cable bandwidth — think Game of Thrones and so much more). Then mobile transformed our lives. Now we are about to move from the Microcosm to the Telecosm to the Cryptocosm. I am by no means alone in thinking Gilder prophetic. The Financial Times recently picked Life After Google as one of their three “business books of summer 2018.” Thus, far from being rat poison, blockchain promises to prove to be the next Big Thing. In 23 chapters plus an epilogue, Gilder plays Virgil to your Dante in exploring the many circles of the Cryptocosm. If you are part of the 1% interested in investing in the Next Big Thing, or just would like to know what’s going to be upending your day-to-day life in the next few years — and how — you’ve come to the right place. Bonus: Gilder keeps it fun, intuitive, and exciting. Life After Google begins with a breathtaking romp through the prototype Back to the Future ride through Hill Valley/a volcano/chased by a T-Rex in a virtual DeLorean. This ride, which Gilder invested in and experienced in prototype, was designed by 2001: A Space Odyssey/Close Encounters/Blade Runner special effects wizard Douglas Trumble. It become a dominant theme park experience. Gilder gives you a private tour. Gilder then takes us on as breathtaking a ride through what he calls Google’s “system of the world.” Google’s is a system based on “free.” But, as he demonstrates, it’s an odd kind of free — free, as in, literally, priceless. Gilder finds this antithetical to true freedom. And to capitalism. By not charging its users — you and me — for its services, Google places itself in a position to harvest immense amounts of data about us. It then uses that data to sell advertising. While this is not quite sinister in the way Senate interrogators like to portray it, this architecture holds within itself the seeds of its own destruction. And Gilder holds that it violates Google’s initial prime directive, “Don’t be evil,” originally a sly dig at Microsoft. The original sin, and inescapable evil, of Google’s “system of the world” is that the data it thus collects are intrinsically, inevitably, insecure. That system demands the hassle of passwords and two-factor authentication and so forth. And yet… the data are warehoused in ways that are intrinsically vulnerable to hackers and phishers and breachers and other nefarious sorts right out of The Inferno’s central casting. Gilder meticulously documents how the lack of security is intrinsic to Google’s priceless “system of the world.” “Pricelessness” may sound pretty wonderful, à la Mastercard’s early 21st century ad campaign. Why? Because of Hayek’s discovery of the power of price as an essential element to free markets and the equitable prosperity that liberty creates. Capitalist pricing, not Marxist pricelessness, turned out to hold the key to obliterating poverty and improving the lot of workers — much to the astonishment of the naive Lincoln Steffanses of this world. Then Gilder shows how the blockchain — the Cryptocosm — will cure the problem of insecurity baked into Google’s System of the World. Crypto promises to make our identities and our valuable digital property secure and to secure their value… for us, rather than for Google. The company store was not a great advance of capitalism during the era of the so-called “robber-barons,” and it is no better today when it is dispersed through the cloud, funded through advertising, and combined with a spurious sharing of free goods. Marxism was historically hyperbolic the first time round, and the next Marxism is delusional today. It is time for a new information architecture for a globally distributed economy. Fortunately, it is on its way. One of the marvels of a George Gilder tech book is how he unfailingly takes us behind the interface on a tour of the workings of the system and the people who created these. He unfailingly shows us the fascinatingly intricate clockwork behind the hands and face of the watch. In Life After Google, Gilder takes us on a whirlwind tour of the World’s Fair of much of what’s actually inside the Internet… and the blockchain. Gilder displays all this as a Cabinet of Wonders. Never a dull moment. Another fascinating element of “The Joy of Gilder” is his taking us to meet the Grand Architects of the Digital Universe, past, present and future. Early on he escorts us into the very moment of the key conference — in 1930 — where a young super-geek named Kurt Gödel — empowered by the intellectual courage of the great von Neumann — quietly but definitively tipped over the first domino that destroyed the prevailing deterministic scientific model of the world. Gödel, empowered by von Neumann, opened the door to a cornucopian cyber age. The blockchain now promises to restore its decentralized glory. That moment led the world out of the desert of determinism and into the age of information theory. (It’s Claude Shannon’s world. We just live in it.) And if you dare to think of the greatness, rareness, muchness, fewness of this precious only endless world in which you say you live I have encountered no better guide to it than Life After Google. Gilder’s excursion to 1930, however, is merely his genuflection to the Logos, the Original Word. He quickly moves us from “In the beginning” to a close encounter with the technological marvels of the world in which we live as obliviously as fish are to water. The Greeks had four words for history: Logos (the Origin, as “In the beginning was the Word”); Mythos (our mythic antecedents); Epos (our Epic ancestry); and Rheimos (contemporary history). Gilder duly begins with the Prime Movers, the utterers of the Logos: von Neumann, Gödel, Turing, Shannon. He then quickly takes us on a magical mystery tour of the Internet’s Mythic era. Meet Google’s founders Sergey Brin and Larry Page, the paladins of “Big Data.” Travel with them to Burning Man! Gilder portrays the founders of Google as Titanic in two senses. They are the Titans in the pre-Olympus sense, primitive, barbaric, early gods such as Cronos, destined to be vanquished by the Olympian deities and banished to Tartarus. Titanic is also an allusion to a certain ill-fated ocean liner, in its brief day the grandest passenger ship ever yet built. Gilder then moves us smartly along to confront the brewing epic battle for supremacy between the insurgent Olympians — featuring the paladins of the blockchain — and the currently reigning Titans. He introduces us to the powerful implications of the parallel processing chips made by Nvidia and of the implications of advanced materials such as the one molecule thick, 60X as strong as steel and 200X as conductive as copper, graphene. This portends a tectonic shift in the world economy. Follow along! Gilder is so steeped in high tech culture that he can readily expose the pretensions of the current reigning Masters of the Universe with their artificial hysteria over Artificial Intelligence. He reveals how their Asilomar conference of 2017 — convened to place an anathema on AI — was mis-founded on a materialist superstition. And he shares how this feckless conclave was held in the same venue as a 1975 conference predicting an apocalypse — apparently by 1985 — from genetic engineering. That never materialized. Neither, declares Gilder, will Elon Musk’s AI apocalypse. After exposing some of the key fallacies and spurious assumptions of the currently reigning Titans of Tech, Gilder moves us from Mythos to Epos, from the mythic age to the epic age we are now entering. Here come the insurgent Olympians, prominently among whom are the wielders of the blockchain. Gilder provides us with a revelatory imaginary encounter with the pseudonymous Satoshi Nakamoto, the inventor of bitcoin, and then introduces us to the ferociously brilliant Vitalik Buterin, “a child prodigy on a Mozartian scale,” the inventor of Bitcoin’s main rival (or complement), Ethereum. Gilder then escorts his readers to meet several enfants terrible of tech who you likely have not — not yet — heard of. Prominent among them is Austin Russell, who is successfully incubating the key laser-radar technology to make self-driving cars safe and affordable. This is “orders of magnitude better than the competition from Google and others,” reports Gilder. Call what is happening “Thiel’s Revenge.” The Olympians overthrowing the Titans is a drama wherein Thiel might be cast as Zeus. The fall of Big Data will occur at the hands of the “flying car” pioneers. Moving along from Logos to Mythos to Epos, Gilder escorts us into an up-close-and-personal look at contemporary history, Rheimos. Enter the blockchain. Gilder conjures a phantasmagoric imaginary encounter with Satoshi and pursues a delightful parlor game as to who Satoshi might (or might not) be. This, in turn, gives way to his recounting of a dramatic “Battle of the Blockchains” — between bitcoin maximalist Craig Steven Wright, who claimed to be, perhaps as a pretender, Satoshi himself. Wright, and bitcoin, are pitched against Vitalik Buterin — another Thiel Fellow — and Ethereum. In its effect on our business, technology, and economic life, Buterin’s contribution is paralleled only by Satoshi’s blockchain itself.… In the history of enterprise there has never been anything like the launch of Ethereum. Andreas Antonopoulos … compares bitcoin and Ethereum to “a lion and a shark.” Each will dominate in its own domain. Each will suffer from limitations and tradeoffs. As 70 percent of all links came to be handled through Google and Facebook, [the Web’s inventor, Sir Tim] Berners-Lee feared that his Web was dying. He would become a Blockstack enthusiast. “When he heard what we were doing he did a little dance,” said Blockstack’s software chief, Jude Nelson. [S]ecurity is not an app or a video game. It is an architecture. Where is Gilder, and the world, going with this? This is about finally making the Internet really secure instead of perilous. This is about causing the inventor of the Web to do “a little dance.” This is about giving power back to the people. And, not so incidentally, this is about making self-driving, possibly even flying, cars, real thereby ameliorating or even ending America’s road-bridge-and-tunnel infrastructure crisis through innovation instead of a trillion dollar government spending spree. Buckle up. Gilder gets even more dazzling. “Basic Attention Tokens” to bring down Google. Or at least send Page and Brin back to the drawing board for a new strategy. The mild-mannered Eich will hit them with a billion BATS. ’Scuse me while I kiss the sky. Governments and investors everywhere should welcome the explosion of creativity in crypto, preparing a new financial system of the world for the moment when the fiat currency piñata bursts at last. Gilder strikes a prophetic note in his penultimate chapter. The revolution in cryptography has caused a great unbundling of the roles of money, promising to reverse the doldrums of the Google Age, which has been an epoch of bundling together, aggregating, all the digital assets of the world.… By reestablishing the connections between computation, finance, and AI on the inexorable metrics of time and space, the great unbundling of the blockchain movement can restore economic reality. Crucial will be the emergence from the crypto-welter of metrics tied to the scarcity of unfolding time. Satoshi was correct in mimicking gold, but because he did not fully grasp the sources of gold’s success, he erred in his parameters for the bitcoin. Satoshi’s error provides opportunities for others only to the extent that they grasp the nature of money and time. A computer industry for a world of information should be oriented to the creative dimension of virtual reality rather than the flat universe of the materialistic superstition. A successful system of the world should be devoted to rendering the full complexity of the human mind. Shades of Edwin Abbott Abbott’s Flatland! Gilder here seems to be promising us that the blockchain will move us from a two-dimensional digital universe as now defined and dominated by Google to a three-dimensional digital universe, both metaphorically and metaphysically, where our dignity and liberty are restored. For us civilians, this portends a more dramatic leap than the one from silent films to talkies, from black-and-white to color. Our world is about to transform, in large measure through the blockchain. Toto, I’ve a feeling we’re not in Kansas anymore. If Cerf reads Life After Google he just might toggle that “No” to “Yes.” Cerf is, after all, a world-historical genius. In any case, it would be riveting to watch a debate between the author of Life After Google and Google’s chief Internet evangelist to, well, hash it out. Also, maybe, just maybe, after reading Gilder, Google will upgrade its System of the World. Sergey and Larry might be a couple of Burning Man hippies. If they are, they are also among the smartest hippies who ever lived. Bring it on. In writing Life After Google, George Gilder has outdone himself. The author of the bible of the Reagan Revolution has now written the bible of the Cryptocosm. The Cryptocosm is a technological breakthrough that promises to transform every aspect of our lives. Gilder is its essential guide. Whether you are reading as an investor, as a voter, or simply to indulge a healthy citizen’s curiosity about the way the world soon will work Life After Google: The Fall of Big Data and The Rise of the Blockchain Economy will endow you with the genesis block of an invaluable roadmap to the future. Buckle your seatbelt and prepare for a ride Back to the Future like nothing else. Welcome to the Cryptocosm.
<reponame>Lornatang/data-structure /************************************ * * * 文件夹: ▲02 线性表\05 MergeList * * * * 内 容: 单链表归并相关函数测试 * * * ************************************/ #include <stdio.h> #include "MergeList.c" //**▲02 线性表**// void PrintElem(LElemType_L e); //测试函数,打印整型 int main(int argc, char **argv) { FILE *fp; LinkList La, Lb, Lc; int m; m = 5; printf("作为示例,La长度设定为 %d ,Lb设定为 %d ,创建La和Lb...\n", m, m); fp = fopen("TestData_HL.txt", "r"); //文件指针,指向数据源 CreateList_HL(fp, &La, m); fclose(fp); fp = fopen("TestData_TL.txt", "r"); //文件指针,指向数据源 CreateList_TL(fp, &Lb, m); fclose(fp); printf("La = "); ListTraverse_L(La, PrintElem); printf("\n"); printf("Lb = "); ListTraverse_L(Lb, PrintElem); printf("\n\n"); PressEnter; MergeList_L(La, &Lb, &Lc); printf("合并La和Lb为Lc = "); ListTraverse_L(Lc, PrintElem); printf("\n\n"); PressEnter; return 0; } void PrintElem(LElemType_L e) { printf("%d ", e); }
Cu/Pd-Catalyzed cis-Borylfluoroallylation of Alkynes for the Synthesis of Boryl-Substituted Monofluoroalkenes. Monofluoroalkenes normally act as metabolically stable bioisosteres for amide groups (-NH-CO-) and have widespread applications in drug discovery. Additionally, they are widely used as building blocks in organic synthesis. In this study, the Cu/Pd-catalyzed cis-borylfluoroallylation of alkynes was achieved, providing a modular and general tactic for the preparation of monofluorinated alkene scaffolds with high regioselectivity and stereoselectivity. Moreover, an array of synthetic building blocks can be generated by downstream transformations.
Tosvinyl and besvinyl as protecting groups of imides, azinones, nucleosides, sultams, and lactams. Catalytic conjugate additions to tosylacetylene. The use of the 2-(4-methylphenylsulfonyl)ethenyl (tosvinyl, Tsv) group for the protection of the NH group of a series of imides, azinones (including AZT), inosines, and cyclic sulfonamides has been examined. The Tsv-protected derivatives are obtained in excellent yields by conjugate addition to tosylacetylene (ethynyl p-tolyl sulfone). The stereochemistry of the double bond can be controlled at will: with only 1 mol % of Et3N or with catalytic amounts of NaH, the Z stereoisomers are generated almost exclusively, while the E isomers are obtained using a stoichiometric amount of DMAP. Analogous phenylsulfonylvinyl-protected groups (with the besvinyl or Bsv group instead of Tsv) are obtained stereospecifically by reaction with (Z)- or (E)-bis(phenylsulfonyl)ethene. For lactams and oxazolidinones, this last method is much better. The Tsv and Bsv groups are stable in the presence of non-nucleophilic bases and to acids. They can be removed highly effectively via a conjugate addition-elimination mechanism using pyrrolidine or sodium dodecanethiolate as nucleophiles.
/** * Checks that the argument is an aggregation function, window function, a * built-in non-constant function or a non-constant field. * WL#12108: it excludes stored procedures and functions, user defined * functions and also does not update the content of expressions * inside Value_generator since Optimize is not called after the expression * is unpacked. * @param item to be checked * @return true for non-const field or functions, false otherwise */ inline bool is_non_const_field_or_function(const Item &item) { return !item.const_for_execution() && (item.type() == Item::FIELD_ITEM || item.type() == Item::FUNC_ITEM || item.type() == Item::SUM_FUNC_ITEM); }
CONCEPTUAL PRINCIPLES OF EFFECTIVE LABOR MOTIVATION AS A PREMISE OF COMPETITIVE FUNCTIONING OF AGRICULTURAL ENTERPRISES Purpose Labor motivation plays a significant role in the successful development of an agricultural enterprise, because only creative workers who display initiative will be able to make the business entity effective and competitive in the market environment. Research method This caused the need to conduct an in-depth study of theoretical and methodological foundations of intensification of labor motivation of employees in agricultural enterprises as prerequisites for their competitive functioning. In the course of researching this issue, the authors of the article proposed a methodological approach, which envisages determining the productivity of labor based on the indicator of gross output at the prices of the current year. Results As a result, it was determined that the index of productivity in agricultural enterprises of the researched region is significantly higher than the similar figure of 2010 which was determined by the constant prices. At the same time, the correlation between the productivity growth rate and the wage in the period from 2016 to 2018 was respectively 1.031 1.269. Implications /originality /value The article and methodical provisions on the balanced scorecard according to the balanced scorecard concept (BSC) are further developed, which enables an in-depth analysis of the impact of certain aspects of business entities on such indicators as productivity and production efficiency, level of competitiveness, etc. Introduction In the conditions of current modernization of the Ukrainian economy, the success and competitiveness of enterprises in any industry, including agriculture, depend on the effective use of the available production resources by business entities. One of the most significant factors of economic development for domestic enterprises are labor resources with their creative potential, professional experience and knowledge. It is considerably more difficult to manage human resources than other types of resources. It is connected with the existence of personal characteristics in people, which exert a significant impact on the effectiveness of their performance at work. Therefore, it is extremely important for enterprises to find different ways to improve productivity by increasing readiness and willingness of their employees to work creatively and fruitfully. Analysis of recent research and publications Research into the problem of labor motivation, effective personnel management and increasing the competitiveness of enterprises was carried out by both foreign and domestic scientists, namely: The works of these scientists cover the theoretical and methodological bases of determination and estimation of labor motivation, effective management of personnel and competitiveness of enterprises as economic entities. The purpose of this study is to substantiate the conceptual principles of effective labor motivation as prerequisites for competitiveness of agricultural enterprises in the modern market environment of the Ukrainian economy. Presentation of main research material Science and production practice have proven that responsible, highly organized and proactive employees strive for self-realization, professional growth and obtaining satisfaction from their achieved performance. In order to induce people to work qualitatively, appropriate mechanisms of labor motivation, which will cause the employees to work effectively for the benefit of the enterprise, are required. A well-designed and organized motivation system is an effective tool for attracting new, creative staff and stabilizing staff turnover. Almost all managers of enterprises attach importance to the latter option -keeping the existing personnel, because it is most effective and least costly. Considering the motivational mechanism of entrepreneurship in agriculture in the market economy, Vantukh stated that motivational mechanism is an economic mechanism for the implementation and reproduction of unity of socioeconomic functions of labor: as a means to a life that is functioning at each stage of its completion in a certain system of macro-and micro-economic coordinates. According to this author, motivation mechanism is a peculiar force of motivation. More precisely, it provides the conditions of self-stimulation, transforms the motivation from possibility into reality . The effective motivational mechanism provides a system of material and nonfinancial incentives. Stimulation of labor in agricultural enterprises is based on the principle that the method of financial incentives combined with other forms of recognition of workers' merits can achieve the most desired result for the enterprise. Labor motivation is carried out in different forms, among which are the following: material compensation, cash and non-monetary rewards. The motivation mechanism is based on the aggregate of three factors: labor market, state regulation and application of collective labor agreements. Each link has a corresponding weight in the overall regulatory system. State regulation ensures minimum level of income for employees in accordance with the minimum wage. Regulation of all questions of remuneration is carried out on the basis of the employment contract, which constitutes an agreement between the employer and employees. The function of direct wage regulator is performed by the labor market, because it is on it that the specific price of different types of work is formed. The main elements of the mechanism of effective labor motivation are subjects and objects of management, a set of principles, criteria, methods and results of effective management of personnel motivation system, implementation and use of management stages in the motivation system. Effective labor motivation is based on the law of fair distribution of the participation of employees in the activity and consists in the application of economic incentives: remuneration and participation in profits and property. The effect of economic incentives is based on wages, bonuses, surcharges, benefits, etc. The growth of productivity provides a salary, and it is possible to raise it through allowances, surcharges and fair assignment of premiums. The effectiveness of stimulating the influence of remuneration depends on gender, age, target priorities, qualifications and competence of the staff. In most cases, the workers themselves choose the factors that motivate them to work in a particular enterprise. They determine their needs, motives, suggestions for positions and the organization of jobs. Because of this, it is very difficult to find a universally appropriate approach and to define an individual effective system of motivation of personnel in the economic entities. It is important to note that material motivation is slightly inferior to intangible motivation. Employees consider the presence of material motivation as such and pay more attention to the additional bonuses that the employer offers to them . In order to build a modern system of motivating personnel it is very important to determine the main motives which compel specialists to work effectively. For the system of motivation of personnel to be appropriate it should include full feedback for achieving the goals of business entities. An effective system of motivation of personnel should be oriented not only on buying the time of employees, but also on buying exceptionally effective results of their work, as well as on providing in advance the possible demographic reasons and on minimizing risks in personnel management . Thus, the system of labor motivation involves the development of concrete methods, levers and mechanisms that stimulate the activities of personnel, thanks to which achieving the most desired targets of the enterprise is possible. The main difficulty in dealing with this issue lies in the fact that an increase in training and competence of employees, as a rule, leads to the growth and diversification of their needs. The task of the head of the company is to provide the employees with certain incentives to encourage active, creative work, to increase their interest in work, to gain satisfaction from the obtained results, to attempt to combine achieving their personal goals with the goals of the enterprise. The system of labor motivation will be effective only if modern forms and methods of staff stimulation are applied. The structure of the motivation of work includes: -needs that the employee wants to satisfy; -the values that are able to meet this need; -labor actions that are necessary to obtain the goods; -price -costs of material and moral nature, which are related to labor activities . The theoretical-methodological basis of the conceptual approaches is common in the economic theory of the concept. They reflect certain aspects of motivation and are the basis for creating the concept of staff motivation, in particular: the welfare concept, the concept of economic development stages and the concept of social exchange . In theory and practice of management, the concept is generally accepted as the basis for human resources management laid motivation. The motivation to work effectively is of particular importance. It is a decisive factor in the enterprise's performance and productivity, which directly lead to an increase in production efficiency in the enterprise. The attention of scientists, as a rule, is focused on the study of the structure and dynamics of motivation of work as well as the analysis of motivation as a process of formation of values and interests, internal stimulation of workforces. The development of motivation system in agricultural enterprises should take into account internal and external motives of employees, clearly determining the relationship between execution of work, of result and internal satisfaction with this result. Production activity of agricultural enterprises is determined by production of gross production, which is the initial result of interaction of production factors, material and cost basis of other final results. In the natural form it represents everything produced during the year, the primary products of crop production, livestock and fish farming, and in cost -rated at comparable prices of the corresponding year . The essence of gross production also consists in the results of work, which are directly determined by the motivation of each employee to work effectively. It is shown schematically in chart 1. CHART 1 Influence of motivation of work on the increase in gross output Source: own elaboration based on: . External motivation of work in the field of production has a great scientific and practical significance, since it depends on the level of labor productivity in the enterprise, and, eventually, the competitiveness of manufactured products. Increasing the level of productivity is a prerequisite for efficient productioneconomic activities of agricultural enterprises as well as an increased payment for employees. In this study, we focus on the compliance of the rate of growth in wages with productivity. In theory, the prerequisite for effective management should be the outgrowth of productivity compared to its payment. Consider this correlation as exemplified by the indicators of production and economic activity of agricultural enterprises in Ternopol region, which is the most powerful region in western Ukraine in terms of agricultural potential (table 1). Internal Labor motivation External Labor motivation Labor motivation Gross products of agricultural enterprises As we can see from table 1, during the last five years, the wage index in agricultural enterprises in the researched region was growing more rapidly than the labor productivity index. Consequently, relative overspending fund wages in business entities. The relative savings (overspending) fund wages E (p) in the enterprise is determined by the formula : where: FLP -Payroll fund in the company Cval -coefficient value of wages and productivity It should be noted, however, that the indicator of labor productivity per one average annual employee was determined based on the constant price of the year 2010. Therefore, we consider it advisable to determine the productivity of labor using the index of produced output at prices of the current year. For this purpose, we will use the price indexes of agricultural products in recent years with respect to 2010. According to the proposed methodical approach, indicators of performance growth and wages in agricultural enterprises of Ternopol region are given in table 2. As can be seen from table 2 data, the productivity Index in agricultural enterprises of the researched region is significantly higher than the similar figure which was determined by the constant prices of 2010. It should also be noted that despite this, the ratio of the smaller unit (0.895) was observed only in 2015. In the period from 2016 to 2018, this indicator had the value of more units and varied in accordance with the range from 1.031 to 1.269. According to this methodological approach, the noted situation indicates that the payment of the Agrarians in the region grows more rapidly than their performance and consequently the expenses of the payroll fund arise. Thus, the motivation of employees of the studied enterprises in Ternopol region decreases. It should be noted, however, that the level of wages in the structure of gross production of agricultural enterprises was very low. The level of wages with its performance is logical. But it turns out that the salary in Ukraine is low not only abstract but inadmissible low in relation to low productivity . Due to the above, it is possible to conclude that, at the present stage, the higher rates of growth in the wage index, compared with the index of labor productivity, are quite natural. Meeting the needs of employees in agricultural enterprises depends on the working conditions, the level of security, mechanization and automation of production, the level of safety, the amount of money meant for wages and development of social sphere. The directions of motivational influence on employees of the enterprise are determined by the accepted production program, level of labor organization and management. Each employee tries to satisfy their needs, on the other hand the enterprise management offers them a certain reward. The closer is the value convergence of motivational factors concerning the fruitful work and the reward offered in the company, the higher the level of satisfaction of the employee's needs. Conversely, if the value of motivational factors and remuneration diverge, this system of motivation of work is unacceptable. TABLE 2 The ratio of growth of productivity and remuneration (the cost of gross product is determined at current prices) in agricultural enterprises of Ternopol region The motivational system must be closely related to the competence approach and anticipate the connection between the presence and acquisition of competence of an employee on the one hand and the reward system -on the other . An effective system of labor motivation and an individual approach to each employee will certainly lead to increased production efficiency, and therefore to the competitive functioning of agricultural enterprises. However, at the present stage of the creation of the employee motivation system, it is necessary to understand that a perfectly developed motivational mechanism is half the battle. It should also be successfully implemented. It is possible only if you understand the strategy of enterprise development by all its employees . Cheban rightly notes that an effective instrument for the implementation of enterprise development strategy can be the balanced scorecard, or the concept of balanced scorecard (BSC). In essence, the balanced scorecard is a mechanism for creating the relationship of strategic ideas and decisions with operational tasks, a way to forward the activities of the entire company (or group) to their achievements. The balanced scorecard helps businesses deal with two key issues: effectively assess the company's performance and implement a strategy . According to Niven , indicators selected for the balanced system are a tool for executives to acquaint their subordinates and other stakeholders with the results and factors of activity through which the company performs its mission and strategic objectives. Source: own elaboration based on: . The sequence of development of the business strategy with the use of the balanced scorecard model is demonstrated on the example of PAP "Agroprodservice", which unites 22 economic entities with almost 37 thousand hectares of sown areas of Ternopol, Ivano-Frankovsk, Lvov and Kherson regions. The main activity there is the crop, including winter wheat, barley, soybeans, rapeseed, corn, sunflower and sugar beet. To develop a balanced scorecard in the PAP "Agroprodservice", a multi-functional group was created, which included the general director and its deputy, chief accountant as well as heads of activities. Through meetings and lengthy discussions, it was determined that the balanced system of indicators should become a necessary economic tool for the effective development of this business structure (table 3). As it is evident from the data provided in table 3, in PAP "Agroprodservice" the indexes of efficiency of the enterprise activity are connected with mechanism of motivation of the personnel, as evidenced by indicators of productivity and efficiency of production, which are quite high. This, in turn, provides a decent level of wages, bonuses as well as other types of material and intangible incentives. Conclusions Extremely important measures of successful management are: motivating employees of agricultural enterprises, making innovative decisions in the process of agrarian production, stimulating personnel's actions aimed at improving the efficiency of production and economic activity and increasing the competitiveness of economic entities. Research has shown that, according to the existing methodological approach, when the index of productivity in agricultural enterprises was determined at constant prices in 2010, the wages of agricultural staff in the Ternopil region were growing at a higher rate than their productivity. Therefore, we propose the use of a methodical approach in which labor productivity is determined by the gross output at prices of the current year. As a result, the labor productivity index in agricultural enterprises of the researched region is much higher than the same indicator, determined at constant prices (in 2018 -1,095 and 1,002 respectively). The ratio of growth rates of labor productivity and wages measured by the proposed approach in the period from 2016 to 2018 was respectively 1,031, 1,233 and 1,269. The concept of balanced scorecard is an effective tool that allows the analysis of the communication of production and economic activity of subjects with indexes of productivity and production efficiency. Methodical provisions of this concept on the balanced scorecard were further developed on the example of PAP "Agroprodservice".
Walk into any slice shop in New York City and a pizzaiolo will claim to specialize in Neapolitan pizza. Naples’ singular approach to the dish has become a shorthand of sorts for any pie that seems to be thin, flat, and round in 2018. But at Una Pizza Napoletana, chef Anthony Mangieri is using imported ingredients and traditional cooking techniques to pay homage to his Neapolitan ancestry, all while creating a product that’s uniquely rooted in the five boroughs. Topped with buffalo mozzarella, San Marzano tomato sauce, sea salt from Trapani, and olive oil from Sorrento, each pie from Una Pizza Napoletana is a carefully orchestrated opera of flavor, the pieces blending together to form one perfectly balanced work of art. A fixture in the NYC slice game for decades, Mangieri made a name for himself as a savant-like pizza purist hellbent on perfection. Today, returning to Manhattan after years on the west coast, the chef just wants to make a pizza that perfectly represents his own unique tastes and experiences. "For me, at this point in my life, I don’t think the pizza is the best. I think that it’s just mine and it’s what I offer," Mangieri says. "That’s what I bring to New York. I bring myself and my ideas and my independence."
<filename>src/libtest/Logs.java package libtest; import java.util.ArrayList; /** * constient une liste de Logs * * @author vthomas * */ public class Logs { /** * la liste de logs */ ArrayList<Log> logs; /** * nom de la classe testee */ String nomClasseTestee; /** * constructeur par defaut * * @param nomClasseTestee * nom de la classe testee */ public Logs(String nomClasseTestee) { this.nomClasseTestee = nomClasseTestee; this.logs = new ArrayList<Log>(); } /** * genere les statistiques des logs. * * @return un objet contenant les statistiques generales sur tous * les tests */ public Stats genererStatistiques() { Stats statistiques = new Stats(); // calculs log statistiques.nbTests = logs.size(); statistiques.nbErreur = 0; statistiques.nbEchec = 0; statistiques.nbOk = 0; for (Log l : logs) { if (l.type.equals("Ok")) statistiques.nbOk++; if (l.type.equals("Erreur")) statistiques.nbErreur++; if (l.type.equals("Echec")) statistiques.nbEchec++; if (l.type.equals("TimeOut")) statistiques.nbTimeOut++; } return (statistiques); } public void ajouterLog(Log log) { this.logs.add(log); } /** * permet d'ajouter une liste de logs * * @param ls * liste de logs a ajouter */ public void ajouterLogs(Logs ls) { for (Log log : ls.logs) { this.ajouterLog(log); } } }
/*************************************************************************** RtpSenderInfo.h - description ------------------- begin : Wed Dec 5 2001 copyright : (C) 2001 by <NAME> email : <EMAIL> ***************************************************************************/ /*************************************************************************** * * * This program 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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef __INET_RTPSENDERINFO_H #define __INET_RTPSENDERINFO_H #include "inet/common/INETDefs.h" #include "inet/transportlayer/rtp/RtpParticipantInfo.h" namespace inet { namespace rtp { /** * The class RtpSenderInfo is used by an Rtp end system for storing information * about itself. With the stored information it can create a SenderReport. */ class INET_API RtpSenderInfo : public RtpParticipantInfo { public: /** * Default constructor. */ RtpSenderInfo(uint32 ssrc = 0); /** * Copy constructor. */ RtpSenderInfo(const RtpSenderInfo& senderInfo); /** * Destructor. */ virtual ~RtpSenderInfo(); /** * Assignment operator. */ RtpSenderInfo& operator=(const RtpSenderInfo& senderInfo); /** * Duplicates this RtpSenderInfo by calling the copy constructor. */ virtual RtpSenderInfo *dup() const override; /** * Stores information about this outgoing RtpPacket. */ virtual void processRTPPacket(Packet *packet, int id, simtime_t arrivalTime) override; /** * Processes an incoming ReceptionReport for this sender. */ virtual void processReceptionReport(const ReceptionReport *report, simtime_t arrivalTime); /** * Returns a SenderReport for this rtp endsystem. * If it hasn't sent rtp data packets during the * last 2 rtcp intervals, it returns nullptr. */ virtual SenderReport *senderReport(simtime_t now) override; /** * Sets the time (simTime) when this endsystem has * started sending rtp packets. */ virtual void setStartTime(simtime_t startTime); /** * Sets the clock rate (in ticks per second) this sender * increases the rtp time stamp. */ virtual void setClockRate(int clockRate); /** * Sets the initial rtp time stamp. */ virtual void setTimeStampBase(uint32 timeStampBase); /** * Sets the initial sequence number. */ virtual void setSequenceNumberBase(uint16 sequenceNumberBase); private: void copy(const RtpSenderInfo& other); protected: /** * The time when the transmission was started. */ simtime_t _startTime; /** * The clock rate this sender increases the rtp time stamp. */ int _clockRate; /** * The initial rtp time stamp. */ uint32 _timeStampBase; /** * The initial sequence number. */ uint16 _sequenceNumberBase; /** * The number of rtp data packets this sender has sent. */ uint32 _packetsSent; /** * The number of data bytes this sender has sent. */ uint32 _bytesSent; }; } // namespace rtp } // namespace inet #endif // ifndef __INET_RTPSENDERINFO_H
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Get Utc Now Offset // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // struct FTimespan ReturnValue (Parm, OutParm, ReturnParm) struct FTimespan UBP_FortExpeditionOverviewWidget_C::Get_Utc_Now_Offset() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Get Utc Now Offset"); UBP_FortExpeditionOverviewWidget_C_Get_Utc_Now_Offset_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Set List Sort Type // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // EFortExpeditionListSort InSortType (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Set_List_Sort_Type(EFortExpeditionListSort InSortType) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Set List Sort Type"); UBP_FortExpeditionOverviewWidget_C_Set_List_Sort_Type_Params params; params.InSortType = InSortType; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Should Disable Build Expedition Action // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // class UFortExpeditionItem* Expedition (Parm, ZeroConstructor, IsPlainOldData) // bool Disable (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Should_Disable_Build_Expedition_Action(class UFortExpeditionItem* Expedition, bool* Disable) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Should Disable Build Expedition Action"); UBP_FortExpeditionOverviewWidget_C_Should_Disable_Build_Expedition_Action_Params params; params.Expedition = Expedition; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Disable != nullptr) *Disable = params.Disable; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Try to Build Expedition // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Expedition (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Try_to_Build_Expedition(class UFortExpeditionItem* Expedition) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Try to Build Expedition"); UBP_FortExpeditionOverviewWidget_C_Try_to_Build_Expedition_Params params; params.Expedition = Expedition; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Try to Abandon Expedition // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Expedition (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Try_to_Abandon_Expedition(class UFortExpeditionItem* Expedition) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Try to Abandon Expedition"); UBP_FortExpeditionOverviewWidget_C_Try_to_Abandon_Expedition_Params params; params.Expedition = Expedition; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Update Active Input For Selected Item // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* InputObject (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Update_Active_Input_For_Selected_Item(class UFortExpeditionItem* InputObject) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Update Active Input For Selected Item"); UBP_FortExpeditionOverviewWidget_C_Update_Active_Input_For_Selected_Item_Params params; params.InputObject = InputObject; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Update Details Visibility // (Public, BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::Update_Details_Visibility() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Update Details Visibility"); UBP_FortExpeditionOverviewWidget_C_Update_Details_Visibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Update List View Area // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::Update_List_View_Area() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Update List View Area"); UBP_FortExpeditionOverviewWidget_C_Update_List_View_Area_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleCollectExpeditionAction // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool PassThrough (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::HandleCollectExpeditionAction(bool* PassThrough) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleCollectExpeditionAction"); UBP_FortExpeditionOverviewWidget_C_HandleCollectExpeditionAction_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (PassThrough != nullptr) *PassThrough = params.PassThrough; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleAbandonExpeditionAction // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool PassThrough (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::HandleAbandonExpeditionAction(bool* PassThrough) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleAbandonExpeditionAction"); UBP_FortExpeditionOverviewWidget_C_HandleAbandonExpeditionAction_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (PassThrough != nullptr) *PassThrough = params.PassThrough; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleBuildExpeditionAction // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool PassThrough (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::HandleBuildExpeditionAction(bool* PassThrough) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleBuildExpeditionAction"); UBP_FortExpeditionOverviewWidget_C_HandleBuildExpeditionAction_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (PassThrough != nullptr) *PassThrough = params.PassThrough; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Determine Active Input Action // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* InItem (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Determine_Active_Input_Action(class UFortExpeditionItem* InItem) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Determine Active Input Action"); UBP_FortExpeditionOverviewWidget_C_Determine_Active_Input_Action_Params params; params.InItem = InItem; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Hide All Input Actions // (Public, BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::Hide_All_Input_Actions() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Hide All Input Actions"); UBP_FortExpeditionOverviewWidget_C_Hide_All_Input_Actions_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Set Current Tab Name // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FName TabId (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Set_Current_Tab_Name(const struct FName& TabId) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Set Current Tab Name"); UBP_FortExpeditionOverviewWidget_C_Set_Current_Tab_Name_Params params; params.TabId = TabId; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.On Widget Activated // (Public, BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::On_Widget_Activated() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.On Widget Activated"); UBP_FortExpeditionOverviewWidget_C_On_Widget_Activated_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.FireCollectCompletedExpedition // (Public, BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::FireCollectCompletedExpedition() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.FireCollectCompletedExpedition"); UBP_FortExpeditionOverviewWidget_C_FireCollectCompletedExpedition_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Setup Expedition Details Widget // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::Setup_Expedition_Details_Widget(class UFortExpeditionItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Setup Expedition Details Widget"); UBP_FortExpeditionOverviewWidget_C_Setup_Expedition_Details_Widget_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Construct"); UBP_FortExpeditionOverviewWidget_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.OnExpeditionTabSelected // (Event, Protected, HasOutParms, BlueprintEvent) // Parameters: // struct FName* TabNameID (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::OnExpeditionTabSelected(struct FName* TabNameID) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.OnExpeditionTabSelected"); UBP_FortExpeditionOverviewWidget_C_OnExpeditionTabSelected_Params params; params.TabNameID = TabNameID; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleAbandonExpedition // (BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::HandleAbandonExpedition() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleAbandonExpedition"); UBP_FortExpeditionOverviewWidget_C_HandleAbandonExpedition_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionTabList_K2Node_ComponentBoundEvent_10_OnTabButtonCreated__DelegateSignature // (BlueprintEvent) // Parameters: // struct FName TabId (Parm, ZeroConstructor, IsPlainOldData) // class UCommonButton* TabButton (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::BndEvt__ExpeditionTabList_K2Node_ComponentBoundEvent_10_OnTabButtonCreated__DelegateSignature(const struct FName& TabId, class UCommonButton* TabButton) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionTabList_K2Node_ComponentBoundEvent_10_OnTabButtonCreated__DelegateSignature"); UBP_FortExpeditionOverviewWidget_C_BndEvt__ExpeditionTabList_K2Node_ComponentBoundEvent_10_OnTabButtonCreated__DelegateSignature_Params params; params.TabId = TabId; params.TabButton = TabButton; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Destruct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::Destruct() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.Destruct"); UBP_FortExpeditionOverviewWidget_C_Destruct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.OnExpeditionOverviewRefresh // (Event, Protected, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::OnExpeditionOverviewRefresh() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.OnExpeditionOverviewRefresh"); UBP_FortExpeditionOverviewWidget_C_OnExpeditionOverviewRefresh_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_3_OnExpeditionListItemSelected__DelegateSignature // (BlueprintEvent) // Parameters: // class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_3_OnExpeditionListItemSelected__DelegateSignature(class UFortExpeditionItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_3_OnExpeditionListItemSelected__DelegateSignature"); UBP_FortExpeditionOverviewWidget_C_BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_3_OnExpeditionListItemSelected__DelegateSignature_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleOnListViewRefreshed // (BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::HandleOnListViewRefreshed() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.HandleOnListViewRefreshed"); UBP_FortExpeditionOverviewWidget_C_HandleOnListViewRefreshed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_12_OnItemClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UObject* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_12_OnItemClicked__DelegateSignature(class UObject* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_12_OnItemClicked__DelegateSignature"); UBP_FortExpeditionOverviewWidget_C_BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_12_OnItemClicked__DelegateSignature_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_38_OnItemHovered__DelegateSignature // (BlueprintEvent) // Parameters: // class UObject* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_38_OnItemHovered__DelegateSignature(class UObject* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_38_OnItemHovered__DelegateSignature"); UBP_FortExpeditionOverviewWidget_C_BndEvt__ExpeditionListView_K2Node_ComponentBoundEvent_38_OnItemHovered__DelegateSignature_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.ExecuteUbergraph_BP_FortExpeditionOverviewWidget // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionOverviewWidget_C::ExecuteUbergraph_BP_FortExpeditionOverviewWidget(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.ExecuteUbergraph_BP_FortExpeditionOverviewWidget"); UBP_FortExpeditionOverviewWidget_C_ExecuteUbergraph_BP_FortExpeditionOverviewWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.OnCollectCompletedExpedition__DelegateSignature // (Public, Delegate, BlueprintCallable, BlueprintEvent) void UBP_FortExpeditionOverviewWidget_C::OnCollectCompletedExpedition__DelegateSignature() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionOverviewWidget.BP_FortExpeditionOverviewWidget_C.OnCollectCompletedExpedition__DelegateSignature"); UBP_FortExpeditionOverviewWidget_C_OnCollectCompletedExpedition__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
Effects of Lattice Structure in the Dynamics of Coupled Elements We investigate the influence of lattice geometry in network dynamics, using a cellular automaton with nearest-neighbor interactions and two admissible local states. We show that there are significant geometric effects in the distribution of local states and in the distribution of clusters, even when the connection topology is kept constant. Moreover, we show that some geometric structures are more cohesive than others, tending to keep a given initial configuration. To characterize the dynamics, we determine the distributions of local states and introduce a cluster coefficient. The lattice geometry is defined from the number of nearest neighbors and their disposition in space', and here we consider four different geometries: a chain, a hexagonal lattice, a square lattice and a cubic lattice.
The new Canadian government is looking to further expand its surveillance powers by requiring decryption capabilities for all services, mandatory storage of both internet and phone records for service providers, backdoors that allow interception, and warrantless access to basic subscriber information. Bill C-51 Last year, under the previous conservative government, Canada passed a controversial “anti-terrorism” law, called Bill C-51, which gave new powers to the country’s police and intelligence agencies with little oversight. The bill has been criticized for allowing the country’s domestic spy agency, the Canadian Security Intelligence Service (CSIS), to become a “secret police” by extending its powers beyond simple information gathering. It also allows 17 agencies to share a wide range of information about Canadian citizens, including medical and financial records, with the Canadian intelligence agencies. Mandatory Decryption After mandatory decryption and encryption backdoors failed to pick up steam in the United States, but succeeded in the UK with the passing of the “Snoopers’ Charter,” Canada is looking to give this idea a try, too. The government is now asking for feedback on whether it should legally force individuals and organizations to decrypt material. This implies that either companies would have to forgo using end-to-end encryption that allows users to encrypt communications with their own keys, or they would need to have some kind of backdoor that would allow them to bypass the end-to-end encryption. Software Backdoors The government also complained about not being able to intercept some communications, and that it should be allowed to use intercept capability against some service providers. Unlike the phone networks, which have had built-in intercept capabilities for decades, many of the chat or email applications don’t (with some exceptions). That’s even more true for end-to-end encrypted services, where the companies themselves can’t see the private communications between users, which means law enforcement can’t either. If the government can’t outlaw end-to-end encryption and can’t require companies to use only encryption that can be decrypted, the next best thing is going to be some kind of software backdoor that disables and bypasses an application’s end-to-end encryption. Then the communications could pass through the company’s servers, where law enforcement could intercept it. The government could even get direct access to the backdoor, and then it could use it whenever it wants, with or without a warrant. However, if something like this passes as law, then it would become public, and more people may start avoiding services that have to abide by this Canadian law. This may be the reason why so many of the western democratic countries are trying to pass such laws almost in unison lately, to make it feel as if the people have no choice but to continue to use the backdoored services. Security experts have almost unanimously come out against the idea of software backdoors, because they represent a grave security risk. Once there’s a way to bypass encryption, it’s not just governments that can use it, but also other bad actors. Mandatory Records Storage The Canadian government is complaining that some services don’t store records long enough, asserting that this is a problem for law enforcement. It also complained that some internet services that are used by Canadians “operate beyond the reach of Canadian law” simply because they have no local headquarters or servers, and thus Canadian law enforcement can’t legally request data from them. The government seems to be targeting privacy services companies such as VPN providers. Some VPN service providers keep no logs whatsoever, and they may not even have servers in Canada. That means the Canadian government can’t request user data or force them to install backdoors. The Canadian government seems to be considering a law where it could both mandate that all service providers, including VPN services, store customer records for a longer period of time, and that it should be able to request that data when needed. Basic Subscriber information The government argues that it should be allowed to get access to basic subscriber information without a warrant. It gives examples of situations such as as when a person is missing, when there is suspicion of a crime, to further investigate a lead, and so on. However, these situations could be addressed by a judge assigned for emergency cases. It’s also not clear which agencies would be able to access this information, but presumably the Canadian government would want to eliminate any sort of restrictions for any agency when it comes to accessing basic subscriber information. For now, it looks like the Canadian government is at least willing to hear people’s opinions on this, and people can submit their comments on these issues on the government’s Public Safety website.
Chronic Hypoxia Enhances Adenosine Release in Rat PC12 Cells by Altering Adenosine Metabolism and Membrane Transport Abstract: Acute exposure to hypoxia causes a release of adenosine (ADO) that is inversely related to the O2 levels in oxygensensitive pheochromocytoma (PC12) cells. In the current study, chronic exposure (48 h) of PC12 cells to moderate hypoxia (5% O2) significantly enhanced the release of ADO during severe, acute hypoxia (1% O2). Investigation into the intra and extracellular mechanisms underpinning the secretion of ADO in PC12 cells chronically exposed to hypoxia revealed changes in gene expression and activities of several key enzymes associated with ADO production and metabolism, as well as the downregulation of a nucleoside transporter. Decreases in the enzymatic activities of ADO kinase and ADO deaminase accompanied by an increase in those of cytoplasmic and ecto5nucleotidases bring about an increased capacity to produce intra and extracellular ADO. This increased potential to generate ADO and decreased capacity to metabolize ADO indicate that PC12 cells shift toward an ADO producer phenotype during hypoxia. The reduced function of the rat equilibrative nucleoside transporter rENT1 also plays a role in controlling extracellular ADO levels. The hypoxiainduced alterations in the ADO metabolic enzymes and the rENT1 transporter seem to increase the extracellular concentration of ADO. The biological significance of this regulation is unclear but is likely to be associated with modulating cellular activity during hypoxia.
Dihydromethysticin, a natural molecule from Kava, suppresses the growth of colorectal cancer via the NLRC3/PI3K pathway Dihydromethysticin (DHM), a natural compound derived from Kava, has been reported to be effective against mental disorders and some malignant tumors. However, little is known about the inhibitory effect of DHM on colorectal cancer (CRC). First, we examined the impact of DHM on human colon cancer cell lines, which demonstrated that DHM inhibits proliferation, migration, and invasion and promotes apoptosis and cell cycle arrest in colon cancer cells in vitro. Using small hairpin RNA, we inhibited nucleotideoligomerization domainlike receptor subfamily C3 (NLRC3)/phosphoinositide 3kinase (PI3K) pathway to elucidate the partial signaling of DHMmediated tumor suppression. Additionally, using an ectopic human CRC model, we verified whether DHM inhibits tumor growth and angiogenesis via the NLRC3/PI3K pathway in vivo. Overall, DHM showed an inhibitory effect on CRC by altering cell proliferation, migration, invasion, apoptosis, cell cycle, and angiogenesis, possibly via the NLRC3/PI3K pathway. Thus, DHM may be a promising candidate for CRC therapy.
NA3HL — Granite City Lumberjacks at North Iowa Bulls, 7:30 p.m. NSIC — Winona State at St. Cloud State, 5:30 p.m. MIAC — Macalester at St. John’s, 3 p.m. NSIC — Winona State at St. Cloud State, 3:30 p.m. MIAC — Macalester at St. Benedict, 1 p.m. NCHC — Miami (OH) at St. Cloud State, 6 p.m. MIAC — St. Benedict at Augsburg, 4 p.m. WCHA — Ohio State at St. Cloud State, 2 p.m. Sauk Rapids invitational, 10 a.m. Cretin-Derham Hall invitational with Sartell, 9 a.m. Blaine invitational with Foley, 9:30 a.m. Wadena-Deer Creek invitational with Royalton, 10 a.m. Nonconference — Foley at Aitkin, 12 p.m.; St. Cloud Tech at Buffalo, 2:30 p.m.; Willmar at Prairie Centre, 7:15 p.m. Nonconference — Albany at Sauk Centre, 2:30 p.m.; Sartell at Bemidji, 5:45 p.m.; Royalton at St. Cloud Cathedral, 7:15 p.m. Nonconference — Detroit Lakes at River Lakes, 3 p.m.; Willmar at Prairie Centre, 5 p.m.
Intralesional Triamcinolone May Not Be Beneficial for Treating Acute Hidradenitis Suppurativa Lesions: A Double-Blind, Randomized, Placebo-Controlled Trial. BACKGROUND Hidradenitis suppurativa (HS) is a chronic, inflammatory condition characterized by recurrent nodules, sinus tracts, comedones, and scarring. Hidradenitis suppurativa is often associated with pain and decreased quality of life. Limited clinical trial data exist regarding the management of acute HS lesions, but clinical experience and a prospective case series suggest that intralesional triamcinolone may be useful. OBJECTIVE To compare the efficacy of intralesional triamcinolone to placebo for the treatment of HS inflammatory lesions. MATERIALS AND METHODS This is a double-blind, randomized, placebo-controlled trial comparing intralesional triamcinolone 10 mg/mL, triamcinolone 40 mg/mL, and normal saline (NS). Thirty-two subjects at University of North Carolina Dermatology and Skin Cancer Centers were enrolled for a total of 67 lesions. Subjects reported pain scores, days to resolution, and satisfaction on a standardized survey over a 14-day period. RESULTS When intralesional injections of triamcinolone 10 mg/mL, triamcinolone 40 mg/mL, and NS were compared, no significant difference was found for days to HS inflammatory lesion clearance, pain reduction at Day 5, or patient satisfaction. CONCLUSION No statistically significant difference was found between varying concentrations of triamcinolone and NS for the treatment of HS lesions. Steroid injections may be less effective for the management of acute HS than typically presumed.
Remittances and households' livelihood in the context of Covid19: Evidence from Burkina Faso Using data from a migration survey conducted in Burkina Faso, this research seeks to understand the Covid-19 pandemic's effects on migrant remittances and households' livelihood. Results suggest that migrant households and those receiving remittances are less likely to report a negative effect of the pandemic on their livelihood. More precisely, we find that if remittances sent by migrants remained the same or increased during the pandemic, households are less likely to report a negative effect on their livelihood. We resort to a recursive bivariate probit model and a two-stage residual inclusion estimator, using variables that capture xenophobia and possession of identity papers as instruments for remittances.
import styled from '@emotion/styled'; import { Breakpoint } from '../../lib/WindowService'; import { useT } from '../../lib/i18n'; import { mq } from '../globals/Constants'; import { PublishedStatus } from '../../lib/api/types/general'; const StyledStatusBar = styled.div` display: flex; position: relative; border-bottom: 1px solid var(--grey-400); `; const StyledStatusBarFlag = styled.div<{ backgroundColor: string }>` background: ${({ backgroundColor }) => backgroundColor}; font-size: var(--font-size-300); line-height: var(--line-height-300); font-weight: 700; margin-left: 0.75rem; padding: 0 0.375rem; border-radius: 0.375rem 0.375rem 0 0; ${mq(Breakpoint.mid)} { padding: 0.375rem 0.75rem; } `; const StatusBarLabel = styled.div` font-size: var(--font-size-300); line-height: var(--line-height-300); font-weight: 700; padding: 0; margin-right: 0.75rem; ${mq(Breakpoint.mid)} { padding: 0.375rem 0; } `; const StyledStatusBarInfo = styled.div` font-size: var(--font-size-300); line-height: var(--line-height-300); position: relative; flex-grow: 1; text-align: right; padding: 0; ${mq(Breakpoint.mid)} { padding: 0.375rem 0; } `; const statusBarStatuses: { [key in PublishedStatus]: { backgroundColor: string; textKey: string }; } = { draft: { backgroundColor: 'var(--yellow)', textKey: 'statusBar.draft', }, published: { backgroundColor: 'var(--green-light)', textKey: 'statusBar.published', }, }; const useStatusBarFlag = (status = PublishedStatus.draft): React.ReactElement => { const t = useT(); return ( <StyledStatusBarFlag backgroundColor={statusBarStatuses[status].backgroundColor}> {t(statusBarStatuses[status].textKey)} </StyledStatusBarFlag> ); }; interface StatusBarProps { status: PublishedStatus; date?: string; } export const StatusBar: React.FC<StatusBarProps> = ({ status }: StatusBarProps) => { const flag = useStatusBarFlag(status); const t = useT(); return ( <StyledStatusBar> <StatusBarLabel>{t('statusBar.status')}</StatusBarLabel> <StyledStatusBarInfo></StyledStatusBarInfo> {flag} </StyledStatusBar> ); };
Identification of magnetosonic modes in Galactic turbulence <p>The multiphase nature of astrophysical environment and diversity of driving mechanisms give rise to spatial variation of turbulence properties. Nevertheless, the employed model of magneto-hydrodynamic turbulence is often oversimplified being assumed to be only Alfvenic due to a lack of observational evidence. Here we report the employment of our novel method, the signature from polarization analysis (SPA), on unveiling the plasma modes in interstellar turbulence. The method is based on the statistical properties of the Stokes parameters (I,Q,U) of the synchrotron radiation polarization. The application of SPA on the synchrotron polarization data from the Galactic medium has for the first time revealed that interstellar turbulence is magnetized with different plasma modes composition, pinpointing the necessity to account for plasma property of turbulence, which is neither hydrodynamic nor purely Alfvenic, but depends on local physical conditions, particularly the driving process. A highly promising research field is foreseen to unroll with ample results anticipated from the advanced analysis of high resolution synchrotron polarization data and multiple wavelength comparison, that will shed light on the role of turbulence in various physical processes.</p>
The present invention relates to apparatus for melt spinning multifilament yarns from fiber-forming polymers at wind-up speeds of at least 2000 m/min, comprising a spinnerette, a tooling means for solidifying the filaments, a convergence element for the filaments and a wind-up means and having, at least between the spinnerette and the first convergence element, an essentially vertical spinline, wherein the cooling means is a porous tube which is open in the spinning direction and concentric relative to the spinline and wherein air for cooling the filaments is drawn through the porous tube solely by the filaments themselves due to the wind up speed of at least 2,000 m/min, as per U.S. application Ser. No. 07/939,936 filed Sep. 2, 1992, the entire disclosure of which is expressly incorporated herein by reference. The invention also concerns the use of this apparatus for manufacturing polyester filament yarns. The present invention has for its object to make available the above apparatus for specific purposes, in particular for wind-up speeds of at least 2000 m/min.
Repeal Trump's Blank Check for War Donald Trump’s reckless language is hurtling us toward a nuclear crisis with North Korea. But our Founders gave the Legislative Branch, not the president, the authority to wage war. That’s why Brand New Congress and Justice Democrats are calling on Congress to immediately repeal Trump’s unconstitutional blank check for war-making. Since 9/11, the 2001 Authorization of Use of Military Force (AUMF) has been an excuse for both the Bush and Obama administrations to engage in over 37 military actions in 14 countries. Congress has turned a blind eye to this vast expansion of executive power for decades. Now, we stand the chance of Trump using the AUMF to justify a "preemptive" war on North Korea without congressional approval. But we do not want another Iraq, especially when there are actual Weapons of Mass Destruction involved this time. We are on the cusp of a crisis, and we need to restore constitutional checks and balances on war-making. No one person should have unlimited power to spark World War III on a whim—not Donald Trump, not any president. The power to declare war rests solely with Congress. Sign this petition to prevent Trump from going to war without congressional approval. As concerned citizens of the United States of America, we call on Congress to immediately vote to repeal the 2001 AUMF. We will not tolerate a preemptive strike on North Korea without a congressional declaration of war. It’s time to uphold the war powers intended by our Constitution.
Amorphous carbon a promising material for sodium ion battery anodes: a first principles study We present a comparative ab initio computational study of sodium and lithium storage in amorphous (glassy) carbon (a-C) vs. graphite. Amorphous structures are obtained by fitting stochastically generated structures to a reference radial distribution function. Li insertion is thermodynamically favored in both graphite and a-C. While sodium insertion is thermodynamically unfavored in graphite, a-C possesses multiple insertion sites with binding energies stronger than Na cohesive energy, making it usable as anode material for Na-ion batteries. Introduction The perspective of a widespread use of clean but intermittent sources of electricity (wind and solar) as well as of hybrid electric vehicles calls for alternatives to Li-ion batteries, as Li resources may be limited. Sodium being abundant, cheap, and a relatively light and small atom, Na-ion batteries have recently attracted much interest. However, while most studies of Na-ion batteries focus on the positive electrode, the negative electrode remains less investigated and an efficient anode material providing all a good capacity, a high cycle life, and a descent rate of charge/discharge, is still not available. Some efficient electrode materials for Li, in particular diamond Si and graphite C, have been shown to not allow the intercalation of Na. Computational studies report positive intercalation energies and therefore suggest that the insertion of Na into the crystalline framework of graphite and Si is thermodynamically not favored: Na atoms prefer to cluster rather than to intercalate into the crystalline phase. Absence of significant Na insertion in graphite is also confirmed experimentally. Na insertion into graphite has only been achieved by co-insertion with some electrolytes. Amorphization of Si has recently been shown to improve substantially the interaction between Si and Na, and amorphous Si (a-Si) has been predicted to allow Na insertion by two independent studies. We hypothesize that the same should hold for amorphization of carbon. To the best of our knowledge, the effect of amorphization of carbon on Na and Li storage has not been computed. Its knowledge is needed for rational design of electrodes for Na-ion batteries as well as for Li-ion batteries. Indeed, carbon is widely used as storage medium and/or conducting binder in both types of batteries. Specifically, nano-sized graphite (which is also sometimes called "amorphous carbon", as opposed to truly amorphous or "glassy" C ) has been used as anode for Na-ion batteries. Amorphous carbon as anode material has been investigated for Li insertion. In Ref., amorphous carbon-coated TiO 2 nanocrystals were used in a lithium-ion battery, while amorphous carbon-coated Na 7 Fe 7 (PO 4 ) 6 F 3 has recently been investigated experimentally as a cathode material in sodium ion batteries, and it was shown that the coated material exhibits twice the capacity of the uncoated sample. Glassy carbon in nanocomposites can be a component of electrodes. An increasing interest lies in the combination of different materials, composite materials, e.g. amorphous phosphorous/carbon composite and nanocomposite Sb/C were investigated as promising anode materials for Na-ion batteries. In this paper, we therefore investigate the effect of amorphization of carbon on the energetics of insertion of Li and Na and show that, contrary to graphite, amorphous (glassy) carbon favors sodium insertion and can therefore work as anode for Na-ion batteries. This is a computational study at the dispersion-corrected Density Functional Theory (DFT-D) level. In Section 2, we introduce the methodology used to make the amorphous structures and to do ab initio calculations. In Section 3, we present calculations of two different amorphous carbon structures and the number of the most stable Page 3 of 13 insertion sites into these two structures (Section 3.1) in comparison to the known lowest site in graphite, as well as the energetics of Li and Na in a-C versus graphite (Section 3.2). We show that amorphization leads to stronger binding of Li and Na to carbon. Section 4 concludes that amorphous carbon is suitable as anode material Na-ion batteries and may also be advantageous for use in Li-ion batteries. Amorphous carbon structure Amorphous structures were generated by randomly sampling distributions of 64 carbon atoms placed in a box of size 8x8x8 3, with periodic boundary conditions. The initial density of about 2.5 g/cm 3 is near that of previously reported amorphous structures. A large number (>10 6 ) of distributions were sampled, for which the radial distribution functions (RDF) were compared to the experimental RDF of Ref.. The structures giving a good fit of the RDF to the experimental RDF were then optimized with DFT-D including optimization of lattice vectors (to zero pressure), which did not result in significant changes of the RDF or of the density. While the method bears similarity to that used in Ref. in that initial random structures are used, we introduce significant improvements in that we fit to the experimental RDF and ensure that the structure is stable under cell vector optimization to target pressure. Ab initio calculations Structures were optimized with density functional theory (DFT) using the SIESTA code. The PBE exchange correlation functional and a double- polarized basis set were used. The basis sets were tuned to reproduce the cohesive energies of Li, Na, and diamond carbon (computed values of, respectivelyt, 1.67, 1.14, and 7.65 eV are in good agreement with reference values ). Core electrons were replaced with Troullier-Martins pseudopotentials. Spin-polarized calculations were performed. The DFT-D2 approach of Grimme is used to model the van der Waals interaction between the C atoms. This is important for comparison with graphite. No correction was used between the C and Li/Na atoms due to significant ionicity of the bonds (large charge donation, see below). The Grimme parameters were tuned to reproduce the spacing of layers of graphite (the computed value of 3.35 is in good agreement with reference values ). This was achieved with Grimme parameter values of s 6 =1.0, D=20, C 6 = 1.75 J nm 6 mol −1, r=1.725. Amorphous carbon structure and insertion sites Two amorphous structures were generated and are shown in Fig. 1(a, b). We use two different structures to ensure that the results are not skewed due to a particular generated structure. Their RDF are shown in Fig. 1(c) together (and in good agreement) with that from neutron diffraction data. Both amorphous structures have a mass density of ~2.5 g/cm 3 and a sp3 fraction of ~0.5, in agreement with amorphous structures generated by melting and quenching (MD) using the DFTB scheme. The fractional sp3 character is related to a coordination number of ~3.5. The amorphous structures are less stable than the graphite phase by 0.80 and 0.92 eV per atom for structures 1 and 2, respectively. To find Li/Na insertion sites in a-C, we performed a k-means clustering analysis of a uniform three-dimensional grid of points covering each structure spaced by 0.2 and excluding points closer than 1.5 to C atoms. This allowed us to identify 17 and 19 potential insertion sites in structures 1 and 2, respectively. These sites were used as initial guesses for the insertion sites and further optimized by DFT-D. The positions of optimized unique insertion sites are also shown in Fig. 1 (a, b). A total of 13/12 unique Li/Na sites were found in both structures. The known lowest energy site in graphite is also shown in Fig. 1(d) and is used for comparison. Insertion energetics of Li and Na into a-C vs. graphite Page 5 of 13 The defect formation energies of Li and Na in all structures are listed in Table 1 and are plotted in Fig. 2(a). The defect formation energy for Li insertion in graphite is -0.09 eV and for Na insertion +0.76, in good agreement with observed anodic voltages for Li, with previous calculations, and with the fact that Na does not intercalate in graphite. In a-C, there is a distribution of E f values, with lowest E f values stabilized by 1.48 eV for Li and 1.99 eV for Na, vs. graphite. This behavior is similar to what we previously observed for Li and Na insertion in amorphous vs. crystalline Si and TiO 2. All Li sites except one have a negative E f. More importantly, the amorphization of carbon makes Na insertion thermodynamically favored, with half the sites showing binding energies stronger than the cohesive energy of Na. a-C will therefore operate as an anode for Na-ion batteries, while graphite does not. Amorphization of carbon could also be used to increase the anodic voltage in Li-ion batteries by up to 1.5 V, which could be useful e.g. to match it with the redox window of the electrolyte and limit electrolyte decomposition. In Fig. 2 |e| for Na. However, no significant correlation of E f to the charges was found. We also investigated the insertion energetics of Li/Na in a-C for higher concentrations x ( in Li) suggest that the insertion of 2 and 3 Li/Na (and 6 Li) per 64 atoms of C is favored in the amorphous phase. For 6 Na atoms, the configurations modeled give a favored insertion in one of the two amorphous structures, and a slightly positive E f in the other. The defect formation energies increase with metal concentration, as expected; we note that the negative of the defect formation energy, -E f, is equal to the average voltage, see Ref.. These results suggest that Na intercalation could happen for a higher concentration than the very dilute concentration of x = 1 64. Conclusions We have shown in a comparative computational study that while the lowest-energy insertion site in graphite does not favor Na intercalation, the amorphous phase (a-C) provides insertion sites with a Page 6 of 13 wide distribution of energies, including sites with binding energies of Na stronger than Na cohesive energy. a-C can therefore operate as an anode for Na-ion batteries, while graphite cannot. Insertion of both Li and Na is stabilized by amorphization, by up to 1.5 and 2.0 eV, respectively. Amorphization of carbon could also be used to increase the anodic voltage in Li-ion batteries to e.g. limit electrolyte decomposition. We also show that it is possible to obtain a reliable amorphous structure in a computationally efficient way by optimizing randomized structures pre-selected to satisfy the desired (e.g. experimental) radial distribution function. Acknowledgments This work was supported by the Ministry of Education of Singapore via an AcRF grant (R-265-000-494-112).
BOULDER, Colo. – About 50 Boulder High School students walked out of class Thursday to protest the daily reading of the Pledge of Allegiance and recited their own version, omitting "one nation, under God." The students say the phrase violates the constitutional separation of church and state. They also say the daily reading of the pledge over the school public address system at the start of the second class takes away from education time and is ignored or mocked by some students. A state law passed in 2004 requires schools to offer the opportunity to recite the pledge each day but does not require students to participate. The protesting students, members of the Student Worker Club, want administrators to hold the pledge reading in the auditorium during each of the school&apos;s two lunch periods for any students who want to participate. Otherwise, they said, they plan to walk out each Thursday when the pledge is read and recite their version, which omits the reference to God and adds allegiance to constitutional rights, diversity and freedom, among other things. "Boulder High has a highly diverse population, not all of whom believe in God, or one God," said Emma Martens, a senior and president of the club, which has about a dozen members. "We didn&apos;t think it was fair for the whole school to have to listen to it. It&apos;s almost religious oppression," she said. Principal Bud Jenkins told the Camera newspaper on its Web site Thursday the pledge will not be moved, but added he was proud of the students for standing up for their beliefs. It was not immediately clear what discipline, if any, the protesting students would face.
def convert(self): if self.getGeomClass() == OdeGeom.GCSphere: return self.convertToSphere() elif self.getGeomClass() == OdeGeom.GCBox: return self.convertToBox() elif self.getGeomClass() == OdeGeom.GCCappedCylinder: return self.convertToCappedCylinder() elif self.getGeomClass() == OdeGeom.GCPlane: return self.convertToPlane() elif self.getGeomClass() == OdeGeom.GCRay: return self.convertToRay() elif self.getGeomClass() == OdeGeom.GCTriMesh: return self.convertToTriMesh() elif self.getGeomClass() == OdeGeom.GCSimpleSpace: return self.convertToSimpleSpace() elif self.getGeomClass() == OdeGeom.GCHashSpace: return self.convertToHashSpace() elif self.getGeomClass() == OdeGeom.GCQuadTreeSpace: return self.convertToQuadTreeSpace()
Anthropometric Comparison of Painting Portraits of Beautiful Women, Femme Fatales, and Artists Mothers Abstract The aim of this study was to compare the painting portraits of beautiful women, femme fatales, and artists mothers using anthropometry. Portraits of each theme were selected in modern novels, essays and picture books, and categorized portraits. A total of 52 samples were collected, including 20 beautiful women, 20 femme fatales, and 12 artists mothers. In 5 persons, 17 anthropometric ratios including the alae-alae/zygion-zygion ratio were compared in a 15-degree oblique view and in anteroposterior view photographs, and they were proved to not differ significantly. To distinguish oblique portraits less than 15 degrees, we measured the exocanthion-stomion-exocanthion (ESE) angle in photographs of 5 volunteers. The mean ± SD of the ESE angle was 64.52 ± 4.87 in the 15-degree angle view and 57.68 ± 54.09 in the 30-degree angle view. Thereafter, if the ESE angle was greater than 65 degrees, we considered the portrait to have less than a 15-degree angle and included it in the samples. The ratio did not differ significantly in 11 anthropometric proportions. However, the remaining 5 proportions were statistically significant. Beautiful women had wider noses (85% of the endocanthion-endocanthion width) than those of the femme fatale group (77%). Lips in the beautiful woman group are nicer and thicker (36% of lips width) compared with the artists mother group (27%). Femme fatales were relatively similar to beautiful women such as those women with nice and thick lips. However, the femme fatale group had an attractive midface ratio (36% of the total face height) that has been mentioned in the older literature, and the noses of the femme fatale group were narrower and sharper (77% of the endocanthion-endocanthion width) than those of the beautiful women (85%). The artists mother group has a relatively narrower upper face (29% of the total face height) and thinner lips (27% of the lip width) compared with the other 2 groups (36%). Proportions from works of art are more ideal and attractive than clinically measured proportions. The ideal ratios measured from historical portraits might be useful in planning facial surgeries.
Charge carrier mobility in conjugated organic polymers: simulation of an electron mobility in a carbazole-benzothiadiazole-based polymer Inorganic (mostly silicon based) solar cells are important devices that are used to solve the world energy and environmental needs. Now days, organic solar cells are attracting considerable attention in the field of photovoltaic cells because of their low cost and processing flexibility. Often conjugated polymers are used in the construction of the organic solar cells. We study the conjugated polymers' charge transport using computational approach that involves the use of the density functional theory (DFT), semiempirical (ZINDO), and Monte Carlo (MC) theoretical methods in order to determine their transfer integrals, reorganization energies, transfer rates (with the use of Marcus-Hush equation) and mobilities. We employ the experimentally determined three dimensional (3D) structure of poly(9,9'-di-n-octylfluorene-alt-benzothiadiazole) (F8BT) to estimate the electron mobility in a similar co-alternating polymer consisting of carbazole and benzothiadiazole units (C8BT). In agreement with our previous work, we found that including an orientational disorder in the crystal reduces the electron mobility in C8BT. We hope that the proposed computational approach can be used to predict charge mobility in organic materials that are used in solar cells.
<filename>px-addons/src/main/java/com/mercadopago/android/px/addons/validator/internal/RuleSet.java package com.mercadopago.android.px.addons.validator.internal; import androidx.annotation.NonNull; import java.util.List; public abstract class RuleSet<T> implements Rule<T> { @Override public final boolean apply(@NonNull final T data) { return apply(data, applyWithOperator()); } private boolean apply(@NonNull final T data, @NonNull final Operator operator) { boolean validation = operator == Operator.AND; for (final Rule<T> rule : getRules()) { validation = operator.evaluate(validation, rule.apply(data)); } return validation; } protected abstract Operator applyWithOperator(); abstract List<Rule<T>> getRules(); enum Operator { OR { @Override public boolean evaluate(final boolean evaluated, final boolean toEvaluate) { return evaluated || toEvaluate; } }, AND { @Override public boolean evaluate(final boolean evaluated, final boolean toEvaluate) { return evaluated && toEvaluate; } }; public abstract boolean evaluate(final boolean evaluated, final boolean toEvaluate); } }
/*- * Copyright (c) 2008, <NAME> <<EMAIL>> * All rights reserved. * * 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 unmodified, 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. * * $FreeBSD: src/sys/dev/ale/if_ale.c,v 1.3 2008/12/03 09:01:12 yongari Exp $ */ /* Driver for Atheros AR8121/AR8113/AR8114 PCIe Ethernet. */ #include <sys/param.h> #include <sys/endian.h> #include <sys/kernel.h> #include <sys/bus.h> #include <sys/interrupt.h> #include <sys/malloc.h> #include <sys/proc.h> #include <sys/rman.h> #include <sys/serialize.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/sysctl.h> #include <net/ethernet.h> #include <net/if.h> #include <net/bpf.h> #include <net/if_arp.h> #include <net/if_dl.h> #include <net/if_llc.h> #include <net/if_media.h> #include <net/ifq_var.h> #include <net/vlan/if_vlan_var.h> #include <net/vlan/if_vlan_ether.h> #include <netinet/ip.h> #include <dev/netif/mii_layer/mii.h> #include <dev/netif/mii_layer/miivar.h> #include <bus/pci/pcireg.h> #include <bus/pci/pcivar.h> #include <bus/pci/pcidevs.h> #include <dev/netif/ale/if_alereg.h> #include <dev/netif/ale/if_alevar.h> /* "device miibus" required. See GENERIC if you get errors here. */ #include "miibus_if.h" /* For more information about Tx checksum offload issues see ale_encap(). */ #define ALE_CSUM_FEATURES (CSUM_TCP | CSUM_UDP) struct ale_dmamap_ctx { int nsegs; bus_dma_segment_t *segs; }; static int ale_probe(device_t); static int ale_attach(device_t); static int ale_detach(device_t); static int ale_shutdown(device_t); static int ale_suspend(device_t); static int ale_resume(device_t); static int ale_miibus_readreg(device_t, int, int); static int ale_miibus_writereg(device_t, int, int, int); static void ale_miibus_statchg(device_t); static void ale_init(void *); static void ale_start(struct ifnet *, struct ifaltq_subque *); static int ale_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *); static void ale_watchdog(struct ifnet *); static int ale_mediachange(struct ifnet *); static void ale_mediastatus(struct ifnet *, struct ifmediareq *); static void ale_intr(void *); static int ale_rxeof(struct ale_softc *sc); static void ale_rx_update_page(struct ale_softc *, struct ale_rx_page **, uint32_t, uint32_t *); static void ale_rxcsum(struct ale_softc *, struct mbuf *, uint32_t); static void ale_txeof(struct ale_softc *); static int ale_dma_alloc(struct ale_softc *); static void ale_dma_free(struct ale_softc *); static int ale_check_boundary(struct ale_softc *); static void ale_dmamap_cb(void *, bus_dma_segment_t *, int, int); static void ale_dmamap_buf_cb(void *, bus_dma_segment_t *, int, bus_size_t, int); static int ale_encap(struct ale_softc *, struct mbuf **); static void ale_init_rx_pages(struct ale_softc *); static void ale_init_tx_ring(struct ale_softc *); static void ale_stop(struct ale_softc *); static void ale_tick(void *); static void ale_get_macaddr(struct ale_softc *); static void ale_mac_config(struct ale_softc *); static void ale_phy_reset(struct ale_softc *); static void ale_reset(struct ale_softc *); static void ale_rxfilter(struct ale_softc *); static void ale_rxvlan(struct ale_softc *); static void ale_stats_clear(struct ale_softc *); static void ale_stats_update(struct ale_softc *); static void ale_stop_mac(struct ale_softc *); #ifdef notyet static void ale_setlinkspeed(struct ale_softc *); static void ale_setwol(struct ale_softc *); #endif static void ale_sysctl_node(struct ale_softc *); static int sysctl_hw_ale_int_mod(SYSCTL_HANDLER_ARGS); /* * Devices supported by this driver. */ static struct ale_dev { uint16_t ale_vendorid; uint16_t ale_deviceid; const char *ale_name; } ale_devs[] = { { VENDORID_ATHEROS, DEVICEID_ATHEROS_AR81XX, "Atheros AR8121/AR8113/AR8114 PCIe Ethernet" }, }; static device_method_t ale_methods[] = { /* Device interface. */ DEVMETHOD(device_probe, ale_probe), DEVMETHOD(device_attach, ale_attach), DEVMETHOD(device_detach, ale_detach), DEVMETHOD(device_shutdown, ale_shutdown), DEVMETHOD(device_suspend, ale_suspend), DEVMETHOD(device_resume, ale_resume), /* Bus interface. */ DEVMETHOD(bus_print_child, bus_generic_print_child), DEVMETHOD(bus_driver_added, bus_generic_driver_added), /* MII interface. */ DEVMETHOD(miibus_readreg, ale_miibus_readreg), DEVMETHOD(miibus_writereg, ale_miibus_writereg), DEVMETHOD(miibus_statchg, ale_miibus_statchg), { NULL, NULL } }; static driver_t ale_driver = { "ale", ale_methods, sizeof(struct ale_softc) }; static devclass_t ale_devclass; DECLARE_DUMMY_MODULE(if_ale); MODULE_VERSION(if_ale, 1); MODULE_DEPEND(if_ale, miibus, 1, 1, 1); DRIVER_MODULE(if_ale, pci, ale_driver, ale_devclass, NULL, NULL); DRIVER_MODULE(miibus, ale, miibus_driver, miibus_devclass, NULL, NULL); static int ale_miibus_readreg(device_t dev, int phy, int reg) { struct ale_softc *sc; uint32_t v; int i; sc = device_get_softc(dev); if (phy != sc->ale_phyaddr) return (0); if (sc->ale_flags & ALE_FLAG_FASTETHER) { if (reg == MII_100T2CR || reg == MII_100T2SR || reg == MII_EXTSR) return (0); } CSR_WRITE_4(sc, ALE_MDIO, MDIO_OP_EXECUTE | MDIO_OP_READ | MDIO_SUP_PREAMBLE | MDIO_CLK_25_4 | MDIO_REG_ADDR(reg)); for (i = ALE_PHY_TIMEOUT; i > 0; i--) { DELAY(5); v = CSR_READ_4(sc, ALE_MDIO); if ((v & (MDIO_OP_EXECUTE | MDIO_OP_BUSY)) == 0) break; } if (i == 0) { device_printf(sc->ale_dev, "phy read timeout : %d\n", reg); return (0); } return ((v & MDIO_DATA_MASK) >> MDIO_DATA_SHIFT); } static int ale_miibus_writereg(device_t dev, int phy, int reg, int val) { struct ale_softc *sc; uint32_t v; int i; sc = device_get_softc(dev); if (phy != sc->ale_phyaddr) return (0); if (sc->ale_flags & ALE_FLAG_FASTETHER) { if (reg == MII_100T2CR || reg == MII_100T2SR || reg == MII_EXTSR) return (0); } CSR_WRITE_4(sc, ALE_MDIO, MDIO_OP_EXECUTE | MDIO_OP_WRITE | (val & MDIO_DATA_MASK) << MDIO_DATA_SHIFT | MDIO_SUP_PREAMBLE | MDIO_CLK_25_4 | MDIO_REG_ADDR(reg)); for (i = ALE_PHY_TIMEOUT; i > 0; i--) { DELAY(5); v = CSR_READ_4(sc, ALE_MDIO); if ((v & (MDIO_OP_EXECUTE | MDIO_OP_BUSY)) == 0) break; } if (i == 0) device_printf(sc->ale_dev, "phy write timeout : %d\n", reg); return (0); } static void ale_miibus_statchg(device_t dev) { struct ale_softc *sc = device_get_softc(dev); struct ifnet *ifp = &sc->arpcom.ac_if; struct mii_data *mii; uint32_t reg; ASSERT_SERIALIZED(ifp->if_serializer); if ((ifp->if_flags & IFF_RUNNING) == 0) return; mii = device_get_softc(sc->ale_miibus); sc->ale_flags &= ~ALE_FLAG_LINK; if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) == (IFM_ACTIVE | IFM_AVALID)) { switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_10_T: case IFM_100_TX: sc->ale_flags |= ALE_FLAG_LINK; break; case IFM_1000_T: if ((sc->ale_flags & ALE_FLAG_FASTETHER) == 0) sc->ale_flags |= ALE_FLAG_LINK; break; default: break; } } /* Stop Rx/Tx MACs. */ ale_stop_mac(sc); /* Program MACs with resolved speed/duplex/flow-control. */ if ((sc->ale_flags & ALE_FLAG_LINK) != 0) { ale_mac_config(sc); /* Reenable Tx/Rx MACs. */ reg = CSR_READ_4(sc, ALE_MAC_CFG); reg |= MAC_CFG_TX_ENB | MAC_CFG_RX_ENB; CSR_WRITE_4(sc, ALE_MAC_CFG, reg); } } static void ale_mediastatus(struct ifnet *ifp, struct ifmediareq *ifmr) { struct ale_softc *sc = ifp->if_softc; struct mii_data *mii = device_get_softc(sc->ale_miibus); ASSERT_SERIALIZED(ifp->if_serializer); mii_pollstat(mii); ifmr->ifm_status = mii->mii_media_status; ifmr->ifm_active = mii->mii_media_active; } static int ale_mediachange(struct ifnet *ifp) { struct ale_softc *sc = ifp->if_softc; struct mii_data *mii = device_get_softc(sc->ale_miibus); int error; ASSERT_SERIALIZED(ifp->if_serializer); if (mii->mii_instance != 0) { struct mii_softc *miisc; LIST_FOREACH(miisc, &mii->mii_phys, mii_list) mii_phy_reset(miisc); } error = mii_mediachg(mii); return (error); } static int ale_probe(device_t dev) { struct ale_dev *sp; int i; uint16_t vendor, devid; vendor = pci_get_vendor(dev); devid = pci_get_device(dev); sp = ale_devs; for (i = 0; i < NELEM(ale_devs); i++) { if (vendor == sp->ale_vendorid && devid == sp->ale_deviceid) { device_set_desc(dev, sp->ale_name); return (0); } sp++; } return (ENXIO); } static void ale_get_macaddr(struct ale_softc *sc) { uint32_t ea[2], reg; int i, vpdc; reg = CSR_READ_4(sc, ALE_SPI_CTRL); if ((reg & SPI_VPD_ENB) != 0) { reg &= ~SPI_VPD_ENB; CSR_WRITE_4(sc, ALE_SPI_CTRL, reg); } vpdc = pci_get_vpdcap_ptr(sc->ale_dev); if (vpdc) { /* * PCI VPD capability found, let TWSI reload EEPROM. * This will set ethernet address of controller. */ CSR_WRITE_4(sc, ALE_TWSI_CTRL, CSR_READ_4(sc, ALE_TWSI_CTRL) | TWSI_CTRL_SW_LD_START); for (i = 100; i > 0; i--) { DELAY(1000); reg = CSR_READ_4(sc, ALE_TWSI_CTRL); if ((reg & TWSI_CTRL_SW_LD_START) == 0) break; } if (i == 0) device_printf(sc->ale_dev, "reloading EEPROM timeout!\n"); } else { if (bootverbose) device_printf(sc->ale_dev, "PCI VPD capability not found!\n"); } ea[0] = CSR_READ_4(sc, ALE_PAR0); ea[1] = CSR_READ_4(sc, ALE_PAR1); sc->ale_eaddr[0] = (ea[1] >> 8) & 0xFF; sc->ale_eaddr[1] = (ea[1] >> 0) & 0xFF; sc->ale_eaddr[2] = (ea[0] >> 24) & 0xFF; sc->ale_eaddr[3] = (ea[0] >> 16) & 0xFF; sc->ale_eaddr[4] = (ea[0] >> 8) & 0xFF; sc->ale_eaddr[5] = (ea[0] >> 0) & 0xFF; } static void ale_phy_reset(struct ale_softc *sc) { /* Reset magic from Linux. */ CSR_WRITE_2(sc, ALE_GPHY_CTRL, GPHY_CTRL_HIB_EN | GPHY_CTRL_HIB_PULSE | GPHY_CTRL_SEL_ANA_RESET | GPHY_CTRL_PHY_PLL_ON); DELAY(1000); CSR_WRITE_2(sc, ALE_GPHY_CTRL, GPHY_CTRL_EXT_RESET | GPHY_CTRL_HIB_EN | GPHY_CTRL_HIB_PULSE | GPHY_CTRL_SEL_ANA_RESET | GPHY_CTRL_PHY_PLL_ON); DELAY(1000); #define ATPHY_DBG_ADDR 0x1D #define ATPHY_DBG_DATA 0x1E /* Enable hibernation mode. */ ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x0B); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_DATA, 0xBC00); /* Set Class A/B for all modes. */ ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x00); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_DATA, 0x02EF); /* Enable 10BT power saving. */ ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x12); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_DATA, 0x4C04); /* Adjust 1000T power. */ ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x04); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x8BBB); /* 10BT center tap voltage. */ ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x05); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, ATPHY_DBG_ADDR, 0x2C46); #undef ATPHY_DBG_ADDR #undef ATPHY_DBG_DATA DELAY(1000); } static int ale_attach(device_t dev) { struct ale_softc *sc = device_get_softc(dev); struct ifnet *ifp = &sc->arpcom.ac_if; int error = 0; uint32_t rxf_len, txf_len; uint8_t pcie_ptr; if_initname(ifp, device_get_name(dev), device_get_unit(dev)); sc->ale_dev = dev; callout_init(&sc->ale_tick_ch); #ifndef BURN_BRIDGES if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) { uint32_t irq, mem; irq = pci_read_config(dev, PCIR_INTLINE, 4); mem = pci_read_config(dev, ALE_PCIR_BAR, 4); device_printf(dev, "chip is in D%d power mode " "-- setting to D0\n", pci_get_powerstate(dev)); pci_set_powerstate(dev, PCI_POWERSTATE_D0); pci_write_config(dev, PCIR_INTLINE, irq, 4); pci_write_config(dev, ALE_PCIR_BAR, mem, 4); } #endif /* !BURN_BRIDGE */ /* Enable bus mastering */ pci_enable_busmaster(dev); /* * Allocate memory mapped IO */ sc->ale_mem_rid = ALE_PCIR_BAR; sc->ale_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->ale_mem_rid, RF_ACTIVE); if (sc->ale_mem_res == NULL) { device_printf(dev, "can't allocate IO memory\n"); return ENXIO; } sc->ale_mem_bt = rman_get_bustag(sc->ale_mem_res); sc->ale_mem_bh = rman_get_bushandle(sc->ale_mem_res); /* * Allocate IRQ */ sc->ale_irq_rid = 0; sc->ale_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->ale_irq_rid, RF_SHAREABLE | RF_ACTIVE); if (sc->ale_irq_res == NULL) { device_printf(dev, "can't allocate irq\n"); error = ENXIO; goto fail; } /* Set PHY address. */ sc->ale_phyaddr = ALE_PHY_ADDR; /* Reset PHY. */ ale_phy_reset(sc); /* Reset the ethernet controller. */ ale_reset(sc); /* Get PCI and chip id/revision. */ sc->ale_rev = pci_get_revid(dev); if (sc->ale_rev >= 0xF0) { /* L2E Rev. B. AR8114 */ sc->ale_flags |= ALE_FLAG_FASTETHER; } else { if ((CSR_READ_4(sc, ALE_PHY_STATUS) & PHY_STATUS_100M) != 0) { /* L1E AR8121 */ sc->ale_flags |= ALE_FLAG_JUMBO; } else { /* L2E Rev. A. AR8113 */ sc->ale_flags |= ALE_FLAG_FASTETHER; } } /* * All known controllers seems to require 4 bytes alignment * of Tx buffers to make Tx checksum offload with custom * checksum generation method work. */ sc->ale_flags |= ALE_FLAG_TXCSUM_BUG; /* * All known controllers seems to have issues on Rx checksum * offload for fragmented IP datagrams. */ sc->ale_flags |= ALE_FLAG_RXCSUM_BUG; /* * Don't use Tx CMB. It is known to cause RRS update failure * under certain circumstances. Typical phenomenon of the * issue would be unexpected sequence number encountered in * Rx handler. */ sc->ale_flags |= ALE_FLAG_TXCMB_BUG; sc->ale_chip_rev = CSR_READ_4(sc, ALE_MASTER_CFG) >> MASTER_CHIP_REV_SHIFT; if (bootverbose) { device_printf(dev, "PCI device revision : 0x%04x\n", sc->ale_rev); device_printf(dev, "Chip id/revision : 0x%04x\n", sc->ale_chip_rev); } /* * Uninitialized hardware returns an invalid chip id/revision * as well as 0xFFFFFFFF for Tx/Rx fifo length. */ txf_len = CSR_READ_4(sc, ALE_SRAM_TX_FIFO_LEN); rxf_len = CSR_READ_4(sc, ALE_SRAM_RX_FIFO_LEN); if (sc->ale_chip_rev == 0xFFFF || txf_len == 0xFFFFFFFF || rxf_len == 0xFFFFFFF) { device_printf(dev,"chip revision : 0x%04x, %u Tx FIFO " "%u Rx FIFO -- not initialized?\n", sc->ale_chip_rev, txf_len, rxf_len); error = ENXIO; goto fail; } device_printf(dev, "%u Tx FIFO, %u Rx FIFO\n", txf_len, rxf_len); /* Get DMA parameters from PCIe device control register. */ pcie_ptr = pci_get_pciecap_ptr(dev); if (pcie_ptr) { uint16_t devctl; sc->ale_flags |= ALE_FLAG_PCIE; devctl = pci_read_config(dev, pcie_ptr + PCIER_DEVCTRL, 2); /* Max read request size. */ sc->ale_dma_rd_burst = ((devctl >> 12) & 0x07) << DMA_CFG_RD_BURST_SHIFT; /* Max payload size. */ sc->ale_dma_wr_burst = ((devctl >> 5) & 0x07) << DMA_CFG_WR_BURST_SHIFT; if (bootverbose) { device_printf(dev, "Read request size : %d bytes.\n", 128 << ((devctl >> 12) & 0x07)); device_printf(dev, "TLP payload size : %d bytes.\n", 128 << ((devctl >> 5) & 0x07)); } } else { sc->ale_dma_rd_burst = DMA_CFG_RD_BURST_128; sc->ale_dma_wr_burst = DMA_CFG_WR_BURST_128; } /* Create device sysctl node. */ ale_sysctl_node(sc); if ((error = ale_dma_alloc(sc) != 0)) goto fail; /* Load station address. */ ale_get_macaddr(sc); ifp->if_softc = sc; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_ioctl = ale_ioctl; ifp->if_start = ale_start; ifp->if_init = ale_init; ifp->if_watchdog = ale_watchdog; ifq_set_maxlen(&ifp->if_snd, ALE_TX_RING_CNT - 1); ifq_set_ready(&ifp->if_snd); ifp->if_capabilities = IFCAP_RXCSUM | IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING; #ifdef notyet ifp->if_capabilities |= IFCAP_TXCSUM; ifp->if_hwassist = ALE_CSUM_FEATURES; #endif ifp->if_capenable = ifp->if_capabilities; /* Set up MII bus. */ if ((error = mii_phy_probe(dev, &sc->ale_miibus, ale_mediachange, ale_mediastatus)) != 0) { device_printf(dev, "no PHY found!\n"); goto fail; } ether_ifattach(ifp, sc->ale_eaddr, NULL); /* Tell the upper layer(s) we support long frames. */ ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header); error = bus_setup_intr(dev, sc->ale_irq_res, INTR_MPSAFE, ale_intr, sc, &sc->ale_irq_handle, ifp->if_serializer); if (error) { device_printf(dev, "could not set up interrupt handler.\n"); ether_ifdetach(ifp); goto fail; } ifq_set_cpuid(&ifp->if_snd, rman_get_cpuid(sc->ale_irq_res)); return 0; fail: ale_detach(dev); return (error); } static int ale_detach(device_t dev) { struct ale_softc *sc = device_get_softc(dev); if (device_is_attached(dev)) { struct ifnet *ifp = &sc->arpcom.ac_if; lwkt_serialize_enter(ifp->if_serializer); sc->ale_flags |= ALE_FLAG_DETACH; ale_stop(sc); bus_teardown_intr(dev, sc->ale_irq_res, sc->ale_irq_handle); lwkt_serialize_exit(ifp->if_serializer); ether_ifdetach(ifp); } if (sc->ale_sysctl_tree != NULL) sysctl_ctx_free(&sc->ale_sysctl_ctx); if (sc->ale_miibus != NULL) device_delete_child(dev, sc->ale_miibus); bus_generic_detach(dev); if (sc->ale_irq_res != NULL) { bus_release_resource(dev, SYS_RES_IRQ, sc->ale_irq_rid, sc->ale_irq_res); } if (sc->ale_mem_res != NULL) { bus_release_resource(dev, SYS_RES_MEMORY, sc->ale_mem_rid, sc->ale_mem_res); } ale_dma_free(sc); return (0); } #define ALE_SYSCTL_STAT_ADD32(c, h, n, p, d) \ SYSCTL_ADD_UINT(c, h, OID_AUTO, n, CTLFLAG_RD, p, 0, d) #define ALE_SYSCTL_STAT_ADD64(c, h, n, p, d) \ SYSCTL_ADD_QUAD(c, h, OID_AUTO, n, CTLFLAG_RD, p, 0, d) static void ale_sysctl_node(struct ale_softc *sc) { struct sysctl_ctx_list *ctx; struct sysctl_oid_list *child, *parent; struct sysctl_oid *tree; struct ale_hw_stats *stats; int error; sysctl_ctx_init(&sc->ale_sysctl_ctx); sc->ale_sysctl_tree = SYSCTL_ADD_NODE(&sc->ale_sysctl_ctx, SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO, device_get_nameunit(sc->ale_dev), CTLFLAG_RD, 0, ""); if (sc->ale_sysctl_tree == NULL) { device_printf(sc->ale_dev, "can't add sysctl node\n"); return; } stats = &sc->ale_stats; ctx = &sc->ale_sysctl_ctx; child = SYSCTL_CHILDREN(sc->ale_sysctl_tree); SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "int_rx_mod", CTLTYPE_INT | CTLFLAG_RW, &sc->ale_int_rx_mod, 0, sysctl_hw_ale_int_mod, "I", "ale Rx interrupt moderation"); SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "int_tx_mod", CTLTYPE_INT | CTLFLAG_RW, &sc->ale_int_tx_mod, 0, sysctl_hw_ale_int_mod, "I", "ale Tx interrupt moderation"); /* * Pull in device tunables. */ sc->ale_int_rx_mod = ALE_IM_RX_TIMER_DEFAULT; error = resource_int_value(device_get_name(sc->ale_dev), device_get_unit(sc->ale_dev), "int_rx_mod", &sc->ale_int_rx_mod); if (error == 0) { if (sc->ale_int_rx_mod < ALE_IM_TIMER_MIN || sc->ale_int_rx_mod > ALE_IM_TIMER_MAX) { device_printf(sc->ale_dev, "int_rx_mod value out of " "range; using default: %d\n", ALE_IM_RX_TIMER_DEFAULT); sc->ale_int_rx_mod = ALE_IM_RX_TIMER_DEFAULT; } } sc->ale_int_tx_mod = ALE_IM_TX_TIMER_DEFAULT; error = resource_int_value(device_get_name(sc->ale_dev), device_get_unit(sc->ale_dev), "int_tx_mod", &sc->ale_int_tx_mod); if (error == 0) { if (sc->ale_int_tx_mod < ALE_IM_TIMER_MIN || sc->ale_int_tx_mod > ALE_IM_TIMER_MAX) { device_printf(sc->ale_dev, "int_tx_mod value out of " "range; using default: %d\n", ALE_IM_TX_TIMER_DEFAULT); sc->ale_int_tx_mod = ALE_IM_TX_TIMER_DEFAULT; } } /* Misc statistics. */ ALE_SYSCTL_STAT_ADD32(ctx, child, "reset_brk_seq", &stats->reset_brk_seq, "Controller resets due to broken Rx sequnce number"); tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "stats", CTLFLAG_RD, NULL, "ATE statistics"); parent = SYSCTL_CHILDREN(tree); /* Rx statistics. */ tree = SYSCTL_ADD_NODE(ctx, parent, OID_AUTO, "rx", CTLFLAG_RD, NULL, "Rx MAC statistics"); child = SYSCTL_CHILDREN(tree); ALE_SYSCTL_STAT_ADD32(ctx, child, "good_frames", &stats->rx_frames, "Good frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "good_bcast_frames", &stats->rx_bcast_frames, "Good broadcast frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "good_mcast_frames", &stats->rx_mcast_frames, "Good multicast frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "pause_frames", &stats->rx_pause_frames, "Pause control frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "control_frames", &stats->rx_control_frames, "Control frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "crc_errs", &stats->rx_crcerrs, "CRC errors"); ALE_SYSCTL_STAT_ADD32(ctx, child, "len_errs", &stats->rx_lenerrs, "Frames with length mismatched"); ALE_SYSCTL_STAT_ADD64(ctx, child, "good_octets", &stats->rx_bytes, "Good octets"); ALE_SYSCTL_STAT_ADD64(ctx, child, "good_bcast_octets", &stats->rx_bcast_bytes, "Good broadcast octets"); ALE_SYSCTL_STAT_ADD64(ctx, child, "good_mcast_octets", &stats->rx_mcast_bytes, "Good multicast octets"); ALE_SYSCTL_STAT_ADD32(ctx, child, "runts", &stats->rx_runts, "Too short frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "fragments", &stats->rx_fragments, "Fragmented frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_64", &stats->rx_pkts_64, "64 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_65_127", &stats->rx_pkts_65_127, "65 to 127 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_128_255", &stats->rx_pkts_128_255, "128 to 255 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_256_511", &stats->rx_pkts_256_511, "256 to 511 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_512_1023", &stats->rx_pkts_512_1023, "512 to 1023 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_1024_1518", &stats->rx_pkts_1024_1518, "1024 to 1518 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_1519_max", &stats->rx_pkts_1519_max, "1519 to max frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "trunc_errs", &stats->rx_pkts_truncated, "Truncated frames due to MTU size"); ALE_SYSCTL_STAT_ADD32(ctx, child, "fifo_oflows", &stats->rx_fifo_oflows, "FIFO overflows"); ALE_SYSCTL_STAT_ADD32(ctx, child, "rrs_errs", &stats->rx_rrs_errs, "Return status write-back errors"); ALE_SYSCTL_STAT_ADD32(ctx, child, "align_errs", &stats->rx_alignerrs, "Alignment errors"); ALE_SYSCTL_STAT_ADD32(ctx, child, "filtered", &stats->rx_pkts_filtered, "Frames dropped due to address filtering"); /* Tx statistics. */ tree = SYSCTL_ADD_NODE(ctx, parent, OID_AUTO, "tx", CTLFLAG_RD, NULL, "Tx MAC statistics"); child = SYSCTL_CHILDREN(tree); ALE_SYSCTL_STAT_ADD32(ctx, child, "good_frames", &stats->tx_frames, "Good frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "good_bcast_frames", &stats->tx_bcast_frames, "Good broadcast frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "good_mcast_frames", &stats->tx_mcast_frames, "Good multicast frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "pause_frames", &stats->tx_pause_frames, "Pause control frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "control_frames", &stats->tx_control_frames, "Control frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "excess_defers", &stats->tx_excess_defer, "Frames with excessive derferrals"); ALE_SYSCTL_STAT_ADD32(ctx, child, "defers", &stats->tx_excess_defer, "Frames with derferrals"); ALE_SYSCTL_STAT_ADD64(ctx, child, "good_octets", &stats->tx_bytes, "Good octets"); ALE_SYSCTL_STAT_ADD64(ctx, child, "good_bcast_octets", &stats->tx_bcast_bytes, "Good broadcast octets"); ALE_SYSCTL_STAT_ADD64(ctx, child, "good_mcast_octets", &stats->tx_mcast_bytes, "Good multicast octets"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_64", &stats->tx_pkts_64, "64 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_65_127", &stats->tx_pkts_65_127, "65 to 127 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_128_255", &stats->tx_pkts_128_255, "128 to 255 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_256_511", &stats->tx_pkts_256_511, "256 to 511 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_512_1023", &stats->tx_pkts_512_1023, "512 to 1023 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_1024_1518", &stats->tx_pkts_1024_1518, "1024 to 1518 bytes frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "frames_1519_max", &stats->tx_pkts_1519_max, "1519 to max frames"); ALE_SYSCTL_STAT_ADD32(ctx, child, "single_colls", &stats->tx_single_colls, "Single collisions"); ALE_SYSCTL_STAT_ADD32(ctx, child, "multi_colls", &stats->tx_multi_colls, "Multiple collisions"); ALE_SYSCTL_STAT_ADD32(ctx, child, "late_colls", &stats->tx_late_colls, "Late collisions"); ALE_SYSCTL_STAT_ADD32(ctx, child, "excess_colls", &stats->tx_excess_colls, "Excessive collisions"); ALE_SYSCTL_STAT_ADD32(ctx, child, "abort", &stats->tx_abort, "Aborted frames due to Excessive collisions"); ALE_SYSCTL_STAT_ADD32(ctx, child, "underruns", &stats->tx_underrun, "FIFO underruns"); ALE_SYSCTL_STAT_ADD32(ctx, child, "desc_underruns", &stats->tx_desc_underrun, "Descriptor write-back errors"); ALE_SYSCTL_STAT_ADD32(ctx, child, "len_errs", &stats->tx_lenerrs, "Frames with length mismatched"); ALE_SYSCTL_STAT_ADD32(ctx, child, "trunc_errs", &stats->tx_pkts_truncated, "Truncated frames due to MTU size"); } #undef ALE_SYSCTL_STAT_ADD32 #undef ALE_SYSCTL_STAT_ADD64 struct ale_dmamap_arg { bus_addr_t ale_busaddr; }; static void ale_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error) { struct ale_dmamap_arg *ctx; if (error != 0) return; KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs)); ctx = (struct ale_dmamap_arg *)arg; ctx->ale_busaddr = segs[0].ds_addr; } /* * Tx descriptors/RXF0/CMB DMA blocks share ALE_DESC_ADDR_HI register * which specifies high address region of DMA blocks. Therefore these * blocks should have the same high address of given 4GB address * space(i.e. crossing 4GB boundary is not allowed). */ static int ale_check_boundary(struct ale_softc *sc) { bus_addr_t rx_cmb_end[ALE_RX_PAGES], tx_cmb_end; bus_addr_t rx_page_end[ALE_RX_PAGES], tx_ring_end; rx_page_end[0] = sc->ale_cdata.ale_rx_page[0].page_paddr + sc->ale_pagesize; rx_page_end[1] = sc->ale_cdata.ale_rx_page[1].page_paddr + sc->ale_pagesize; tx_ring_end = sc->ale_cdata.ale_tx_ring_paddr + ALE_TX_RING_SZ; tx_cmb_end = sc->ale_cdata.ale_tx_cmb_paddr + ALE_TX_CMB_SZ; rx_cmb_end[0] = sc->ale_cdata.ale_rx_page[0].cmb_paddr + ALE_RX_CMB_SZ; rx_cmb_end[1] = sc->ale_cdata.ale_rx_page[1].cmb_paddr + ALE_RX_CMB_SZ; if ((ALE_ADDR_HI(tx_ring_end) != ALE_ADDR_HI(sc->ale_cdata.ale_tx_ring_paddr)) || (ALE_ADDR_HI(rx_page_end[0]) != ALE_ADDR_HI(sc->ale_cdata.ale_rx_page[0].page_paddr)) || (ALE_ADDR_HI(rx_page_end[1]) != ALE_ADDR_HI(sc->ale_cdata.ale_rx_page[1].page_paddr)) || (ALE_ADDR_HI(tx_cmb_end) != ALE_ADDR_HI(sc->ale_cdata.ale_tx_cmb_paddr)) || (ALE_ADDR_HI(rx_cmb_end[0]) != ALE_ADDR_HI(sc->ale_cdata.ale_rx_page[0].cmb_paddr)) || (ALE_ADDR_HI(rx_cmb_end[1]) != ALE_ADDR_HI(sc->ale_cdata.ale_rx_page[1].cmb_paddr))) return (EFBIG); if ((ALE_ADDR_HI(tx_ring_end) != ALE_ADDR_HI(rx_page_end[0])) || (ALE_ADDR_HI(tx_ring_end) != ALE_ADDR_HI(rx_page_end[1])) || (ALE_ADDR_HI(tx_ring_end) != ALE_ADDR_HI(rx_cmb_end[0])) || (ALE_ADDR_HI(tx_ring_end) != ALE_ADDR_HI(rx_cmb_end[1])) || (ALE_ADDR_HI(tx_ring_end) != ALE_ADDR_HI(tx_cmb_end))) return (EFBIG); return (0); } static int ale_dma_alloc(struct ale_softc *sc) { struct ale_txdesc *txd; bus_addr_t lowaddr; struct ale_dmamap_arg ctx; int error, guard_size, i; if ((sc->ale_flags & ALE_FLAG_JUMBO) != 0) guard_size = ALE_JUMBO_FRAMELEN; else guard_size = ALE_MAX_FRAMELEN; sc->ale_pagesize = roundup(guard_size + ALE_RX_PAGE_SZ, ALE_RX_PAGE_ALIGN); lowaddr = BUS_SPACE_MAXADDR; again: /* Create parent DMA tag. */ error = bus_dma_tag_create( NULL, /* parent */ 1, 0, /* alignment, boundary */ lowaddr, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ BUS_SPACE_MAXSIZE_32BIT, /* maxsize */ 0, /* nsegments */ BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_parent_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create parent DMA tag.\n"); goto fail; } /* Create DMA tag for Tx descriptor ring. */ error = bus_dma_tag_create( sc->ale_cdata.ale_parent_tag, /* parent */ ALE_TX_RING_ALIGN, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ ALE_TX_RING_SZ, /* maxsize */ 1, /* nsegments */ ALE_TX_RING_SZ, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_tx_ring_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create Tx ring DMA tag.\n"); goto fail; } /* Create DMA tag for Rx pages. */ for (i = 0; i < ALE_RX_PAGES; i++) { error = bus_dma_tag_create( sc->ale_cdata.ale_parent_tag, /* parent */ ALE_RX_PAGE_ALIGN, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ sc->ale_pagesize, /* maxsize */ 1, /* nsegments */ sc->ale_pagesize, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_rx_page[i].page_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create Rx page %d DMA tag.\n", i); goto fail; } } /* Create DMA tag for Tx coalescing message block. */ error = bus_dma_tag_create( sc->ale_cdata.ale_parent_tag, /* parent */ ALE_CMB_ALIGN, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ ALE_TX_CMB_SZ, /* maxsize */ 1, /* nsegments */ ALE_TX_CMB_SZ, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_tx_cmb_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create Tx CMB DMA tag.\n"); goto fail; } /* Create DMA tag for Rx coalescing message block. */ for (i = 0; i < ALE_RX_PAGES; i++) { error = bus_dma_tag_create( sc->ale_cdata.ale_parent_tag, /* parent */ ALE_CMB_ALIGN, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ ALE_RX_CMB_SZ, /* maxsize */ 1, /* nsegments */ ALE_RX_CMB_SZ, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_rx_page[i].cmb_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create Rx page %d CMB DMA tag.\n", i); goto fail; } } /* Allocate DMA'able memory and load the DMA map for Tx ring. */ error = bus_dmamem_alloc(sc->ale_cdata.ale_tx_ring_tag, (void **)&sc->ale_cdata.ale_tx_ring, BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->ale_cdata.ale_tx_ring_map); if (error != 0) { device_printf(sc->ale_dev, "could not allocate DMA'able memory for Tx ring.\n"); goto fail; } ctx.ale_busaddr = 0; error = bus_dmamap_load(sc->ale_cdata.ale_tx_ring_tag, sc->ale_cdata.ale_tx_ring_map, sc->ale_cdata.ale_tx_ring, ALE_TX_RING_SZ, ale_dmamap_cb, &ctx, 0); if (error != 0 || ctx.ale_busaddr == 0) { device_printf(sc->ale_dev, "could not load DMA'able memory for Tx ring.\n"); goto fail; } sc->ale_cdata.ale_tx_ring_paddr = ctx.ale_busaddr; /* Rx pages. */ for (i = 0; i < ALE_RX_PAGES; i++) { error = bus_dmamem_alloc(sc->ale_cdata.ale_rx_page[i].page_tag, (void **)&sc->ale_cdata.ale_rx_page[i].page_addr, BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->ale_cdata.ale_rx_page[i].page_map); if (error != 0) { device_printf(sc->ale_dev, "could not allocate DMA'able memory for " "Rx page %d.\n", i); goto fail; } ctx.ale_busaddr = 0; error = bus_dmamap_load(sc->ale_cdata.ale_rx_page[i].page_tag, sc->ale_cdata.ale_rx_page[i].page_map, sc->ale_cdata.ale_rx_page[i].page_addr, sc->ale_pagesize, ale_dmamap_cb, &ctx, 0); if (error != 0 || ctx.ale_busaddr == 0) { device_printf(sc->ale_dev, "could not load DMA'able memory for " "Rx page %d.\n", i); goto fail; } sc->ale_cdata.ale_rx_page[i].page_paddr = ctx.ale_busaddr; } /* Tx CMB. */ error = bus_dmamem_alloc(sc->ale_cdata.ale_tx_cmb_tag, (void **)&sc->ale_cdata.ale_tx_cmb, BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->ale_cdata.ale_tx_cmb_map); if (error != 0) { device_printf(sc->ale_dev, "could not allocate DMA'able memory for Tx CMB.\n"); goto fail; } ctx.ale_busaddr = 0; error = bus_dmamap_load(sc->ale_cdata.ale_tx_cmb_tag, sc->ale_cdata.ale_tx_cmb_map, sc->ale_cdata.ale_tx_cmb, ALE_TX_CMB_SZ, ale_dmamap_cb, &ctx, 0); if (error != 0 || ctx.ale_busaddr == 0) { device_printf(sc->ale_dev, "could not load DMA'able memory for Tx CMB.\n"); goto fail; } sc->ale_cdata.ale_tx_cmb_paddr = ctx.ale_busaddr; /* Rx CMB. */ for (i = 0; i < ALE_RX_PAGES; i++) { error = bus_dmamem_alloc(sc->ale_cdata.ale_rx_page[i].cmb_tag, (void **)&sc->ale_cdata.ale_rx_page[i].cmb_addr, BUS_DMA_WAITOK | BUS_DMA_ZERO, &sc->ale_cdata.ale_rx_page[i].cmb_map); if (error != 0) { device_printf(sc->ale_dev, "could not allocate " "DMA'able memory for Rx page %d CMB.\n", i); goto fail; } ctx.ale_busaddr = 0; error = bus_dmamap_load(sc->ale_cdata.ale_rx_page[i].cmb_tag, sc->ale_cdata.ale_rx_page[i].cmb_map, sc->ale_cdata.ale_rx_page[i].cmb_addr, ALE_RX_CMB_SZ, ale_dmamap_cb, &ctx, 0); if (error != 0 || ctx.ale_busaddr == 0) { device_printf(sc->ale_dev, "could not load DMA'able " "memory for Rx page %d CMB.\n", i); goto fail; } sc->ale_cdata.ale_rx_page[i].cmb_paddr = ctx.ale_busaddr; } /* * Tx descriptors/RXF0/CMB DMA blocks share the same * high address region of 64bit DMA address space. */ if (lowaddr != BUS_SPACE_MAXADDR_32BIT && (error = ale_check_boundary(sc)) != 0) { device_printf(sc->ale_dev, "4GB boundary crossed, " "switching to 32bit DMA addressing mode.\n"); ale_dma_free(sc); /* * Limit max allowable DMA address space to 32bit * and try again. */ lowaddr = BUS_SPACE_MAXADDR_32BIT; goto again; } /* * Create Tx buffer parent tag. * AR81xx allows 64bit DMA addressing of Tx buffers so it * needs separate parent DMA tag as parent DMA address space * could be restricted to be within 32bit address space by * 4GB boundary crossing. */ error = bus_dma_tag_create( NULL, /* parent */ 1, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ BUS_SPACE_MAXSIZE_32BIT, /* maxsize */ 0, /* nsegments */ BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_buffer_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create parent buffer DMA tag.\n"); goto fail; } /* Create DMA tag for Tx buffers. */ error = bus_dma_tag_create( sc->ale_cdata.ale_buffer_tag, /* parent */ 1, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ ALE_TSO_MAXSIZE, /* maxsize */ ALE_MAXTXSEGS, /* nsegments */ ALE_TSO_MAXSEGSIZE, /* maxsegsize */ 0, /* flags */ &sc->ale_cdata.ale_tx_tag); if (error != 0) { device_printf(sc->ale_dev, "could not create Tx DMA tag.\n"); goto fail; } /* Create DMA maps for Tx buffers. */ for (i = 0; i < ALE_TX_RING_CNT; i++) { txd = &sc->ale_cdata.ale_txdesc[i]; txd->tx_m = NULL; txd->tx_dmamap = NULL; error = bus_dmamap_create(sc->ale_cdata.ale_tx_tag, 0, &txd->tx_dmamap); if (error != 0) { device_printf(sc->ale_dev, "could not create Tx dmamap.\n"); goto fail; } } fail: return (error); } static void ale_dma_free(struct ale_softc *sc) { struct ale_txdesc *txd; int i; /* Tx buffers. */ if (sc->ale_cdata.ale_tx_tag != NULL) { for (i = 0; i < ALE_TX_RING_CNT; i++) { txd = &sc->ale_cdata.ale_txdesc[i]; if (txd->tx_dmamap != NULL) { bus_dmamap_destroy(sc->ale_cdata.ale_tx_tag, txd->tx_dmamap); txd->tx_dmamap = NULL; } } bus_dma_tag_destroy(sc->ale_cdata.ale_tx_tag); sc->ale_cdata.ale_tx_tag = NULL; } /* Tx descriptor ring. */ if (sc->ale_cdata.ale_tx_ring_tag != NULL) { if (sc->ale_cdata.ale_tx_ring_map != NULL) bus_dmamap_unload(sc->ale_cdata.ale_tx_ring_tag, sc->ale_cdata.ale_tx_ring_map); if (sc->ale_cdata.ale_tx_ring_map != NULL && sc->ale_cdata.ale_tx_ring != NULL) bus_dmamem_free(sc->ale_cdata.ale_tx_ring_tag, sc->ale_cdata.ale_tx_ring, sc->ale_cdata.ale_tx_ring_map); sc->ale_cdata.ale_tx_ring = NULL; sc->ale_cdata.ale_tx_ring_map = NULL; bus_dma_tag_destroy(sc->ale_cdata.ale_tx_ring_tag); sc->ale_cdata.ale_tx_ring_tag = NULL; } /* Rx page block. */ for (i = 0; i < ALE_RX_PAGES; i++) { if (sc->ale_cdata.ale_rx_page[i].page_tag != NULL) { if (sc->ale_cdata.ale_rx_page[i].page_map != NULL) bus_dmamap_unload( sc->ale_cdata.ale_rx_page[i].page_tag, sc->ale_cdata.ale_rx_page[i].page_map); if (sc->ale_cdata.ale_rx_page[i].page_map != NULL && sc->ale_cdata.ale_rx_page[i].page_addr != NULL) bus_dmamem_free( sc->ale_cdata.ale_rx_page[i].page_tag, sc->ale_cdata.ale_rx_page[i].page_addr, sc->ale_cdata.ale_rx_page[i].page_map); sc->ale_cdata.ale_rx_page[i].page_addr = NULL; sc->ale_cdata.ale_rx_page[i].page_map = NULL; bus_dma_tag_destroy( sc->ale_cdata.ale_rx_page[i].page_tag); sc->ale_cdata.ale_rx_page[i].page_tag = NULL; } } /* Rx CMB. */ for (i = 0; i < ALE_RX_PAGES; i++) { if (sc->ale_cdata.ale_rx_page[i].cmb_tag != NULL) { if (sc->ale_cdata.ale_rx_page[i].cmb_map != NULL) bus_dmamap_unload( sc->ale_cdata.ale_rx_page[i].cmb_tag, sc->ale_cdata.ale_rx_page[i].cmb_map); if (sc->ale_cdata.ale_rx_page[i].cmb_map != NULL && sc->ale_cdata.ale_rx_page[i].cmb_addr != NULL) bus_dmamem_free( sc->ale_cdata.ale_rx_page[i].cmb_tag, sc->ale_cdata.ale_rx_page[i].cmb_addr, sc->ale_cdata.ale_rx_page[i].cmb_map); sc->ale_cdata.ale_rx_page[i].cmb_addr = NULL; sc->ale_cdata.ale_rx_page[i].cmb_map = NULL; bus_dma_tag_destroy( sc->ale_cdata.ale_rx_page[i].cmb_tag); sc->ale_cdata.ale_rx_page[i].cmb_tag = NULL; } } /* Tx CMB. */ if (sc->ale_cdata.ale_tx_cmb_tag != NULL) { if (sc->ale_cdata.ale_tx_cmb_map != NULL) bus_dmamap_unload(sc->ale_cdata.ale_tx_cmb_tag, sc->ale_cdata.ale_tx_cmb_map); if (sc->ale_cdata.ale_tx_cmb_map != NULL && sc->ale_cdata.ale_tx_cmb != NULL) bus_dmamem_free(sc->ale_cdata.ale_tx_cmb_tag, sc->ale_cdata.ale_tx_cmb, sc->ale_cdata.ale_tx_cmb_map); sc->ale_cdata.ale_tx_cmb = NULL; sc->ale_cdata.ale_tx_cmb_map = NULL; bus_dma_tag_destroy(sc->ale_cdata.ale_tx_cmb_tag); sc->ale_cdata.ale_tx_cmb_tag = NULL; } if (sc->ale_cdata.ale_buffer_tag != NULL) { bus_dma_tag_destroy(sc->ale_cdata.ale_buffer_tag); sc->ale_cdata.ale_buffer_tag = NULL; } if (sc->ale_cdata.ale_parent_tag != NULL) { bus_dma_tag_destroy(sc->ale_cdata.ale_parent_tag); sc->ale_cdata.ale_parent_tag = NULL; } } static int ale_shutdown(device_t dev) { return (ale_suspend(dev)); } #ifdef notyet /* * Note, this driver resets the link speed to 10/100Mbps by * restarting auto-negotiation in suspend/shutdown phase but we * don't know whether that auto-negotiation would succeed or not * as driver has no control after powering off/suspend operation. * If the renegotiation fail WOL may not work. Running at 1Gbps * will draw more power than 375mA at 3.3V which is specified in * PCI specification and that would result in complete * shutdowning power to ethernet controller. * * TODO * Save current negotiated media speed/duplex/flow-control to * softc and restore the same link again after resuming. PHY * handling such as power down/resetting to 100Mbps may be better * handled in suspend method in phy driver. */ static void ale_setlinkspeed(struct ale_softc *sc) { struct mii_data *mii; int aneg, i; mii = device_get_softc(sc->ale_miibus); mii_pollstat(mii); aneg = 0; if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) == (IFM_ACTIVE | IFM_AVALID)) { switch IFM_SUBTYPE(mii->mii_media_active) { case IFM_10_T: case IFM_100_TX: return; case IFM_1000_T: aneg++; break; default: break; } } ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, MII_100T2CR, 0); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, MII_ANAR, ANAR_TX_FD | ANAR_TX | ANAR_10_FD | ANAR_10 | ANAR_CSMA); ale_miibus_writereg(sc->ale_dev, sc->ale_phyaddr, MII_BMCR, BMCR_RESET | BMCR_AUTOEN | BMCR_STARTNEG); DELAY(1000); if (aneg != 0) { /* * Poll link state until ale(4) get a 10/100Mbps link. */ for (i = 0; i < MII_ANEGTICKS_GIGE; i++) { mii_pollstat(mii); if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) == (IFM_ACTIVE | IFM_AVALID)) { switch (IFM_SUBTYPE( mii->mii_media_active)) { case IFM_10_T: case IFM_100_TX: ale_mac_config(sc); return; default: break; } } ALE_UNLOCK(sc); pause("alelnk", hz); ALE_LOCK(sc); } if (i == MII_ANEGTICKS_GIGE) device_printf(sc->ale_dev, "establishing a link failed, WOL may not work!"); } /* * No link, force MAC to have 100Mbps, full-duplex link. * This is the last resort and may/may not work. */ mii->mii_media_status = IFM_AVALID | IFM_ACTIVE; mii->mii_media_active = IFM_ETHER | IFM_100_TX | IFM_FDX; ale_mac_config(sc); } static void ale_setwol(struct ale_softc *sc) { struct ifnet *ifp; uint32_t reg, pmcs; uint16_t pmstat; int pmc; ALE_LOCK_ASSERT(sc); if (pci_find_extcap(sc->ale_dev, PCIY_PMG, &pmc) != 0) { /* Disable WOL. */ CSR_WRITE_4(sc, ALE_WOL_CFG, 0); reg = CSR_READ_4(sc, ALE_PCIE_PHYMISC); reg |= PCIE_PHYMISC_FORCE_RCV_DET; CSR_WRITE_4(sc, ALE_PCIE_PHYMISC, reg); /* Force PHY power down. */ CSR_WRITE_2(sc, ALE_GPHY_CTRL, GPHY_CTRL_EXT_RESET | GPHY_CTRL_HIB_EN | GPHY_CTRL_HIB_PULSE | GPHY_CTRL_PHY_PLL_ON | GPHY_CTRL_SEL_ANA_RESET | GPHY_CTRL_PHY_IDDQ | GPHY_CTRL_PCLK_SEL_DIS | GPHY_CTRL_PWDOWN_HW); return; } ifp = sc->ale_ifp; if ((ifp->if_capenable & IFCAP_WOL) != 0) { if ((sc->ale_flags & ALE_FLAG_FASTETHER) == 0) ale_setlinkspeed(sc); } pmcs = 0; if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0) pmcs |= WOL_CFG_MAGIC | WOL_CFG_MAGIC_ENB; CSR_WRITE_4(sc, ALE_WOL_CFG, pmcs); reg = CSR_READ_4(sc, ALE_MAC_CFG); reg &= ~(MAC_CFG_DBG | MAC_CFG_PROMISC | MAC_CFG_ALLMULTI | MAC_CFG_BCAST); if ((ifp->if_capenable & IFCAP_WOL_MCAST) != 0) reg |= MAC_CFG_ALLMULTI | MAC_CFG_BCAST; if ((ifp->if_capenable & IFCAP_WOL) != 0) reg |= MAC_CFG_RX_ENB; CSR_WRITE_4(sc, ALE_MAC_CFG, reg); if ((ifp->if_capenable & IFCAP_WOL) == 0) { /* WOL disabled, PHY power down. */ reg = CSR_READ_4(sc, ALE_PCIE_PHYMISC); reg |= PCIE_PHYMISC_FORCE_RCV_DET; CSR_WRITE_4(sc, ALE_PCIE_PHYMISC, reg); CSR_WRITE_2(sc, ALE_GPHY_CTRL, GPHY_CTRL_EXT_RESET | GPHY_CTRL_HIB_EN | GPHY_CTRL_HIB_PULSE | GPHY_CTRL_SEL_ANA_RESET | GPHY_CTRL_PHY_IDDQ | GPHY_CTRL_PCLK_SEL_DIS | GPHY_CTRL_PWDOWN_HW); } /* Request PME. */ pmstat = pci_read_config(sc->ale_dev, pmc + PCIR_POWER_STATUS, 2); pmstat &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE); if ((ifp->if_capenable & IFCAP_WOL) != 0) pmstat |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE; pci_write_config(sc->ale_dev, pmc + PCIR_POWER_STATUS, pmstat, 2); } #endif /* notyet */ static int ale_suspend(device_t dev) { struct ale_softc *sc = device_get_softc(dev); struct ifnet *ifp = &sc->arpcom.ac_if; lwkt_serialize_enter(ifp->if_serializer); ale_stop(sc); #ifdef notyet ale_setwol(sc); #endif lwkt_serialize_exit(ifp->if_serializer); return (0); } static int ale_resume(device_t dev) { struct ale_softc *sc = device_get_softc(dev); struct ifnet *ifp = &sc->arpcom.ac_if; uint16_t cmd; lwkt_serialize_enter(ifp->if_serializer); /* * Clear INTx emulation disable for hardwares that * is set in resume event. From Linux. */ cmd = pci_read_config(sc->ale_dev, PCIR_COMMAND, 2); if ((cmd & 0x0400) != 0) { cmd &= ~0x0400; pci_write_config(sc->ale_dev, PCIR_COMMAND, cmd, 2); } #ifdef notyet if (pci_find_extcap(sc->ale_dev, PCIY_PMG, &pmc) == 0) { uint16_t pmstat; int pmc; /* Disable PME and clear PME status. */ pmstat = pci_read_config(sc->ale_dev, pmc + PCIR_POWER_STATUS, 2); if ((pmstat & PCIM_PSTAT_PMEENABLE) != 0) { pmstat &= ~PCIM_PSTAT_PMEENABLE; pci_write_config(sc->ale_dev, pmc + PCIR_POWER_STATUS, pmstat, 2); } } #endif /* Reset PHY. */ ale_phy_reset(sc); if ((ifp->if_flags & IFF_UP) != 0) ale_init(sc); lwkt_serialize_exit(ifp->if_serializer); return (0); } static int ale_encap(struct ale_softc *sc, struct mbuf **m_head) { struct ale_txdesc *txd, *txd_last; struct tx_desc *desc; struct mbuf *m; bus_dma_segment_t txsegs[ALE_MAXTXSEGS]; struct ale_dmamap_ctx ctx; bus_dmamap_t map; uint32_t cflags, poff, vtag; int error, i, nsegs, prod; M_ASSERTPKTHDR((*m_head)); m = *m_head; cflags = vtag = 0; poff = 0; prod = sc->ale_cdata.ale_tx_prod; txd = &sc->ale_cdata.ale_txdesc[prod]; txd_last = txd; map = txd->tx_dmamap; ctx.nsegs = ALE_MAXTXSEGS; ctx.segs = txsegs; error = bus_dmamap_load_mbuf(sc->ale_cdata.ale_tx_tag, map, *m_head, ale_dmamap_buf_cb, &ctx, BUS_DMA_NOWAIT); if (error == EFBIG) { m = m_defrag(*m_head, MB_DONTWAIT); if (m == NULL) { m_freem(*m_head); *m_head = NULL; return (ENOMEM); } *m_head = m; ctx.nsegs = ALE_MAXTXSEGS; ctx.segs = txsegs; error = bus_dmamap_load_mbuf(sc->ale_cdata.ale_tx_tag, map, *m_head, ale_dmamap_buf_cb, &ctx, BUS_DMA_NOWAIT); if (error != 0) { m_freem(*m_head); *m_head = NULL; return (error); } } else if (error != 0) { return (error); } nsegs = ctx.nsegs; if (nsegs == 0) { m_freem(*m_head); *m_head = NULL; return (EIO); } /* Check descriptor overrun. */ if (sc->ale_cdata.ale_tx_cnt + nsegs >= ALE_TX_RING_CNT - 2) { bus_dmamap_unload(sc->ale_cdata.ale_tx_tag, map); return (ENOBUFS); } bus_dmamap_sync(sc->ale_cdata.ale_tx_tag, map, BUS_DMASYNC_PREWRITE); m = *m_head; /* Configure Tx checksum offload. */ if ((m->m_pkthdr.csum_flags & ALE_CSUM_FEATURES) != 0) { /* * AR81xx supports Tx custom checksum offload feature * that offloads single 16bit checksum computation. * So you can choose one among IP, TCP and UDP. * Normally driver sets checksum start/insertion * position from the information of TCP/UDP frame as * TCP/UDP checksum takes more time than that of IP. * However it seems that custom checksum offload * requires 4 bytes aligned Tx buffers due to hardware * bug. * AR81xx also supports explicit Tx checksum computation * if it is told that the size of IP header and TCP * header(for UDP, the header size does not matter * because it's fixed length). However with this scheme * TSO does not work so you have to choose one either * TSO or explicit Tx checksum offload. I chosen TSO * plus custom checksum offload with work-around which * will cover most common usage for this consumer * ethernet controller. The work-around takes a lot of * CPU cycles if Tx buffer is not aligned on 4 bytes * boundary, though. */ cflags |= ALE_TD_CXSUM; /* Set checksum start offset. */ cflags |= (poff << ALE_TD_CSUM_PLOADOFFSET_SHIFT); /* Set checksum insertion position of TCP/UDP. */ cflags |= ((poff + m->m_pkthdr.csum_data) << ALE_TD_CSUM_XSUMOFFSET_SHIFT); } /* Configure VLAN hardware tag insertion. */ if ((m->m_flags & M_VLANTAG) != 0) { vtag = ALE_TX_VLAN_TAG(m->m_pkthdr.ether_vlantag); vtag = ((vtag << ALE_TD_VLAN_SHIFT) & ALE_TD_VLAN_MASK); cflags |= ALE_TD_INSERT_VLAN_TAG; } desc = NULL; for (i = 0; i < nsegs; i++) { desc = &sc->ale_cdata.ale_tx_ring[prod]; desc->addr = htole64(txsegs[i].ds_addr); desc->len = htole32(ALE_TX_BYTES(txsegs[i].ds_len) | vtag); desc->flags = htole32(cflags); sc->ale_cdata.ale_tx_cnt++; ALE_DESC_INC(prod, ALE_TX_RING_CNT); } /* Update producer index. */ sc->ale_cdata.ale_tx_prod = prod; /* Finally set EOP on the last descriptor. */ prod = (prod + ALE_TX_RING_CNT - 1) % ALE_TX_RING_CNT; desc = &sc->ale_cdata.ale_tx_ring[prod]; desc->flags |= htole32(ALE_TD_EOP); /* Swap dmamap of the first and the last. */ txd = &sc->ale_cdata.ale_txdesc[prod]; map = txd_last->tx_dmamap; txd_last->tx_dmamap = txd->tx_dmamap; txd->tx_dmamap = map; txd->tx_m = m; /* Sync descriptors. */ bus_dmamap_sync(sc->ale_cdata.ale_tx_ring_tag, sc->ale_cdata.ale_tx_ring_map, BUS_DMASYNC_PREWRITE); return (0); } static void ale_start(struct ifnet *ifp, struct ifaltq_subque *ifsq) { struct ale_softc *sc = ifp->if_softc; struct mbuf *m_head; int enq; ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq); ASSERT_SERIALIZED(ifp->if_serializer); if ((sc->ale_flags & ALE_FLAG_LINK) == 0) { ifq_purge(&ifp->if_snd); return; } if ((ifp->if_flags & IFF_RUNNING) == 0 || ifq_is_oactive(&ifp->if_snd)) return; /* Reclaim transmitted frames. */ if (sc->ale_cdata.ale_tx_cnt >= ALE_TX_DESC_HIWAT) ale_txeof(sc); enq = 0; while (!ifq_is_empty(&ifp->if_snd)) { m_head = ifq_dequeue(&ifp->if_snd, NULL); if (m_head == NULL) break; /* * Pack the data into the transmit ring. If we * don't have room, set the OACTIVE flag and wait * for the NIC to drain the ring. */ if (ale_encap(sc, &m_head)) { if (m_head == NULL) break; ifq_prepend(&ifp->if_snd, m_head); ifq_set_oactive(&ifp->if_snd); break; } enq = 1; /* * If there's a BPF listener, bounce a copy of this frame * to him. */ ETHER_BPF_MTAP(ifp, m_head); } if (enq) { /* Kick. */ CSR_WRITE_4(sc, ALE_MBOX_TPD_PROD_IDX, sc->ale_cdata.ale_tx_prod); /* Set a timeout in case the chip goes out to lunch. */ ifp->if_timer = ALE_TX_TIMEOUT; } } static void ale_watchdog(struct ifnet *ifp) { struct ale_softc *sc = ifp->if_softc; ASSERT_SERIALIZED(ifp->if_serializer); if ((sc->ale_flags & ALE_FLAG_LINK) == 0) { if_printf(ifp, "watchdog timeout (lost link)\n"); IFNET_STAT_INC(ifp, oerrors, 1); ale_init(sc); return; } if_printf(ifp, "watchdog timeout -- resetting\n"); IFNET_STAT_INC(ifp, oerrors, 1); ale_init(sc); if (!ifq_is_empty(&ifp->if_snd)) if_devstart(ifp); } static int ale_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr) { struct ale_softc *sc; struct ifreq *ifr; struct mii_data *mii; int error, mask; ASSERT_SERIALIZED(ifp->if_serializer); sc = ifp->if_softc; ifr = (struct ifreq *)data; error = 0; switch (cmd) { case SIOCSIFMTU: if (ifr->ifr_mtu < ETHERMIN || ifr->ifr_mtu > ALE_JUMBO_MTU || ((sc->ale_flags & ALE_FLAG_JUMBO) == 0 && ifr->ifr_mtu > ETHERMTU)) error = EINVAL; else if (ifp->if_mtu != ifr->ifr_mtu) { ifp->if_mtu = ifr->ifr_mtu; if ((ifp->if_flags & IFF_RUNNING) != 0) ale_init(sc); } break; case SIOCSIFFLAGS: if ((ifp->if_flags & IFF_UP) != 0) { if ((ifp->if_flags & IFF_RUNNING) != 0) { if (((ifp->if_flags ^ sc->ale_if_flags) & (IFF_PROMISC | IFF_ALLMULTI)) != 0) ale_rxfilter(sc); } else { if ((sc->ale_flags & ALE_FLAG_DETACH) == 0) ale_init(sc); } } else { if ((ifp->if_flags & IFF_RUNNING) != 0) ale_stop(sc); } sc->ale_if_flags = ifp->if_flags; break; case SIOCADDMULTI: case SIOCDELMULTI: if ((ifp->if_flags & IFF_RUNNING) != 0) ale_rxfilter(sc); break; case SIOCSIFMEDIA: case SIOCGIFMEDIA: mii = device_get_softc(sc->ale_miibus); error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, cmd); break; case SIOCSIFCAP: mask = ifr->ifr_reqcap ^ ifp->if_capenable; if ((mask & IFCAP_TXCSUM) != 0 && (ifp->if_capabilities & IFCAP_TXCSUM) != 0) { ifp->if_capenable ^= IFCAP_TXCSUM; if ((ifp->if_capenable & IFCAP_TXCSUM) != 0) ifp->if_hwassist |= ALE_CSUM_FEATURES; else ifp->if_hwassist &= ~ALE_CSUM_FEATURES; } if ((mask & IFCAP_RXCSUM) != 0 && (ifp->if_capabilities & IFCAP_RXCSUM) != 0) ifp->if_capenable ^= IFCAP_RXCSUM; if ((mask & IFCAP_VLAN_HWTAGGING) != 0 && (ifp->if_capabilities & IFCAP_VLAN_HWTAGGING) != 0) { ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING; ale_rxvlan(sc); } break; default: error = ether_ioctl(ifp, cmd, data); break; } return (error); } static void ale_mac_config(struct ale_softc *sc) { struct mii_data *mii; uint32_t reg; mii = device_get_softc(sc->ale_miibus); reg = CSR_READ_4(sc, ALE_MAC_CFG); reg &= ~(MAC_CFG_FULL_DUPLEX | MAC_CFG_TX_FC | MAC_CFG_RX_FC | MAC_CFG_SPEED_MASK); /* Reprogram MAC with resolved speed/duplex. */ switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_10_T: case IFM_100_TX: reg |= MAC_CFG_SPEED_10_100; break; case IFM_1000_T: reg |= MAC_CFG_SPEED_1000; break; } if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) { reg |= MAC_CFG_FULL_DUPLEX; #ifdef notyet if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0) reg |= MAC_CFG_TX_FC; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0) reg |= MAC_CFG_RX_FC; #endif } CSR_WRITE_4(sc, ALE_MAC_CFG, reg); } static void ale_stats_clear(struct ale_softc *sc) { struct smb sb; uint32_t *reg; int i; for (reg = &sb.rx_frames, i = 0; reg <= &sb.rx_pkts_filtered; reg++) { CSR_READ_4(sc, ALE_RX_MIB_BASE + i); i += sizeof(uint32_t); } /* Read Tx statistics. */ for (reg = &sb.tx_frames, i = 0; reg <= &sb.tx_mcast_bytes; reg++) { CSR_READ_4(sc, ALE_TX_MIB_BASE + i); i += sizeof(uint32_t); } } static void ale_stats_update(struct ale_softc *sc) { struct ale_hw_stats *stat; struct smb sb, *smb; struct ifnet *ifp; uint32_t *reg; int i; ifp = &sc->arpcom.ac_if; stat = &sc->ale_stats; smb = &sb; /* Read Rx statistics. */ for (reg = &sb.rx_frames, i = 0; reg <= &sb.rx_pkts_filtered; reg++) { *reg = CSR_READ_4(sc, ALE_RX_MIB_BASE + i); i += sizeof(uint32_t); } /* Read Tx statistics. */ for (reg = &sb.tx_frames, i = 0; reg <= &sb.tx_mcast_bytes; reg++) { *reg = CSR_READ_4(sc, ALE_TX_MIB_BASE + i); i += sizeof(uint32_t); } /* Rx stats. */ stat->rx_frames += smb->rx_frames; stat->rx_bcast_frames += smb->rx_bcast_frames; stat->rx_mcast_frames += smb->rx_mcast_frames; stat->rx_pause_frames += smb->rx_pause_frames; stat->rx_control_frames += smb->rx_control_frames; stat->rx_crcerrs += smb->rx_crcerrs; stat->rx_lenerrs += smb->rx_lenerrs; stat->rx_bytes += smb->rx_bytes; stat->rx_runts += smb->rx_runts; stat->rx_fragments += smb->rx_fragments; stat->rx_pkts_64 += smb->rx_pkts_64; stat->rx_pkts_65_127 += smb->rx_pkts_65_127; stat->rx_pkts_128_255 += smb->rx_pkts_128_255; stat->rx_pkts_256_511 += smb->rx_pkts_256_511; stat->rx_pkts_512_1023 += smb->rx_pkts_512_1023; stat->rx_pkts_1024_1518 += smb->rx_pkts_1024_1518; stat->rx_pkts_1519_max += smb->rx_pkts_1519_max; stat->rx_pkts_truncated += smb->rx_pkts_truncated; stat->rx_fifo_oflows += smb->rx_fifo_oflows; stat->rx_rrs_errs += smb->rx_rrs_errs; stat->rx_alignerrs += smb->rx_alignerrs; stat->rx_bcast_bytes += smb->rx_bcast_bytes; stat->rx_mcast_bytes += smb->rx_mcast_bytes; stat->rx_pkts_filtered += smb->rx_pkts_filtered; /* Tx stats. */ stat->tx_frames += smb->tx_frames; stat->tx_bcast_frames += smb->tx_bcast_frames; stat->tx_mcast_frames += smb->tx_mcast_frames; stat->tx_pause_frames += smb->tx_pause_frames; stat->tx_excess_defer += smb->tx_excess_defer; stat->tx_control_frames += smb->tx_control_frames; stat->tx_deferred += smb->tx_deferred; stat->tx_bytes += smb->tx_bytes; stat->tx_pkts_64 += smb->tx_pkts_64; stat->tx_pkts_65_127 += smb->tx_pkts_65_127; stat->tx_pkts_128_255 += smb->tx_pkts_128_255; stat->tx_pkts_256_511 += smb->tx_pkts_256_511; stat->tx_pkts_512_1023 += smb->tx_pkts_512_1023; stat->tx_pkts_1024_1518 += smb->tx_pkts_1024_1518; stat->tx_pkts_1519_max += smb->tx_pkts_1519_max; stat->tx_single_colls += smb->tx_single_colls; stat->tx_multi_colls += smb->tx_multi_colls; stat->tx_late_colls += smb->tx_late_colls; stat->tx_excess_colls += smb->tx_excess_colls; stat->tx_abort += smb->tx_abort; stat->tx_underrun += smb->tx_underrun; stat->tx_desc_underrun += smb->tx_desc_underrun; stat->tx_lenerrs += smb->tx_lenerrs; stat->tx_pkts_truncated += smb->tx_pkts_truncated; stat->tx_bcast_bytes += smb->tx_bcast_bytes; stat->tx_mcast_bytes += smb->tx_mcast_bytes; /* Update counters in ifnet. */ IFNET_STAT_INC(ifp, opackets, smb->tx_frames); IFNET_STAT_INC(ifp, collisions, smb->tx_single_colls + smb->tx_multi_colls * 2 + smb->tx_late_colls + smb->tx_abort * HDPX_CFG_RETRY_DEFAULT); /* * XXX * tx_pkts_truncated counter looks suspicious. It constantly * increments with no sign of Tx errors. This may indicate * the counter name is not correct one so I've removed the * counter in output errors. */ IFNET_STAT_INC(ifp, oerrors, smb->tx_abort + smb->tx_late_colls + smb->tx_underrun); IFNET_STAT_INC(ifp, ipackets, smb->rx_frames); IFNET_STAT_INC(ifp, ierrors, smb->rx_crcerrs + smb->rx_lenerrs + smb->rx_runts + smb->rx_pkts_truncated + smb->rx_fifo_oflows + smb->rx_rrs_errs + smb->rx_alignerrs); } static void ale_intr(void *xsc) { struct ale_softc *sc = xsc; struct ifnet *ifp = &sc->arpcom.ac_if; uint32_t status; ASSERT_SERIALIZED(ifp->if_serializer); status = CSR_READ_4(sc, ALE_INTR_STATUS); if ((status & ALE_INTRS) == 0) return; /* Acknowledge and disable interrupts. */ CSR_WRITE_4(sc, ALE_INTR_STATUS, status | INTR_DIS_INT); if ((ifp->if_flags & IFF_RUNNING) != 0) { int error; error = ale_rxeof(sc); if (error) { sc->ale_stats.reset_brk_seq++; ale_init(sc); return; } if ((status & (INTR_DMA_RD_TO_RST | INTR_DMA_WR_TO_RST)) != 0) { if ((status & INTR_DMA_RD_TO_RST) != 0) device_printf(sc->ale_dev, "DMA read error! -- resetting\n"); if ((status & INTR_DMA_WR_TO_RST) != 0) device_printf(sc->ale_dev, "DMA write error! -- resetting\n"); ale_init(sc); return; } ale_txeof(sc); if (!ifq_is_empty(&ifp->if_snd)) if_devstart(ifp); } /* Re-enable interrupts. */ CSR_WRITE_4(sc, ALE_INTR_STATUS, 0x7FFFFFFF); } static void ale_txeof(struct ale_softc *sc) { struct ifnet *ifp = &sc->arpcom.ac_if; struct ale_txdesc *txd; uint32_t cons, prod; int prog; if (sc->ale_cdata.ale_tx_cnt == 0) return; bus_dmamap_sync(sc->ale_cdata.ale_tx_ring_tag, sc->ale_cdata.ale_tx_ring_map, BUS_DMASYNC_POSTREAD); if ((sc->ale_flags & ALE_FLAG_TXCMB_BUG) == 0) { bus_dmamap_sync(sc->ale_cdata.ale_tx_cmb_tag, sc->ale_cdata.ale_tx_cmb_map, BUS_DMASYNC_POSTREAD); prod = *sc->ale_cdata.ale_tx_cmb & TPD_CNT_MASK; } else prod = CSR_READ_2(sc, ALE_TPD_CONS_IDX); cons = sc->ale_cdata.ale_tx_cons; /* * Go through our Tx list and free mbufs for those * frames which have been transmitted. */ for (prog = 0; cons != prod; prog++, ALE_DESC_INC(cons, ALE_TX_RING_CNT)) { if (sc->ale_cdata.ale_tx_cnt <= 0) break; prog++; ifq_clr_oactive(&ifp->if_snd); sc->ale_cdata.ale_tx_cnt--; txd = &sc->ale_cdata.ale_txdesc[cons]; if (txd->tx_m != NULL) { /* Reclaim transmitted mbufs. */ bus_dmamap_unload(sc->ale_cdata.ale_tx_tag, txd->tx_dmamap); m_freem(txd->tx_m); txd->tx_m = NULL; } } if (prog > 0) { sc->ale_cdata.ale_tx_cons = cons; /* * Unarm watchdog timer only when there is no pending * Tx descriptors in queue. */ if (sc->ale_cdata.ale_tx_cnt == 0) ifp->if_timer = 0; } } static void ale_rx_update_page(struct ale_softc *sc, struct ale_rx_page **page, uint32_t length, uint32_t *prod) { struct ale_rx_page *rx_page; rx_page = *page; /* Update consumer position. */ rx_page->cons += roundup(length + sizeof(struct rx_rs), ALE_RX_PAGE_ALIGN); if (rx_page->cons >= ALE_RX_PAGE_SZ) { /* * End of Rx page reached, let hardware reuse * this page. */ rx_page->cons = 0; *rx_page->cmb_addr = 0; bus_dmamap_sync(rx_page->cmb_tag, rx_page->cmb_map, BUS_DMASYNC_PREWRITE); CSR_WRITE_1(sc, ALE_RXF0_PAGE0 + sc->ale_cdata.ale_rx_curp, RXF_VALID); /* Switch to alternate Rx page. */ sc->ale_cdata.ale_rx_curp ^= 1; rx_page = *page = &sc->ale_cdata.ale_rx_page[sc->ale_cdata.ale_rx_curp]; /* Page flipped, sync CMB and Rx page. */ bus_dmamap_sync(rx_page->page_tag, rx_page->page_map, BUS_DMASYNC_POSTREAD); bus_dmamap_sync(rx_page->cmb_tag, rx_page->cmb_map, BUS_DMASYNC_POSTREAD); /* Sync completed, cache updated producer index. */ *prod = *rx_page->cmb_addr; } } /* * It seems that AR81xx controller can compute partial checksum. * The partial checksum value can be used to accelerate checksum * computation for fragmented TCP/UDP packets. Upper network stack * already takes advantage of the partial checksum value in IP * reassembly stage. But I'm not sure the correctness of the * partial hardware checksum assistance due to lack of data sheet. * In addition, the Rx feature of controller that requires copying * for every frames effectively nullifies one of most nice offload * capability of controller. */ static void ale_rxcsum(struct ale_softc *sc, struct mbuf *m, uint32_t status) { struct ifnet *ifp = &sc->arpcom.ac_if; struct ip *ip; char *p; m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED; if ((status & ALE_RD_IPCSUM_NOK) == 0) m->m_pkthdr.csum_flags |= CSUM_IP_VALID; if ((sc->ale_flags & ALE_FLAG_RXCSUM_BUG) == 0) { if (((status & ALE_RD_IPV4_FRAG) == 0) && ((status & (ALE_RD_TCP | ALE_RD_UDP)) != 0) && ((status & ALE_RD_TCP_UDPCSUM_NOK) == 0)) { m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR; m->m_pkthdr.csum_data = 0xffff; } } else { if ((status & (ALE_RD_TCP | ALE_RD_UDP)) != 0 && (status & ALE_RD_TCP_UDPCSUM_NOK) == 0) { p = mtod(m, char *); p += ETHER_HDR_LEN; if ((status & ALE_RD_802_3) != 0) p += LLC_SNAPFRAMELEN; if ((ifp->if_capenable & IFCAP_VLAN_HWTAGGING) == 0 && (status & ALE_RD_VLAN) != 0) p += EVL_ENCAPLEN; ip = (struct ip *)p; if (ip->ip_off != 0 && (status & ALE_RD_IPV4_DF) == 0) return; m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR; m->m_pkthdr.csum_data = 0xffff; } } /* * Don't mark bad checksum for TCP/UDP frames * as fragmented frames may always have set * bad checksummed bit of frame status. */ } /* Process received frames. */ static int ale_rxeof(struct ale_softc *sc) { struct ifnet *ifp = &sc->arpcom.ac_if; struct ale_rx_page *rx_page; struct rx_rs *rs; struct mbuf *m; uint32_t length, prod, seqno, status, vtags; int prog; rx_page = &sc->ale_cdata.ale_rx_page[sc->ale_cdata.ale_rx_curp]; bus_dmamap_sync(rx_page->cmb_tag, rx_page->cmb_map, BUS_DMASYNC_POSTREAD); bus_dmamap_sync(rx_page->page_tag, rx_page->page_map, BUS_DMASYNC_POSTREAD); /* * Don't directly access producer index as hardware may * update it while Rx handler is in progress. It would * be even better if there is a way to let hardware * know how far driver processed its received frames. * Alternatively, hardware could provide a way to disable * CMB updates until driver acknowledges the end of CMB * access. */ prod = *rx_page->cmb_addr; for (prog = 0; ; prog++) { if (rx_page->cons >= prod) break; rs = (struct rx_rs *)(rx_page->page_addr + rx_page->cons); seqno = ALE_RX_SEQNO(le32toh(rs->seqno)); if (sc->ale_cdata.ale_rx_seqno != seqno) { /* * Normally I believe this should not happen unless * severe driver bug or corrupted memory. However * it seems to happen under certain conditions which * is triggered by abrupt Rx events such as initiation * of bulk transfer of remote host. It's not easy to * reproduce this and I doubt it could be related * with FIFO overflow of hardware or activity of Tx * CMB updates. I also remember similar behaviour * seen on RealTek 8139 which uses resembling Rx * scheme. */ if (bootverbose) device_printf(sc->ale_dev, "garbled seq: %u, expected: %u -- " "resetting!\n", seqno, sc->ale_cdata.ale_rx_seqno); return (EIO); } /* Frame received. */ sc->ale_cdata.ale_rx_seqno++; length = ALE_RX_BYTES(le32toh(rs->length)); status = le32toh(rs->flags); if ((status & ALE_RD_ERROR) != 0) { /* * We want to pass the following frames to upper * layer regardless of error status of Rx return * status. * * o IP/TCP/UDP checksum is bad. * o frame length and protocol specific length * does not match. */ if ((status & (ALE_RD_CRC | ALE_RD_CODE | ALE_RD_DRIBBLE | ALE_RD_RUNT | ALE_RD_OFLOW | ALE_RD_TRUNC)) != 0) { ale_rx_update_page(sc, &rx_page, length, &prod); continue; } } /* * m_devget(9) is major bottle-neck of ale(4)(It comes * from hardware limitation). For jumbo frames we could * get a slightly better performance if driver use * m_getjcl(9) with proper buffer size argument. However * that would make code more complicated and I don't * think users would expect good Rx performance numbers * on these low-end consumer ethernet controller. */ m = m_devget((char *)(rs + 1), length - ETHER_CRC_LEN, ETHER_ALIGN, ifp, NULL); if (m == NULL) { IFNET_STAT_INC(ifp, iqdrops, 1); ale_rx_update_page(sc, &rx_page, length, &prod); continue; } if ((ifp->if_capenable & IFCAP_RXCSUM) != 0 && (status & ALE_RD_IPV4) != 0) ale_rxcsum(sc, m, status); if ((ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0 && (status & ALE_RD_VLAN) != 0) { vtags = ALE_RX_VLAN(le32toh(rs->vtags)); m->m_pkthdr.ether_vlantag = ALE_RX_VLAN_TAG(vtags); m->m_flags |= M_VLANTAG; } /* Pass it to upper layer. */ ifp->if_input(ifp, m); ale_rx_update_page(sc, &rx_page, length, &prod); } return 0; } static void ale_tick(void *xsc) { struct ale_softc *sc = xsc; struct ifnet *ifp = &sc->arpcom.ac_if; struct mii_data *mii; lwkt_serialize_enter(ifp->if_serializer); mii = device_get_softc(sc->ale_miibus); mii_tick(mii); ale_stats_update(sc); callout_reset(&sc->ale_tick_ch, hz, ale_tick, sc); lwkt_serialize_exit(ifp->if_serializer); } static void ale_reset(struct ale_softc *sc) { uint32_t reg; int i; /* Initialize PCIe module. From Linux. */ CSR_WRITE_4(sc, 0x1008, CSR_READ_4(sc, 0x1008) | 0x8000); CSR_WRITE_4(sc, ALE_MASTER_CFG, MASTER_RESET); for (i = ALE_RESET_TIMEOUT; i > 0; i--) { DELAY(10); if ((CSR_READ_4(sc, ALE_MASTER_CFG) & MASTER_RESET) == 0) break; } if (i == 0) device_printf(sc->ale_dev, "master reset timeout!\n"); for (i = ALE_RESET_TIMEOUT; i > 0; i--) { if ((reg = CSR_READ_4(sc, ALE_IDLE_STATUS)) == 0) break; DELAY(10); } if (i == 0) device_printf(sc->ale_dev, "reset timeout(0x%08x)!\n", reg); } static void ale_init(void *xsc) { struct ale_softc *sc = xsc; struct ifnet *ifp = &sc->arpcom.ac_if; struct mii_data *mii; uint8_t eaddr[ETHER_ADDR_LEN]; bus_addr_t paddr; uint32_t reg, rxf_hi, rxf_lo; ASSERT_SERIALIZED(ifp->if_serializer); mii = device_get_softc(sc->ale_miibus); /* * Cancel any pending I/O. */ ale_stop(sc); /* * Reset the chip to a known state. */ ale_reset(sc); /* Initialize Tx descriptors, DMA memory blocks. */ ale_init_rx_pages(sc); ale_init_tx_ring(sc); /* Reprogram the station address. */ bcopy(IF_LLADDR(ifp), eaddr, ETHER_ADDR_LEN); CSR_WRITE_4(sc, ALE_PAR0, eaddr[2] << 24 | eaddr[3] << 16 | eaddr[4] << 8 | eaddr[5]); CSR_WRITE_4(sc, ALE_PAR1, eaddr[0] << 8 | eaddr[1]); /* * Clear WOL status and disable all WOL feature as WOL * would interfere Rx operation under normal environments. */ CSR_READ_4(sc, ALE_WOL_CFG); CSR_WRITE_4(sc, ALE_WOL_CFG, 0); /* * Set Tx descriptor/RXF0/CMB base addresses. They share * the same high address part of DMAable region. */ paddr = sc->ale_cdata.ale_tx_ring_paddr; CSR_WRITE_4(sc, ALE_TPD_ADDR_HI, ALE_ADDR_HI(paddr)); CSR_WRITE_4(sc, ALE_TPD_ADDR_LO, ALE_ADDR_LO(paddr)); CSR_WRITE_4(sc, ALE_TPD_CNT, (ALE_TX_RING_CNT << TPD_CNT_SHIFT) & TPD_CNT_MASK); /* Set Rx page base address, note we use single queue. */ paddr = sc->ale_cdata.ale_rx_page[0].page_paddr; CSR_WRITE_4(sc, ALE_RXF0_PAGE0_ADDR_LO, ALE_ADDR_LO(paddr)); paddr = sc->ale_cdata.ale_rx_page[1].page_paddr; CSR_WRITE_4(sc, ALE_RXF0_PAGE1_ADDR_LO, ALE_ADDR_LO(paddr)); /* Set Tx/Rx CMB addresses. */ paddr = sc->ale_cdata.ale_tx_cmb_paddr; CSR_WRITE_4(sc, ALE_TX_CMB_ADDR_LO, ALE_ADDR_LO(paddr)); paddr = sc->ale_cdata.ale_rx_page[0].cmb_paddr; CSR_WRITE_4(sc, ALE_RXF0_CMB0_ADDR_LO, ALE_ADDR_LO(paddr)); paddr = sc->ale_cdata.ale_rx_page[1].cmb_paddr; CSR_WRITE_4(sc, ALE_RXF0_CMB1_ADDR_LO, ALE_ADDR_LO(paddr)); /* Mark RXF0 is valid. */ CSR_WRITE_1(sc, ALE_RXF0_PAGE0, RXF_VALID); CSR_WRITE_1(sc, ALE_RXF0_PAGE1, RXF_VALID); /* * No need to initialize RFX1/RXF2/RXF3. We don't use * multi-queue yet. */ /* Set Rx page size, excluding guard frame size. */ CSR_WRITE_4(sc, ALE_RXF_PAGE_SIZE, ALE_RX_PAGE_SZ); /* Tell hardware that we're ready to load DMA blocks. */ CSR_WRITE_4(sc, ALE_DMA_BLOCK, DMA_BLOCK_LOAD); /* Set Rx/Tx interrupt trigger threshold. */ CSR_WRITE_4(sc, ALE_INT_TRIG_THRESH, (1 << INT_TRIG_RX_THRESH_SHIFT) | (4 << INT_TRIG_TX_THRESH_SHIFT)); /* * XXX * Set interrupt trigger timer, its purpose and relation * with interrupt moderation mechanism is not clear yet. */ CSR_WRITE_4(sc, ALE_INT_TRIG_TIMER, ((ALE_USECS(10) << INT_TRIG_RX_TIMER_SHIFT) | (ALE_USECS(1000) << INT_TRIG_TX_TIMER_SHIFT))); /* Configure interrupt moderation timer. */ reg = ALE_USECS(sc->ale_int_rx_mod) << IM_TIMER_RX_SHIFT; reg |= ALE_USECS(sc->ale_int_tx_mod) << IM_TIMER_TX_SHIFT; CSR_WRITE_4(sc, ALE_IM_TIMER, reg); reg = CSR_READ_4(sc, ALE_MASTER_CFG); reg &= ~(MASTER_CHIP_REV_MASK | MASTER_CHIP_ID_MASK); reg &= ~(MASTER_IM_RX_TIMER_ENB | MASTER_IM_TX_TIMER_ENB); if (ALE_USECS(sc->ale_int_rx_mod) != 0) reg |= MASTER_IM_RX_TIMER_ENB; if (ALE_USECS(sc->ale_int_tx_mod) != 0) reg |= MASTER_IM_TX_TIMER_ENB; CSR_WRITE_4(sc, ALE_MASTER_CFG, reg); CSR_WRITE_2(sc, ALE_INTR_CLR_TIMER, ALE_USECS(1000)); /* Set Maximum frame size of controller. */ if (ifp->if_mtu < ETHERMTU) sc->ale_max_frame_size = ETHERMTU; else sc->ale_max_frame_size = ifp->if_mtu; sc->ale_max_frame_size += ETHER_HDR_LEN + EVL_ENCAPLEN + ETHER_CRC_LEN; CSR_WRITE_4(sc, ALE_FRAME_SIZE, sc->ale_max_frame_size); /* Configure IPG/IFG parameters. */ CSR_WRITE_4(sc, ALE_IPG_IFG_CFG, ((IPG_IFG_IPGT_DEFAULT << IPG_IFG_IPGT_SHIFT) & IPG_IFG_IPGT_MASK) | ((IPG_IFG_MIFG_DEFAULT << IPG_IFG_MIFG_SHIFT) & IPG_IFG_MIFG_MASK) | ((IPG_IFG_IPG1_DEFAULT << IPG_IFG_IPG1_SHIFT) & IPG_IFG_IPG1_MASK) | ((IPG_IFG_IPG2_DEFAULT << IPG_IFG_IPG2_SHIFT) & IPG_IFG_IPG2_MASK)); /* Set parameters for half-duplex media. */ CSR_WRITE_4(sc, ALE_HDPX_CFG, ((HDPX_CFG_LCOL_DEFAULT << HDPX_CFG_LCOL_SHIFT) & HDPX_CFG_LCOL_MASK) | ((HDPX_CFG_RETRY_DEFAULT << HDPX_CFG_RETRY_SHIFT) & HDPX_CFG_RETRY_MASK) | HDPX_CFG_EXC_DEF_EN | ((HDPX_CFG_ABEBT_DEFAULT << HDPX_CFG_ABEBT_SHIFT) & HDPX_CFG_ABEBT_MASK) | ((HDPX_CFG_JAMIPG_DEFAULT << HDPX_CFG_JAMIPG_SHIFT) & HDPX_CFG_JAMIPG_MASK)); /* Configure Tx jumbo frame parameters. */ if ((sc->ale_flags & ALE_FLAG_JUMBO) != 0) { if (ifp->if_mtu < ETHERMTU) reg = sc->ale_max_frame_size; else if (ifp->if_mtu < 6 * 1024) reg = (sc->ale_max_frame_size * 2) / 3; else reg = sc->ale_max_frame_size / 2; CSR_WRITE_4(sc, ALE_TX_JUMBO_THRESH, roundup(reg, TX_JUMBO_THRESH_UNIT) >> TX_JUMBO_THRESH_UNIT_SHIFT); } /* Configure TxQ. */ reg = (128 << (sc->ale_dma_rd_burst >> DMA_CFG_RD_BURST_SHIFT)) << TXQ_CFG_TX_FIFO_BURST_SHIFT; reg |= (TXQ_CFG_TPD_BURST_DEFAULT << TXQ_CFG_TPD_BURST_SHIFT) & TXQ_CFG_TPD_BURST_MASK; CSR_WRITE_4(sc, ALE_TXQ_CFG, reg | TXQ_CFG_ENHANCED_MODE | TXQ_CFG_ENB); /* Configure Rx jumbo frame & flow control parameters. */ if ((sc->ale_flags & ALE_FLAG_JUMBO) != 0) { reg = roundup(sc->ale_max_frame_size, RX_JUMBO_THRESH_UNIT); CSR_WRITE_4(sc, ALE_RX_JUMBO_THRESH, (((reg >> RX_JUMBO_THRESH_UNIT_SHIFT) << RX_JUMBO_THRESH_MASK_SHIFT) & RX_JUMBO_THRESH_MASK) | ((RX_JUMBO_LKAH_DEFAULT << RX_JUMBO_LKAH_SHIFT) & RX_JUMBO_LKAH_MASK)); reg = CSR_READ_4(sc, ALE_SRAM_RX_FIFO_LEN); rxf_hi = (reg * 7) / 10; rxf_lo = (reg * 3)/ 10; CSR_WRITE_4(sc, ALE_RX_FIFO_PAUSE_THRESH, ((rxf_lo << RX_FIFO_PAUSE_THRESH_LO_SHIFT) & RX_FIFO_PAUSE_THRESH_LO_MASK) | ((rxf_hi << RX_FIFO_PAUSE_THRESH_HI_SHIFT) & RX_FIFO_PAUSE_THRESH_HI_MASK)); } /* Disable RSS. */ CSR_WRITE_4(sc, ALE_RSS_IDT_TABLE0, 0); CSR_WRITE_4(sc, ALE_RSS_CPU, 0); /* Configure RxQ. */ CSR_WRITE_4(sc, ALE_RXQ_CFG, RXQ_CFG_ALIGN_32 | RXQ_CFG_CUT_THROUGH_ENB | RXQ_CFG_ENB); /* Configure DMA parameters. */ reg = 0; if ((sc->ale_flags & ALE_FLAG_TXCMB_BUG) == 0) reg |= DMA_CFG_TXCMB_ENB; CSR_WRITE_4(sc, ALE_DMA_CFG, DMA_CFG_OUT_ORDER | DMA_CFG_RD_REQ_PRI | DMA_CFG_RCB_64 | sc->ale_dma_rd_burst | reg | sc->ale_dma_wr_burst | DMA_CFG_RXCMB_ENB | ((DMA_CFG_RD_DELAY_CNT_DEFAULT << DMA_CFG_RD_DELAY_CNT_SHIFT) & DMA_CFG_RD_DELAY_CNT_MASK) | ((DMA_CFG_WR_DELAY_CNT_DEFAULT << DMA_CFG_WR_DELAY_CNT_SHIFT) & DMA_CFG_WR_DELAY_CNT_MASK)); /* * Hardware can be configured to issue SMB interrupt based * on programmed interval. Since there is a callout that is * invoked for every hz in driver we use that instead of * relying on periodic SMB interrupt. */ CSR_WRITE_4(sc, ALE_SMB_STAT_TIMER, ALE_USECS(0)); /* Clear MAC statistics. */ ale_stats_clear(sc); /* * Configure Tx/Rx MACs. * - Auto-padding for short frames. * - Enable CRC generation. * Actual reconfiguration of MAC for resolved speed/duplex * is followed after detection of link establishment. * AR81xx always does checksum computation regardless of * MAC_CFG_RXCSUM_ENB bit. In fact, setting the bit will * cause Rx handling issue for fragmented IP datagrams due * to silicon bug. */ reg = MAC_CFG_TX_CRC_ENB | MAC_CFG_TX_AUTO_PAD | MAC_CFG_FULL_DUPLEX | ((MAC_CFG_PREAMBLE_DEFAULT << MAC_CFG_PREAMBLE_SHIFT) & MAC_CFG_PREAMBLE_MASK); if ((sc->ale_flags & ALE_FLAG_FASTETHER) != 0) reg |= MAC_CFG_SPEED_10_100; else reg |= MAC_CFG_SPEED_1000; CSR_WRITE_4(sc, ALE_MAC_CFG, reg); /* Set up the receive filter. */ ale_rxfilter(sc); ale_rxvlan(sc); /* Acknowledge all pending interrupts and clear it. */ CSR_WRITE_4(sc, ALE_INTR_MASK, ALE_INTRS); CSR_WRITE_4(sc, ALE_INTR_STATUS, 0xFFFFFFFF); CSR_WRITE_4(sc, ALE_INTR_STATUS, 0); sc->ale_flags &= ~ALE_FLAG_LINK; /* Switch to the current media. */ mii_mediachg(mii); callout_reset(&sc->ale_tick_ch, hz, ale_tick, sc); ifp->if_flags |= IFF_RUNNING; ifq_clr_oactive(&ifp->if_snd); } static void ale_stop(struct ale_softc *sc) { struct ifnet *ifp = &sc->arpcom.ac_if; struct ale_txdesc *txd; uint32_t reg; int i; ASSERT_SERIALIZED(ifp->if_serializer); /* * Mark the interface down and cancel the watchdog timer. */ ifp->if_flags &= ~IFF_RUNNING; ifq_clr_oactive(&ifp->if_snd); ifp->if_timer = 0; callout_stop(&sc->ale_tick_ch); sc->ale_flags &= ~ALE_FLAG_LINK; ale_stats_update(sc); /* Disable interrupts. */ CSR_WRITE_4(sc, ALE_INTR_MASK, 0); CSR_WRITE_4(sc, ALE_INTR_STATUS, 0xFFFFFFFF); /* Disable queue processing and DMA. */ reg = CSR_READ_4(sc, ALE_TXQ_CFG); reg &= ~TXQ_CFG_ENB; CSR_WRITE_4(sc, ALE_TXQ_CFG, reg); reg = CSR_READ_4(sc, ALE_RXQ_CFG); reg &= ~RXQ_CFG_ENB; CSR_WRITE_4(sc, ALE_RXQ_CFG, reg); reg = CSR_READ_4(sc, ALE_DMA_CFG); reg &= ~(DMA_CFG_TXCMB_ENB | DMA_CFG_RXCMB_ENB); CSR_WRITE_4(sc, ALE_DMA_CFG, reg); DELAY(1000); /* Stop Rx/Tx MACs. */ ale_stop_mac(sc); /* Disable interrupts again? XXX */ CSR_WRITE_4(sc, ALE_INTR_STATUS, 0xFFFFFFFF); /* * Free TX mbufs still in the queues. */ for (i = 0; i < ALE_TX_RING_CNT; i++) { txd = &sc->ale_cdata.ale_txdesc[i]; if (txd->tx_m != NULL) { bus_dmamap_unload(sc->ale_cdata.ale_tx_tag, txd->tx_dmamap); m_freem(txd->tx_m); txd->tx_m = NULL; } } } static void ale_stop_mac(struct ale_softc *sc) { uint32_t reg; int i; reg = CSR_READ_4(sc, ALE_MAC_CFG); if ((reg & (MAC_CFG_TX_ENB | MAC_CFG_RX_ENB)) != 0) { reg &= ~MAC_CFG_TX_ENB | MAC_CFG_RX_ENB; CSR_WRITE_4(sc, ALE_MAC_CFG, reg); } for (i = ALE_TIMEOUT; i > 0; i--) { reg = CSR_READ_4(sc, ALE_IDLE_STATUS); if (reg == 0) break; DELAY(10); } if (i == 0) device_printf(sc->ale_dev, "could not disable Tx/Rx MAC(0x%08x)!\n", reg); } static void ale_init_tx_ring(struct ale_softc *sc) { struct ale_txdesc *txd; int i; sc->ale_cdata.ale_tx_prod = 0; sc->ale_cdata.ale_tx_cons = 0; sc->ale_cdata.ale_tx_cnt = 0; bzero(sc->ale_cdata.ale_tx_ring, ALE_TX_RING_SZ); bzero(sc->ale_cdata.ale_tx_cmb, ALE_TX_CMB_SZ); for (i = 0; i < ALE_TX_RING_CNT; i++) { txd = &sc->ale_cdata.ale_txdesc[i]; txd->tx_m = NULL; } *sc->ale_cdata.ale_tx_cmb = 0; bus_dmamap_sync(sc->ale_cdata.ale_tx_cmb_tag, sc->ale_cdata.ale_tx_cmb_map, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(sc->ale_cdata.ale_tx_ring_tag, sc->ale_cdata.ale_tx_ring_map, BUS_DMASYNC_PREWRITE); } static void ale_init_rx_pages(struct ale_softc *sc) { struct ale_rx_page *rx_page; int i; sc->ale_cdata.ale_rx_seqno = 0; sc->ale_cdata.ale_rx_curp = 0; for (i = 0; i < ALE_RX_PAGES; i++) { rx_page = &sc->ale_cdata.ale_rx_page[i]; bzero(rx_page->page_addr, sc->ale_pagesize); bzero(rx_page->cmb_addr, ALE_RX_CMB_SZ); rx_page->cons = 0; *rx_page->cmb_addr = 0; bus_dmamap_sync(rx_page->page_tag, rx_page->page_map, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(rx_page->cmb_tag, rx_page->cmb_map, BUS_DMASYNC_PREWRITE); } } static void ale_rxvlan(struct ale_softc *sc) { struct ifnet *ifp; uint32_t reg; ifp = &sc->arpcom.ac_if; reg = CSR_READ_4(sc, ALE_MAC_CFG); reg &= ~MAC_CFG_VLAN_TAG_STRIP; if ((ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0) reg |= MAC_CFG_VLAN_TAG_STRIP; CSR_WRITE_4(sc, ALE_MAC_CFG, reg); } static void ale_rxfilter(struct ale_softc *sc) { struct ifnet *ifp; struct ifmultiaddr *ifma; uint32_t crc; uint32_t mchash[2]; uint32_t rxcfg; ifp = &sc->arpcom.ac_if; rxcfg = CSR_READ_4(sc, ALE_MAC_CFG); rxcfg &= ~(MAC_CFG_ALLMULTI | MAC_CFG_BCAST | MAC_CFG_PROMISC); if ((ifp->if_flags & IFF_BROADCAST) != 0) rxcfg |= MAC_CFG_BCAST; if ((ifp->if_flags & (IFF_PROMISC | IFF_ALLMULTI)) != 0) { if ((ifp->if_flags & IFF_PROMISC) != 0) rxcfg |= MAC_CFG_PROMISC; if ((ifp->if_flags & IFF_ALLMULTI) != 0) rxcfg |= MAC_CFG_ALLMULTI; CSR_WRITE_4(sc, ALE_MAR0, 0xFFFFFFFF); CSR_WRITE_4(sc, ALE_MAR1, 0xFFFFFFFF); CSR_WRITE_4(sc, ALE_MAC_CFG, rxcfg); return; } /* Program new filter. */ bzero(mchash, sizeof(mchash)); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; crc = ether_crc32_le(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN); mchash[crc >> 31] |= 1 << ((crc >> 26) & 0x1f); } CSR_WRITE_4(sc, ALE_MAR0, mchash[0]); CSR_WRITE_4(sc, ALE_MAR1, mchash[1]); CSR_WRITE_4(sc, ALE_MAC_CFG, rxcfg); } static int sysctl_hw_ale_int_mod(SYSCTL_HANDLER_ARGS) { return (sysctl_int_range(oidp, arg1, arg2, req, ALE_IM_TIMER_MIN, ALE_IM_TIMER_MAX)); } static void ale_dmamap_buf_cb(void *xctx, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsz __unused, int error) { struct ale_dmamap_ctx *ctx = xctx; int i; if (error) return; if (nsegs > ctx->nsegs) { ctx->nsegs = 0; return; } ctx->nsegs = nsegs; for (i = 0; i < nsegs; ++i) ctx->segs[i] = segs[i]; }
/////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) Regents of the University of Michigan - All Rights Reserved // // Unauthorized copying of this file, via any medium is strictly prohibited // // // // Author: <NAME> <<EMAIL>> // // // /////////////////////////////////////////////////////////////////////////////////////////////// #include "CommonPara.h" #include "BasicFunc.h" #include "ParsePDB.h" #include "SegCluster.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SegCluster::SegCluster() { nosample=0; fv=NULL; ck=0; cfv=NULL; rmin=0; rmax=1000000; } SegCluster::~SegCluster() { int i; if(fv) { delete[]fv; fv=NULL; } if(cfv) { for(i=0;i<ck;i++) { delete[]cfv[i].ind2vec; } delete[]cfv; cfv=NULL; } } double SegCluster::calckmeanmodels( int num, int nk, double **inmat, modelinfo *minf, bool **flagmodels ) { int i,j; double totvar; int numiter=0; int totchange=0; int totcenterchange=0; int *indcenter=new int[nk]; int deli=num/nk; int stai=0; if(deli==0) { printf("Not enough samples %d %d\n",num,nk); return 0; } for(i=0;i<nk;i++) { for(j=0;j<num;j++) { flagmodels[i][j]=false; } minf[i].ind=stai; stai+=deli; } calckmeanclass(num,nk,inmat,minf,flagmodels); for(i=0;i<nk;i++) { indcenter[i]=calckmeancenter(num,inmat,flagmodels[i]); minf[i].ind=indcenter[i]; } calckmeanvar(num,nk,inmat,minf,flagmodels); do { totchange=calckmeanclass(num,nk,inmat,minf,flagmodels); totcenterchange=0; for(i=0;i<nk;i++) { indcenter[i]=calckmeancenter(num,inmat,flagmodels[i]); if(indcenter[i]!=minf[i].ind) { totcenterchange++; } minf[i].ind=indcenter[i]; } totvar=calckmeanvar(num,nk,inmat,minf,flagmodels); numiter++; } while(numiter<200 && totchange>num*0.01); delete[]indcenter; /////////////////////////////////////////////largest clu in front modelinfo tm; bool *tmflag=new bool[num]; for(i=0;i<nk-1;i++) { for(j=i+1;j<nk;j++) { if(minf[i].totnei<minf[j].totnei) { tm=minf[i]; minf[i]=minf[j]; minf[j]=tm; memcpy(tmflag,flagmodels[i],num*sizeof(bool)); memcpy(flagmodels[i],flagmodels[j],num*sizeof(bool)); memcpy(flagmodels[j],tmflag,num*sizeof(bool)); } } } delete[]tmflag; return totvar; } double SegCluster::calckmeanmodels2( int num, int nk, double **inmat, modelinfo *minf, bool **flagmodels )//no initial center { int i,j; double totvar; int numiter=0; int totchange=0; int totcenterchange=0; int *indcenter=new int[nk]; do { totchange=calckmeanclass(num,nk,inmat,minf,flagmodels); totcenterchange=0; for(i=0;i<nk;i++) { indcenter[i]=calckmeancenter(num,inmat,flagmodels[i]); if(indcenter[i]!=minf[i].ind) { totcenterchange++; } minf[i].ind=indcenter[i]; } totvar=calckmeanvar(num,nk,inmat,minf,flagmodels); numiter++; } while(numiter<200 && totchange>num*0.01); delete[]indcenter; /////////////////////////////////////////////largest clu in front modelinfo tm; bool *tmflag=new bool[num]; for(i=0;i<nk-1;i++) { for(j=i+1;j<nk;j++) { if(minf[i].totnei<minf[j].totnei) { tm=minf[i]; minf[i]=minf[j]; minf[j]=tm; memcpy(tmflag,flagmodels[i],num*sizeof(bool)); memcpy(flagmodels[i],flagmodels[j],num*sizeof(bool)); memcpy(flagmodels[j],tmflag,num*sizeof(bool)); } } } delete[]tmflag; return totvar; } void SegCluster::calckmeanmodelsiter( int num, int nk, double **inmat, modelinfo *minf, bool **flagmodels ) { int i,j; int ii,jj; int numiter=0; int minii,minij,maxiv; double totvar; int indvar=-1; double minvar; bool *flagclusterii=new bool[num]; bool *flagclusterjj=new bool[num]; minvar=calckmeanmodels(num,nk,inmat,minf,flagmodels); calckmeansplit(num,nk,inmat,minf,flagmodels,&minii,&minij,&maxiv); if(maxiv>=0) { calckmeanfarest(num,inmat,flagmodels[maxiv],&ii,&jj,flagclusterii,flagclusterjj); } while(numiter<20 && maxiv>=0 && inmat[minf[minii].ind][minf[minij].ind]<1.0*(minf[minii].cut+minf[minij].cut)) { for(i=0;i<num;i++) { if(flagmodels[minij][i]) { flagmodels[minii][i]=true; } } minf[minii].totnei+=minf[minij].totnei; j=calckmeancenter(num,inmat,flagmodels[minii]); minf[minii].ind=j; //minf[minij].ind=ii; memcpy(flagmodels[minij],flagclusterii,num*sizeof(bool)); j=calckmeancenter(num,inmat,flagmodels[minij]); minf[minij].ind=j; //minf[maxiv].ind=jj; memcpy(flagmodels[maxiv],flagclusterjj,num*sizeof(bool)); j=calckmeancenter(num,inmat,flagmodels[maxiv]); minf[maxiv].ind=j; totvar=calckmeanmodels2(num,nk,inmat,minf,flagmodels); calckmeansplit(num,nk,inmat,minf,flagmodels,&minii,&minij,&maxiv); if(maxiv>=0) { calckmeanfarest(num,inmat,flagmodels[maxiv],&ii,&jj,flagclusterii,flagclusterjj); } numiter++; if(totvar<minvar) { minvar=totvar; indvar=numiter; } } //redo calckmeanmodels(num,nk,inmat,minf,flagmodels); calckmeansplit(num,nk,inmat,minf,flagmodels,&minii,&minij,&maxiv); if(maxiv>=0) { calckmeanfarest(num,inmat,flagmodels[maxiv],&ii,&jj,flagclusterii,flagclusterjj); } for(int k=0;k<indvar;k++) { for(i=0;i<num;i++) { if(flagmodels[minij][i]) { flagmodels[minii][i]=true; } } minf[minii].totnei+=minf[minij].totnei; j=calckmeancenter(num,inmat,flagmodels[minii]); minf[minii].ind=j; //minf[minij].ind=ii; memcpy(flagmodels[minij],flagclusterii,num*sizeof(bool)); j=calckmeancenter(num,inmat,flagmodels[minij]); minf[minij].ind=j; //minf[maxiv].ind=jj; memcpy(flagmodels[maxiv],flagclusterjj,num*sizeof(bool)); j=calckmeancenter(num,inmat,flagmodels[maxiv]); minf[maxiv].ind=j; totvar=calckmeanmodels2(num,nk,inmat,minf,flagmodels); calckmeansplit(num,nk,inmat,minf,flagmodels,&minii,&minij,&maxiv); if(maxiv>=0) { calckmeanfarest(num,inmat,flagmodels[maxiv],&ii,&jj,flagclusterii,flagclusterjj); } if(totvar<minvar) { minvar=totvar; indvar=numiter; } } delete[]flagclusterii; delete[]flagclusterjj; } void SegCluster::calckmeansplit( int num, int nk, double **inmat, modelinfo *minf, bool **flagmodels, int *minii, int *minij, int *maxiv ) { int i,j; double minidist,maxivar; double **matcen; matcen=new double*[nk]; for(i=0;i<nk;i++) { matcen[i]=new double[nk]; } for(i=0;i<nk;i++) { for(j=0;j<nk;j++) { matcen[i][j]=inmat[minf[i].ind][minf[j].ind]; } } minidist=1000000000; for(i=0;i<nk;i++) { for(j=i+1;j<nk;j++) { if(matcen[i][j]<minidist) { minidist=matcen[i][j]; *minii=i; *minij=j; } } } maxivar=-1000000; for(i=0;i<nk;i++) { if(i!=*minii && i!=*minij) { if(minf[i].cut>maxivar && minf[i].totnei>1 && minf[i].totnei>0.05*num) { maxivar=minf[i].cut; *maxiv=i; } } } if(maxivar<0) { for(i=0;i<nk;i++) { if(i!=*minii && i!=*minij) { if(minf[i].cut>maxivar && minf[i].totnei>1) { maxivar=minf[i].cut; *maxiv=i; } } } } if(maxivar<0 && minf[0].totnei>1) { *maxiv=0; maxivar=minf[0].cut; minidist=1000000000; for(i=1;i<nk;i++) { for(j=i+1;j<nk;j++) { if(matcen[i][j]<minidist) { minidist=matcen[i][j]; *minii=i; *minij=j; } } } } if(maxivar<0 || minidist>10000000) { printf("No cluster for split %d %d\n",num,nk); *maxiv=-1; } for(i=0;i<nk;i++) { delete[]matcen[i]; } delete[]matcen; } void SegCluster::calckmeanfarest( int num, double **inmat, bool *flagcluster, int *ii, int *jj, bool *flagclusterii, bool *flagclusterjj ) { int i,j; double tdist=-1000000; for(i=0;i<num;i++) { if(flagcluster[i]) { for(j=i+1;j<num;j++) { if(flagcluster[j]) { if(tdist<inmat[i][j]) { tdist=inmat[i][j]; *ii=i; *jj=j; } } } } } for(i=0;i<num;i++) { flagclusterii[i]=false; flagclusterjj[i]=false; if(flagcluster[i]) { if(inmat[*ii][i]<inmat[*jj][i]) { flagclusterii[i]=true; } else { flagclusterjj[i]=true; } if(i==*ii) { flagclusterii[i]=true; flagclusterjj[i]=false; } else if(i==*jj) { flagclusterii[i]=false; flagclusterjj[i]=true; } } } } double SegCluster::calckmeanvar( int num, int nk, double **inmat, modelinfo *minf, bool **flagmodels ) { int i,j; double totvar=0; double tvar; int tnum; for(i=0;i<nk;i++) { tvar=0; tnum=0; if(minf[i].totnei==1) { minf[i].cut=0; continue; } for(j=0;j<num;j++) { if(flagmodels[i][j]) { tnum++; tvar+=inmat[minf[i].ind][j]*inmat[minf[i].ind][j]; } } totvar+=tvar; tvar/=double(tnum-1); minf[i].cut=sqrt(tvar); } totvar/=double(num-nk); totvar=sqrt(totvar); return totvar; } int SegCluster::calckmeanclass( int num, int nk, double **inmat, modelinfo *minf, bool **flagmodels )//know center calc neighbors totchange { int i,j; int totchange=0; double tmin; int indmin; for(i=0;i<nk;i++) { minf[i].totnei=0; } for(i=0;i<num;i++) { tmin=1000000000; for(j=0;j<nk;j++) { if(inmat[i][minf[j].ind]<tmin) { tmin=inmat[i][minf[j].ind]; indmin=j; } if(i==minf[j].ind) { indmin=j; break; } } if(!flagmodels[indmin][i]) { for(j=0;j<nk;j++) { flagmodels[j][i]=false; } flagmodels[indmin][i]=true; totchange++; } minf[indmin].totnei++; } return totchange; } int SegCluster::calckmeancenter( int num, double **inmat, bool *flagcluster )//each cluster calc new center index { int i,j,indmin; double ttot; double tmin=1000000000000; for(i=0;i<num;i++) { if(flagcluster[i]) { ttot=0; for(j=0;j<num;j++) { if(flagcluster[j]) { ttot+=inmat[i][j]*inmat[i][j]*inmat[i][j]; } } if(ttot<tmin) { indmin=i; tmin=ttot; } } } return indmin; } int SegCluster::calcgaumodels( int num, double **inmat, double sigma, int *vind, double probmin, double probmax, double deltadist, int nummodel, modelinfo *minf, bool **flagmodels ) { int i,j; bool *flagexclude=new bool[num]; bool *flagcluster=new bool[num]; for(i=0;i<num;i++) { flagexclude[i]=true; } int totremain=num; int totneigh,indmod; double tmpdist=sigma; for(i=0;i<nummodel;i++) { tmpdist=sigma; if(totremain<5) { break; } for(j=0;j<num;j++) { if(flagexclude[vind[j]]) { indmod=vind[j]; break; } } int iternum=0; do { totneigh=calcnumcluster(num,indmod,inmat,tmpdist,flagexclude,flagcluster); if(totneigh/double(totremain)>probmax) { tmpdist-=deltadist; } else if(totneigh/double(totremain)<probmin) { tmpdist+=deltadist; } iternum++; if(iternum>1000) { break; } } while(totneigh/double(totremain)<probmin || totneigh/double(totremain)>probmax); if(iternum>1000) { break; } minf[i].ind=indmod; minf[i].totnei=totneigh; minf[i].cut=tmpdist; memcpy(flagmodels[i],flagcluster,num*sizeof(bool)); totremain-=totneigh; for(j=0;j<num;j++) { if(flagcluster[j]) { flagexclude[j]=false; } } } delete[]flagexclude; delete[]flagcluster; return i; } int SegCluster::calcmodels( int num, double **inmat, double probmin, double probmax, double initdist, double deltadist, int nummodel, modelinfo *minf, bool **flagmodels ) { int i,j; double ddeltadist=deltadist; bool *flagexclude=new bool[num]; bool *flagcluster=new bool[num]; for(i=0;i<num;i++) { flagexclude[i]=true; } double tmpdist=initdist; bool flagsl[2]; int totremain=num; int totneigh,indmod; for(i=0;i<nummodel;i++) { tmpdist=initdist; if(totremain<5) { break; } int iternum=0; do { flagsl[1]=flagsl[0]; indmod=calcmaxneighbor(num,inmat,tmpdist,flagexclude,&totneigh,flagcluster); if(totneigh/double(totremain)>probmax && tmpdist>rmin) { flagsl[0]=false; if(iternum>1000) { if(flagsl[0]!=flagsl[1])//deltadist is big { ddeltadist/=1.5; } else//deltadist is too small, drop too slow { ddeltadist*=1.2; } iternum=0; } tmpdist-=ddeltadist; if(tmpdist<rmin) tmpdist=rmin; } else if(totneigh/double(totremain)<probmin && tmpdist<rmax) { flagsl[0]=true; if(iternum>1000) { if(flagsl[0]!=flagsl[1])//deltadist is big { ddeltadist/=1.5; } else//deltadist is too small, rise too slow { ddeltadist*=1.2; } iternum=0; } tmpdist+=ddeltadist; if(tmpdist>rmax) tmpdist=rmax; } else { break; } iternum++; if(iternum>1000) { break; } if(ddeltadist<epsilon || ddeltadist>10000000) { break; } } while(totneigh/double(totremain)<probmin || totneigh/double(totremain)>probmax); minf[i].ind=indmod; minf[i].totnei=totneigh; minf[i].cut=tmpdist; fprintf(stderr,"cluster %2d size %7d cutoff %10.5f ratio %.3f niter %5d remain %7d\n", i, minf[i].totnei, minf[i].cut,totneigh/double(totremain),iternum,totremain); memcpy(flagmodels[i],flagcluster,num*sizeof(bool)); totremain-=totneigh; for(j=0;j<num;j++) { if(flagcluster[j]) { flagexclude[j]=false; } } } delete[]flagexclude; delete[]flagcluster; return i; } int SegCluster::calcmaxneighbor( int num, double **inmat, double distcut, bool *flagexclude, int *totneigh, bool *flagcluster ) { int i; int maxneigbor=-1; int indmax; int tmpnum; for(i=0;i<num;i++) if(flagexclude[i]) { tmpnum=calcnumcluster(num,i,inmat,distcut,flagexclude,flagcluster); if(tmpnum>maxneigbor) { indmax=i; maxneigbor=tmpnum; *totneigh=maxneigbor; } } calcnumcluster(num,indmax,inmat,distcut,flagexclude,flagcluster); return indmax; } //return which one int SegCluster::calcmaxneighbor( int num, char *distname, double distcut, bool *flagexclude, int *totneigh, bool *flagcluster ) { int i; int maxneigbor=-1; int indmax; int tmpnum; for(i=0;i<num;i++) if(flagexclude[i]) { tmpnum=calcnumcluster(num,i,distname,distcut,flagexclude,flagcluster); if(tmpnum>maxneigbor) { indmax=i; maxneigbor=tmpnum; *totneigh=maxneigbor; } } calcnumcluster(num,indmax,distname,distcut,flagexclude,flagcluster); return indmax; } int SegCluster::calcnumcluster( int num, int indi, double **inmat, double distcut, bool *flagexclude, bool *flagcluster ) { int tot=0; int i; for(i=0;i<num;i++) { flagcluster[i]=false; if(flagexclude[i] && inmat[indi][i]<=distcut) { tot++; flagcluster[i]=true; } } return tot; } int SegCluster::calcnumcluster( int num, int indi, char *distname, double distcut, bool *flagexclude, bool *flagcluster ) { int tot=0; int i; FILE *file; float tdist; char tmpname[150]; sprintf(tmpname,"%s%d.txt",distname,indi); file=fopen(tmpname,"rt"); for(i=0;i<num;i++) { flagcluster[i]=false; fgets(tmpname,150,file); sscanf(tmpname,"%f",&tdist); if(tdist<=distcut && flagexclude[i]) { tot++; flagcluster[i]=true; } } fclose(file); return tot; } void SegCluster::calcgaussian( int num, double **inmat, double sigma, double *outvect ) { int i,j; double tdist; BasicFunc bf; for(i=0;i<num;i++) { outvect[i]=1; for(j=i+1;j<num;j++) { tdist=bf.fungaussian(inmat[i][j],1,sigma,0); outvect[i]+=tdist; outvect[j]+=tdist; } } } void SegCluster::calcfragdistmat( int indi, char *fragname, double **outmat ) { int i,j,k; FILE *file,*file2; point3f ptmp; double tdist,pmat[9],ptrans[3]; ParsePDB pp; char namefrag[200]; double pin[3*nosegunit],pout[3*nosegunit]; sprintf(namefrag,"%s%d.topse",fragname,indi); file=fopen(namefrag,"rt"); if(file==NULL) { printf("not found frag file %s\n",namefrag); return; } for(i=0;i<topno;i++) { fgets(namefrag,200,file); for(j=0;j<nosegunit;j++) { fgets(namefrag,200,file); sscanf(namefrag,"%c %f %f %f %c %f %f %f %f %f %f %f %f %f %f %f %f", &ptmp.residueid,&ptmp.x,&ptmp.y,&ptmp.z,&ptmp.stype,&ptmp.phi, &ptmp.leng,&ptmp.angl,&ptmp.tor[0],&ptmp.len[0],&ptmp.ang[0], &ptmp.tor[1],&ptmp.len[1],&ptmp.ang[1],&ptmp.tor[2],&ptmp.len[2], &ptmp.ang[2]); pin[j]=ptmp.x; pin[nosegunit+j]=ptmp.y; pin[2*nosegunit+j]=ptmp.z; } sprintf(namefrag,"%s%d.topse",fragname,indi); file2=fopen(namefrag,"rt"); for(j=0;j<topno;j++) { fgets(namefrag,200,file2); for(k=0;k<nosegunit;k++) { fgets(namefrag,200,file2); sscanf(namefrag,"%c %f %f %f %c %f %f %f %f %f %f %f %f %f %f %f %f", &ptmp.residueid,&ptmp.x,&ptmp.y,&ptmp.z,&ptmp.stype,&ptmp.phi, &ptmp.leng,&ptmp.angl,&ptmp.tor[0],&ptmp.len[0],&ptmp.ang[0], &ptmp.tor[1],&ptmp.len[1],&ptmp.ang[1],&ptmp.tor[2],&ptmp.len[2], &ptmp.ang[2]); pout[k]=ptmp.x; pout[nosegunit+k]=ptmp.y; pout[2*nosegunit+k]=ptmp.z; } tdist=pp.lsfrmsd(pin,pout,nosegunit,pmat,ptrans); outmat[i][j]=tdist; outmat[j][i]=tdist; } fclose(file2); } fclose(file); } void SegCluster::calcdistmat( int num, dihedral *intor, double **outmat ) { int i,j; double tdist,delx,dely,tx,ty; for(i=0;i<num;i++) { outmat[i][i]=0; for(j=i+1;j<num;j++) { delx=fabs(intor[i].phi-intor[j].phi); tx=fabs(intor[i].phi-intor[j].phi+360); if(delx>tx) { delx=tx; } tx=fabs(intor[i].phi-intor[j].phi-360); if(delx>tx) { delx=tx; } dely=fabs(intor[i].psi-intor[j].psi); ty=fabs(intor[i].psi-intor[j].psi+360); if(dely>ty) { dely=ty; } ty=fabs(intor[i].psi-intor[j].psi-360); if(dely>ty) { dely=ty; } tdist=sqrt(delx*delx+dely*dely); outmat[i][j]=tdist; outmat[j][i]=tdist; } } } bool SegCluster::extractone( char *filename, int indnum, char *outname ) { int j; FILE *file,*fileout; char oneline[300]; file=fopen(filename,"rt"); if(!file) { printf("not found remc %s\n",filename); return false; } do { fgets(oneline,300,file); j=-10000; if(!(oneline[0]=='M' && oneline[1]=='O' && oneline[2]=='D' && oneline[3]=='E' && oneline[4]=='L')) { continue; } sscanf(oneline+9,"%d",&j); } while(j!=indnum && !feof(file)); fileout=fopen(outname,"wt"); fprintf(fileout,"%s",oneline); while(!feof(file) && !(oneline[0]=='E' && oneline[1]=='N' && oneline[2]=='D' && oneline[3]=='M')) { fgets(oneline,300,file); if(strlen(oneline)>14 && oneline[13]=='S' && oneline[14]=='G') continue; fprintf(fileout,"%s",oneline); } fclose(fileout); fclose(file); return true; } int SegCluster::extractremc( int istart, int iend, char *prename, int nummc, char *outname ) { int i,k; FILE *file,*fileout; char pdbname[200]; int indmc=0; for(i=istart;i<=iend;i++) { sprintf(pdbname,"%s%d.pdb",prename,i); file=fopen(pdbname,"rt"); if(!file) { printf("not found remc %s\n",pdbname); return -1; } for(k=0;k<nummc;k++) { sprintf(pdbname,"%s%d.pdb",outname,indmc); printf("%s\n",pdbname); fileout=fopen(pdbname,"wt"); do { fgets(pdbname,200,file); fprintf(fileout,"%s",pdbname); } while(!(pdbname[0]=='E' && pdbname[1]=='N' && pdbname[2]=='D' && pdbname[3]=='M' && pdbname[4]=='D') && !feof(file)); if(feof(file) && !(pdbname[0]=='E' && pdbname[1]=='N' && pdbname[2]=='D' && pdbname[3]=='M' && pdbname[4]=='D')) { fclose(fileout); break; } fclose(fileout); indmc++; } fclose(file); } return indmc; } int SegCluster::extractremc( char *filename, int indstart, char *outname ) { FILE *file,*fileout; int indmc=0; char oneline[300]; file=fopen(filename,"rt"); if(!file) { printf("not found remc %s\n",filename); return indmc; } while(!feof(file)) { sprintf(oneline,"%s%d.pdb",outname,indstart+indmc); fileout=fopen(oneline,"wt"); do { fgets(oneline,300,file); fprintf(fileout,"%s",oneline); } while(!(oneline[0]=='E' && oneline[1]=='N' && oneline[2]=='D' && oneline[3]=='M' && oneline[4]=='D') && !feof(file)); if(feof(file) && !(oneline[0]=='E' && oneline[1]=='N' && oneline[2]=='D' && oneline[3]=='M' && oneline[4]=='D')) { fclose(fileout); break; } fclose(fileout); indmc++; } fclose(file); return indmc; } int SegCluster::extractremc( int istart, int iend, int numseq, char *prename, int nummc, char *outname ) { int i,k; FILE *file,*fileout; char pdbname[200]; int indmc=0; for(i=istart;i<=iend;i++) { sprintf(pdbname,"%s/%d.pdb",prename,i); file=fopen(pdbname,"rt"); if(!file) { printf("not found remc %s\n",pdbname); return -1; } for(k=0;k<nummc;k++) { sprintf(pdbname,"%s/%d.pdb",outname,indmc); fileout=fopen(pdbname,"wt"); do { fgets(pdbname,200,file); fprintf(fileout,"%s",pdbname); } while(!(pdbname[0]=='E' && pdbname[1]=='N' && pdbname[2]=='D' && pdbname[3]=='M' && pdbname[4]=='D')&& !feof(file)); if(feof(file) && !(pdbname[0]=='E' && pdbname[1]=='N' && pdbname[2]=='D' && pdbname[3]=='M' && pdbname[4]=='D')) { fclose(fileout); break; } fclose(fileout); indmc++; } fclose(file); } return indmc; } void SegCluster::outputdist( int num, int indi, char *proname, double sigma, char *outname, double *gauval ) { ParsePDB pp1,pp2; int i,j; double tdist; FILE *file; char tmpname[150]; double totval=0; BasicFunc bf; sprintf(tmpname,"%s.%d",proname,indi+1); pp1.loadpdb(tmpname); pp1.extractbb(0,-1,1); double pmat[9],ptrans[3]; double *pout=new double[pp1.numbb*3]; double *pin=new double[pp1.numbb*3]; for(i=0;i<pp1.numbb;i++) { if(pp1.bb[i].indca==-1) pp1.bb[i].indca=0; pin[i]=pp1.proseq[pp1.bb[i].indca].x; pin[i+pp1.numbb]=pp1.proseq[pp1.bb[i].indca].y; pin[i+2*pp1.numbb]=pp1.proseq[pp1.bb[i].indca].z; } sprintf(tmpname,"%s%d.txt",outname,indi); file=fopen(tmpname,"wt"); for(j=0;j<num;j++) { if(j==indi) { fprintf(file,"%f\n",0.0); continue; } sprintf(tmpname,"%s.%d",proname,j+1); pp2.loadpdb(tmpname); pp2.extractbb(0,-1,1); for(i=0;i<pp1.numbb;i++) { if(pp2.bb[i].indca==-1) pp2.bb[i].indca=0; pout[i]=pp2.proseq[pp2.bb[i].indca].x; pout[i+pp1.numbb]=pp2.proseq[pp2.bb[i].indca].y; pout[i+2*pp1.numbb]=pp2.proseq[pp2.bb[i].indca].z; } tdist=pp1.lsfrmsd(pin,pout,pp1.numbb,pmat,ptrans); tdist+=fabs(dscore[indi]-dscore[j]); fprintf(file,"%f\n",tdist); totval+=bf.fungaussian(tdist,1,sigma,0); } fclose(file); delete[]pin; delete[]pout; *gauval=totval; } double SegCluster::eucdist( int p, int c ) { double dist; int i; dist=0; for(i=0;i<vecleng;i++) { dist += (cfv[c].f[i]-fv[p].f[i])*(cfv[c].f[i]-fv[p].f[i]); } return dist; } int SegCluster::closestcluster( int pat ) { int i,clustid; double mindist,d; mindist=100000000; clustid=-1; for(i=0;i<ck;i++) { d=eucdist(pat,i); if(d<mindist) { mindist=d; clustid=i; } } return clustid; } void SegCluster::distrisamples() { int i,pat,clustid,memberindex; for(i=0;i<ck;i++) { cfv[i].num=0; } for(pat=0;pat<nosample;pat++) { clustid=closestcluster(pat); memberindex=cfv[clustid].num; cfv[clustid].ind2vec[memberindex]=pat; cfv[clustid].num++; } } bool SegCluster::calcnewcenters() { int vectid,i,j,k; bool convflag; double tmp[vecleng]; convflag=true; for(i=0;i<ck;i++) { for(j=0;j<vecleng;j++) { tmp[j]=0.0; } for(j=0;j<cfv[i].num;j++) { vectid=cfv[i].ind2vec[j]; for(k=0;k<vecleng;k++) { tmp[k]+=fv[vectid].f[k]; } } for(k=0;k<vecleng;k++) { tmp[k]=tmp[k]/cfv[i].num; if(tmp[k]!=cfv[i].f[k]) { convflag=false; } cfv[i].f[k]=tmp[k]; } } return convflag; } void SegCluster::runkmeans() { bool converged; numiter=0; converged=false; while(converged==false) { distrisamples(); converged=calcnewcenters(); numiter++; } }
Deciding positivity of multisymmetric polynomials The question how to certify non-negativity of a polynomial function lies at the heart of Real Algebra and also has important applications to Optimization. In this article we investigate the question of non-negativity in the context of multisymmetric polynomials. In this setting we generalize the characterization of non-negative symmetric polynomials by adapting the method of proof developed by the second author. One particular case where our results can be applied is the question of certifying that a (multi-)symmetric polynomial defines a convex function. As a direct corollary of our main result we are able to derive that in the case of (multi-)symmetric polynomials of a fixed degree testing for convexity can be done in a time which is polynomial in the number of variables. This is in sharp contrast to the general case, where it is known that testing for convexity is NP-hard already in the case of quartic polynomials. Introduction A real polynomial is called positive (non-negative) if its evaluation on every real point is positive (non-negative). The study of this property of polynomials functions is one of the aspects that separates Real Algebraic Geometry from Algebraic Geometry over algebraically closed fields. Indeed, Real Algebraic Geometry developed building on Hilbert's problem of characterizing non-negative polynomials via sums of squares. On the complexity side, it is know that the problem to algorithmically decide whether a given polynomial assumes only positive or non-negative values is NP-hard in general (see for example ) and is essential for example to understand global optimization of polynomial functions. Besides the general results some authors have studied particular cases of polynomials which are invariant under group actions, for example by permuting the variables. In particular, symmetric polynomials exhibit some interesting properties that behave differently over real closed and algebraically closed fields. For example, in the authors show, that the equivariant cohomology of a complex variety which is defined by symmetric polynomials of a given maximal degree is bounded by a quantity which (for a large number of variables) only depends on this maximal degree. In contrast to that there are examples of real varieties where this does not hold, i.e., this quantity actually grows with the number of variables. A seminal characterization of symmetric polynomials that are positive is due to Procesi. Building on work by Harris, Timofte was able to provide a characterization of symmetric non-negative functions that can be used to algorithmically certify non-negativity: He could establish that a symmetric polynomial of degree 2d is non-negative if and only if it is nonnegative on all points with at most d distinct components. This observation leads to a number of interesting consequences. For example, it provides an essential part to the description of the asymptotical behavior of the cone of symmetric non-negative forms of a given degree when the number of variables grows. Algorithmically, this result allows to show that the complexity of deciding non-negativity of a symmetric function with a fixed degree only grows polynomially in the number of variables. Following the work of Timofte, the second author was able to provide short proofs of this characterization of symmetric non-negative polynomials. Contributions: In this article we extend the previous results on symmetric polynomials to arrive at a similar characterization of multisymmetric polynomial functions that assume only positive (non-negative) values. The class of multisymmetric polynomials naturally generalizes the symmetric polynomials. They can be thought of as functions which are invariant under simultaneously permuting k-tupels of variables. Similar to the case of symmetric polynomials, we are able to show that when the degree of such a polynomial is sufficiently smaller than the number of variables, also for these multisymmetric polynomials non-negativity can be checked on a lowerdimensional subset consisting of points whose orbit length is not maximal. As in the case of the usual action of the symmetric group, these points lie on linear subspaces. Our main result is Theorem 14 which bounds the dimension of subspaces one has to consider to decide non-negativity of a multisymmetric polynomial. Besides this general bound the idea of the proof can be adjusted in particular situations to derive stronger bounds. We give several other bounds to illustrate this. As an application of our results we investigate the question of deciding, if a given symmetric or multisymmetric polynomial defines a convex function. It is straightforward to observe that the question of convexity of a k-symmetric polynomial leads to the question of certifying whether a 2k-symmetric polynomial is non-negative. Consequently, we show in Theorems 26 and 28 that our results on non-negativity of multisymmetric polynomials imply in particular that for (multi-)symmetric polynomials of a fixed degree the complexity of deciding convexity does not grow exponentially in the number of variables. The article is structured as follows. In the next section we will give a brief introduction to the theory of multisymmetric polynomials and provide a relation between k-multisymmetric polynomials and k-variat polynomials which will play a crucial role in our arguments. With these preliminaries at hand we are able to state and prove the main result in Section 3. The last section is then devoted to the application of the non-negativity result to the problem of deciding convexity. This section also includes some refinements of our main results which apply to this setting. Multisymmetric Polynomials For n ∈ N let S n denote the symmetric group on n elements which acts on the n-dimensional vector space V := R n by permuting coordinates. For every k ∈ N we consider the diagonal action of S n on the vector space of k-tuples of vectors from V. The action of S n extends to the ring R, which is just the polynomial ring R after identifying X i1,..., X ik with the standard basis of the i-th direct summand of V k. It is convenient to think of these variables as an n k array as indicated in the following notation. Notation 1. Throughout this paper let denote an n k array of variables. By X i and X j we denote the i-th row of X and the j-th column of X, respectively. Following this notation, S n permutes the rows of X. The invariant ring of the polynomial ring R = R with respect to this action is the algebra of k-(multi-)symmetric polynomials, denoted by R Sn. Alternatively, R Sn can be thought of as the n-fold symmetric product of the polynomial R-algebra in k variables, which is a classically studied object (see ). Note that for k = 1 this is the algebra of symmetric polynomials, which is a polynomial ring. In the case k > 1, n > 1 the symmetric group S n is not operating as a finite reflection group, thus the algebra of k-symmetric polynomials is no longer a polynomial ring. However, for all k it is finitely generated as R-algebra. For our purposes the representation in terms of so called multisymmetric power sums will be crucial. Definition 2. Given a polynomial f ∈ R, we denote its symmetrization, that is, the sum over its S n -orbit, by sym(f ) ∈ R Sn. For all ∈ N k we define the (multisymmetric) power sum This is is a generalization of the power sum polynomials used in, where the symmetric case k = 1 is considered. In that case, the first n power sum polynomials form an algebraically independent set generating the R-algebra of symmetric polynomials. In the k-symmetric case, this statement does not generalize, i.e., the generators are no longer algebraically independent. In the following, we study the k-symmetric power sums and their connection to k-symmetric functions. Definition 3. Let w := (w 1,..., w k ) be a k-tuple of positive integers. We consider the grading on the R-algebra R given by defining Y j to be homogeneous of degree w j. This grading also induces a grading on the R-algebra R by the algebra-homomorphism : Alternatively, the latter grading is given by defining each X ij to be homogeneous of degree w j. with respect to the above grading is called the w-weighted degree, or simply w-degree, of f. j, respectively, where,,..., (n) ∈ N k. After that, one extends this definition to a polynomial f by taking the maximal w-degree of all monomials of f. Note that we retrieve the usual degree from this definition by setting all weights w j equal to 1. Example 4. Fix n ∈ N rather large and consider for all (nonzero) parameters ∈ R 7 the 2-symmetric polynomial given by where all sums go from 1 to n. We have deg Recognizing that the exponents of the column X 2 are small compared to the exponents of X 1 one could give more weight to the second column, e. g. by considering the -degree: deg considering the gradings as above. Thus, Let deg w (f ) = d. Then the interpretation above gives rise to a very useful view on the w-degree as a hyperplane defining a simplex {y ∈ R k ≥0 | w T y ≤ d} enclosing E f. Applied to Example 4, where k = 2, we can consider Figure 1 In the following Theorem, we see that the lattice points contained in the simplex which is given by some weights w have an emerging meaning when we consider the according power sums. The R-algebra generated by all power sums p with || w := w T ≤ d contains all k-symmetric polynomials of w-degree at most d. Proof. Reviewing the proof of yields the assertion: It is enough to show that the first power sums generate all k-symmetric monomial functions m,..., (ℓ) := sym(X 1 X (ℓ) ℓ ) there are only polynomials of w-degree equal or less than d on the right-hand side of this identity. Hence, we can write a monomial function with ℓ + 1 exponent tuples as combination of a power sum of w-degree at most d and some monomial functions with ℓ exponent tuples, both of w-degree at most d. Noticing that a monomial function with only one exponent tuple is a power sum ends the proof. Reconsider Figure 1. Taking the lattice points contained in the simplices given by w 1 and w 2, respectively, we get two sets of power sums, each of them sufficient to describe f as a polynomial expression in its elements. In fact, the proof of Theorem 6 shows even more. Then f can be written as a polynomial expression in the power sums associated to the lattice points that are contained in the intersection The reason why we are interested in a different way of describing k-symmetric polynomials is illuminated by the following observation. For all ∈ N k the partial derivative with respect to X ij of p is a polynomial in the variables X i. Moreover, for every j ∈ {1,..., k} there exists one polynomial Note that r j does not depend on i. This makes the derivatives of power sums easier to handle than the derivatives of the usual generaing set, that is the set of monomials of w-degree at most d. We immediately conclude the following result for linear combinations of power sums: andq j is of w-degree at most d − w j for each j ∈ {1,..., k}. We will use this fact in the proof of Theorem 14. 3. Positivity of multisymmetric polynomials Note that (f ) ≤ n in any case. If f ∈ R, k = 1, i.e., the case of a symmetric polynomials, it is known that (f ) ≤ max{2, deg f 2 } (see ). In Theorem 14 below we will show a bound for a k-symmetric polynomial f ∈ R Sn in terms of the (weighted) degree of f. We observe that is lower semi-continuous: be a sequence of continuous functions converging pointwise to some f ∈ C 0 (V k ). Then Proof. Note, that by compactness of B r the sequence f ℓ | Br converges uniformly to f | Br.This implies that for all m ∈ N, min x∈Br f ℓ (x) and min x∈Br∩Am f ℓ (x) converge to min x∈Br f (x) and min x∈Br∩Am f (x), respectively. The following Proposition gives a rough estimate on the number of ℓ-partitions for a fixed natural number n. Proposition 13. Let n ∈ N. Then for every ℓ ∈ N the number of ℓ-partitions of n is bounded by n ℓ. Algorithmically checking for the global properties in Proposition 11 is an instance of a decision problem. As mentioned, it is known that deciding global positivity of a multivariate polynomial is NP-hard in general (see for example ). Our aim is to exploit the structure of k-symmetric polynomials f by bounding (f ). Observe, that A m is a union of km-dimensional subspaces, each of which corresponds to one particular way of assigning the m distinct rows. It follows that modulo the action of S n on the rows each of these choices is uniquely represented by an mpartition of n. Therefore the statements in Proposition 11 amount to saying that all of the mentioned global properties can be checked by verifying them on each of the k (f )-dimensional subspaces corresponding to the various (f )-partitions of n. The number of such partitions can be bounded by n (f ), so if (f ) can be bounded by a quantity independent of n for a certain family of polynomials f, this implies that the complexity of testing for those global properties for k-symmetric polynomials grows only polynomially in the number of variables -in the contrast to the general case. Our main result is now presented in the following Theorem. Fix r > 0 and let > 0. Consider a point z * ∈ B r where f | Br is minimized. We have to show z * ∈ A. all monomials Y with j > d j for some 1 ≤ j ≤ k can be rewritten as a sum of monomials of smaller w-degree. Hence, #V(q 1,..., q k ) ≤, so at most of the rows z * 1,..., z * n can be different, that is, z * ∈ A. Remark 15. Note that the proof of Theorem 14 given above works in exactly the same manner for a more general setting: If f ∈ C 1 (V k ) and there exists, then we get the same bound for (f ). Additionally, we can further extend this bound by Proposition 10 to functions of the Example 16. We consider the case k = 2. The family of polynomials is not bounded with respect to any weighted degree. However, all f m,ℓ 1 can be written in terms of the power sum polynomials of (usual) degree at most 3. Thus, by the preceding remark, we still get the bound (f m,ℓ 1 ) ≤ 9 for all m, ℓ ∈ N. Even for the rational function f 2 := (p − 2p p )/(p 2 + 1) and the functions N) we get that the -value is at most 9. For a very rough estimation of (f ) we can just use the usual degree and get the following upper bound without any effort. Remark 17. Note that in the proof of Theorem 14 the bound for (f ) is given by an upper bound on the number of complex solutions of a certain However, Theorem 14 is much stronger. Recall that, using Notation 5, the condition that f is of w-degree at most d can be expressed as E f ⊂ {y ∈ R k ≥0 | w T y ≤ d} and note that the hyperplane {y ∈ R k | w T y = d} defining this enclosing simplex intersects the j-th coordinate axis at the point (d/w j )e j (where e 1,..., e k is the standard basis of R k ). This gives the following geometric reformulation of the Theorem 14. a k-symmetric polynomial and let a 1,..., a k ∈ Q ≥2 such that E f is contained in the simplex ∆(a 1,..., a k ) := conv(0, a 1 e 1,..., a k e k )⊂ R k. Then (f ) is bounded by k j=1 ⌊a j ⌋, i.e. the number of lattice points in [0, Note that this number of lattice points is approximately k! vol (∆(a 1,..., a k )). Therefore, finding a good bound for (f ) via Theorem 19 roughly amounts to finding the smallest simplex ∆(a 1,..., a k ) enclosing E f. Figure 1. The triangle described by w = minimizes the number of lattice points. Counting the lattice points in the rectangle drawn in Figure 2 gives the upper bound (f ) ≤ 8. This bound holds for all n and for all choices of the parameters in Example 4. Example 20 (Example 4 continued). Reconsider In the case k > 2 drawing a picture and fitting the right simplex might not be that easy. However, we can provide a further bound on (f ). Note that this bound is better than the bound given in Corollary 18 in the case that the degree of some columns X j is much smaller than the others. Corollary 21. Let k ≥ 2 and let f ∈ R Sn be a k-symmetric polynomial such that each column X j occurs only with degree at most d j ≥ 1. Deciding Convexity of multisymmetric polynomials In this section we apply Theorem 19 to the problem of algorithmically deciding (strict) convexity of a polynomial of fixed degree. Already for general quartic polynomials deciding convexity is an NP-hard problem (see ). However, we will see that in the case of symmetric (or, more generally, k-symmetric) polynomials of a bounded degree, a convexity test can be provided whose complexity is mainly determined by the degree in the sense that for a fixed degree it is polynomial in the number of variables. Recall that convexity of a function is defined as follows. Definition 22. Let C ⊂ R m be a convex set and f : C → R be a real valued function. Then f is called strictly convex if We remark that convexity is of particular interest also for the question of deciding if a polynomial is non-negative. Since ∈ A 1, the statement follows. Using the classical definition above we remark the following characterizations which will allow the use of our main theorem. Proposition 24. Let f : R m → R be a polynomial function. ( 1) Then f is convex (or strictly convex) if and only if the polynomial function is non-negative (or positive, respectively). ( Let f ∈ R Sn be a k-symmetric polynomial and consider (g f ) for the 2k-symmetric function g f defined in. Then f is (strictly) convex if and only if the restriction of f onto each of the linear subspaces defining Proof. The first assertion is a direct consequence of Taylor's theorem. For the second statement observe that for each ∈ S m such that f ((x)) = f (x) for all x ∈ R m, we get g f ((x), (x)) = g f (x,x) for all x,x ∈ R m, from which the assertion follows. The last statement follows directly from and and the definition of (g f ). Now we fix k and d ≥ 2 and consider k-symmetric polynomials f of degree d. By Proposition 24, it follows that (strict) convexity of f can algorithmically be checked using Theorem 14. Let c(ℓ, d) be an upper bound for the complexity of deciding if a polynomial in ℓ variables of degree at most d is convex. Then, we can conclude with Propositions 11 and 13 that the complexity of deciding convexity of f is bounded by c(k (f ), d) n (g f ). Since deg(g f ) ≤ d, we can directly deduce from Corollary 18 that (g f ) ≤ d 2k, which implies that the complexity (for fixed k and d) grows polynomially in the number of variables. Additionally, since for each of the resulting k (f )-dimensional polynomials convexity can be decided independently, this approach can be parallelized. However, the bound for (g f ) can be improved considerably by exploiting the specific structure of g f. Note that for any x,x ∈ R nk the polynomial g f (X,x) is of degree at most d − 2 and g f (x,X) of degree at most 2. So, Corollary 21 can be used to infer that which is a better bound in case d ≥ 8k 2. In fact, we will prove below (Corollary 29) that the term k 2k is superfluous. For this purpose, we examine the non-negativity of g f using the reformulation in terms of lattice points presented in Theorem 19. In the following Proposition we examine the possible exponent vectors of g f. We make use of Notation 5 to formulate our result. In particular,..., 2), Proof. This immediately follows by examining the definition of g f : Just note that if h is a second partial derivative of f with respect to variables in columns i and j, The above observations now yield the following Theorem. Example 27 (Example 4 continued). Consider again the family of 2-symmetric polynomials f which was studied in Example 4. By reading E f from Figure 1 we can easily construct H f (see Proposition 25). We need to fit a w-degree line such that the originating triangle encloses H f. With a view to Theorem 26, we should choose a triangle ∆(a 1, a 2 ) that minimizes ⌊2a 1 ⌋⌊2a 2 ⌋. With the choice indicated in Figure 3 we get a 1 < 2.5 and a 2 < 2. Hence, (g f ) ≤ 108. However, it turns out that the bound can be improved by taking a closer look at E g f using (4.1). By solving a small optimization problem we are able to find that E g f ⊂ ∆(9 −, 3 −, 4 −, 2 − ) for a small > 0. From this observation one can deduce the better bound (f ) ≤ 48. Apart from this geometrical view we provide a formulation in terms of weighted degrees. Note that this formulation is a bit weaker than Theorem 26, but it might still be useful as we need less information about the function in question in order to calculate the resulting bound. Proof. Choosing all weights equal to 1 we get the following Corollary, Corollary 29. Let f ∈ R Sn be a k-symmetric polynomial of degree d ≥ 3. Then The following Corollary is just a reformulation of our results, which we include to emphasize the results in the case of convexity of symmetric polynomials.
package download.crossally.apps.hizkiyyah.bean; import java.io.Serializable; public class UserBean implements Serializable { String id; String name; String email; String profile_pic; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getProfile_pic() { return profile_pic; } public void setProfile_pic(String profile_pic) { this.profile_pic = profile_pic; } }
The safety of monoclonal antibodies for treatment of colorectal cancer ABSTRACT Introduction: Monoclonal antibodies such as bevacizumab, ramucirumab, cetuximab and panitumumab play an important role in the treatment of metastatic colorectal cancer (mCRC). With the introduction of these drugs considerable improvements in both progression-free survival (PFS) and overall survival (OS) were achieved. However these antibodies are associated with a unique side effect profile. Areas covered: This review provides an overview about drug efficacy of bevacizumab, cetuximab, panitumumab and ramucirumab in the treatment algorithm of mCRC. Additionally, we discuss the most common toxicites of these monoclonal antibodies. Expert opinion: The most common toxicities associated with the VEGF-A directed antibody bevacizumab are hypertension, proteinuria, thromboembolism, bleeding, gastrointestinal perforation and prolonged wound healing. Similarly, the rate of hypertension and proteinuria is increased during treatment with the VEGFR2 antibody ramucirumab. On the other hand the most frequent side effects of EGFR targeted antibodies are skin rash, hypersensitivity reactions and hypomagnesemia. Due to the murine portions of cetuximab the incidence of infusion reactions is more frequent compared to panitumumab which is a pure human monoclonal antibody.
Narrowband to wideband conversion of speech using GMM based transformation Reconstruction of wideband speech from its narrowband version is an attractive issue, since it can enhance the speech quality without modifying the existing communication networks. This paper proposes a new recovery method of wideband speech from narrowband speech. In the proposed method, the narrowband spectral envelope of input speech is transformed to a wideband spectral envelope based on the Gaussian mixture model (GMM), whose parameters are calculated by a joint density estimation technique. Then the lowband and highband speech signal is reconstructed by the LPC synthesizer using the reconstructed spectral envelope. This paper also proposes a codeword-dependent power estimation method. Both the objective and subjective test results shows that the proposed algorithm outperforms the conventional codebook mapping method.
package com.leo.prj.service.img; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.List; import javax.imageio.ImageIO; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.leo.prj.bean.UploadFilesResult; import com.leo.prj.constant.CommonConstant; import com.leo.prj.enumeration.UploadFileStatus; import com.leo.prj.service.FileCheckerService; import com.leo.prj.service.UploadService; import com.leo.prj.util.FilePathUtil; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.name.Rename; @Service public class ImageUploadService { private static final Logger logger = Logger.getLogger(ImageUploadService.class); private static final int MAX_THUMNAIL_WIDTH = 230; private static final int MAX_THUMNAIL_HEIGH = 200; @Autowired private UploadService uploadService; @Autowired private FileCheckerService imageCheckerService; @Autowired private ObjectFactory<UploadFilesResult> resultFactory; public UploadFileStatus uploadImage(final MultipartFile uploadFile, final String directoryPath) { final String fileName = this.createFileName(uploadFile); if (this.imageCheckerService.isExist(directoryPath, fileName)) { logger.info("The path [" + directoryPath + File.separator + fileName + "] is existed"); return UploadFileStatus.EXIST; } if (!this.imageCheckerService.isValid(uploadFile, directoryPath, fileName)) { logger.info("The file: '" + uploadFile.getName() + "' is invalid"); return UploadFileStatus.INVALID; } final UploadFileStatus uploadFileStatus = this.uploadService.uploadFile(uploadFile, Paths.get(directoryPath).toFile(), fileName) ? UploadFileStatus.VALID : UploadFileStatus.INVALID; this.createThumbnail(FilePathUtil.from(directoryPath).add(fileName).getPath().toFile()); return uploadFileStatus; } public boolean createThumbnail(final MultipartFile uploadFile, final Path directoryPath) { try { this.uploadService.uploadFile(uploadFile, directoryPath.toFile(), uploadFile.getOriginalFilename()); Files.delete(FilePathUtil.from(directoryPath).add(uploadFile.getOriginalFilename()).getPath()); } catch (final IOException e) { throw new RuntimeException("Can't delete file: " + uploadFile.getOriginalFilename()); } return true; } public void createThumbnail(File file) { try { final BufferedImage bufferedImage = ImageIO.read(file); Thumbnails.of(file) .size(Math.min(MAX_THUMNAIL_WIDTH, bufferedImage.getWidth()), Math.min(MAX_THUMNAIL_HEIGH, bufferedImage.getHeight())) .useExifOrientation(true).useOriginalFormat().toFiles(Rename.SUFFIX_DOT_THUMBNAIL); } catch (final Exception e) { logger.error("Error happen when create thumnail", e); throw new RuntimeException(e); } } private String createFileName(MultipartFile uploadFile) { final String fileNameWithExtension = uploadFile.getOriginalFilename(); return FilenameUtils.removeExtension(fileNameWithExtension) + CommonConstant.DOT + new Date().getTime() + CommonConstant.DOT + FilenameUtils.getExtension(fileNameWithExtension); } public UploadFilesResult uploadImages(final List<MultipartFile> uploadFiles, String directoryPath) { final UploadFilesResult result = this.createUploadFilesResult(); uploadFiles.forEach(file -> { final UploadFileStatus status = this.uploadImage(file, directoryPath); switch (status) { case INVALID: result.increaseInvalidFiles(); return; case EXIST: result.increaseExistFiles(); return; default: result.increaseUploadedFiles(); return; } }); return result; } private UploadFilesResult createUploadFilesResult() { return this.resultFactory.getObject(); } }
/** * Adds all members of ste2's charset to ste1's charset and then deletes ste2 */ void Automata::mergeSTEs(STE *ste1, STE *ste2){ for(uint32_t i = 0; i < ste2->getBitColumn().size(); i++) { if(ste2->match(i)){ ste1->addSymbolToSymbolSet(i); } } removeElement(ste2); }
PatchR: A Framework for Linked Data Change Requests Incorrect or outdated data is a common problem when working with Linked Data in real world applications. Linked Data is distributed over the web and under control of various dataset publishers. It is difficult for data publishers to ensure the quality and timeliness of the data all by themselves, though they might receive individual complaints by data users, who identified incorrect or missing data. Indeed, the authors see Linked Data consumers equally responsible for the quality of the datasets they use. PatchR provides a vocabulary to report incorrect data and to propose changes to correct them. Based on the PatchR ontology a framework is suggested that allows users to efficiently report and data publishers to handle change requests for their datasets.
package com.babylonhealth.lit.hl7_java.codes; import com.babylonhealth.lit.hl7.DISCRIMINATOR_TYPE; public interface DiscriminatorType { public static final DISCRIMINATOR_TYPE EXISTS = DISCRIMINATOR_TYPE.EXISTS$.MODULE$; public static final DISCRIMINATOR_TYPE PATTERN = DISCRIMINATOR_TYPE.PATTERN$.MODULE$; public static final DISCRIMINATOR_TYPE PROFILE = DISCRIMINATOR_TYPE.PROFILE$.MODULE$; public static final DISCRIMINATOR_TYPE TYPE = DISCRIMINATOR_TYPE.TYPE$.MODULE$; public static final DISCRIMINATOR_TYPE VALUE = DISCRIMINATOR_TYPE.VALUE$.MODULE$; }
The last time I actually screamed at my television due to seriously flawed news coverage was February 2, 2012. The cause was an ABC “news” “report” on Planned Parenthood that was riddled with errors and framing flaws. The “news” story was in reaction to the Susan G. Komen foundation’s attempt to extricate itself from funding Planned Parenthood. Said annual funding was keeping pro-lifers from giving money to the foundation. Planned Parenthood went public with the news of Komen’s decision (through David Crary, a friendly reporter at The Associated Press) at the same moment it launched a savvy and expensive public relations campaign intending to make an example out of Komen. The media tsunami took over. Over at ABC News, Claire Shipman and Diane Sawyer repeatedly talked about how shocking this move was because Planned Parenthood was so awesome and did so many mammograms. A couple weeks ago, Planned Parenthood CEO Cecile Richards finally admitted what pro-lifers had been trying to get the media to stop falsely and uncritically repeating on behalf of the organization for years: Planned Parenthood doesn’t do mammograms. Not a single one. Their facilities aren’t equipped or authorized to do mammograms. The corporation’s repeated claims and insinuations that they did mammograms were fraudulent. Politically helpful, absolutely. But fraudulent. Here’s a sample from that “news” story that reads like PR spin on behalf of Planned Parenthood: That ubiquitous pink ribbon for decades uniting women in the greater good is sporting a black eye today. Thousands of women saying they will no longer support the Komen foundation or buy pink. Women like Monique Benoit who benefited from a Komen Planned Parenthood mammogram. Compare that with her testimony a few weeks ago where Richards said, “We do not have mammogram machines at our health centers and we’ve never stated that we did.” (Except she herself did, in this video.) Which brings us to this unbelievably awful CNN report by Drew Griffin that aired this week. It also made me scream because of the errors, half-truths, and deceptions that it contained in its lengthy defense of the country’s largest abortion provider. It’s so tremendously bad that I don’t actually know where to begin. 1) “The real story behind those Planned Parenthood videos” The segment, which lasts more than 11 minutes, promises to give you “the real story behind those Planned Parenthood videos.” The graphic at the beginning of the report hilariously says, “keeping them honest.” Anderson Cooper introduces the segment promising, “Now, there has been a lot of finger pointing and claims about those videos, so we put senior investigative correspondent, Drew Griffin, on the case to try to find out which side is telling the truth.” As of right now, the Center for Medical Progress has released 18 hours, 57 minutes and 19 seconds of footage from its undercover journalism investigation of Planned Parenthood’s participation in the human organ trade. Much of this was distilled into 11 shorter videos ranging from two minutes to 15 minutes in length. These videos are intensely graphic, including footage of aborted baby organs being lifted up by technicians inside Planned Parenthood clinics. It includes discussion of high-ranking Planned Parenthood officials talking about how to abort babies using “less crunchy” methods or how to alter a procedure so as to procure valuable organs from the aborted baby. It includes discussion from high-ranking Planned Parenthood officials talking about how to avoid scrutiny of the practice by the media and the government. It includes discussion of officials negotiating prices for the parts, despite claims that they only received reimbursements (which would be, of course, fixed). It includes discussion of officials talking about how to get creative with accounting. It also includes stories of callous abortionists, clinics with STAPH infections, and any number of angles that the country’s reporters should have immediately dug into. This news report doesn’t give us the real story behind anything, much less ‘those’ Planned Parenthood videos. This news report doesn’t give us the real story behind anything, much less “those” Planned Parenthood videos. It doesn’t dig into the human organ harvesting business. It doesn’t dig into anything mentioned above. It doesn’t for even a moment investigate the claims made in the videos. And it doesn’t check out any of the claims made by Planned Parenthood in defense of their practices. Instead, it spends the majority of the report pretending to be confused about how video editing works. 2) How many times can we say “edited” “edited” “edited” “edited”? When Cecile Richards gave her first interview (to longtime Clinton associate, ABC News’ George Stephanopolous) in the aftermath of the scandal breaking, I wrote about her four talking points. The first — her main talking point — was that the videos were “edited.” She said it over and over and over again. And yet she didn’t say it even a fraction as much as CNN did in this report. If the CNN report said “edited” once, it must have said it 20 times. It was the entire frame of the report. We’re going to get into how particularly stupid CNN’s obsession was on this, but we need to remember that all journalism is edited. Literally all journalism. This goes quadruple for video journalism. And unlike every other journalistic outfit around, including CNN, and including this particular report from CNN, the Center for Medical Progress has actually released the full footage of its interviews with Planned Parenthood officials. The “edited” videos run a total of nearly 2 hours while the “full” footage videos run more than 17 hours. For what it’s worth, I asked Griffin for the unedited footage of his videos with his two sources for his report. I’ll update if and when he provides them to me. In any case, back in July I wrote, “Precisely because Planned Parenthood is running so hard with this talking point, objective journalists need to make sure people know that unlike most all the things that are edited in the world, full footage is public and ready for anyone to see.” I didn’t imagine that CNN would instead take Planned Parenthood’s talking point, buy it a nice dress and some jewelry, pay to get its hair done, and throw a party for it. 3) Video editing — how does it work? For some seven minutes, which is forever in broadcast media terms, Drew Griffin pretends to be confused about how video journalism works. This is a bad look on anyone, but a really bad look on someone who makes a living as a video journalist and does literally everything his report highlights then pretends to be confused or upset when journalist David Daleiden does it. He sets aside 19 hours of footage from “those videos” we were promised to learn about in order to focus on two 10-second clips showing images of babies at the same gestational age as a baby whose brain was harvested by a human organ procurement technician inside a Planned Parenthood clinic. You can watch the full 10:37 video here (and you really should if you haven’t at this point!). But it combines clips from previous videos in the series — such as some of the statements of Planned Parenthood officials — with the claims of others in the baby organ procurement business. The centerpiece is the first-person testimony of Holly O’Donnell, a Stem Express technician who worked at Planned Parenthood clinics, explaining how a late-term baby boy was aborted and how she didn’t know if he was technically alive or not since the heart was beating. She says she harvested his brain by cutting his head open beginning at the chin. She describes how afterwards she had difficulty shoving him into a container because he was so big. She says it was the hardest experience she ever had. O’Donnell describes harvesting the boy’s body parts with her colleague: “… its nose was very pronounced, it had eyelids, and its mouth was pronounced. And then since the fetus was still intact, she said, ‘okay, well, this is a really good fetus, and it looks like we can procure a lot from it. We’re going to procure brains.’” While she’s talking about this, footage of another aborted later-term baby kicking his legs in a dish is shown. Later we see a picture of yet another boy who was born premature and died in his parents’ arms. CNN finds the most anodyne portion of the entire video and characterizes it this way: O’DONNELL: I remember holding that fetus in my hands when everybody else was busy and started crying and opened the lid and put it back in. GRIFFIN: But there is a problem, the baby Holly O’Donnell is talking about is not the baby shown in the video. The filmmaker pulled an image off the Internet. Are you kidding me? Are you kidding me? Of COURSE the baby O’Donnell just described is not the baby shown in the video. I mean, first off, why would O’Donnell have footage of herself holding a baby in an abortion clinic? I mean, who would have been snapping that shot of her holding the baby in her hands while she’s crying and they’re all busy? That would make literally no sense. Further, O’Donnell describes holding a baby whose brain and other organs she just harvested before stuffing his body in a container. The picture is of a baby whose head shows not a single sign of trauma, whose body shows no signs of trauma, and whose umbilical cord is clamped. Unless you’re confused about brain and liver harvesting, there is no way you could think this image was of a post-organ harvested baby on his way to the medical waste bin. I see no reason to pretend that we’re this stupid. We’re not this stupid. 4) Pretending to not understand B-roll Which brings us to the main idiocy of the prior point. Video journalists use B-roll to illustrate stories. They all do it. In fact, immediately after finishing the Daleiden interview, Griffin goes to B-roll! What is B-roll, you ask? Here, I’ll let, oh, dear, this is uncomfortable, but I’ll let CNN explain it to you: Make sure to have plenty of material to work with When taking video, the general rule is the more material, the better. You need to make sure to have lots of B-roll, or alternate material, in order to add dimension and secondary footage to a story. B-roll helps with cutaways and gives a much more fluid look to a package. That literally comes from a CNN explainer about how to do journalism that might get aired on CNN. In another explainer at CNN, a journalist says: “Today I’m going to teach you about B-roll. That’s jargon. A technical term we use in news, B-roll is video you see while you hear [people] talking but you don’t actually see them on camera. Then other times there may be a reporter on camera and you see video in a box off to the side of them. … this is important because you’ve heard it said that pictures are worth a thousand words. This gives you that image that is compelling.” So let’s say you’ve got a lengthy, first-person report about how the harvesting of organs from aborted babies works, and it’s an amazing coup that you got someone actually involved in the trade to speak on camera. But you want to “add dimension and secondary footage” to the story, perhaps it would be helpful to illustrate the age and gestation of the baby in question. You need an “image that is compelling.” You would, according to CNN, do exactly what CNN is now claiming is awful of Daleiden to have done. Heck, here’s a sample of CNN’s own “medical footage” B-roll! The notion that Griffin would spend some seven minutes pretending to be outraged by B-roll footage is embarrassing and inexcusable. And it would have been even if he didn’t cut away to B-roll footage of a completely unrelated Planned Parenthood clinic in Los Angeles immediately after his heavily edited Daleiden interview segment. I also note that Griffin used a stock photo when he tweeted out this very story. I mean, really. 5) Cartoonishly misdirected outrage I can’t possibly convey to you how long Griffin spends on this ridiculous pretense that (literally) 20-seconds of B-roll destroys 19 hours undercover video journalism. So, for example: GRIFFIN: The problem people are having this is not an aborted child and not the baby Holly is talking about, and that seems very — that does seem very deceptive to me. DALEIDEN: I don’t see the deception, and frankly, I think it’s kind of, I think it’s kind of a controversy drummed up by the media… By the way, the cut-away from Daleiden in the middle of the first sentence of his response is so harshly done as to be jarring. And a curious choice for people who are spending 11 minutes decrying any and all editing as problematic. The edit was so jarring that it prompted me to ask Griffin for the full footage of his interview or, at least, a transcript. We’ll see if he’s able to be as transparent as the journalist he decries. Daleiden patiently tries to explain how journalistic illustrations work, to a man pretending to be confused by them. But it gets worse: DALEIDEN: The only people that raised that criticism are first started with Planned Parenthood and their allies and some of the pro-abortion blogs, and then it migrated to some of the mainstream media outlets, but apart from that, no one else has seemed to be confused by it or deceived by it. GRIFFIN: That is not true. The confusion of David Daleiden’s sloppy edits has made its way into the Republican presidential race. FIORINA: Watch a fully formed fetus on the table. Its heart beating. Its legs kicking. GRIFFIN: In the second Republican debate, an impassioned Carly Fiorina made this attack on Planned Parenthood, citing this video clip of another baby in Daleiden’s documentary, again with Holly O’Donnell providing the narration. Uh, so what’s not true? Fiorina described a fully formed fetus on the table. Its heart beating. Its legs kicking. Want to see a picture of the leg kicking? It’s graphic but you can see a GIF here. You can and should watch the full video given how many people are talking about it without having seen it. Again, when Griffin says, “That. Is. Not. True,” what’s not true? And what’s sloppy? And what confusion? The only confusion we have here is people feigning confusion in order to avoid dealing with the horrific video where a woman describes harvesting the brain from a baby born alive after an abortion at a Planned Parenthood clinic. The idea that you’d have an eyewitness, first-person account of such a horrific thing, that you would illustrate it with a completely appropriate video, and that the media would spend 11 minutes questioning your editing? It’s a clown show. By the way, Griffin goes on to interrogate Daleiden about where this footage of the aborted baby comes from. He could have just, you know, watched the video, since it says it clear as day in the lower right-hand corner which library it comes from (and you can read what the owners of the footage have to say about it here). Griffin goes on (and on! and on!) interrogating Daleiden about this 10-second clip of a different aborted baby. It’s unbelievable. As if we can care about only one aborted baby and we can care only about that aborted baby if we both hear about how his brain was harvested and see him flailing about on a table. There are no words to describe how ridiculous and obfuscatory this standard is. DALEIDEN: Right. Right. And that’s — this specific sequence right here with Holly O’Donnell is talking about an infant that was born alive in a Planned Parenthood clinic that they then harvested the brain from. GRIFFIN: Only once again, not this baby. If there’s a Pulitzer for “missing the point,” Griffin’s in contention. 6) Failing to mention forensic analysis of videos After CNN spends seven mother-bleeping minutes on 20-seconds of B-roll from the 19 hours of footage, Griffin asks a couple of puff questions of Dawn Laguens, the woman who has been handling the other softball interviews from Planned Parenthood allies in the media: GRIFFIN: Planned Parenthood has used controversial video edits to attack the entire production as being a fraud. DAWN LAGUENS, PLANNED PARENTHOOD VP: All of the tape and footage that David Daleiden has released out into the world has been heavily edited and I think pretty thoroughly discredited. Now, if you were an objective reporter, now might be the time to push back on that talking point. Hard. The Alliance Defending Freedom commissioned a forensic analysis of the footage. The report came out weeks ago. Unlike a Planned Parenthood-financed and commissioned study that received a great deal of media coverage, this report was done not by a partisan opposition research firm but by Coalfire, a third-party digital security and forensics firm with experience providing evidence for civil and criminal investigations. Unlike the Planned Parenthood-commissioned audit, Coalfire had access to every second of released audio and video investigative footage. The Fusion report had access to only four full-length videos released on YouTube through August 4 and none of the source material. The report utterly destroyed the talking point pushed by Planned Parenthood for months: Coalfire, one of the country’s most trusted digital forensic analysis companies, released a report indicating the undercover videos recorded by the Center for Medical Progress are ‘authentic and show no evidence of manipulation.’ Forensic analysts were granted access to all of the raw investigated footage recorded by the Center for Medical Progress and checked it against the full length videos posted on the CMP YouTube account. They found the only events not depicted in the publicly available videos fell into five common categories: commuting, waiting, adjusting recording equipment, meals, and restroom breaks. All of the edited content was ‘non-pertinent’ to the actual investigation. I’m not sure a single word in Laguens statement is true. In fact, full footage has been released and none of the edits were pertinent, according to the forensic analysis. Instead of a hard pushback or even a gentle pushback, here’s what the CNN report said: GRIFFIN: Dawn Laguens is executive vice president at Planned Parenthood, and discrediting the misuse of video was easy. So after treating Daleiden like a criminal for his use of the common and ubiquitous journalistic practice of illustration, Griffin responds this way? What a joke. 7) When Planned Parenthood makes a claim, no need to check it out Just note how Griffin routinely shades the story. He claims that there are “problems” in the video that aren’t problems. Unless, again, edits are a problem or B-rolls are problems. But since he uses both of them throughout his piece, that’s not fair. He refers to Walter Fretz as stillborn, not aborted. Technically Fretz died in his parents’ arms shortly after he was born. He repeatedly asserts that Daleiden was “deceptive” and asserts that the video was not “clear” and says “that’s not true” in response to a claim Daleiden makes that actually is true. He obsesses over when and where the aborted baby in the B-roll was aborted and ignores literally 19 hours of other footage. But when it comes to Planned Parenthood, Griffin slides right into euphemisms. Except for a brief portion of an exchange with Daleiden, abortion is not mentioned. Even though those 19 hours of footage are full of Planned Parenthood executives saying grisly things about kidneys, gonads, lungs, livers, and brains, Griffin sanitizes it all into “fetal tissue samples.” And claims made by Planned Parenthood are accepted without a moment’s hesitation. Griffin repeatedly notes that Planned Parenthood says it was only reimbursed for costs but makes no effort to determine the veracity of Planned Parenthood’s claim. Is it more truthful than that claim the media parroted for years about mammograms, or less truthful? And either way, how do we know? He also repeats their claim that the human organ sales were only happening at a “tiny fraction” of Planned Parenthood clinics, but doesn’t tell us what that fraction represents, what’s considered tiny, or how we know that Planned Parenthood is accurately conveying how many clinics do it. Again, is it more truthful than that claim about mammograms that they ran with for years or less truthful? Same level of truth? Since when do journalists not attempt to check out claims? The idea that we’d spend seven minutes litigating whether B-roll is acceptable — in a report that uses B-roll — and give Planned Parenthood a pass on all the organ harvesting is a perfect demonstration of how awful our media have been in covering this story.
<reponame>rollends/SE499<filename>simulator/include/rose499/sylvester.hpp #ifndef ROSE499_SYLVESTERCONTROL_HPP #define ROSE499_SYLVESTERCONTROL_HPP #include <Eigen/Core> #include "rose499/diffdrive.hpp" #include "rose499/spline.hpp" struct SylvesterController : public DriveController { SylvesterController(DriveSystem&, Eigen::Matrix<ValueType, 2, 1> goal, ValueType goalRadius); virtual DriveController::ValueType genTurnControl(DriveController::StateType x, double t) override; Eigen::Matrix<DriveController::ValueType, 2, 1> const & linearizedState() const; protected: std::ostream& printSpecificHeaders(std::ostream& s) const override; std::ostream& printSpecificData(std::ostream& s) const override; private: Eigen::Matrix<DriveController::ValueType, 2, 1> mXi; }; Eigen::Matrix<SimulatorTypes::ValueType, 2, 2> quinticHessian( SimulatorTypes::ValueType A1, SimulatorTypes::ValueType A2, SimulatorTypes::ValueType A3, SimulatorTypes::ValueType A4, SimulatorTypes::ValueType A5, SimulatorTypes::ValueType A6, SimulatorTypes::ValueType B1, SimulatorTypes::ValueType B2, SimulatorTypes::ValueType B3, SimulatorTypes::ValueType B4, SimulatorTypes::ValueType B5, SimulatorTypes::ValueType B6, SimulatorTypes::ValueType x1, SimulatorTypes::ValueType x2 ); Eigen::Matrix<SimulatorTypes::ValueType, 1, 2> quinticJacobian( SimulatorTypes::ValueType A1, SimulatorTypes::ValueType A2, SimulatorTypes::ValueType A3, SimulatorTypes::ValueType A4, SimulatorTypes::ValueType A5, SimulatorTypes::ValueType A6, SimulatorTypes::ValueType B1, SimulatorTypes::ValueType B2, SimulatorTypes::ValueType B3, SimulatorTypes::ValueType B4, SimulatorTypes::ValueType B5, SimulatorTypes::ValueType B6, SimulatorTypes::ValueType x1, SimulatorTypes::ValueType x2 ); SimulatorTypes::ValueType quinticLevelSet( SimulatorTypes::ValueType A1, SimulatorTypes::ValueType A2, SimulatorTypes::ValueType A3, SimulatorTypes::ValueType A4, SimulatorTypes::ValueType A5, SimulatorTypes::ValueType A6, SimulatorTypes::ValueType B1, SimulatorTypes::ValueType B2, SimulatorTypes::ValueType B3, SimulatorTypes::ValueType B4, SimulatorTypes::ValueType B5, SimulatorTypes::ValueType B6, SimulatorTypes::ValueType x1, SimulatorTypes::ValueType x2 ); #endif
package com.cloudibpm.blo.om.user; import com.alibaba.fastjson.JSON; import com.aliyuncs.exceptions.ClientException; import com.cloudibpm.blo.buildtime.id.BuildtimeIDGenerator; import com.cloudibpm.blo.message.AliyunMessageBlo; import com.cloudibpm.core.authorization.AuthorityGroup; import com.cloudibpm.core.code.StatusCode; import com.cloudibpm.core.organization.Organization; import com.cloudibpm.core.repository.BusinessLogicObject; import com.cloudibpm.core.user.Login; import com.cloudibpm.core.user.User; import com.cloudibpm.core.user.UserLoginHistory; import com.cloudibpm.core.util.DateUtility; import com.cloudibpm.core.util.VerifyCode; import com.cloudibpm.core.util.encode.MD5Util; import com.cloudibpm.core.util.serviceresult.ServiceResult; import com.cloudibpm.eso.om.authorization.AutorityGroupEso; import com.cloudibpm.eso.om.organization.WfOrganizationEso; import com.cloudibpm.eso.om.user.WfGroupMemberEso; import com.cloudibpm.eso.om.user.WfStaffEso; import com.cloudibpm.eso.om.user.WfUserEso; import com.cloudibpm.redis.RedisUtil; import com.model.Contact; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.*; import java.util.concurrent.TimeUnit; @Service //@Transactional public class WfUserBlo extends BusinessLogicObject { private final WfOrganizationEso wfOrganizationEso; private final WfUserEso wfUserEso; private final WfStaffBlo wfStaffBlo; private final WfStaffEso wfStaffEso; private final WfGroupMemberEso wfGroupMemberEso; private final AutorityGroupEso autorityGroupEso; private final BuildtimeIDGenerator buildtimeIDGenerator; private final WfLoginHistoryBlo wfLoginHistoryBlo; private final RedisUtil redisUtil; private final AliyunMessageBlo aliyunMessageBlo; @Autowired public WfUserBlo(WfOrganizationEso wfOrganizationEso, WfUserEso wfUserEso, WfStaffBlo wfStaffBlo, WfStaffEso wfStaffEso, WfGroupMemberEso wfGroupMemberEso, AutorityGroupEso autorityGroupEso, BuildtimeIDGenerator buildtimeIDGenerator, WfLoginHistoryBlo wfLoginHistoryBlo, RedisUtil redisUtil, AliyunMessageBlo aliyunMessageBlo) { this.wfOrganizationEso = wfOrganizationEso; this.wfUserEso = wfUserEso; this.wfStaffBlo = wfStaffBlo; this.wfStaffEso = wfStaffEso; this.wfGroupMemberEso = wfGroupMemberEso; this.autorityGroupEso = autorityGroupEso; this.buildtimeIDGenerator = buildtimeIDGenerator; this.wfLoginHistoryBlo = wfLoginHistoryBlo; this.redisUtil = redisUtil; this.aliyunMessageBlo = aliyunMessageBlo; } /** * Add new workflow user. * * @param user * @return */ public int createNewUser(User user) throws Exception { return wfUserEso.insert(user); } public int updateUser(User user) throws Exception { return wfUserEso.update(user); } public void updateUserLoginCounting(String userid) throws Exception { wfUserEso.updateLoginCounting(userid); } //根据用户名查询用户 public User getUserByUserName(String username) throws Exception { return wfUserEso.queryByUserName(username); } //根据用户名查询用户 public User getUserByMobile(String username) throws Exception { return wfUserEso.queryUserByMobile(username); } public Login checkUserName(String username, String password) throws Exception { User usr = wfUserEso.queryUsername(username); if (usr == null) { // 0: user does not exist return new Login(0, null, null); // user name does't exists } else if (usr.getIsBanned() == 1) { // -10: user has been banned return new Login(-10, usr, null); } else if (!password.equals(usr.getPasswd())) { // -1: password is incorrect return new Login(-1, usr, null); } else if (usr.getPasswdExpirationDate() != null && usr.getPasswdExpirationDate().getTime() < Calendar.getInstance().getTimeInMillis()) { // -9: password expired return new Login(-9, usr, null); } else { usr.setPasswd(null);// clean password to protect password. return new Login(1, usr, null); // successful } } public Login checkMobile(String mobile) throws Exception { User usr = wfUserEso.queryMobile(mobile); if (usr == null) { // 0: user does not exist return new Login(0, null, null); // user name does't exists } else if (usr.getIsBanned() == 1) { // -10: user has been banned return new Login(-10, usr, null); } else if (usr.getPasswdExpirationDate() != null && usr.getPasswdExpirationDate().getTime() < Calendar.getInstance().getTimeInMillis()) { // -9: password expired return new Login(-9, usr, null); } else { usr.setPasswd(<PASSWORD>);// clean password to protect password. return new Login(1, usr, null); // successful } } public void importNormalStaff(ArrayList<String> list) throws Exception { ArrayList<String> userlist = new ArrayList<String>(); ArrayList<String> stafflist = new ArrayList<String>();// 已有useid的staff列表 ArrayList<String> stafflist2 = new ArrayList<String>();// 表里没有的useid的staff列表 ArrayList<String> staffResultList = new ArrayList<String>(); ArrayList<String> repeatUserlist = new ArrayList<String>(); ArrayList<String> repeatUserOrglist = new ArrayList<String>(); ArrayList<String> idNumberList = new ArrayList<String>(); Map<String, String> companyMap = new LinkedHashMap<>(); Map<String, String> companyAuthorityMap = new LinkedHashMap<>(); Map<String, String> repeatIdNumberMap = new LinkedHashMap<>(); Map<String, String> repeatUserIdMap = new LinkedHashMap<>(); Map<String, String> userCompanyRelationship = new LinkedHashMap<>(); java.sql.Date date = new java.sql.Date(System.currentTimeMillis()); // 存储员工公司对应关系 for (int i = 0; i < list.size(); i = i + 14) { userCompanyRelationship.put(list.get(i + 4), list.get(i)); } // idNumber查重 for (int i = 0; i < list.size(); i = i + 14) { idNumberList.add(list.get(i + 4)); } // 查询已存在user ArrayList<String> idNumberResultList = wfUserEso.queryInIdNumber(idNumberList);// 返回了idnumber和userid if (idNumberResultList != null && idNumberResultList.size() > 0) { for (int i = 0; i < idNumberResultList.size(); i = i + 2) { repeatIdNumberMap.put(idNumberResultList.get(i), idNumberResultList.get(i + 1)); } } // 公司查询 for (int i = 0; i < list.size(); i = i + 14) { companyMap.put(list.get(i), null); companyAuthorityMap.put(list.get(i), null); } for (java.util.Map.Entry<String, String> entry : companyMap.entrySet()) { // 将原来MAP的VALUE放入新的MAP的VALUE里面 Organization organization = wfOrganizationEso.queryByNameLocal(entry.getKey()); if (organization != null) { companyMap.put(entry.getKey(), organization.getId()); // 查找公司权限组 AuthorityGroup group = autorityGroupEso.queryByOwner(organization.getId()); companyAuthorityMap.put(entry.getKey(), group.getId()); } } // 把重复user对应的userid和orgId插入stafflist和stafforglist if (idNumberResultList != null && idNumberResultList.size() > 0) { for (int i = 0; i < idNumberResultList.size(); i = i + 2) { if (companyMap.get(userCompanyRelationship.get(idNumberResultList.get(i))) != null) { repeatUserlist.add(idNumberResultList.get(i + 1)); } } for (int i = 0; i < idNumberResultList.size(); i = i + 2) { if (companyMap.get(userCompanyRelationship.get(idNumberResultList.get(i))) != null) { repeatUserOrglist.add(companyMap.get(userCompanyRelationship.get(idNumberResultList.get(i)))); } } } // 查询重复user在公司有无staff,没有则批量插入 if (repeatUserlist.size() > 0) { staffResultList = wfStaffEso.queryInUserId(repeatUserlist, repeatUserOrglist);// 返回了staffid、userid、orgid } if (staffResultList != null && staffResultList.size() > 0) { for (int i = 0; i < staffResultList.size(); i = i + 3) { repeatUserIdMap.put(staffResultList.get(i + 1), staffResultList.get(i + 2)); } } if (idNumberResultList != null && idNumberResultList.size() > 0) { for (int i = 0; i < idNumberResultList.size(); i = i + 2) { if (repeatUserIdMap.get(idNumberResultList.get(i + 1)) == null) { stafflist.add(buildtimeIDGenerator.getNewBuildTimeID()); stafflist.add(idNumberResultList.get(i + 1)); // useid stafflist.add(companyMap.get(userCompanyRelationship.get(idNumberResultList.get(i)))); // orgid stafflist.add(companyAuthorityMap.get(userCompanyRelationship.get(idNumberResultList.get(i)))); // 权限组id } } } if (stafflist.size() > 0) { wfStaffEso.updateBatchStaff(stafflist, date);// 返回一个userid和idnumber列表,进行批量插入staff和权限组 wfGroupMemberEso.updateBatchAuthorityGroup(stafflist); } // 开始批量插入不存在的user for (int i = 0; i < list.size(); i = i + 14) { if (companyMap.get(list.get(i)) != null && repeatIdNumberMap.get(list.get(i + 4)) == null) { userlist.add(buildtimeIDGenerator.getNewBuildTimeID());// Pk_User userlist.add(list.get(i + 4));// UserName 2 1 userlist.add("<PASSWORD>");// Passwd 3 2 String name = list.get(i + 1); String xing = name.substring(0, 1); String ming = name.substring(1, name.length()); userlist.add(ming);// FirstName 5 3 userlist.add(xing);// LastName 6 4 if (list.get(i + 2).equals("女")) { userlist.add("W");// Gender 7 5 } else { userlist.add("M");// Gender 7 5 } if (list.get(i + 4).length() != 18) { userlist.add("1");// IdType 9 6 } else { userlist.add("0");// IdType 9 6 } userlist.add(list.get(i + 4));// IdNumber 10 7 userlist.add(list.get(i + 6));// Address 15 8 userlist.add(list.get(i + 8));// Mobile 19 9 userlist.add(list.get(i + 3));// Nation 21 10 userlist.add(list.get(i + 7));// HouseholdAddress 22 11 userlist.add(companyMap.get(list.get(i)));// HouseholdAddress 22 // 11 } } if (userlist.size() > 0) { wfUserEso.updateBatchUser(userlist, date); // 开始批量插入staff for (int i = 0; i < userlist.size(); i = i + 13) { stafflist2.add(buildtimeIDGenerator.getNewBuildTimeID()); stafflist2.add(userlist.get(i)); // useid stafflist2.add(companyMap.get(userCompanyRelationship.get(userlist.get(i + 1)))); // orgid stafflist2.add(companyAuthorityMap.get(userCompanyRelationship.get(userlist.get(i + 1)))); // 权限组id } } if (stafflist2.size() > 0) { wfStaffEso.updateBatchStaff(stafflist2, date);// 返回一个userid和idnumber列表,进行批量插入staff和权限组 wfGroupMemberEso.updateBatchAuthorityGroup(stafflist2); } } public int checkUserNameandEmail(String username, String email) throws Exception { if (wfUserEso.existsUsername(username)) { User user = wfUserEso.queryByUsername(username); if (user.getEmail() != null) { if (user.getEmail().equals(email)) { return 1; // correct } else { return -6; // -6: email is not correct } } else { return -6; // -6: email is not correct } } return 0; // user does't exist; } public void updatePasswordUserName(String username, String password) throws Exception { wfUserEso.updatePassword(username, password); } public int updatePasswordMobile(String mobile, String password) throws Exception { return wfUserEso.updatePasswordByMobile(mobile, password); } public boolean existsUsername(String username) throws Exception { return wfUserEso.existsUsername(username); } public boolean existsEmail(String email) throws SQLException { return wfUserEso.existsEmail(email); } public boolean existsMobile(String mobile) throws SQLException { return wfUserEso.existsMobile(mobile); } public boolean existsidNumber(String idNumber) throws SQLException { return wfUserEso.existsidNumber(idNumber); } /** * Get a cloud BPM user according to ID. * * @param id * @return * @throws SQLException */ public User getUserByID(String id) throws Exception { return wfUserEso.queryByPKnoPW(id); } public User getUserByIDNumber(String idnumber) throws Exception { return wfUserEso.queryByIdNumber(idnumber); } /** * 根据用户ID查询用户 * * @param ids * @return * @throws SQLException */ public List<User> getAllUserById(List<String> ids) throws SQLException { List<User> userList = null; for (String id : ids) { userList.add(wfUserEso.queryByPK(id)); } return userList; } // public User[] getNotInGroupUsers(User[] users, Group group) // throws Exception { // List<User> notingroup = new ArrayList<User>(); // List<User> allUsers = getAllOrganizationUsers(); // for (User user : allUsers) { // // belong to same owner // boolean found = false; // if (user.getOwner().getId().equals((group).getOwner().getId())) { // for (User usr : users) { // WorkflowEntity entity = usr; // if (entity.getId().equals(user.getId())) { // found = true; // } // } // if (!found) // notingroup.add(user); // } // } // User[] notingroupUsers = new User[notingroup.size()]; // for (int i = 0; i < notingroup.size(); i++) { // notingroupUsers[i] = (User) notingroup.get(i); // } // return notingroupUsers; // } /** * Get a workflow user according to user code. * * @param id * @return */ // public User getUserByCode(String code) throws Exception { // WfUserEso userEso = new WfUserEso(); // WfUserRo userRo = (WfUserRo) userEso.queryByCode(code); // if (userRo != null) { // return (User) userRo.getEntity(); // } // return null; // } /** * Gets all workflow users in all organizatons in current repository; * * @return * @throws SQLException */ // public List<User> getAllOrganizationUsers() throws Exception { // // List<User> users = new ArrayList<User>(); // List<RecordObject> userRos = wfUserEso.queryAll(); // for (RecordObject userRo : userRos) { // users.add((User) userRo.getEntity()); // } // return users; // } /** * 该方法查询出来用户选择对话框的左边列表中所有用户。 * * @param in * 任务中所有的参与者的ID列表。 * @return * @throws SQLException */ // public User[] getAllOrganizationUsersNotIn(Object[] in) throws Exception // { // // List<User> users = new ArrayList<User>(); // List<RecordObject> userRos = wfUserEso.queryAll(); // if (in != null && in.length > 0) { // for (RecordObject userRo : userRos) { // boolean found = false; // for (int i = 0; i < in.length; i++) { // if (in[i].equals(userRo.getPrimaryKey())) { // found = true; // break; // } // } // if (!found) // users.add((User) userRo.getEntity()); // } // } else { // for (RecordObject userRo : userRos) { // users.add((User) userRo.getEntity()); // } // } // User[] selectedUsers = new User[users.size()]; // for (int i = 0; i < users.size(); i++) { // selectedUsers[i] = (User) users.get(i); // } // return selectedUsers; // } /** * 该方法查询出来用户选择对话框的右边列表中所有用户。 * * @param in * 任务中所有的参与者的ID列表。 * @return * @throws SQLException */ // public User[] getAllOrganizationUsersIn(Object[] in) throws Exception { // List<User> users = getOrganizationUsersIn(in); // User[] selectedUsers = new User[users.size()]; // for (int i = 0; i < users.size(); i++) { // selectedUsers[i] = (User) users.get(i); // } // return selectedUsers; // } /** * 获取公司用户 * * @param in * @return * @throws SQLException */ // public List<User> getOrganizationUsersIn(Object[] in) throws Exception { // // List<User> users = new ArrayList<User>(); // if (in != null && in.length > 0) { // for (int i = 0; i < in.length; i++) { // RecordObject userRo = wfUserEso.queryByPK(in[i].toString()); // if (userRo != null) // users.add((User) userRo.getEntity()); // } // } // return users; // } // // public List<User> getOrganizationUsers(Object[] in, Organization org) // throws Exception { // // List<User> users = new ArrayList<User>(); // List<RecordObject> userRos = wfUserEso.queryAll(org.getId()); // for (RecordObject userRo : userRos) { // if (in != null && in.length > 0) { // for (int i = 0; i < in.length; i++) { // if (!in[i].equals(userRo.getPrimaryKey())) // users.add((User) userRo.getEntity()); // } // } else // users.add((User) userRo.getEntity()); // } // return users; // } /** * Delete an unused user according to user database primary key. * * @param id * String */ // public void deleteUserByID(String id) throws Exception { // // 先从列表中把该用户删除。 // WfContactEso cESO = new WfContactEso(); // cESO.delete(id); // // wfUserEso.delete(id); // } /** * Modify workflow user information * * @param user */ // public void modifyUser(User user) throws Exception { // // 此处要对列表中的同一个ID的用户对象进行重新赋值。并通知更新到数据库中。 // // WfUserRo uRO = new WfUserRo(); // uRO.setRecordObject(user); // wfUserEso.update(uRO); // // delete all old contacts and save all new contacts for user // WfContactEso cESO = new WfContactEso(); // cESO.delete(user.getId()); // saveContact(user.getContacts(), user); // } /** * save all contacts of user. * * @param list * @param usr */ // private void saveContact(ContactList list, User usr) throws Exception { // if (list.size() > 0) { // for (int i = 0; i < list.size(); i++) { // Contact contact = list.get(i); // contact.setOwner(usr); // WfContactRo cRO = new WfContactRo(); // cRO.setRecordObject(contact); // WfContactEso cESO = new WfContactEso(); // cESO.insert(cRO); // } // } // } /** * Return true if the specified user code has existed. * * @param code * @return * @throws SQLException */ // public boolean codeExisted(String code) throws Exception { // // return wfUserEso.queryCode(code); // } /** * Get page count of all records of workflow users. * * @param pagesize * @return */ // private int getPageCount(int pagesize, List<User> users) { // int count = users.size(); // int p = count / pagesize; // int r = count % pagesize; // int pagecount = 0; // if (r == 0) // pagecount = p; // else // pagecount = p + 1; // return pagecount; // } /** * Gets workflow user list of current page. The condition firstly filters * out available users according to organization <code>owner</code>, if * <code>owner</code> is not null, and return users of No * <code>currentpage</code> page according to the specified * <code>pagesize</code>. * * @param pagesize * @param currentpage * @param condition * @param owner * @return * @throws Exception */ // public Page getCurrentPageUsers(int pagesize, int currentpage, // String condition, String ownerId) throws Exception { // Page currentPage = new Page(); // List<User> allPagesUsersList = getUsersByCondition(condition, ownerId); // currentPage.setCurrentPageNumber(currentpage); // currentPage.setPageCount(getPageCount(pagesize, allPagesUsersList)); // currentPage.setCurrentPageEntities(filterCurrentPageUsers( // allPagesUsersList, pagesize, currentpage)); // return currentPage; // } // // private static User[] filterCurrentPageUsers(List<User> users, // int pagesize, int currentpage) { // List<User> userList = new ArrayList<User>(); // int start = (currentpage - 1) * pagesize; // int end = currentpage * pagesize; // for (int i = start; i < end; i++) { // if (i <= users.size() - 1) { // userList.add(users.get(i)); // } // } // if (userList.size() > 0) { // User[] wfusers = new User[userList.size()]; // for (int i = 0; i < wfusers.length; i++) { // wfusers[i] = (User) userList.get(i); // } // return wfusers; // } // return null; // } // // private List<User> getUsersByCondition(String condition, String ownerId) // throws Exception { // List<User> userList = new ArrayList<User>(); // List<User> allUsers = getAllOrganizationUsers(); // for (User user : allUsers) { // if (ownerId != null && !user.getOwner().getId().equals(ownerId)) // continue; // if (condition != null && !condition.equals("")) { // if (user.getUserCode().indexOf(condition) > 0 // || user.getFullName().indexOf(condition) > 0 // || user.getName().indexOf(condition) > 0) { // userList.add(user); // } // } else { // userList.add(user); // } // } // return userList; // } /** * Update user password policy. * * @param usr * @throws SQLException */ // public void modifyPasswordPolicy(User usr) throws Exception { // // WfUserRo uRO = new WfUserRo(); // uRO.setPrimaryKey(usr.getId()); // // uRO.setCanModifyPassword(<PASSWORD>()); // // uRO.setRememberPassword(<PASSWORD>()); // // uRO.setMustModifyPassword(<PASSWORD>()); // wfUserEso.updatePasswordPolicy(uRO); // } /** * check user is banned * * @param userid * @return * @throws Exception */ public int checkStatus(String userid) throws Exception { int result = 1;// 1: success; // check organization status; // check user status; User usr = wfUserEso.queryByPK(userid); if (usr == null) { // 0: user does not exist return StatusCode.USER_NOT_EXISTS; // user name does't exists } else if (usr.getIsBanned() == 1) { // -10: user has been banned return StatusCode.BANNED; } return result; } /** * @param username * @param sessiondata * @param password * @param token * @param details * @param loginType 判断登录方使,0:用户名密码登录, 1:手机验证码登录 * @return * @throws Exception */ public ServiceResult authenticate(String username, String sessiondata, String password, String token, String[] details, int loginType) throws Exception { Login login = null; String sessionId = null; ServiceResult serviceResult = null; if (check(username, sessiondata, password, token)) { // return Logged in Staff or -10, -9, -1, 0, or 1; if (loginType == 0) { login = this.checkUserName(username, password); } else { login = this.checkMobile(username); } if (login.getUser() != null) { // return Logged in Staff login = wfStaffBlo.getStaffShips(login); } else { login = new Login(StatusCode.PASSWORD_INCORRECT, null, null); } } else { // -4: invalid login (might be hacker login); //ServiceResult<?, Integer> e2 = ServiceResult.error(1, "error")); login = new Login(StatusCode.INVALID_LOGIN, null, null); serviceResult = ServiceResult.error(StatusCode.INVALID_LOGIN, "登录校验失败!"); } // 1: success // 0: user does not exist // -1: password is incorrect // -6: email is not correct // -9: password expired // -10: user has been banned if (login.getStatusCode() == StatusCode.BANNED || login.getStatusCode() == StatusCode.NOT_A_STAFF || login.getStatusCode() == StatusCode.NO_AUTHORIZATION || login.getStatusCode() == StatusCode.INVALID_LOGIN || login.getStatusCode() == StatusCode.PASSWORD_INCORRECT || login.getStatusCode() == StatusCode.SUCCESS) { UserLoginHistory history = new UserLoginHistory(); history.setId(buildtimeIDGenerator.getNewRunTimeID()); if (login.getUser() != null) history.setFk_User(login.getUser().getId()); history.setLastLoginTime(new Date()); history.setStatusCode(login.getStatusCode()); history.setDevice(details[0]); history.setDeviceType(details[1]); history.setDeviceManufacturer(details[2]); history.setOs(details[3]); history.setOsType(details[4]); history.setOsManufacturer(details[5]); history.setBrowser(details[6]); history.setBrowserType(details[7]); history.setBrowserVersion(details[8]); history.setBrowserManufacturer(details[9]); history.setIPv4(details[10]); history.setIPv6(details[11]); history.setCountry(details[12]); history.setProvince(details[13]); history.setCity(details[14]); history.setTown(details[15]); history.setSessionId(details[16]); if (login.getStatusCode() == StatusCode.SUCCESS) { String id = login.getUser().getId(); // sessionId = MD5Util.getMD5(username + id + DateUtility.getCurrentDate()); User user = login.getUser(); if (StringUtils.isBlank(user.getFullName())) { String userdName = user.getUsedName(); if (StringUtils.isNotBlank(userdName)) { user.setSurname(userdName.substring(0, 1)); user.setGivenname(userdName.substring(1)); } } sessionId = MD5Util.getMD5(username + id); redisUtil.set("SESSION_" + sessionId, JSON.toJSONString(login)); redisUtil.expire("SESSION_" + sessionId, 7200, TimeUnit.SECONDS); this.updateUserLoginCounting(login.getUser().getId()); history.setLoginDescription(StringEscapeUtils.escapeJava(username + "登录成功")); Map<String, Object> map = new HashMap<>(); map.put("sessionId", "SESSION_" + sessionId); map.put("login", login); map.put("expire", System.currentTimeMillis() + 7200000); serviceResult = ServiceResult.success(map); } else if (login.getStatusCode() == StatusCode.PASSWORD_INCORRECT) { history.setLoginDescription(StringEscapeUtils.escapeJava(username + "尝试登录,但密码不正确")); serviceResult = ServiceResult.error(StatusCode.PASSWORD_INCORRECT, "尝试登录,但密码不正确"); } else if (login.getStatusCode() == StatusCode.INVALID_LOGIN) { history.setLoginDescription(StringEscapeUtils.escapeJava(username + "无效登录,可能是黑客在尝试登录")); serviceResult = ServiceResult.error(StatusCode.INVALID_LOGIN, "无效登录,可能是黑客在尝试登录"); } else if (login.getStatusCode() == StatusCode.PASSWORD_ERROR) { history.setLoginDescription(StringEscapeUtils.escapeJava(username + "密码已经过期,请重新设置密码")); serviceResult = ServiceResult.error(StatusCode.PASSWORD_ERROR, "密码已经过期,请重新设置密码"); } else if (login.getStatusCode() == StatusCode.BANNED) { history.setLoginDescription(StringEscapeUtils.escapeJava(username + "无效登录,该账号已经被永久封禁")); serviceResult = ServiceResult.error(StatusCode.BANNED, "无效登录,该账号已经被永久封禁"); } wfLoginHistoryBlo.createLoginHistory(history); } return serviceResult; } private boolean check(String username, String sessiondata, String password, String token) { String sessiondata1 = MD5Util.getMD5(token + username + "cloudbpm" + password + DateUtility.getCurrentDate()); if (sessiondata1.equals(sessiondata)) { return true; } return false; } public List<Contact> getAllUserByOrgId(String orgId, String userId) throws Exception { return wfUserEso.getAllUserByOrgId(orgId, userId); } public List<Contact> getUsersWithoutOwner(String userId) throws Exception { return wfUserEso.getUsersWithoutOwner(userId); } /** * 发送验证码 * * @param phoneNumber * @return * @throws ClientException */ public String sendCode(String phoneNumber) throws ClientException { String code = VerifyCode.getVerifyCode(6);//生成6位随机码 aliyunMessageBlo.sendSms(phoneNumber, code); String key = "codePhone_" + phoneNumber; redisUtil.set(key, code); redisUtil.expire(key, 5, TimeUnit.MINUTES); return "true"; } /** * 重新发送验证码 * * @param phoneNumber * @return * @throws ClientException */ public ServiceResult reSendCode(String phoneNumber) throws ClientException { String key = "codePhone_" + phoneNumber; String code = redisUtil.get(key); if (!StringUtils.isBlank(code)) { aliyunMessageBlo.sendSms(phoneNumber, code); } else { code = VerifyCode.getVerifyCode(6);//生成6位随机码 aliyunMessageBlo.sendSms(phoneNumber, code); redisUtil.set(key, code); redisUtil.expire(key, 5, TimeUnit.MINUTES); } return ServiceResult.success(); } /** * 校验验证码,成功返回login信息以及sessionID,错误返回错误码 * * @param phoneNumber * @param code * @return */ public String checkCode(String phoneNumber, String code) throws Exception { Map<String, Object> resultMap = new HashMap<>(); String key = "codePhone_" + phoneNumber; String redisCode = redisUtil.get(key); if (StringUtils.isBlank(redisCode)) {//验证码已过期 resultMap.put("status", "0"); return JSON.toJSONString(resultMap); } if (StringUtils.isBlank(code)) {//验证码不得为空 resultMap.put("status", "1"); return JSON.toJSONString(resultMap); } if (!StringUtils.equals(code, redisCode)) {//验证失败 resultMap.put("status", "2"); return JSON.toJSONString(resultMap); } //处理验证成功情况 Login login = this.checkMobile(phoneNumber); if (login.getStatusCode() == 0) {//没有这个用户 resultMap.put("status", "3"); return JSON.toJSONString(resultMap); // User user = new User(); // try { // user.setId(buildtimeIDGenerator.getNewBuildTimeID()); // } catch (Exception e1) { // e1.printStackTrace(); // } // user.setName(phoneNumber); // user.setGivenname(""); // user.setSurname(""); // user.setEmail(" "); // user.setPasswd(<PASSWORD>Util.get<PASSWORD>("<PASSWORD>")); // user.setMobile(phoneNumber); // user.setRegistrationDate(new Date()); // user.setLastupdate(new Date()); // this.createNewUser(user); // login.setUser(user); // login = wfStaffBlo.getStaffShips(login); // String id = login.getUser().getId(); // String sessionId = MD5Util.getMD5(phoneNumber + id); // redisUtil.set("SESSION_" + sessionId, JSON.toJSONString(login)); // redisUtil.expire("SESSION_" + sessionId, 7200, TimeUnit.SECONDS); // resultMap.put("status", "3"); // resultMap.put("sessionId", "SESSION_" + sessionId); // resultMap.put("login", login); // resultMap.put("expire", System.currentTimeMillis() + 7200000); // return JSON.toJSONString(resultMap); } login = wfStaffBlo.getStaffShips(login); String id = login.getUser().getId(); String sessionId = MD5Util.getMD5(phoneNumber + id); redisUtil.set("SESSION_" + sessionId, JSON.toJSONString(login)); redisUtil.expire("SESSION_" + sessionId, 7200, TimeUnit.SECONDS); resultMap.put("status", "4"); resultMap.put("sessionId", sessionId); resultMap.put("login", login); resultMap.put("expire", System.currentTimeMillis() + 7200000); return JSON.toJSONString(resultMap); } public String updateUsedName(String userId, String name) throws SQLException { User user=wfUserEso.queryByPK(userId); if(StringUtils.isBlank(user.getFullName())){ wfUserEso.updateName(userId, name); } wfUserEso.updateUsedName(userId, name); return "true"; } /** * 浏览器验证码注册 * * @param phoneNumber 手机号 * @param code 验证码 * @return */ public ServiceResult registerUserByCodeForPC(String phoneNumber, String code) throws Exception { String key = "codePhone_" + phoneNumber; String redisCode = redisUtil.get(key); Map<String, Object> resultMap = new HashMap<>(); if (StringUtils.isBlank(redisCode)) {//验证码已过期 return ServiceResult.error(1001, "验证码已过期!"); } if (StringUtils.isBlank(code)) {//验证码不得为空 return ServiceResult.error(1002, "验证码不得为空!"); } if (!StringUtils.equals(code, redisCode)) {//验证失败 return ServiceResult.error(1003, "验证码输入错误,请重试!"); } Login login = this.checkMobile(phoneNumber); if (login.getStatusCode() == 0) {//没有这个用户 User user = new User(); try { user.setId(buildtimeIDGenerator.getNewBuildTimeID()); } catch (Exception e1) { e1.printStackTrace(); } user.setName(phoneNumber); user.setGivenname(""); user.setSurname(""); user.setEmail(""); user.setUsedName(generateName()); user.setGivenname(user.getUsedName().substring(1)); user.setSurname(user.getUsedName().substring(0,1)); user.setPasswd(<PASSWORD>("<PASSWORD>")); user.setMobile(phoneNumber); user.setRegistrationDate(new Date()); user.setLastupdate(new Date()); this.createNewUser(user); login.setUser(user); login = wfStaffBlo.getStaffShips(login); String id = login.getUser().getId(); String sessionId = MD5Util.getMD5(phoneNumber + id); redisUtil.set("SESSION_" + sessionId, JSON.toJSONString(login)); redisUtil.expire("SESSION_" + sessionId, 7200, TimeUnit.SECONDS); resultMap.put("status", "new"); resultMap.put("sessionId", "SESSION_" + sessionId); resultMap.put("login", login); } else {// return ServiceResult.error(1004, "您已经是轩琦云会员了,请勿重复注册!"); } return ServiceResult.success(resultMap); } public ServiceResult refreshSession(String userName, String sessionId) throws Exception { if (StringUtils.isNotBlank(sessionId)) { String session = redisUtil.get(sessionId); if (StringUtils.isNotBlank(session)) { redisUtil.expire(sessionId, 2, TimeUnit.HOURS); Map<String, Long> map = new HashMap<>(); map.put("expire", System.currentTimeMillis() + 7200000); return ServiceResult.success(map); } } Map<String, Object> resultMap = new HashMap<>(); User usr = wfUserEso.queryUsername(userName); Login login = new Login(1, usr, null); login = wfStaffBlo.getStaffShips(login); String userId = usr.getId(); sessionId = MD5Util.getMD5(userName + userId); redisUtil.set("SESSION_" + sessionId, JSON.toJSONString(login)); redisUtil.expire("SESSION_" + sessionId, 7200, TimeUnit.SECONDS); resultMap.put("expire", System.currentTimeMillis() + 7200000); resultMap.put("sessionId", "SESSION_" + sessionId); resultMap.put("login", login); return ServiceResult.success(resultMap); } public ServiceResult registerUser(String code,String phoneNumber,String name,String orgId,String password) throws Exception { if(StringUtils.isBlank(code)){ return ServiceResult.error(1001,"验证码不得为空"); } if(StringUtils.isBlank(phoneNumber)){ return ServiceResult.error(1002,"手机号不得为空"); } if(StringUtils.isBlank(name)){ return ServiceResult.error(1003,"昵称不得为空"); } String key = "codePhone_" + phoneNumber; String redisCode = redisUtil.get(key); if(!StringUtils.equals(code, redisCode)){ return ServiceResult.error(1004,"验证码校验失败"); } Login login = this.checkMobile(phoneNumber); if(login.getStatusCode()!=0){ return ServiceResult.error(1005,"该手机号已经注册,请勿重复注册"); } User user = new User(); try { String userId = buildtimeIDGenerator.getNewBuildTimeID(); user.setId(userId); } catch (Exception e1) { e1.printStackTrace(); } Organization organization=null; if(StringUtils.isNotBlank(orgId)){ organization = wfOrganizationEso.queryByPK(orgId); if(organization==null){ return ServiceResult.error(1005,"该组织不存在"); } } user.setName(phoneNumber); user.setGivenname(""); user.setSurname(""); user.setEmail(" "); user.setUsedName(name); user.setPasswd(password); user.setMobile(phoneNumber); user.setRegistrationDate(new Date()); user.setLastupdate(new Date()); this.createNewUser(user); if(organization!=null){ wfStaffBlo.createStaff(user,organization); } return ServiceResult.success(); } private String generateName() { Random random = new Random(); StringBuilder name = new StringBuilder("匿名用户_"); for (int i = 0; i < 4; i++) { int i1 = random.nextInt(9);//生成随机数字 name.append(i1); } return name.toString(); } }
A rubber seal material is extensively used as a general seal material that can easily ensure a sealing property by a low tightening force. For instance, a rubber seal material is used as a seal material for a semiconductor manufacturing apparatus or a gate valve for vacuum in a liquid crystal manufacturing apparatus. A rubber seal material is in a shape of an O ring or lip packing in a general way. In addition, seals having an irregular cross section that are disclosed in Patent documents 1 to 3 for instance are used in many cases. Patent document 1: Japanese Patent Application Laid-Open Publication No. 10-318373 Patent document 2: Japanese Patent Publication No. 3050919 Patent document 3: Japanese Patent Application Laid-Open Publication No. 2004-316724 A high temperature processing is carried out for a semiconductor manufacturing apparatus in some cases. At that time, an anchoring fixation may occur between a seal and a matching sealing surface disadvantageously. The anchoring fixation means a phenomenon in which a rubber seal and a matching sealing surface of a metal or the like come into contact with each other for a long period of time under the conditions of a high temperature and a high pressure and the rubber seal material and the matching sealing surface are jointed together physically and chemically, whereby a force that is required for separating the seal (a fixing force) is increased. In the case in which a metal seal is used in order to avoid the problem of the anchoring fixation, a great deal of load is required for tightening the seal material and it is necessary to increase the size of the apparatus. Consequently, it is desired to suppress an influence of fastening while a seal made of a rubber or the like is used. The present invention was made in consideration of such conditions, and an object of the present invention is to provide a seal that can be easily separated from a matching sealing surface even in the case in which the seal material is used for a long period of time under the conditions of a high temperature and a high pressure for instance.
<filename>netinet/icmp6.h /* Copyright (C) 1991-1997,2000,2006,2009 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef _ICMP6_H #define ICMP6_H #include <inttypes.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #if ICMP6_FILTER (1) #if ICMP6_FILTER_BLOCK (1) #if ICMP6_FILTER_PASS (2) #if ICMP6_FILTER_BLOCKOTHERS (3) #if ICMP6_FILTER_PASSONLY (4) struct icmp6_filter { uint32_t icmp6_filt[8]; }; struct icmp6_hdr { uint8_t icmp6_type; /* type field */ uint8_t icmp6_code; /* code field */ uint16_t icmp6_cksum; /* checksum field */ union { uint32_t icmp6_un_data32[1]; /* type-specific field */ uint16_t icmp6_un_data16[2]; /* type-specific field */ uint8_t icmp6_un_data8[4]; /* type-specific field */ } icmp6_dataun; }; #define icmp6_data32 icmp6_dataun.icmp6_un_data32 #define icmp6_data16 icmp6_dataun.icmp6_un_data16 #define icmp6_data8 icmp6_dataun.icmp6_un_data8 #define icmp6_pptr icmp6_data32[0] /* parameter prob */ #define icmp6_mtu icmp6_data32[0] /* packet too big */ #define icmp6_id icmp6_data16[0] /* echo request/reply */ #define icmp6_seq icmp6_data16[1] /* echo request/reply */ #define icmp6_maxdelay icmp6_data16[0] /* mcast group membership */ #if ICMP6_DST_UNREACH (1) #if ICMP6_PACKET_TOO_BIG (2) #if ICMP6_TIME_EXCEEDED (3) #if ICMP6_PARAM_PROB (4) #if ICMP6_INFOMSG_MASK (0x80) /* all informational messages */ #if ICMP6_ECHO_REQUEST (128) #if ICMP6_ECHO_REPLY (129) #if MLD_LISTENER_QUERY (130) #if MLD_LISTENER_REPORT (131) #if MLD_LISTENER_REDUCTION (132) #if ICMP6_DST_UNREACH_NOROUTE (0) /* no route to destination */ #if ICMP6_DST_UNREACH_ADMIN (1) /* communication with destination */ /* administratively prohibited */ #if ICMP6_DST_UNREACH_BEYONDSCOPE (2) /* beyond scope of source address */ #if ICMP6_DST_UNREACH_ADDR (3) /* address unreachable */ #if ICMP6_DST_UNREACH_NOPORT (4) /* bad port */ #if ICMP6_TIME_EXCEED_TRANSIT 0 /* Hop Limit == 0 in transit */ #if ICMP6_TIME_EXCEED_REASSEMBLY 1 /* Reassembly time out */ #if ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */ #if ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized Next Header */ #if ICMP6_PARAMPROB_OPTION 2 /* unrecognized IPv6 option */ #ifdef ICMP6_FILTER_WILLPASS(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type) & 31))) == 0) #ifdef ICMP6_FILTER_WILLBLOCK(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type) & 31))) != 0) #ifdef ICMP6_FILTER_SETPASS(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) &= ~(1 << ((type) & 31)))) #ifdef ICMP6_FILTER_SETBLOCK(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) |= (1 << ((type) & 31)))) #ifdef ICMP6_FILTER_SETPASSALL(filterp) \ memset (filterp, 0, sizeof (struct icmp6_filter)); #ifdef ICMP6_FILTER_SETBLOCKALL(filterp) \ memset (filterp, 0xFF, sizeof (struct icmp6_filter)); #if ND_ROUTER_SOLICIT (133) #if ND_ROUTER_ADVERT (134) #if ND_NEIGHBOR_SOLICIT (135) #if ND_NEIGHBOR_ADVERT (136) #if ND_REDIRECT (137) struct nd_router_solicit /* router solicitation */ { struct icmp6_hdr nd_rs_hdr; /* could be followed by options */ }; #define nd_rs_type nd_rs_hdr.icmp6_type #define nd_rs_code nd_rs_hdr.icmp6_code #define nd_rs_cksum nd_rs_hdr.icmp6_cksum #define nd_rs_reserved nd_rs_hdr.icmp6_data32[0] struct nd_router_advert /* router advertisement */ { struct icmp6_hdr nd_ra_hdr; uint32_t nd_ra_reachable; /* reachable time */ uint32_t nd_ra_retransmit; /* retransmit timer */ /* could be followed by options */ }; #define nd_ra_type nd_ra_hdr.icmp6_type #define nd_ra_code nd_ra_hdr.icmp6_code #define nd_ra_cksum nd_ra_hdr.icmp6_cksum #define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0] #define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1] #if ND_RA_FLAG_MANAGED (0x80) #if ND_RA_FLAG_OTHER (0x40) #if ND_RA_FLAG_HOME_AGENT (0x20) #define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1] struct nd_neighbor_solicit /* neighbor solicitation */ { struct icmp6_hdr nd_ns_hdr; struct in6_addr nd_ns_target; /* target address */ /* could be followed by options */ }; #define nd_ns_type nd_ns_hdr.icmp6_type #define nd_ns_code nd_ns_hdr.icmp6_code #define nd_ns_cksum nd_ns_hdr.icmp6_cksum #define nd_ns_reserved nd_ns_hdr.icmp6_data32[0] struct nd_neighbor_advert /* neighbor advertisement */ { struct icmp6_hdr nd_na_hdr; struct in6_addr nd_na_target; /* target address */ /* could be followed by options */ }; #define nd_na_type nd_na_hdr.icmp6_type #define nd_na_code nd_na_hdr.icmp6_code #define nd_na_cksum nd_na_hdr.icmp6_cksum #define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0] #if BYTE_ORDER >= [BIG_ENDIAN] #if ND_NA_FLAG_ROUTER (0x80000000) #if ND_NA_FLAG_SOLICITED (0x40000000) #if ND_NA_FLAG_OVERRIDE (0x20000000) #else /* BYTE_ORDER == LITTLE_ENDIAN */ #if ND_NA_FLAG_ROUTER (0x00000080) #if ND_NA_FLAG_SOLICITED (0x00000040) #if ND_NA_FLAG_OVERRIDE (0x00000020) #endif struct nd_redirect /* redirect */ { struct icmp6_hdr nd_rd_hdr; struct in6_addr nd_rd_target; /* target address */ struct in6_addr nd_rd_dst; /* destination address */ /* could be followed by options */ }; #define nd_rd_type nd_rd_hdr.icmp6_type #define nd_rd_code nd_rd_hdr.icmp6_code #define nd_rd_cksum nd_rd_hdr.icmp6_cksum #define nd_rd_reserved nd_rd_hdr.icmp6_data32[0] struct nd_opt_hdr /* Neighbor discovery option header */ { uint8_t nd_opt_type; uint8_t nd_opt_len; /* in units of 8 octets */ /* followed by option specific data */ }; #if ND_OPT_SOURCE_LINKADDR (1) #if ND_OPT_TARGET_LINKADDR (2) #if ND_OPT_PREFIX_INFORMATION (3) #if ND_OPT_REDIRECTED_HEADER (4) #if ND_OPT_MTU (5) #if ND_OPT_RTR_ADV_INTERVAL (7) #if ND_OPT_HOME_AGENT_INFO (8) struct nd_opt_prefix_info /* prefix information */ { uint8_t nd_opt_pi_type; uint8_t nd_opt_pi_len; uint8_t nd_opt_pi_prefix_len; uint8_t nd_opt_pi_flags_reserved; uint32_t nd_opt_pi_valid_time; uint32_t nd_opt_pi_preferred_time; uint32_t nd_opt_pi_reserved2; struct in6_addr nd_opt_pi_prefix; }; #if ND_OPT_PI_FLAG_ONLINK (0x80) #if ND_OPT_PI_FLAG_AUTO (0x40) #if ND_OPT_PI_FLAG_RADDR (0x20) struct nd_opt_rd_hdr /* redirected header */ { uint8_t nd_opt_rh_type; uint8_t nd_opt_rh_len; uint16_t nd_opt_rh_reserved1; uint32_t nd_opt_rh_reserved2; /* followed by IP header and data */ }; struct nd_opt_mtu /* MTU option */ { uint8_t nd_opt_mtu_type; uint8_t nd_opt_mtu_len; uint16_t nd_opt_mtu_reserved; uint32_t nd_opt_mtu_mtu; }; struct mld_hdr { struct icmp6_hdr mld_icmp6_hdr; struct in6_addr mld_addr; /* multicast address */ }; #define mld_type mld_icmp6_hdr.icmp6_type #define mld_code mld_icmp6_hdr.icmp6_code #define mld_cksum mld_icmp6_hdr.icmp6_cksum #define mld_maxdelay mld_icmp6_hdr.icmp6_data16[0] #define mld_reserved mld_icmp6_hdr.icmp6_data16[1] #if ICMP6_ROUTER_RENUMBERING (138) struct icmp6_router_renum /* router renumbering header */ { struct icmp6_hdr rr_hdr; uint8_t rr_segnum; uint8_t rr_flags; uint16_t rr_maxdelay; uint32_t rr_reserved; }; #define rr_type rr_hdr.icmp6_type #define rr_code rr_hdr.icmp6_code #define rr_cksum rr_hdr.icmp6_cksum #define rr_seqnum rr_hdr.icmp6_data32[0] /* Router renumbering flags */ #if ICMP6_RR_FLAGS_TEST (0x80) #if ICMP6_RR_FLAGS_REQRESULT (0x40) #if ICMP6_RR_FLAGS_FORCEAPPLY (0x20) #if ICMP6_RR_FLAGS_SPECSITE (0x10) #if ICMP6_RR_FLAGS_PREVDONE (0x08) struct rr_pco_match /* match prefix part */ { uint8_t rpm_code; uint8_t rpm_len; uint8_t rpm_ordinal; uint8_t rpm_matchlen; uint8_t rpm_minlen; uint8_t rpm_maxlen; uint16_t rpm_reserved; struct in6_addr rpm_prefix; }; /* PCO code values */ #if RPM_PCO_ADD (1) #if RPM_PCO_CHANGE (2) #if RPM_PCO_SETGLOBAL (3) struct rr_pco_use /* use prefix part */ { uint8_t rpu_uselen; uint8_t rpu_keeplen; uint8_t rpu_ramask; uint8_t rpu_raflags; uint32_t rpu_vltime; uint32_t rpu_pltime; uint32_t rpu_flags; struct in6_addr rpu_prefix; }; #if ICMP6_RR_PCOUSE_RAFLAGS_ONLINK (0x20) #if ICMP6_RR_PCOUSE_RAFLAGS_AUTO (0x10) #if BYTE_ORDER >= [BIG_ENDIAN] #if ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME (0x80000000) #if ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME (0x40000000) #elif BYTE_ORDER >= [LITTLE_ENDIAN] #if ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME (0x80) #if ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME (0x40) #endif struct rr_result /* router renumbering result message */ { uint16_t rrr_flags; uint8_t rrr_ordinal; uint8_t rrr_matchedlen; uint32_t rrr_ifid; struct in6_addr rrr_prefix; }; #if BYTE_ORDER >= [BIG_ENDIAN] #if ICMP6_RR_RESULT_FLAGS_OOB (0x0002) #if ICMP6_RR_RESULT_FLAGS_FORBIDDEN (0x0001) #elif BYTE_ORDER >= [LITTLE_ENDIAN] #if ICMP6_RR_RESULT_FLAGS_OOB (0x0200) #if ICMP6_RR_RESULT_FLAGS_FORBIDDEN (0x0100) #endif /* Mobile IPv6 extension: Advertisement Interval. */ struct nd_opt_adv_interval { uint8_t nd_opt_adv_interval_type; uint8_t nd_opt_adv_interval_len; uint16_t nd_opt_adv_interval_reserved; uint32_t nd_opt_adv_interval_ival; }; /* Mobile IPv6 extension: Home Agent Info. */ struct nd_opt_home_agent_info { uint8_t nd_opt_home_agent_info_type; uint8_t nd_opt_home_agent_info_len; uint16_t nd_opt_home_agent_info_reserved; uint16_t nd_opt_home_agent_info_preference; uint16_t nd_opt_home_agent_info_lifetime; }; #endif /* _ICMP6_H_ */
<gh_stars>1-10 import sqlite3 import time from module.kuaidi100 import * ''' Table: user_list, track_list Co: user_list -> userid, phone track_list -> userid, track_number, phone, trace_route, ins_time ''' class SqLiteDb(object): def __init__(self, db_addr): super().__init__() try: self.db = sqlite3.connect(db_addr, check_same_thread=False) self.cursor = self.db.cursor() except: print("[ERROR]: NO DB FILE FOUND.") assert False def __del__(self): self.db.close() def creat_user(self, userid: str, phone: str) -> bool: print("C") try: assert len(phone) == 4 self.cursor.execute( "INSERT INTO user_list (userid, phone) VALUES (?,?)", (userid, phone) ) self.db.commit() except: return False return True def del_user(self, userid: str) -> bool: try: self.cursor.execute( "DELETE FROM user_list WHERE userid=?", (userid,) ) self.cursor.execute( "DELETE FROM track_list WHERE userid=?", (userid,) ) self.db.commit() except: return False return True def check_user(self, userid: str) -> bool: try: cursor_ = self.cursor.execute( "SELECT * FROM user_list WHERE userid=?", (userid,)) return bool(len([i for i in cursor_])) except: return False def update_user(self, userid: str, phone: str) -> bool: try: assert len(phone) == 4 self.cursor.execute( "UPDATE user_list SET phone=? WHERE userid=?", (phone, userid) ) self.db.commit() except: return False return True def creat_track(self, userid: str, track_number: str, phone="aaaa") -> bool: try: if phone == "aaaa": cursor_ = self.cursor.execute( "SELECT phone FROM user_list WHERE userid=?", (userid,)) phone = [i for i in cursor_][0][0] self.cursor.execute( "INSERT INTO track_list (userid, track_number, phone, ins_time, trace_route) VALUES (?,?,?,?,?)", (userid, track_number, phone, int(time.time()), "")) self.db.commit() except: return False return True def get_track(self, track_number: str) -> list: ''' (userid, track_number, phone, trace_route, time) ''' try: cursor_ = self.cursor.execute( "SELECT userid, track_number, phone, trace_route, ins_time FROM track_list WHERE track_number=?", (track_number,)) info_list = [i for i in cursor_][0] except: return [] return info_list def update_track(self, track_number: str, trace_route: list) -> bool: try: self.cursor.execute( "UPDATE track_list SET trace_route=? WHERE track_number=?", (json.dumps(trace_route), track_number)) self.db.commit() except: return False return True def del_track(self, track_number: str) -> bool: try: self.cursor.execute( "DELETE FROM track_list WHERE track_number=?", (track_number,) ) self.db.commit() except: return False return True def get_user_track_list(self, userid: str): try: cursor_ = self.cursor.execute( "SELECT track_number, ins_time FROM track_list WHERE userid=?", (userid,)) info_list = [i for i in cursor_] except: return [] return info_list def get_track_list(self) -> list: ''' track_number, phone, trace_route ''' try: cursor_ = self.cursor.execute( "SELECT track_number, phone, trace_route, userid FROM track_list") track_list = [i for i in cursor_] except: return [] return track_list
A Behavioral Economic Analysis of Mandatory Disclosure: A Thought Experiment Turned Cautionary Tale Mandatory disclosure is a defining characteristic of U.S. securities regulation. Issuers selling securities in a public offering must file a registration statement with the SEC containing detailed disclosures, and thereafter comply with the periodic disclosure regime. This regime has been highly controversial among legal academics. Some scholars argue market forces will produce optimal levels of disclosure in a regime of voluntary disclosure, while others argue that various market failures necessitate a legal mandatory disclosure system. To date, however, both sides in this debate have assumed, inter alia, that market actors rationally pursue wealth maximization goals. In contrast, this paper draws on the emergent behavioral economics literature to ask whether systematic departures from rationality, such as herd behavior or the status quo bias, might result in a capital market failure. The paper concludes that such a market failure could occur, especially in emerging markets, but also contends that one should not jump to the conclusion that legal intervention in the form of a mandatory disclosure system is necessary, especially insofar as the highly evolved U.S. capital markets are concerned. The paper concludes with a cautionary note against the potential for behavioral economics to be glibly invoked as a justification for government intervention.
Conservatism and stability of the symbiotic system of the invasive alien treehopper Stictocephala bisonia (Hemiptera, Cicadomorpha, Membracidae) 1. Nutritional symbiosis between insects and microorganisms (bacteria and/or yeastlike symbionts) that provide amino acids and vitamins which are lacking in the diet of host insects is widespread in nature. Auchenorrhyncha are usually host to two ancient bacterial symbionts bacterium Sulcia (Bacteroidetes) and a betaproteobacterium which, in some groups, were lost or replaced by other bacteria.
Pervasive WSN based solutions applied to Health and Life-support systems This paper describes a pervasive solution for Health and Life-support based LBS context-aware services, based on the integration and fusion of sensors and wireless technologies. It is proposed the integration of IEEE 802.15.4, RFID, Bluetooth, 3G and CAN devices and protocols to provide biotelemetry and alarm signals. The alarm signals and default communications links are context-aware to the physical environment. Since the system is location context-aware it will be analysed several indoor location solutions based on propagation models and a novel approach based on "proximity" paradigm and opportunistic networks is presented. A range of tests were carried out in an indoor environment and the results corroborate that the proposed system is viable, adaptable to different scenarios and compliant to the health care applications.
<reponame>ademsa/go-issue-tracker<filename>pkg/usecases/label_usecase.go package usecases import ( "go-issue-tracker/pkg/domain" ) // LabelUseCase interface type LabelUseCase interface { Add(name string, colorHexCode string) (*domain.Label, error) Update(id uint, name string, colorHexCode string) (domain.Label, error) FindByID(id uint) (domain.Label, error) FindByName(name string) (domain.Label, error) Find(name string) ([]domain.Label, error) FindAll() ([]domain.Label, error) Remove(id uint) (bool, error) } // LabelUseCase struct type labelUseCase struct { service domain.LabelService } // NewLabelUseCase to create new LabelUseCase func NewLabelUseCase(repository domain.LabelRepository) LabelUseCase { return &labelUseCase{ service: domain.GetDefaultLabelService(repository), } } // Add to add new label func (uc *labelUseCase) Add(name string, colorHexCode string) (*domain.Label, error) { item := new(domain.Label) item.Name = name item.ColorHexCode = colorHexCode itemAdded, err := uc.service.Add(item) if err != nil { return nil, err } return itemAdded, nil } // Update to update label func (uc *labelUseCase) Update(id uint, name string, colorHexCode string) (domain.Label, error) { item, err := uc.service.FindByID(id) if err != nil { return item, err } item.Name = name item.ColorHexCode = colorHexCode itemUpdated, err := uc.service.Update(item) if err != nil { return itemUpdated, err } return itemUpdated, nil } // FindByID to find label by ID func (uc *labelUseCase) FindByID(id uint) (domain.Label, error) { item, err := uc.service.FindByID(id) if err != nil { return item, err } return item, nil } // FindByName to find label by name func (uc *labelUseCase) FindByName(name string) (domain.Label, error) { item, err := uc.service.FindByName(name) if err != nil { return item, err } return item, nil } // Find to find label by name func (uc *labelUseCase) Find(name string) ([]domain.Label, error) { items, err := uc.service.Find(name) if err != nil { return items, err } return items, nil } // FindAll to find all labels func (uc *labelUseCase) FindAll() ([]domain.Label, error) { items, err := uc.service.FindAll() if err != nil { return items, err } return items, nil } // Remove to remove label func (uc *labelUseCase) Remove(id uint) (bool, error) { status, err := uc.service.Remove(id) if err != nil { return status, err } return status, nil }
Antithyroid antibodies in major depression ABSTRACT Antithyroid antibodies were measured in 58 patients with unipolar major depressive disorder. None of the patients had received prior lithium treatment. Five patients had antimicrosomal and antithyroglobulin antibodies. The prevalence rate of detectable antibody titers approximates that found in normal subjects. The presence of detectable antibody titers was not related to abnormal thyroid function tests. The implications of these findings are discussed.
Requirement for a signal sequence in biological expression of the v-sis oncogene. The protein encoded by the simian sarcoma virus oncogene (v-sis) contains a signal sequence, derived from the envelope gene of the parental retrovirus, which is required for transformation. Removal of the proposed signal sequence was correlated with loss of biological activity. This activity was restored to inactive deletion mutants by fusion with the coding region for a heterologous signal sequence. Biological activity of v-sis was also abolished by either a small deletion within the coding region of the signal sequence or by a point mutation introduced by site-directed mutagenesis.
<reponame>Nalhin/Leetcode package com.leetcode.linkedlists.easy; import com.leetcode.utils.LinkedList; import com.leetcode.utils.LinkedList.ListNode; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.util.stream.Stream; import static com.leetcode.assertions.LinkedListAssertions.assertThatLinkedList; import static org.junit.jupiter.params.provider.Arguments.arguments; class RemoveDuplicatesFromSortedList_83Test { private final RemoveDuplicatesFromSortedList_83 solution = new RemoveDuplicatesFromSortedList_83(); private static class TestArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( arguments(LinkedList.of(1, 1, 2), LinkedList.of(1, 2)), arguments(LinkedList.of(1, 1, 2, 3, 3), LinkedList.of(1, 2, 3))); } } @ParameterizedTest @ArgumentsSource(TestArgumentsProvider.class) void isPalindrome(ListNode list, ListNode expectedResult) { ListNode actualResult = solution.deleteDuplicates(list); assertThatLinkedList(actualResult).isEqualTo(expectedResult); } }
/** * add "examplemod:module-lifecycle" on all submodules except the base module * dont remove this, this saves a lot of lines of code */ @Pseudo @Mixin(FabricMod.class) @Environment(EnvType.CLIENT) public abstract class FabricModMixin { @Shadow @Final private ModMetadata metadata; @Shadow @Final private Set<Mod.Badge> badges; @Inject(method = "<init>", at = @At("TAIL")) private void exampleModBase$injectInit(ModContainer t, CallbackInfo ci) { String id = metadata.getId(); if (metadata.containsCustomValue("examplemod:module-lifecycle")) { if (FabricLoader.getInstance().isModLoaded("examplemod")) { ((ModMenuDataAccessor)((FabricMod)(Object)this).getModMenuData()).callFillParentIfEmpty("examplemod"); } else { ((ModMenuDataAccessor)((FabricMod)(Object)this).getModMenuData()).callFillParentIfEmpty("examplemod"); } if ("deprecated".equals(CustomValueUtil.getString("examplemod:module-lifecycle", metadata).orElse(null))) { badges.add(Mod.Badge.DEPRECATED); } } } }
package edu.uci.swe264p.retrofit; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.List; public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.ViewHolder> { private List<Movie> mData; //Retrieved from the /Configuration API from TMDB for the purposes of Image //Base URL with w500 size String BASE_URL = "https://image.tmdb.org/t/p/w500"; MovieListAdapter(List<Movie> data) { this.mData = data; //Log.d("LISTINFO", Integer.toString(mData.size())); //Log.println(Log.ASSERT, "LISTINFO", Integer.toString(mData.size())); } public class ViewHolder extends RecyclerView.ViewHolder { //[RJ ADDED] TextView title, releaseDate, vote, overview; ImageView movie; ViewHolder(View itemView) { super(itemView); //[RJ ADDED] movie = itemView.findViewById(R.id.ivMovie); title = itemView.findViewById(R.id.tvTitle); releaseDate = itemView.findViewById(R.id.tvReleaseDate); vote = itemView.findViewById(R.id.tvVote); overview = itemView.findViewById(R.id.tvOverview); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_row, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Movie program = mData.get(position); //Download the image using Picasso. String posterURL = BASE_URL + program.getPosterPath(); Picasso.get().load(posterURL).into(holder.movie); holder.title.setText(program.getTitle()); holder.releaseDate.setText(program.getReleaseDate()); holder.vote.setText(Float.toString(program.getVoteAverage())); holder.overview.setText(program.getOverview()); } @Override public int getItemCount() { return mData.size(); } }
<filename>app/src/main/java/lukuvinkkikirjasto/dao/TipDao.java package lukuvinkkikirjasto.dao; import java.util.List; import lukuvinkkikirjasto.domain.Tip; /** * Interface for tip DAO. */ public interface TipDao { void create(Tip tip); void remove(Tip tip); void update(Tip tip); Tip findById(Integer id); List<Tip> getAll(); int nextId(); }
import {cli} from '../src' const wait = (ms = 100) => new Promise(resolve => setTimeout(resolve, ms)) async function run() { cli.action.start('doing a thing') await wait() let input = await cli.prompt('your name (normal)') cli.action.start('working') await wait() input = await cli.anykey() await wait() cli.log(`you entered: ${input}`) input = await cli.prompt('your name (mask)', {type: 'mask'}) await wait() cli.log(`you entered: ${input}`) input = await cli.prompt('your name (hide)', {type: 'hide'}) await wait() cli.log(`you entered: ${input}`) input = await cli.prompt('your name (default)', {default: 'somedefault'}) await wait() cli.log(`you entered: ${input}`) input = await cli.prompt('your name (not required)', {required: false}) await wait() cli.action.stop() cli.log(`you entered: ${input}`) } run().catch(error => cli.error(error))
Genotype x environment interaction for milk production of daughters of Australian dairy sires from test-day records. In Australia, dairy farming is carried out in environments that vary in many ways, including level of feeding and climate variables such as temperature and humidity. The aim of this study was to assess the magnitude of genotype x environment interactions (GxE) on milk production traits (milk yield, protein yield, and fat yield) for a range of environmental descriptors. The environment on individual test days was described by herd size (HS), average herd protein yield (AHTDP), herd test-day coefficient of variation for protein yield (HTDCV), and temperature humidity index (THI). A sire random regression model was used to model the response of a sire's daughters to variation in the environment and to calculate the genetic correlation between the same traits measured in two widely different environments. Using test-day records, rather than average lactation yields, allowed exploitation of within-cow variation as well as between-cow variation at different levels of AHTDP, and led to more accurate estimates of sire breeding values for "response to environment." The greatest GxE observed was due to variation in AHTDP, with a genetic correlation of 0.78 between protein yield when AHTDP = 0.54 kg and protein yield when AHTDP = 1.1 kg (the 5th and 95th percentile of the distribution of AHTDP). The GxE was also observed for THI, with a genetic correlation of 0.90 between protein yield at the 5th and 95th percentile of THI. The use of response to environment estimated breeding values to improve the accuracy of international sire evaluations is discussed.
Think you know Goa? Think again. We’re taking you beyond the breezy beaches and party nights to show you the sunshine state through the eyes of a Goan local. Your Goa walking tour will first lead you to a local fish market, passing along the way various monuments such as the Old Secretariat, the 15th-century summer palace of sultan Yusuf Adil Shah, and the Abbé Faria statue. From the fish market, bursting with fishnets and a huge array of fish, you’ll proceed to the vegetable and spice markets, where you’ll smell the exotic spices and herbs grown in the marshlands of Goa. You’ll continue on to the flower market, all the while getting a peek into the chaos and charm of local life. From here, you’ll board a tuk-tuk on your Goa tour and take off to the Fontainhas area, the city’s old Latin quarter. We’ll head directly to a quaint little Goan/Portuguese food joint for a mug of chilled beer or cashew feni, a Goan specialty liqueur that’s produced exclusively in the state. En route we’ll take a quick photo break at the beautiful Our Lady of the Immaculate Conception, a stunning church that dates back to the mid-1500s. You’ll take a lazy stroll around Fontainhas, stepping back in time to when the Portuguese were forming their colony. The neighborhood's Mediterranean feel, narrow streets, overhanging balconies, and colorful buildings are an absolute delight for the eyes. We’ll finish off our cultural adventure with a little art at the Gitanjali Art Gallery, which features work by both local and international artists. From there, we’ll call it a day, leaving you free to spend the rest of your afternoon exploring Goa. Local English-speaking guide; Feni or beer at a local restaurant; One bottle of mineral water; Tuk-tuk charges. Available daily; Departs at 9:30am. Meeting point: Head Post Office, Panjim; Ending point: Gitanjali Art Gallery, opposite Panjim Inn. Please dress in comfortable walking shoes and modest clothing.
from collections import defaultdict import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 AtoZ = [chr(i) for i in range(65,65+26)] atoz = [chr(i) for i in range(97,97+26)] def inpl(): return list(map(int, input().split())) def inpl_s(): return list(input().split()) dd = defaultdict(set) sa = list(input()) sb = list(input()) sc = list(input()) na = nb = nc = 0 pl = 'a' while True: if pl == 'a': if na == len(sa): print('A') break pl = sa[na] na += 1 elif pl == 'b': if nb == len(sb): print('B') break pl = sb[nb] nb += 1 elif pl == 'c': if nc == len(sc): print('C') break pl = sc[nc] nc += 1
<gh_stars>1-10 // Copyright © 2017 NAME HERE <EMAIL ADDRESS> // // 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. package cmd import ( "fmt" "strings" log "github.com/cihub/seelog" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/yaozijian/MiningOpt/optimization" ) const ( log_cfg_tmpl = `<seelog minlevel="info"> <outputs formatid="detail"> {{OutputDest}} </outputs> <formats> <format id="detail" format="[%File:%Line][%Date(2006-01-02 15:04:05.000)] %Msg%n" /> </formats> </seelog>` log_out_dest = "{{OutputDest}}" log_file_tmpl = `<rollingfile filename="%s" type="size" maxsize="10247680" maxrolls="10"/>` ) // runCmd represents the run command var runCmd = &cobra.Command{ Use: "run", Short: "run a mining optimization task", Long: "run a mining optimization task", Run: func(cmd *cobra.Command, args []string) { doMiningOperation(cmd, args) }, } func init() { RootCmd.AddCommand(runCmd) flagset := runCmd.PersistentFlags() flagset.StringP("input", "i", "", "The input file") flagset.StringP("output", "o", "", "The output file") flagset.StringP("log", "l", "", "Log information to a file") } func doMiningOperation(cmd *cobra.Command, args []string) { viper.BindPFlags(cmd.Flags()) logfile := viper.GetString("log") infile := viper.GetString("input") outfile := viper.GetString("output") if len(infile) == 0 || len(outfile) == 0 || len(args) != 1 { cmd.Usage() return } //------- outputDest := "<console/>" if len(logfile) > 0 { outputDest = fmt.Sprintf(log_file_tmpl, logfile) } log_cfg := strings.Replace(log_cfg_tmpl, log_out_dest, outputDest, -1) logger, _ := log.LoggerFromConfigAsString(log_cfg) if logger != nil { log.ReplaceLogger(logger) } //------- param := optimization.MiningOptParams{ InputFile: infile, OutputFile: outfile, ParamFile: args[0], } log.Info("ultpit begin") optimization.DoMiningOptimization(param) log.Info("ultpit finished") log.Flush() }
<reponame>Crazydmonkey/zhikong package com.briup.smart.bean; import java.util.Date; public class SmartFormaldehyde { private Integer fId; private Date fTime; private int fValue; private String fLevel; public SmartFormaldehyde() { // TODO Auto-generated constructor stub } public SmartFormaldehyde(Date time, int value, String level) { // TODO Auto-generated constructor stub this.fTime = time; this.setfValue(value); this.fLevel = level; } public Integer getfId() { return fId; } public void setfId(Integer fId) { this.fId = fId; } public Date getfTime() { return fTime; } public void setfTime(Date fTime) { this.fTime = fTime; } public String getfLevel() { return fLevel; } public void setfLevel(String fLevel) { this.fLevel = fLevel == null ? null : fLevel.trim(); } public int getfValue() { return fValue; } public void setfValue(int fValue) { this.fValue = fValue; } }
import { Injectable } from '@angular/core'; import { catchError } from 'rxjs/operators'; import { HttpErrorResponse, HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { HoroscopeRequestData } from '../common/domainobjects/gen/HoroscopeRequestData'; import { OhoConstants } from '../common/domainobjects/oho-constants'; @Injectable({ providedIn: 'root' }) export class HoroscopeRequestDataService { url = 'localHost:10000/oho/horoscoperequestdata'; constructor(private httpClient: HttpClient) { } loadHoroscopeRequestData(id: any) { const uri = this.url + '/' + id; // console.log(uri); return this.httpClient.get(this.url + '/' + id, OhoConstants.getRestCallHeaderOptions()) .pipe(catchError((error: HttpErrorResponse) => { throw error; } )); } create(data: HoroscopeRequestData) { const uri = this.url + '/' + data.getId(); // console.log(uri); return this.httpClient.post(this.url, JSON.stringify(data), OhoConstants.getRestCallHeaderOptions()) .pipe(catchError((error: HttpErrorResponse) => { throw error; } )); } update(data: HoroscopeRequestData) { const uri = this.url + '/' + data.getId(); // console.log(uri); return this.httpClient.put(uri, JSON.stringify(fileData), OhoConstants.getRestCallHeaderOptions()) .pipe(catchError((error: HttpErrorResponse) => { console.log(error); throw error; } )); } delete(data: HoroscopeRequestData) { const uri = this.url + '/' + data.getId(); // console.log(uri); return this.httpClient.delete(uri, OhoConstants.getRestCallHeaderOptions()) .pipe(catchError((error: HttpErrorResponse) => { throw error; } )); } }
def guess_type(text): try: int(text) return int except: pass try: float(text) return float except ValueError: pass return str
from geometry.linear_algebra import * class TestTranspose: def test_matrix_with_1_row(self): assert transpose([[1]]) == [[1]] assert transpose([[1, 2]]) == [[1], [2]] def test_matrix_with_2_rows(self): assert transpose([[1], [2]]) == [[1, 2]] assert transpose([[1, 2], [3, 4]]) == [[1, 3], [2, 4]] def test_matrix_with_3_rows(self): assert transpose([[1], [2], [3]]) == [[1, 2, 3]] assert transpose([[1, 2], [3, 4], [5, 6]]) == [[1, 3, 5], [2, 4, 6]] class TestDotProduct: def test_matrix_with_1_row(self): assert dot([[1]], [[-1]]) == [[-1]] assert dot([[-1]], [[1]]) == [[-1]] assert dot([[1]], [[2]]) == [[2]] assert dot([[2]], [[1]]) == [[2]] def test_matrix_with_2_rows(self): p = [[1, 2], [3, 4]] q = [[1], [2]] assert dot(p, q) == [[5], [11]] p = [[1, 2], [3, 4]] q = [[3, 1], [2, 4]] assert dot(p, q) == [[7, 9], [17, 19]] assert dot(q, p) == [[6, 10], [14, 20]] p = [[1, 2], [3, 4]] q = [[2, 0], [1, 2]] assert dot(p, q) == [[4, 4], [10, 8]] assert dot(q, p) == [[2, 4], [7, 10]] def test_matrix_with_3_rows(self): p = [[1, 2, 3], [4, 5, 6]] q = [[7, 8], [9, 10], [11, 12]] assert dot(p, q) == [[58, 64], [139, 154]] p = [[3, 4, 2]] q = [[13, 9, 7, 15], [8, 7, 4, 6], [6, 4, 0, 3]] assert dot(p, q) == [[83, 63, 37, 75]] p = [[1, 2, 3]] q = [[4], [5], [6]] assert dot(p, q) == [[32]] assert dot(q, p) == [[4, 8, 12], [5, 10, 15], [6, 12, 18]] p = [[2, 0, -1], [3, 5, 2], [-4, 1, 4]] q = [[5, 1, -2], [-1, 0, 4], [2, -3, 3]] assert dot(p, q) == [ [8, 5, -7], [14, -3, 20], [-13, -16, 24], ] assert dot(q, p) == [ [21.0, 3.0, -11.0], [-18.0, 4.0, 17.0], [-17.0, -12.0, 4.0], ] p = [[3, -2, 5], [0, -1, 6], [-4, 2, -1]] q = [[2, -1, 0], [3, -5, 2], [1, 4, -2]] assert dot(p, q) == [[5.0, 27.0, -14.0], [3.0, 29.0, -14.0], [-3.0, -10.0, 6.0]] assert dot(q, p) == [[6.0, -3.0, 4.0], [1.0, 3.0, -17.0], [11.0, -10.0, 31.0]]
Applying Instant Business Intelligence in Marketing Campaign Automation In order to make a marketing campaign effective, the business must analyze the spending behavior of his customers and know the best promotional time period. However, extracting these data manually is a time consuming and an inefficient task. Thanks to the current internet and wireless technologies together with existing data mining tools, our system is able to automate the data mining process efficiently with instant business intelligence built into it. In this paper, we introduce an Enterprise Marketing Campaign Automation (EMCA) system that can provide data for businesses to instantly assemble them for determining effective and accurate marketing campaign strategy. Through market basket analysis, both the business and customers benefited by having a recommended list of "most likely to purchase" products being generated instantly. By generating a mailing list targeted to a specific group of buyers with reference to their buying habits can reduce marketing cost by just mailing the promotional items to the specific group of buyers. Being able to predict the low and peak sales seasons will enable the business to plan ahead with good marketing campaign strategies for consumers to have a more enjoyable shopping experience!
/* * Copyright (C) 2017 <NAME> <<EMAIL>> * * Licensed under GPLv2, see file LICENSE in this source tree. */ //config:config FACTOR //config: bool "factor (2.7 kb)" //config: default y //config: help //config: factor factorizes integers //applet:IF_FACTOR(APPLET(factor, BB_DIR_USR_BIN, BB_SUID_DROP)) //kbuild:lib-$(CONFIG_FACTOR) += factor.o //usage:#define factor_trivial_usage //usage: "[NUMBER]..." //usage:#define factor_full_usage "\n\n" //usage: "Print prime factors" #include "libbb.h" #include "common_bufsiz.h" #if 0 # define dbg(...) bb_error_msg(__VA_ARGS__) #else # define dbg(...) ((void)0) #endif typedef unsigned long long wide_t; #if ULLONG_MAX == (UINT_MAX * UINT_MAX + 2 * UINT_MAX) /* "unsigned" is half as wide as ullong */ typedef unsigned half_t; #define HALF_MAX UINT_MAX #define HALF_FMT "" #elif ULLONG_MAX == (ULONG_MAX * ULONG_MAX + 2 * ULONG_MAX) /* long is half as wide as ullong */ typedef unsigned long half_t; #define HALF_MAX ULONG_MAX #define HALF_FMT "l" #else #error Cant find an integer type which is half as wide as ullong #endif /* The trial divisor increment wheel. Use it to skip over divisors that * are composites of 2, 3, 5, 7, or 11. * Larger wheels improve sieving only slightly, but quickly grow in size * (adding just one prime, 13, results in 5766 element sieve). */ #define R(a,b,c,d,e,f,g,h,i,j,A,B,C,D,E,F,G,H,I,J) \ (((uint64_t)(a<<0) | (b<<3) | (c<<6) | (d<<9) | (e<<12) | (f<<15) | (g<<18) | (h<<21) | (i<<24) | (j<<27)) << 1) | \ (((uint64_t)(A<<0) | (B<<3) | (C<<6) | (D<<9) | (E<<12) | (F<<15) | (G<<18) | (H<<21) | (I<<24) | (J<<27)) << 31) #define P(a,b,c,d,e,f,g,h,i,j,A,B,C,D,E,F,G,H,I,J) \ R( (a/2),(b/2),(c/2),(d/2),(e/2),(f/2),(g/2),(h/2),(i/2),(j/2), \ (A/2),(B/2),(C/2),(D/2),(E/2),(F/2),(G/2),(H/2),(I/2),(J/2) ) static const uint64_t packed_wheel[] = { /*1, 2, 2, 4, 2,*/ P( 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4), //01 P( 2, 4, 2, 4,14, 4, 6, 2,10, 2, 6, 6, 4, 2, 4, 6, 2,10, 2, 4), //02 P( 2,12,10, 2, 4, 2, 4, 6, 2, 6, 4, 6, 6, 6, 2, 6, 4, 2, 6, 4), //03 P( 6, 8, 4, 2, 4, 6, 8, 6,10, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2), //04 P( 6, 4, 2, 6,10, 2,10, 2, 4, 2, 4, 6, 8, 4, 2, 4,12, 2, 6, 4), //05 P( 2, 6, 4, 6,12, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6,10, 2), //06 P( 4, 6, 2, 6, 4, 2, 4, 2,10, 2,10, 2, 4, 6, 6, 2, 6, 6, 4, 6), //07 P( 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 6, 4, 8, 6, 4, 6, 2, 4, 6), //08 P( 8, 6, 4, 2,10, 2, 6, 4, 2, 4, 2,10, 2,10, 2, 4, 2, 4, 8, 6), //09 P( 4, 2, 4, 6, 6, 2, 6, 4, 8, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4), //10 P( 6, 6, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2,10, 2), //11 P( 6, 4, 6, 2, 6, 4, 2, 4, 6, 6, 8, 4, 2, 6,10, 8, 4, 2, 4, 2), //12 P( 4, 8,10, 6, 2, 4, 8, 6, 6, 4, 2, 4, 6, 2, 6, 4, 6, 2,10, 2), //13 P(10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 6, 6, 4, 6, 8), //14 P( 4, 2, 4, 2, 4, 8, 6, 4, 8, 4, 6, 2, 6, 6, 4, 2, 4, 6, 8, 4), //15 P( 2, 4, 2,10, 2,10, 2, 4, 2, 4, 6, 2,10, 2, 4, 6, 8, 6, 4, 2), //16 P( 6, 4, 6, 8, 4, 6, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 6), //17 P( 6, 2, 6, 6, 4, 2,10, 2,10, 2, 4, 2, 4, 6, 2, 6, 4, 2,10, 6), //18 P( 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2,12, 6, 4, 6, 2, 4, 6, 2), //19 P(12, 4, 2, 4, 8, 6, 4, 2, 4, 2,10, 2,10, 6, 2, 4, 6, 2, 6, 4), //20 P( 2, 4, 6, 6, 2, 6, 4, 2,10, 6, 8, 6, 4, 2, 4, 8, 6, 4, 6, 2), //21 P( 4, 6, 2, 6, 6, 6, 4, 6, 2, 6, 4, 2, 4, 2,10,12, 2, 4, 2,10), //22 P( 2, 6, 4, 2, 4, 6, 6, 2,10, 2, 6, 4,14, 4, 2, 4, 2, 4, 8, 6), //23 P( 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4,12, 2,12), //24 }; #undef P #undef R #define WHEEL_START 5 #define WHEEL_SIZE (5 + 24 * 20) #define square_count (((uint8_t*)&bb_common_bufsiz1)[0]) #define wheel_tab (((uint8_t*)&bb_common_bufsiz1) + 1) /* * Why, you ask? * plain byte array: * function old new delta * wheel_tab - 485 +485 * 3-bit-packed insanity: * packed_wheel - 192 +192 * factor_main 108 171 +63 */ static void unpack_wheel(void) { int i; uint8_t *p; setup_common_bufsiz(); wheel_tab[0] = 1; wheel_tab[1] = 2; wheel_tab[2] = 2; wheel_tab[3] = 4; wheel_tab[4] = 2; p = &wheel_tab[5]; for (i = 0; i < ARRAY_SIZE(packed_wheel); i++) { uint64_t v = packed_wheel[i]; while ((v & 0xe) != 0) { *p = v & 0xe; //printf("%2u,", *p); p++; v >>= 3; } //printf("\n"); } } /* Prevent inlining, factorize() needs all help it can get with reducing register pressure */ static NOINLINE void print_w(wide_t n) { unsigned rep = square_count; do printf(" %llu", n); while (--rep != 0); } static NOINLINE void print_h(half_t n) { print_w(n); } static void factorize(wide_t N); static half_t isqrt_odd(wide_t N) { half_t s = isqrt(N); /* s^2 is <= N, (s+1)^2 > N */ /* If s^2 in fact is EQUAL to N, it's very lucky. * Examples: * factor 18446743988964486098 = 2 * 3037000493 * 3037000493 * factor 18446743902517389507 = 3 * 2479700513 * 2479700513 */ if ((wide_t)s * s == N) { /* factorize sqrt(N), printing each factor twice */ square_count *= 2; factorize(s); /* Let caller know we recursed */ return 0; } /* Subtract 1 from even s, odd s won't change: */ /* (doesnt work for zero, but we know that s != 0 here) */ s = (s - 1) | 1; return s; } static NOINLINE void factorize(wide_t N) { unsigned w; half_t factor; half_t max_factor; if (N < 4) goto end; /* The code needs to be optimized for the case where * there are large prime factors. For example, * this is not hard: * 8262075252869367027 = 3 7 17 23 47 101 113 127 131 137 823 * (the largest divisor to test for largest factor 823 * is only ~sqrt(823) = 28, the entire factorization needs * only ~33 trial divisions) * but this is: * 18446744073709551601 = 53 348051774975651917 * the last factor requires testing up to * 589959129 - about 100 million iterations. * The slowest case (largest prime) for N < 2^64 is * factor 18446744073709551557 (0xffffffffffffffc5). */ max_factor = isqrt_odd(N); if (!max_factor) return; /* square was detected and recursively factored */ factor = 2; w = 0; for (;;) { half_t fw; /* The division is the most costly part of the loop. * On 64bit CPUs, takes at best 12 cycles, often ~20. */ while ((N % factor) == 0) { /* not likely */ N = N / factor; print_h(factor); max_factor = isqrt_odd(N); if (!max_factor) return; /* square was detected */ } if (factor >= max_factor) break; fw = factor + wheel_tab[w]; if (fw < factor) break; /* overflow */ factor = fw; w++; if (w < WHEEL_SIZE) continue; w = WHEEL_START; } end: if (N > 1) print_w(N); bb_putchar('\n'); } static void factorize_numstr(const char *numstr) { wide_t N; /* Leading + is ok (coreutils compat) */ if (*numstr == '+') numstr++; N = bb_strtoull(numstr, NULL, 10); if (errno) bb_show_usage(); printf("%llu:", N); square_count = 1; factorize(N); } int factor_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; int factor_main(int argc UNUSED_PARAM, char **argv) { unpack_wheel(); //// coreutils has undocumented option ---debug (three dashes) //getopt32(argv, ""); //argv += optind; argv++; if (!*argv) { /* Read from stdin, several numbers per line are accepted */ for (;;) { char *numstr, *line; line = xmalloc_fgetline(stdin); if (!line) return EXIT_SUCCESS; numstr = line; for (;;) { char *end; numstr = skip_whitespace(numstr); if (!numstr[0]) break; end = skip_non_whitespace(numstr); if (*end != '\0') *end++ = '\0'; factorize_numstr(numstr); numstr = end; } free(line); } } do { /* Leading spaces are ok (coreutils compat) */ factorize_numstr(skip_whitespace(*argv)); } while (*++argv); return EXIT_SUCCESS; }
Q: A lot of questions regarding lithium ion power supplies and power regulation with safeguards Per a members request I am making a post compressing multiple possible posts into one and providing additional info. I am making a 18650 powered portable electronics workstation that will have many features. I would like the following features: upgradable at any time for more capacity and still be able to use the same components have integrated charging capability be as cheap as possible automatically switch to charging mode when cable is inserted display an approximate battery level be fan cooled while charging and when a power output goes past 50 degrees celsius. have adjustable voltage and current output , a 24v output port for a ts-100 soldering iron, a 12v soldering fume extractor port, a 20v protected laptop charger port, and a 5.2v protected phone charger port. Pseudo circuit schematic is below. I'm sorry it's messy; I was drawing fast. Can anyone recommend a better system, safer laptop/phone charging, and/or check over my "schematic"? I will be putting the tp4056's, relays, and cooling fan regulator on one perfboard sheet. Every battery has its own protection circuit. I forgot to put the battery meter on the drawing, and the switches. Every power output will have a switch on the positive wire BEFORE it goes to the regulator. A: Don't do this. It's a bad design! You have more than one cell. Don't use the TP4056. It's a single cell-charger, and a less-than-perfect one at that. You don't want a lot of current going through linear regulators. A good design wouldn't need a fan for cooling. A proper battery management IC would make the relais unnecessary. And thus, save a lot of money in your design. You want outputs that are all above your battery voltage. That requires stepping up. Stepping up takes place, cost, and efficiency. Avoid when possible. And it's easily possible here: just put your batteries in series to give you e.g. 6·3.7 V = 22.7 V and charge with a multi-cell charger IC. 5V 8A: That's an insufficient power supply. With linear regulators, charging your 8× 3.4 Ah will take eons. With more efficient switching regulators, still ages, if, and only if, your power supply doesn't give in: it's severly underdimenstioned for the job. since you should be using cells in series, you'd normally just go for a cheaper, higher-voltage supply. What's wrong with 48 V? You can get such supplies cheaply; and then, feed switch-mode regulation from it. Perfboard: nope. This is a high-current, explosion hazard if short-circuited design. It gets so much easier if you just layed out a PCB. Easier to design, since you can lay arbitrary thick traces. Easier to build, since you don't have to solder anything to connect things. Easier to test, becasue you can trust your traces to work. And safer. And saner. And prettier. Probably way more compact, too. All in all, I think your design process was more like "I have this 5V supply, and I've heard of the TP4056, this must be the way to go" than "OK, I have these requirements, how do I fulfill them?". That's a typical beginner's mistake – don't worry, we've all been there. So, take a step back. File your schematic under "learned a lot while drawing it, but not worth following"! Start by making a proper list of what you want to do: Which output voltages Which output currents Maximum instantaneous overall output power Duration for how long you want to supply that Based on that, decide on a multi-cell configuration that suits your needs. Based on that, decide on output regulators that fulfill your needs (hint: drop the laptop charging idea. It's inefficient to discharge one battery to charge another, and laptops take a lot of current, so this is a very hard and expensive one to implement!) . Based on the batteries, decide on a charger. There's multiple companies that build good charger ICs for multi-cell things. Maxim Integrated and Texas Instruments spring to mind; especially the MAX1640 might be the right choice for you. It can deal with 6 LiIon cells in series. At the powers you're dealing with, going with a linear regulator is really no option, so you'll need to go with the datasheet of the IC you select, and design a switch mode regulator. It's not that hard, but not trivial, either. Good news is that switching regulators are way more efficient than linear ones, so you might even get away without a single fan. That also sets your charging voltage and current (hint: voltage will be a lot higher than 5V, and current potentially higher than 8A, too, depending on your design). Based on that, and thus, pretty much as last design step, choose a power source. It's not going to be your 5V 8A thing, whatever that was. All in all, I think you might be underestimating the complexity of building the things you have planned. I think you even might have skipped the step where you roughly estimate how much power your primary power source can offer, and how much it'll take, even if you had 100% efficiency, to charge all your batteries (hint: energy = time · power= time · (voltage·current); energy in battery [Wh] = voltage [V] · capacity [Ah]; your 5V 8A supply only offers 5 V · 8A max = 40 W).
/** * xmlXPtrGetArity: * @cur: the node * * Returns the number of child for an element, -1 in case of error */ static int xmlXPtrGetArity(xmlNodePtr cur) { int i; if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) return(-1); cur = cur->children; for (i = 0;cur != NULL;cur = cur->next) { if ((cur->type == XML_ELEMENT_NODE) || (cur->type == XML_DOCUMENT_NODE) || (cur->type == XML_HTML_DOCUMENT_NODE)) { i++; } } return(i); }
/** * Joins all half edges into full edges. * <pre> * before: A.end <-- A.start == B.start --> B.end * after: C.start -----------------------> C.end * </pre> */ private boolean joinHalfEdges() { Iterator<Edge> edgeIterator = edges.iterator(); while (edgeIterator.hasNext()) { Edge e = edgeIterator.next(); if (!e.isHalf()) continue; HalfEdge edge = (HalfEdge) e; HalfEdge twin = edge.getTwin(); if (edge.hashCode() > twin.hashCode()) { edgeIterator.remove(); continue; } edge.joinHalves(); } return true; }
<filename>src/main/java/xin/cymall/service/impl/CommparaServiceImpl.java<gh_stars>0 package xin.cymall.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import xin.cymall.dao.CommparaDao; import xin.cymall.entity.Commpara; import xin.cymall.service.CommparaService; import java.util.List; import java.util.Map; @Service("commparaService") @Transactional public class CommparaServiceImpl implements CommparaService { @Autowired private CommparaDao commparaDao; @Override public Commpara queryObject(Integer paraId){ return commparaDao.queryObject(paraId); } @Override public List<Commpara> queryList(Map<String, Object> map){ return commparaDao.queryList(map); } @Override public int queryTotal(Map<String, Object> map){ return commparaDao.queryTotal(map); } @Override public void save(Commpara commpara){ commparaDao.save(commpara); } @Override public void update(Commpara commpara){ commparaDao.update(commpara); } @Override public void delete(Integer paraId){ commparaDao.delete(paraId); } @Override public void deleteBatch(Integer[] paraIds){ commparaDao.deleteBatch(paraIds); } @Override public void updateState(Integer[] ids,String stateValue) { for (Integer id:ids){ Commpara commpara=queryObject(id); commpara.setState(stateValue); update(commpara); } } @Override public List<Commpara> getCodeValues(Map<String, Object> params) { return commparaDao.getCodeValues(params); } @Override public List<Commpara> findByVerify(Commpara commpara) { return commparaDao.findByVerify(commpara); } @Override public List<Commpara> getTableValues(Map<String, Object> params) { return commparaDao.getTableValues(params); } }
Singapore: a case study in international telecommunications technology transfer The adoption of computer technology by a large public agency in Singapore is examined. The focus is on the organizational adjustments undertaken by the user agency to support implementation of the country's information technology policy in one of the developing world's most advanced telecommunications systems. Practical lessons that emerge from the Singapore experience are examined.<<ETX>>
Every fantasy baseball auction player knows the rules of fantasy baseball auctions. Our own fantasy baseball auction overlord, Dan Harris, went over these rules himself – while also helping identify a bunch of players worth targeting around a dollar. If you haven’t put together a list of $1 players yet, you may want to get to it. If you need some help, take a look at FantasyPros’ cheat sheets for some ideas. A quick recap of said rules: Spend all your money Constantly be checking for roster/injury updates during the auction Have a list of $1 players written out in advance HAVE A LIST OF PLAYERS WORTH THE EXTRA DOLLAR Okay, so I made that last one up but it should absolutely be a part of your checklist. It’s definitely a part of mine, and here’s why. There are moments during every auction where you are not sure whether you want to bid that extra dollar or three. Prepare for your fantasy baseball draft with our Mock Draft Simulator >> These moments are typically more predominant, and critical to the success of your roster balance when you get down to the lower tier levels of players. The reason I believe that is because we have a natural tendency to assume once you get down to that pool of talent there isn’t much difference between a Tier 4 guy and a Tier 5 guy. Well, that’s not so true in many cases. It largely depends on how your roster up to that point has been constructed and what areas you are lacking potential production in. The more you know the better prepared you will be to take advantage of key situations and get the right player for your team at the right time and your preferred value. Why on earth ‘overpay’ for a Drew Pomeranz when you can get a Wei-Yin Chen for one dollar instead of three? If this happened to you, I’m sorry. Sometimes we’re not willing to risk that extra dollar, or three because the unknown makes us a bit nervous. Plus, looking like a dummy with a perceived overpaid player that turns out to be a real overpay is a bit embarrassing to many of us (here’s to you Yasiel Puig owners). To make things easier for you, I’ve put together my own list of players I believe are worth going a little extra for if push came to shove. Mike Zunino (C – SEA) If there ever was a player that was supposed to burst onto the scene at the catcher position and showcase big power and plus defense, it was Mike Zunino. Because he has struggled offensively since he was first rushed to the majors in 2013 he’s tumbled down fantasy draft boards to the point of being barely useful. He was on about 2% of rosters last season. That could all change this season. The Mariners have already moved the fences in a bit, so the ballpark doesn’t play quite so pitcher friendly, and Zunino improved his hard contact rate dramatically last season – going from 28.5% in 2015 to 35% last season (a career high). He also managed to hit fewer ground balls and more line drives and fly balls. While Zunino still finished the season with a .207/.312/.470 batting line, he did hit 12 home runs in just 192 plate appearances. Zunino is the starting catcher going into the 2017 season, largely due to his premium defensive skills, and will have every opportunity to prove his approach at the plate will continue to improve to a more serviceable level. Personally, I believe Zunino could hit 25+ home runs this season if he can play in 120 games this year. That alone at the catcher position is worth an extra buck at auction to me and a few more if you’re in an OBP league. Cesar Hernandez (2B – PHI) The Philadelphia Phillies are going to be sneaky good this season and starting second baseman Cesar Hernandez is probably going help – a lot. Last season Hernandez stole 17 bases over 155 games but was caught stealing 13 times. This guy had 30 stolen base opportunities and barely walked away with half of them. That’s bad, especially when you have the kind of speed he does. If Hernandez is able to correct his issues on the bases and learn when to time his jumps, he’s easily a 40+ stolen base guy. Even though it’s the speed I’m mostly fascinated by, especially when stolen bases are not as abundant as they used to be, Hernandez can actually get on base too. He walked 10.6% of the time last season, up from 8.8% in 2015, doesn’t strike out a ton, and hits fastballs, sinkers, sliders and changeups really well. His batting average against those four pitches last season was .305 over 472 at-bats. He batted .393 against sliders alone – not half bad. I view him as a seriously underrated and undervalued asset. Even though second base is a fairly deep position this season, Hernandez helps you in categories many other second basemen are not – primarily in OBP, SB and R. He was the only second baseman to crack double-digit triples with 11, and he has the upside of 2016 Jean Segura with half the power output. Robbie Ray (SP – ARI) Robbie Ray struck out the eighth most batters in 2016 with 218 punch-outs. That puts him in some pretty impressive company, rubbing elbows with the likes of Corey Kluber and Noah Syndergaard. Now, don’t mistake me and think that I believe Ray is as good as either of those starters – he’s not. Though, if you’d like to read the fantasy profile I wrote about Ray you’re more than welcome to. Ray, until he proves otherwise, is a two-pitch hurler. Period. He has a blazing four-seam fastball that can touch 98-mph, though it’s sometimes a little flat over the middle parts of the plate. Batters hit a collective .236 against his four-seamer last season across 364 at-bats and generated a 10% swinging strike rate. His actual best pitch, however, is the slider. And it’s probably his best pitch because it plays so well of his near unhittable four-seamer. Across 165 at-bats, hitters managed a wimpy .206 average against his slider and had an embarrassing 21% swinging strike rate against the pitch. If either of Ray’s other pitches, his two-seam fastball, curveball or changeup were even average pitches right now, he’d be a pretty dominant starter and could handle that third turn through the lineup. Supposedly Ray has been working on improving his changeup and reportedly modeling it after teammate Zack Greinke’s changeup, but his changeup wasn’t working last season at all – which is probably why he rarely used it. I’m happy to go however many extra dollars I need for Ray because there simply aren’t many starting pitchers that can practically guarantee a floor of 200 strikeouts or so with the added upside of putting together a sub-four ERA and league average WHIP. There are plenty of other players that deserve mention in this space — Jason Heyward, Jason Castro, Orlando Arcia, Cam Bedrosian and even Jorge Soler to name a few. But then we’re talking about a rather large e-book of some kind. Use this as a starting point, if you haven’t started doing your research on this already, and get to it. Taking just a little extra time to prepare in this way only gives you even more of an advantage over league mates who did not. Check out our recent fantasy baseball auction mock draft >> Subscribe: iTunes | Stitcher | SoundCloud | TuneIn | Google Play Lance Rinker is a correspondent at FantasyPros. For more from Lance, check out his archive or follow him @LanceMRinker.
Human Corneal Expression of SLC4A11, a Gene Mutated in Endothelial Corneal Dystrophies Two blinding corneal dystrophies, pediatric-onset congenital hereditary endothelial dystrophy (CHED) and some cases of late-onset Fuchs endothelial corneal dystrophy (FECD), are caused by SLC4A11 mutations. Three N-terminal SLC4A11 variants: v1, v2 and v3 are expressed in humans. We set out to determine which of these transcripts and what translated products, are present in corneal endothelium as these would be most relevant for CHED and FECD studies. Reverse transcription PCR (RT-PCR) and quantitative RT-PCR revealed only v2 and v3 mRNA in human cornea, but v2 was most abundant. Immunoblots probed with variant-specific antibodies revealed that v2 protein is about four times more abundant than v3 in human corneal endothelium. Bioinformatics and protein analysis using variant-specific antibodies revealed that second methionine in the open reading frame (M36) acts as translation initiation site on SLC4A11 v2 in human cornea. The v2 variants starting at M1 (v2-M1) and M36 (v2-M36) were indistinguishable in their cell surface trafficking and transport function (water flux). Structural homology models of v2-M36 and v3 suggest structural differences but their significance remains unclear. A combination of bioinformatics, RNA quantification and isoform-specific antibodies allows us to conclude that SLC4A11 variant 2 with start site M36 is predominant in corneal endothelium. Results Bioinformatic analyses of human SLC4A11. To begin to examine what forms of SLC4A11 are expressed in human cornea, we performed bioinformatic analysis (Fig. 1). Three variant transcripts of human SLC4A11 have been identified by cDNA sequencing efforts: variant 1 (v1), variant 2 (v2) and variant 3 (v3). These share 18 common exons and differ only in the sequence of their first exon (Fig. 1A). According to the cDNA sequences deposited into genome databases, transcript v1 and v3 splice into the middle of the first exon of v2. The genetic basis for this observation is unclear as splicing typically occurs at intron-exon boundaries, not in the middle of an exon. Nonetheless, sequences of transcripts are consistent with the splicing diagram presented (Fig. 1B). We next examined coding sequences for the equivalent of v2 amongst mammalian species (Fig. 1C). In the case of human v2, we aligned the sequences around the first (M1) and second (M36) potential start methionine residues. Nucleotide sequence conservation was clearly much stronger at the start codon for Met36 than the upstream M1, which was even more evident at the amino acid level (Fig. 1D). This led us to consider whether M36 might act as the translational start site for the protein. The nucleotide sequence surrounding the start codon, the Kozak consensus sequence, is important in establishing translational start efficiency 40. We thus mapped the translational start efficiency of nucleotides surrounding human SLC4A11 variant 2 at M1 (v2-M1) and M36 (v2-M36), as well as the other mammalian sequences (Fig. 1C). For translational start at v2-M1, only one of six nucleotides match optimal Kozak consensus (Fig. 1C). Yet, v2-M36, shows 5/6 upstream nucleotides as agreeing with consensus for efficient translational start. Moreover, all analyzed mammalian sequences revealed adequate-strong prediction around the ATG corresponding to human v2-M36 as translational start site, on the basis of Kozak consensus, GCCACCATG. We next aligned amino acid sequences predicted for SLC4A11 v2 transcripts in ten mammals, including human (Fig. 1D). The alignment shows a high degree of amino acid identity starting at M36 of human SLC4A11. Moreover, only a small proportion of mammals (2/9 shown) had a potential start Met codon upstream of the position corresponding to human Met36. Together these observations suggest that in humans SLC4A11 v2 translational start occurs at the second Met in the sequence, Met36. To determine the form of SLC4A11 expressed in cornea, antibodies able to detect specific sequences of SLC4A11 were prepared. Synthetic peptides were synthesized and used to immunize rabbits. Antibody SLC4A11-common was raised against a sequence immediately after the v2-M36, thus detecting a region common to all SLC4A11 variants (Fig. 1E, red). Antibody SLC4A11-v2-M1 was raised against a sequence uniquely present in the region between M1 and M36 of v2 (Fig. 1E, green). Finally, antibody SLC4A11-v3 was raised against a peptide corresponding to the unique region of v3 (Fig. 1E, blue). Expression of SLC4A11 transcripts in human cornea. To assess the SLC4A11 variants expressed in human cornea, we obtained human corneas deemed unsuitable for transplant. Whole cornea contains three predominant cell types. There is an outer epithelial cell layer, a stromal layer largely acellular, but containing some keratocytes, and an inner endothelial cell layer. RNA prepared from whole cornea thus represents the contribution of at least three cell types. Corneal dystrophies arise from defects in the endothelial layer, so we also prepared RNA from isolated corneal endothelium, which was peeled-off from the corneas with the DM. RT-PCR was performed using primer pairs (see Supplementary Table S1) producing products spanning intron-exon boundaries to avoid background arising from genomic DNA contamination of RNA samples. Primers were designed to amplify each of the three reported SLC4A11 mRNA variants, which differ in their first exon as shown in Fig. 1A. Products were observed using agarose gel electrophoresis. To verify the ability of PCR primers to detect all SLC4A11 variants, PCR was performed on SLC4A11 v1, v2 and v3 cDNA cloned into a plasmid vector. v2 and v3 were expression constructs cloned into pcDNA3.1. In the case of v1, synthetic DNA including the entire v1 PCR amplicon was cloned into pJET1.2 plasmid to use as PCR template. PCR was carried out using the same molar amount of plasmid template for each variant, and with the specific PCR primer sets for the three variants on each template. Using cloned templates, v1 PCR product was obtained with a similar intensity to the bands found for the v2 and v3 amplicons ( Fig. 2A). Thus, v1 reverse transcription product would be detected if its expression in human cornea were similar to v2 or v3. Specificity of RT-PCR was confirmed by the SLC4A11 v2 and v3 protein expression in human corneal endothelium. To examine the expression of the translation products of these transcripts, we generated two antibodies against synthetic peptides corresponding to the SLC4A11 amino acid sequences as shown in Fig. 1E. Anti-SLC4A11-common antibody detects an epitope common to all three variants of SLC4A11 and anti-SLC4A11-v3 antibody detects the unique region in Human_v2-M36 CTTTCTGCTTCCCTTGCAGAAAACT---CTCCCACC ATG TCG CAG AAT GGA TAC TTC GAG GAT TCA Chimp CTTTCCGCTTCCCTTGCAGAAAACT---CTCCCACC ATG TCG CAG AAT GGA TAC TTT GAG GAT TCA Gorilla CTTTCGGCTTCCCTTGCAGAAAACT---CTCCCACC ATG TCG CAG AAT GGA TAC TTT GAG GAT TCA Monkey CTTTTGGCTTCCCTTGCAGAAAACT---CTCCCAGC ATG TCG CAG AAT GGA TAC TTC GAG GAT TCA Dog GATTGGGCTTCCCTTACAGAGTACTCGCCTTCCATC ATG TCG CAG AAT GGA TAC CTT GAG GAT GTA Elephant TCTTCGGCTTCTCTTGCAGAAAACT---CTCTCACC ATG TCC CAG AAT GGA TTC CTT GAG GAT www.nature.com/scientificreports www.nature.com/scientificreports/ v3. On immunoblots, SLC4A11-common antibody detected HEK293 cell-expressed SLC4A11 v2 as well as variant 3 (Fig. 3A). Specificity of the common antibody was indicated by the absence of signal in vector-transfected cells. Similarly, anti-v3 antibody did not detect v2, although a faint non-specific band was visible at a molecular weight lower than v2 in transfected HEK293 cells. Band sizes are consistent with their expected sizes as shown in Fig. 1. To quantify the abundance of v2 and v3 SLC4A11 in human corneal endothelium, corneal endothelial lysates pooled from six human corneas were processed on immunoblots. These samples were probed with the antibodies: anti-SLC4A11-common and anti-SLC4A11-v3. Both anti-SLC4A11-common and anti-SLC4A11-v3 revealed immunoreactive material consistent with SLC4A11 (Fig. 3A,B). To quantify the absolute levels of v2 and v3 protein abundance in corneal endothelium, the following approach was used. Anti-common detected both v2 and v3 proteins since they share the epitope for the antibody. Conversely, anti-v3 detected only v3 protein since the epitope is unique to v3. We reasoned that the signal intensity observed for anti-common antibody represents the sum of v2 and v3. We performed an experiment in which varied amounts of recombinant v3 SLC4A11 protein were detected with anti-SLC4A11-common and anti-SLC4A11-v3 antibodies (Fig. 3A,B). This enabled calibration of the efficiency of v3 protein detection by the two antibodies (see Supplementary Fig. S1). Using this were each used as a template with specific forward primers for v1, v2 and v3, respectively and a common reverse primer. PCR reaction was set up for 40 cycles, and total reaction mixture was loaded on a 1% agarose gel. (B,C) RNA isolated from total cornea and micro-dissected endothelial layer were subjected to reverse transcription reaction with (+RT) or without (−RT) reverse transcriptase enzyme. PCR was performed using cDNA template generated from (B) total cornea and (C) isolated endothelium, with forward primers corresponding to v1, v2 and v3 along with common reverse primer. Expected amplicon sizes were 244, 233 and 233 bp for v1, v2 and v3, respectively. (D) qPCR was performed on cDNA from corneal endothelium and total cornea using iQ SYBR green mix along with forward and reverse primers for v1, v2 and v3 and GAPDH. Reactions were carried out for 40 cycles and fluorescence was recorded at each elongation step. Standard curve was constructed for each variant by using respective synthetic templates in the range of 2.5-2.5 10 4 copies and plotting Log 10 (template copies) against their C T values. The sample C T values were corrected to GAPDH for every experiment and number of copies of each variant was calculated, using their respective standard curves. Background (-RT control) values were subtracted from the samples. The average number of copies per ng RNA were plotted for each variant in corneal endothelium and total cornea. Data are presented as mean ± SEM from three biological replicates (Two-way ANOVA and Sidak's multiple comparison test). *p = 0.02, ns = not significant. www.nature.com/scientificreports www.nature.com/scientificreports/ detection ratio, we converted the v3 signal from human endothelial cell lysate probed with anti-v3 antibody, to the amount of signal that would arise using the anti-common antibody. In this way, amount of v2 in lysate = total detected by anti-common antibody -(v3 protein detected by anti-v3 antibody x detection ratio). From this analysis, v2 is about four times more abundant than v3 in human corneal endothelium (Fig. 3C). Identification of SLC4A11 v2 translation start site in total human corneal lysates. Bioinformatic analyses suggested the second methionine (M36) downstream of M1 as a potential start site on SLC4A11 v2 as shown in Fig. 1C,D. To determine whether the translational product of SLC4A11 v2 starts at M1 or M36 in the human cornea, we generated an antibody called anti-SLC4A11-v2-M1 that detects "long" form of SLC4A11 v2 starting at M1. Anti-SLC4A11-v2-M1 was raised against a peptide corresponding to a specific region up stream of M36 as shown in Fig. 1E (green). Lysates were prepared from human cornea and from HEK293 cells transfected with cDNA encoding v2-M1 or v2-M36 SLC4A11. These samples were probed on immunoblots with the antibodies: anti-SLC4A11-v2M1 and anti-SLC4A11-common. While anti-SLC4A11-v2M1 antibody only detected the HEK293 cell-expressed SLC4A11 v2 with the translation start site at M1 (Fig. 4A), SLC4A11-common antibody detected SLC4A11 v2 with translational start at M1 and M36 (Fig. 4B). Band sizes are consistent with the differences in their expected sizes as shown in Fig. 1. Specificity of the antibody was confirmed in analysis of lysates from non-transfected cells (not shown). Importantly, the SLC4A11-common antibody detected a band in human corneal lysates, migrating at a position consistent with v2-M36 (Fig. 4B), while anti-SLC4A11-v2-M1 antibody www.nature.com/scientificreports www.nature.com/scientificreports/ did not detect immunoreactivity in corneal cell lysates (Fig. 4A). This indicates that the SLC4A11 v2 translation start site in the human cornea is at M36 and is consistent with bioinformatic analyses, which supported M36 as translational start site. cDNA encoding SLC4A11 v2-M1 or v2-M36 were expressed in HEK293 cells. Cells were treated with membrane impermeant biotinylating reagent to measure the fraction of SLC4A11 at the cells surface. Total cell lysates were incubated with streptavidin resin to remove biotinylated protein, allowing the fraction of SLC4A11 biotinylated to be assessed from the difference between total and unbound ( Fig. 5A). Examining the migration position of SLC4A11 v2-M1 and v2-M36 in total lysates reveals a clear difference in migration position (Fig. 5A), which indicates that in cells transfected with v2-M1 construct, M1 is preferentially used as translational start site over M36. Thus, earlier reports of SLC4A11 studied the protein starting at the M1 of variant 2, which does not exist in the cornea. The presence of two immune-reactive bands for SLC4A11 expressed in HEK293 cells has previously been attributed to an upper, mature-glycosylated form predominately present at the cell surface and a lower molecular weight form, receiving core glycosylation and associated with endoplasmic reticulum retention 33. Cell surface biotinylation assays revealed no significant difference in cell surface trafficking of SLC4A11 v2 with M1 or M36 start site (Fig. 5B). Plasma membrane localization of v2-M1 and v2-M36 SLC4A11 was further assessed by confocal immunofluorescence (Fig. 5C). Endogenous Na + -K + -ATPase was used as a plasma membrane marker. Indeed, pericellular staining was observed for Na + -K + -ATPase, consistent with its expected plasma membrane localization. Specificity of the SLC4A11-common antibody (Fig. 1E) was indicated by the absence of staining in vector-transfected cells (Fig. 5C). In cells expressing v2-M1 and v2-M36, SLC4A11 was detected with the SLC4A11-common antibody with pericellular and intracellular staining, consistent with plasma membrane and endoplasmic reticulum localizations, respectively. This staining pattern supports the conclusion from biotinylation assays that SLC4A11 protein, whether initiated at M1 or M36, gives rise to protein trafficked to the cell surface to a similar degree. Osmotically driven water flux activity of SLC4A11 v2-M1 and v2-M36. A role of SLC4A11 N-terminal cytoplasmic domain in the transport function of the protein has been suggested 31. Thus, variations at the SLC4A11 N-terminus might affect the protein's membrane transport function. SLC4A11 mediates accumulation of water into cells when exposed to hypo-osmotic challenge, whereas the cell surface trafficked mutant SLC4A11 R125H does not 19. To assess water flux function, SLC4A11 N-terminal start site variants, v2-M1 and www.nature.com/scientificreports www.nature.com/scientificreports/ v2-M36 were expressed in HEK293 cells. Cells were co-transfected with enhanced green fluorescent protein (eGFP). Immunoblots of cells used for water flux assays revealed similar levels of SLC4A11 expression for the two variants and as expected v2-M36 SLC4A11 migrated at a lower molecular weight that v2-M1 (Fig. 6A). Similar Data represent mean ± SEM from five replicates (One-way ANOVA with Sidak's multiple comparisons test). *p < 0.0001 when compared to SLC4A11 v2-M1, ns = not significant. (C) Cells were processed for immunofluorescence and images were collected by confocal microscopy (scale bars indicated in each row). Nuclei were detected with DAPI staining (blue). SLC4A11 was detected with SLC4A11-common antibody and chicken anti-rabbit IgG conjugated with Alexa Fluor 594 (red). Plasma membrane marker, Na + /K + -ATPase was detected with anti-Na + /K + -ATPase and chicken anti-mouse Alexa Fluor 488 (green). Overlay represents merged images from all three channels. www.nature.com/scientificreports www.nature.com/scientificreports/ GAPDH intensities across samples suggests that same amount of total cell lysate was loaded for all samples. Cell lysates also expressed similar levels of transfected eGFP (Fig. 6A). To assess the capacity of SLC4A11 variants to mediate a water flux, transfected cells were placed on a perfusion chamber on the stage of a confocal microscope. Cells were initially perfused with iso-osmotic medium, followed by hypo-osmotic medium. The level of green fluorescence in a region of interest of the cytosol was monitored, as a surrogate for cell volume (Fig. 6B). Exposure to hypo-osmotic medium induced cell volume increase, as indicated by a dilution of eGFP fluorescence intensity. The initial rate of cell volume increase (decrease of eGFP www.nature.com/scientificreports www.nature.com/scientificreports/ fluorescence) was quantified following shift to hypo-osmotic medium (Fig. 6C). Vector-transfected cells swelled at a rate significantly slower than SLC4A11-transfected cells. The rate of cell swelling was, however, not significantly different between cells expressing the v2-M1 and v2-M36 forms of SLC4A11, indicating that SLC4A11 functional activity is not altered whether translation initiates at M1 or M36. Functional and structural differences between v2-M36-SLC4A11 and v3-SLC4A11. We next looked at the functional and structural differences between the two SLC4A11 variants of human corneal endothelium: v2-M36 and v3. We performed assays of osmotically driven water flux as described. No significant differences in water flux were found between HEK293 cells expressing v2-M36 and v3 (Fig. 6D,E), suggesting the unique amino acids in v3 do not affect transport function. To assess the structural differences between v2-M36 and v3, we created structural homology models for the cytoplasmic domains of v2-M36-SLC4A11 (M36-Y340) and v3-SLC4A11 (M1-Y359,) using the crystal structure of human erythrocyte Band 3 (SLC4A1) cytoplasmic domain (PDB: 1HYN) as the template 49. Earlier analysis indicated that SLC4A11 cytoplasmic domain had the same fold as Band 3 31. Two different models were generated for each variant using Iterative Threading Assembly Refinement (I-TASSER) 50 and Protein Homology/ Analogy Recognition Engine V 2.0 (Phyre 2 ) 51. Homology models predicted through I-TASSER (Fig. 7) had estimated TM-score of 0.44 ± 0.14 (v2-M36) and 0.41 ± 0.14 (v3) and estimated RMSD of 12.0 ± 4.4 (v2-M36) and 12.9 ± 4.2 (v3). While the two structures had a common fold at their C-termini, the N-termini had significant differences (Fig. 7C). The N-terminal loops of each variant are almost 180° apart. The unique sequence at the v3 N-terminus (M1-T19, highlighted in pink), however, is surface exposed, enabling a potential role in protein-protein interaction. Homology models generated by Phyre 2 revealed large differences in the N-terminal region of the two variants with a common conserved C-terminal fold (see Supplementary Fig. S2). Although these models highlight potential functional differences of the two variants, their N-termini were modeled with low confidence. Computational predictions of eukaryotic phosphorylation sites in the unique N-terminal region of v3 (M1-T19) were performed using NetPhos 3.1 52 with a cut-off score of 0.8. Threonine at position 5 (N-MAAATRRVFHLQPC-C) was predicted as a potential phosphorylation site for Protein Kinase C (PKC) with high score (0.887). PKC is crucial in corneal endothelial cell proliferation and cell cycle 53. v3-SLC4A11 could be specifically phosphorylated at Thr5 as part of corneal endothelial cell proliferative regulation. Discussion This study used bioinformatic, transcriptomic and protein level analyses to identify the SLC4A11 translational product in human cornea. Bioinformatic analysis predicted SLC4A11 v2 starting at Met36 to share the highest nucleotide and amino acid sequence conservation with SLC4A11 from other mammals. RT-PCR and qRT-PCR further revealed the presence of only v2 and v3 transcripts in human cornea and the endothelium, where variant 2 is the predominant transcript in the endothelium. Protein analysis showed the predominance of v2 protein in the endothelium when compared to v3. Further, antibodies targeting v2-M1 and v2-M36 SLC4A11 confirmed the presence of SLC4A11 v2-M36 in the human cornea. Homology models of the cytoplasmic domains of v2-M36 and v3 displayed substantial differences in the N-termini of both variants with a common c-terminal fold. No differences were, however, observed in the water flux function of these variants. Data here support that v2-SLC4A11, with translation start at the transcript's second Met is the predominant SLC4A11 protein of human corneal endothelium, although the v3 variant is present at a significant level. No difference in cell surface trafficking or transport function could be detected arising from differences in the N-terminal region of SLC4A11. Using custom-designed antibodies, we found v2 to be four-times more abundant than v3 in the human corneal endothelium. We also found higher v2 abundance than v3 at the transcript level with negligible v1 in the cornea. Mass spectrometry, unfortunately, was unable to differentiate between v2 and v3 in the human cornea due to the absence of specific tryptic sites in the short unique N-terminal region of v3-SLC4A11 (data not shown). An earlier study found SLC4A11 v3 to be the predominant corneal endothelial SLC4A11 transcript 23, however, the source of the endothelial mRNA used was unclear and extraction method was not described. Additionally, the earlier study did not analyze the variants at the protein level. Variant 2 in human cornea has an alternative start site at methionine 36 (v2-M36) but most studies of SLC4A11 variant 2 have used the protein starting at methionine 1 (v2-M1) (see Supplementary Table S2). We did not find significant difference in the cell surface abundance of the v2-M36 vs v2-M1. The N-terminal cytoplasmic domain of SLC4A11, however, is required for its transport function 31. Since we did not observe a difference of SLC4A11 water flux function between SLC4A11 v2 starting at M1 or M36, earlier functional studies of SLC4A11 v2-M1 are likely reliable. Our recent studies have used SLC4A11 v2-M36 after being identified as the relevant isoform to be studied in the cornea (see Supplementary Table S2). Only one study mentions the use of SLC4A11 v1 25 for functional analyses (see Supplementary Fig. S2). The presence of SLC4A11 v2-M36 and v3 in the cornea suggests unique functional roles of the two variants. Homology models of their respective cytoplasmic domains revealed large differences in the N-terminal region of the variants. The location of the unique region of v3-SLC4A11 (Fig. 7B,C) on the surface of the cytoplasmic domain is consistent with a role in protein-protein interaction. Potential phosphorylation sites in the unique region of v3 further suggests a role in protein-protein interaction and modulation by regulatory pathways. No functional differences were, however, found in osmotically driven water flux functions between the two variants. Other SLC4A11 substrates, H + /OH − /NH 3, remain to be tested to explain the presence of two N-terminal splice variants of SLC4A11 in human cornea. Studying the physiologically relevant form of SLC4A11 is crucial to the success investigations of SLC4A11, in particular of molecular therapeutics. Our data indicate that SLC4A11 Variant 2 starting at Met36 is the principal 9:9681 | https://doi.org/10.1038/s41598-019-46094-y www.nature.com/scientificreports www.nature.com/scientificreports/ variant of human corneal endothelium, but variant 3 also contributes to SLC4A11's role in corneal biology to a lesser extent. www.nature.com/scientificreports www.nature.com/scientificreports/ Maximum Sensitivity Substrate, Taq DNA polymerase, CloneJET PCR cloning kit, phenyl methane sulfonyl fluoride (PMSF), glass coverslips and anti-GFP antibody were from Thermo Fisher Scientific (Ottawa, ON, Canada). Poly-L-lysine was from Sigma-Aldrich (Oakville, ON, Canada). Immobilon-P PVDF membranes were from Millipore (Billerica, MA). Monoclonal antibody against glyceraldehyde-3-phosphate dehydrogenase (GAPDH) was from Santa Cruz Biotechnology (Santa Cruz, CA, USA). Monoclonal antibody against green fluorescent protein was from Thermo Fisher Scientific (Ottawa, ON, Canada). Horseradish peroxidase-conjugated sheep anti-mouse IgG was from GE Healthcare Bio-Sciences Corp. (Piscattaway, NJ, USA). ECL chemiluminescent reagent was from Perkin Elmer Life Sciences (Waltham, MA, USA). iQ SYBR green super mix was from Bio-Rad Laboratories (Hercules, CA, USA). Trizol was from Life Technologies (Carlsbad, CA, USA). DNA constructs. Eukaryotic-expression construct for splicing variant 2 of human SLC4A11 encoding an 891 amino acid protein (NCBI Reference Sequence: NG_017072.1), N-terminally tagged with the HA epitope (pSKL1), was reported earlier 34. This construct encodes "long" SLC4A11, starting at presumed start codon Met 1 (SLC4A11 v2-M1). A shortened version of pSKL1, removing the first 35 amino acids of the protein, resulting in an expression construct (pAMC1) encoding an 856 amino acid protein (SLC4A11 v2-M36), was created using the Q5 ® site directed mutagenesis kit. The primers used were 5atctcgcagaatggatacttcg3 and 5gctagccagcttgg-gtct3. gBlock gene fragment encoding the first 135 amino acids of SLC4A11 variant 1 with a BamHI site at the 5 end was synthesized from Integrated DNA technologies and cloned blunt in pJET1.2 vector (pDM16) using the CloneJET PCR cloning kit. This was used as a positive control for variant 1 amplification as it contains the target sequence amplified by SLC4A11 variant 1 primers. SLC4A11 variant 3 with a c-terminal HA epitope tag was in pCDNA3.1 (pCML13). Integrity of all the clones was confirmed by DNA sequencing (Institute for Biomolecular Design, Department of Biochemistry, University of Alberta). Materials Bioinformatic analysis. SLC4A11 v2-M1 nucleotide sequences immediately upstream of the first and second possible translation initiation start codons (ATG) were compared to the human Kozak consensus sequence (GCCACC). To identify SLC4A11 genes in other organisms human SLC4A11 sequence was used as a BLAST query of other species genome databases available through Ensembl. Genomic DNA surrounding and inclusive of SLC4A11 coding sequence was exported and used to search for DNA sequences corresponding to the unique 297 bp, 184 bp and 147 bp regions of human SLC4A11 v1, 2, and 3, respectively. Genomic DNA was manually searched since many databases only contain predicted transcripts, not fully sequenced cDNAs. High sequence conservation allowed identification of the M36 codon readily. Sequences upstream of the M36 codon were carefully examined for the presence of an upstream M1 start codon corresponding to human v2-M1. Translated upstream sequences were aligned to human SLC4A11-v2-M1 amino acid sequences. Preparation of human corneal lysates. Human cadaver corneas, obtained post-mortem with informed consent of next of the kin of deceased donors, were prepared for transplant by the Comprehensive Tissue Centre (University of Alberta Hospital, Edmonton Canada). Human corneas used in this study were deemed unsuitable for transplant and made available for research. Experiments using human corneas were approved by the University of Alberta Human Research Ethics Board (HREB) and experiments followed guidelines from HREB. For protein isolation, six corneal samples were pooled. Average age of donors was 54 years and average endothelial cell density was 2641 cells/mm 2. Lysates from intact corneas and endothelial layer were prepared separately. Briefly, intact corneas were frozen in liquid nitrogen and crushed using a mortar and pestle. The resulting tissue powder was solubilized in IP buffer (1% (v/v) IGEPAL CA-630, 5 mM EDTA, 150 mM NaCl, 0.5% (w/v) sodium deoxycholate, 10 mM Tris, pH 7.5), containing Complete Protease Inhibitor cocktail (mini-complete, Roche) and PMSF. For endothelial cell lysates, six corneas were micro-dissected and the endothelial layers were peeled off along with the Descemet's membrane and pooled. Tissues were also lysed in IP buffer, containing Complete Protease Inhibitor cocktail. Both samples were incubated on ice for 20 min and were centrifuged at 13200 x g for 20 min at 4 °C and protein concentration was determined by BCA Assay 55. Cell surface processing assays. Cell surface processing assays were performed as described earlier 33. Transfected cells were rinsed with 4 °C phosphate buffered saline (PBS) (140 mM NaCl, 3 mM KCl, 6.5 mM Na 2 HPO 3, 1.5 mM KH 2 PO 3, pH 7.4), washed with 4 °C Borate buffer (154 mM NaCl, 7.2 mM KCl, 1.8 mM CaCl 2, 10 mM boric acid, pH 9.0) and labelled with Sulpho-NHS-SS-Biotin (0.5 mg/ml). After washing three times with 4 °C Quenching buffer (192 mM glycine, 25 mM Tris, pH 8.3), cells were solubilised in 500 l of IPB buffer, containing Complete Protease Inhibitor. For each sample, half of the recovered supernatant was retained for later SDS-PAGE analysis (Total Protein, T). The remaining half of the recovered supernatants was combined with 100 l of 50% suspension of High Capacity Streptavidin Agarose resin to precipitate the biotinylated proteins and the supernatant was collected (Unbound Protein, U). The T and U fractions of each sample were processed for SDS-PAGE analysis and immunoblotting as described above. Densitometry using GE image analysis Software and the formula (T-U)/T x 100% was used to calculate the percentage of biotinylated protein. Reverse transcription PCR. Human corneas, deemed unfit for transplantation, were from the Comprehensive Tissue Centre, University of Alberta Hospital. Corneas were either used intact or subjected to dissection to isolate corneal endothelium with Descemet's membrane. Total corneal RNA and isolated endothelial cell RNA each came from three corneas, respectively with average donor age 62 and 52 years and average endothelial cell density 3256 and 3046 cells/mm 2. RNA was isolated from tissues using Trizol reagent (Life Technologies) according to the manufacturer's instructions. The resulting RNA was then used as template with SuperScript TM III Reverse Transcriptase (Invitrogen) (or without enzyme as a negative control) to generate cDNA according to manufacturer's instructions. Resulting cDNA (100 ng) was used as template in PCR with Taq Polymerase along with the corresponding primers (see Supplementary Table S1). PCR was performed using an MJ Research Inc. PTC-100 thermal cycler. PCR conditions were: 2 min 95 °C, 40 cycles of (30 s at 95 °C, 30 s at 54 °C (variant 1, 2, 3 primers), 15 s at 72 °C) and 10 min at 72 °C. Resulting PCR products were visualized by agarose gel electrophoresis. To check the specificity of each primer pair, PCR was performed using the primer pairs for each variant with three synthetic templates (pDM16, pSKL1 and pCML13), using similar conditions as mentioned above. Resulting PCR products were visualized by agarose gel electrophoresis. Real Time quantitative PCR. cDNA from total cornea and isolated endothelium were used with primer pairs for variant 1, 2, 3 and GAPDH (see Supplementary Table S1) and iQ SYBR green super mix on Rotor Gene RG-3000 real time analysis system (Corbett life Science, San Francisco, CA, USA). Reactions were performed in 20 l reaction mixture with cDNA (from 1 ng RNA), 1X SYBR green mix and 300 nM of forward and reverse primer. Reactions without reverse transcriptase enzyme samples were used to quantify the background and reactions without template were used as a negative control for each group. Primers for GAPDH were used as an internal control. PCR conditions were: 10 min for 95 °C, 40 cycles of (10 s at 95 °C, 15 s at 54 °C, 20 s at 72 °C). To quantify transcript abundance, a standard curve was constructed for each variant using a range of copies for each synthetic template (2.5 to 2.5 10 4 copies) in the similar reaction conditions as above. Fluorescence was recorded at the end of each elongation step. After 40 cycles, a melting curve was generated by slowly increasing the temperature (0.1 °C/s) from 54 °C to 95 °C, while the fluorescence was measured. The threshold cycle (C T ) was calculated manually and kept consistent throughout. A standard curve was constructed for each variant by plotting the Log 10 of the copies against the C T values. The C T for the samples were normalized for GAPDH and plotted in the standard curve to estimate the number of copies of each transcript per reaction. The values for No RT control were subtracted for each variant in each group. Assays of osmotically driven water flux. HEK293 cells were grown on poly-L-lysine-coated 25 mm round glass coverslips and co-transfected with cytosolic enhanced green fluorescent protein (eGFP) (peGFP-C1 vector, Clontech, USA) and, or pcDNA 3.1 (empty vector) or the indicated SLC4A11 plasmid constructs in a 1:8 molar ratio 19. After 48 h, coverslips were mounted in a 35 mm diameter Attofluor Cell Chamber (Molecular Probes) and washed with 1X PBS. During experiments, the chamber was perfused at 3.5 ml/min with isotonic MBSS buffer (90 mM NaCl, 5.4 mM KCl, 0.4 mM MgCl 2, 0.4 mM MgSO 4, 3.3 mM NaHCO 3, 2 mM CaCl 2, 5.5 mM glucose, 100 mM D-mannitol and 10 mM HEPES, pH 7.4, 300 mOsm/kg) and then with hypotonic (200 mOsm/ kg) MBSS buffer, pH 7.4 (same composition as previous but lacking D-mannitol). The chamber was mounted on the stage of a Wave FX Spinning Disc Confocal Microscope (Quorum Technologies, Guelph, Canada), with a Yokogawa CSU10 scanning head. The microscope has a motorized XY stage with Piezo Focus Drive (ASI, MS-4000 XYZ Automated Stage) and a live cell environment chamber (Chamlide, Korea), set to 24 °C for the duration of the experiment. Acquisition was performed with a Hamamatsu C9100-13 Digital Camera (EM-CCD) and a 20X objective during excitation with laser (Spectral Applied Research, Richmond Hill, ON, Canada) at 491 nm. eGFP fluorescence, collected though a dichroic cube (Quorum Technologies, Guelph, Canada) at wavelengths 520-540 nm, was acquired at 1 point s −1 for 4-6 min. Quantitative image analysis was performed by selecting a region of interest for each HEK293 cell with Volocity 6.0 software (PerkinElmer, ON, Canada). Following the switch to hypotonic medium, the rate of fluorescence change was determined from the initial 15 s of linear fluorescence change. 9:9681 | https://doi.org/10.1038/s41598-019-46094-y www.nature.com/scientificreports www.nature.com/scientificreports/
/** * Created by tjnorris on 10/13/15. */ public class UserInfo { private String _name; private Date _birthday; private Long _currentPack; private Date _lastAppUse; public String getName() { return _name; } public void setName(String name) { _name = name; } public Date getBirthday() { return _birthday; } public void setBirthday(Date birthday) { _birthday = birthday; } public Long getCurrentPack() { return _currentPack; } public void setCurrentPack(Long currentPack) { _currentPack = currentPack; } public Date getLastAppUse() { return _lastAppUse; } public void setLastAppUse(Date lastAppUse) { _lastAppUse = lastAppUse; } }
from pynetdicom import AE, evt from pynetdicom.sop_class import VerificationSOPClass from pynetdicom.apps.common import ElementPath from pydicom.dataset import Dataset import os.path import csv import time import datetime import pytz import signal import threading import tqdm import concurrent.futures import numpy as np import inquirer import ast import sys from pydicom.uid import ( ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian, generate_uid ) from pynetdicom import ( AE, QueryRetrievePresentationContexts, BasicWorklistManagementPresentationContexts, PYNETDICOM_UID_PREFIX, PYNETDICOM_IMPLEMENTATION_UID, PYNETDICOM_IMPLEMENTATION_VERSION ) from pynetdicom._globals import DEFAULT_MAX_LENGTH from pynetdicom.pdu_primitives import SOPClassExtendedNegotiation from pynetdicom.sop_class import ( PatientRootQueryRetrieveInformationModelFind, StudyRootQueryRetrieveInformationModelFind, PatientStudyOnlyQueryRetrieveInformationModelFind, PatientRootQueryRetrieveInformationModelMove, StudyRootQueryRetrieveInformationModelMove, PatientStudyOnlyQueryRetrieveInformationModelMove ) continue_extraction = True def sigint_handler(signal, frame): global continue_extraction continue_extraction = False raise KeyboardInterrupt print('Stopping extraction') def watch_sigint(): signal.signal(signal.SIGINT, sigint_handler) class hashabledict(dict): def __hash__(self): return hash(tuple(sorted(self.items()))) def dataset_to_csv(ds, filepath, fieldnames): write_dict = {} for key in fieldnames: write_dict[key] = str(ds[key].value) dict_to_csv(write_dict, filepath, fieldnames) def request_from_csv(filepath): if os.path.exists(filepath): with open(filepath, 'r') as csvfile: reader = csv.DictReader(csvfile) rows = [] for row in reader: rows.append(hashabledict(row)) return rows else: return [] def dict_to_csv(write_dict, filepath, fieldnames): if os.path.exists(filepath): with open(filepath, 'a', newline='', ) as csvfile: writer = csv.DictWriter(csvfile, fieldnames=sorted(fieldnames), dialect='excel') writer.writerow(write_dict) else: with open(filepath, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=sorted(fieldnames), dialect='excel') writer.writeheader() writer.writerow(write_dict) def add_element_to_list(element_list, key, value): match_elements = [x if ((x.partition('=')[0] == key) or (x == key)) else None for x in element_list] if match_elements.count(None) != len(match_elements): theVal = [f'{key}={value}' if ((x.partition('=')[0] == key) or (x == key)) else x for x in element_list] return theVal else: theVal = f'{key}={value}' element_list.append(theVal) return element_list def create_dataset(request): ds = Dataset() try: elements = [ElementPath(path) for path in request['elements']] for elem in elements: ds = elem.update(ds) except Exception as exc: raise exc return ds def create_requests(config): requests = [] if 'elements_batch_file' in config['request']: if os.path.exists(config['request']['elements_batch_file']): with open(config['request']['elements_batch_file'], newline='') as csvfile: reader = csv.DictReader(csvfile, dialect='excel') for row in reader: row_request = config['request'].copy() for key in row: row_request['elements'] = add_element_to_list(row_request['elements'], key, row[key]) row_request['elements'] = sorted(row_request['elements']) requests.append(row_request) else: requests.append(config['request']) else: requests.append(config['request']) filepath_requests = os.path.join(config['output']['directory'], 'requests.whole') filepath_requests_completed = os.path.join(config['output']['directory'], 'requests.completed') filepath_requests_failed = os.path.join(config['output']['directory'], 'requests.failed') if os.path.exists(filepath_requests): os.remove(filepath_requests) if os.path.exists(filepath_requests_completed): os.remove(filepath_requests_completed) if os.path.exists(filepath_requests_failed): os.remove(filepath_requests_failed) for request in requests: dict_to_csv(request, filepath_requests, request.keys()) return requests def pending_requests(config): """ Returns pending requests to enable resuming """ filepath_requests = os.path.join(config['output']['directory'], 'requests.whole') filepath_requests_completed = os.path.join(config['output']['directory'], 'requests.completed') reqs1 = request_from_csv(filepath_requests) reqs2 = [] if os.path.isfile(filepath_requests_completed): reqs2 = request_from_csv(filepath_requests_completed) requests = list(set(reqs1) - set(reqs2)) for request in requests: request['elements'] = list(sorted(ast.literal_eval(request['elements']))) request['throttle_time'] = float(request['throttle_time']) request['threads'] = int(request['threads']) questions = [] if requests: questions = [ inquirer.List('resume', message="A partial extraction was detected. Do you want to resume or overwrite?", choices=['Resume', 'Overwrite'], ), ] else: questions = [ inquirer.List('resume', message="A completed extraction was detected. Do you want to overwrite?", choices=['Cancel', 'Overwrite'], ), ] answers = inquirer.prompt(questions) if answers['resume'] == 'Overwrite': requests = create_requests(config) return requests def failed_requests(config): """ Returns failed requests to enable re-trying """ filepath_requests_failed = os.path.join(config['output']['directory'], 'requests.failed') questions = [ inquirer.List('failed', message="Failed requests from a previous extraction were detected. Do you want to re-try the failed requests?", choices=['Re-try failed requests', 'Remove failed requests'], ), ] answers = inquirer.prompt(questions) requests = [] if answers['failed'] == 'Remove failed requests': requests = pending_requests(config) else: reqs1 = request_from_csv(filepath_requests_failed) requests = list(set(reqs1)) for request in requests: request['elements'] = list(sorted(ast.literal_eval(request['elements']))) request['throttle_time'] = float(request['throttle_time']) request['threads'] = int(request['threads']) if os.path.exists(filepath_requests_failed): os.remove(filepath_requests_failed) return requests def thread_scu_function(config, pbar, requests): scu = SCU(config) scu.pbar = pbar scu.process_requests_batch(list(requests)) return def process_request_batch(config): requests = [] filepath_requests = os.path.join(config['output']['directory'], 'requests.whole') filepath_requests_completed = os.path.join(config['output']['directory'], 'requests.completed') filepath_requests_failed = os.path.join(config['output']['directory'], 'requests.failed') if (os.path.isfile(filepath_requests)): # Previous extraction detected if os.path.isfile(filepath_requests_failed): # Failed requests detected requests = failed_requests(config) else: # No failed requests detected, return pending requests requests = pending_requests(config) else: # No previous extraction detected requests = create_requests(config) if requests: watch_sigint() split_requests = np.array_split(requests, config['request']['threads']) print('To stop extraction, press CTRL-C. Extraction can be resumed at a later time.') pbar = tqdm.tqdm(total=len(requests), desc='Sending {} requests '.format(config['request']['type']), unit='rqst') fn = lambda x : thread_scu_function(config, pbar, x) if config['request']['threads'] > 1: with concurrent.futures.ThreadPoolExecutor(max_workers=config['request']['threads']) as executor: executor.map(fn, split_requests) else: fn(split_requests[0]) pbar.close() else: print('No further requests pending') def seconds_until(time_str, tzname): """ Returns the number of seconds from now until the time in format HH:mm """ list_time_str = time_str.split(':') h = int(list_time_str[0]) m = int(list_time_str[1]) tz = pytz.timezone(tzname) now = datetime.datetime.now(tz=tz) return int((datetime.timedelta(hours=24) - (now - now.replace(hour=h, minute=m, second=0, microsecond=0))) .total_seconds() % (24 * 3600)) class SCU(object): """ SCU class This class is used to send batches of DIMSE requests (c-find, c-echo, c-move) to a remote SCP """ def __init__(self, config): self.config = config self.ae = self.create_ae() self.query_model = self.create_query_model() self.pbar = None def create_ae(self): # Create application entity ae = AE(ae_title=self.config['local']['aet']) # Set timeouts ae.acse_timeout = 300 ae.dimse_timeout = 300 ae.network_timeout = 300 # Set the Presentation Contexts we are requesting the Find SCP support if self.config['request']['type'].lower() == 'c-find': ae.requested_contexts = QueryRetrievePresentationContexts elif self.config['request']['type'].lower() == 'c-echo': ae.requested_contexts = [VerificationSOPClass] elif self.config['request']['type'].lower() == 'c-move': ae.requested_contexts = QueryRetrievePresentationContexts return ae def establish_association(self): return self.ae.associate(self.config['pacs']['hostname'], self.config['pacs']['port'], ae_title=self.config['pacs']['aet'], max_pdu=16382) def wait_until_scheduled_time(self): if 'schedule' in self.config: if self.config['schedule']['enabled']: sec_until_start = seconds_until(self.config['schedule']['start_time'], self.config['schedule']['timezone']) sec_until_end = seconds_until(self.config['schedule']['end_time'], self.config['schedule']['timezone']) if sec_until_end > sec_until_start: if self.pbar: self.pbar.set_description('Extraction PAUSED (will resume at {})'.format(self.config['schedule']['start_time'])) time.sleep(sec_until_start) else: if self.pbar: self.pbar.set_description('Sending {} requests (will pause at {})'.format(self.config['request']['type'], self.config['schedule']['end_time'])) def retry_association(self): for i in range(100): if not self.association.is_established: time.sleep(1) print('Re-trying association') self.association = self.establish_association() else: return sys.exit(1) def create_query_model(self): request = self.config['request'] query_model = None if request['type'].lower() == 'c-find': if request['model'] == 'study': query_model = StudyRootQueryRetrieveInformationModelFind elif self.config['request']['model'] == 'psonly': query_model = PatientStudyOnlyQueryRetrieveInformationModelFind else: query_model = PatientRootQueryRetrieveInformationModelFind elif request['type'].lower() == 'c-move': if request['model'] == 'study': query_model = StudyRootQueryRetrieveInformationModelMove elif self.config['request']['model'] == 'psonly': query_model = PatientStudyOnlyQueryRetrieveInformationModelMove else: query_model = PatientRootQueryRetrieveInformationModelMove return query_model def process_requests_batch(self, requests): global continue_extraction self.association = self.establish_association() for request in requests: if continue_extraction: self.wait_until_scheduled_time() self.process_request(request) time.sleep(request['throttle_time']) self.association.release() def process_request(self, request): if request['type'].lower() == 'c-find': self.send_find(request) if request['type'].lower() == 'c-move': self.send_move(request) return def send_find(self, request): identifier = create_dataset(request) keywords = [ElementPath(path).keyword for path in request['elements']] if not self.association.is_established: self.retry_association() if self.association.is_established: responses = self.association.send_c_find(identifier, self.query_model) for (status, rsp_identifier) in responses: if 'Status' in status: if status and status.Status in [0xFF00, 0xFF01]: # Status pending path = os.path.join(self.config['output']['directory'], self.config['output']['database_file']) dataset_to_csv(rsp_identifier, path, keywords) else: if self.pbar: self.pbar.update(1) if hasattr(status, 'Status'): identifier.Status = hex(status.Status) else: identifier.Status = 'timeout' # Status Success, Warning, Cancel, Failure if identifier.Status in [hex(0x0000)]: filepath_requests_completed = os.path.join(self.config['output']['directory'], 'requests.completed') dict_to_csv(request, filepath_requests_completed, request.keys()) else: print('Failed with code ', hex(status.Status)) filepath_requests_failed = os.path.join(self.config['output']['directory'], 'requests.failed') dict_to_csv(request, filepath_requests_failed, request.keys()) def send_move(self, request): identifier = create_dataset(request) keywords = [ElementPath(path).keyword for path in request['elements']] if not self.association.is_established: self.retry_association() if self.association.is_established: responses = self.association.send_c_move(identifier, self.config['local']['aet'], self.query_model) for (status, rsp_identifier) in responses: if status and status.Status in [0xFF00]: # Status pending pass else: # Status Success, Warning, Cancel, Failure if self.pbar: self.pbar.update(1) if hasattr(status, 'Status'): identifier.Status = hex(status.Status) else: identifier.Status = 'timeout' keywords.append('Status') path = os.path.join(self.config['output']['directory'], self.config['output']['database_file']) dataset_to_csv(identifier, path, keywords) if identifier.Status in [hex(0x0000)]: filepath_requests_completed = os.path.join(self.config['output']['directory'], 'requests.completed') dict_to_csv(request, filepath_requests_completed, request.keys()) else: filepath_requests_failed = os.path.join(self.config['output']['directory'], 'requests.failed') dict_to_csv(request, filepath_requests_failed, request.keys())
Following worldwide uproar, the deputy mayor who organized the Orthodox Jewish students responsible for the burning of hundreds of New Testaments has publicly apologized to Christians worldwide for the intolerant act and for any hurt feelings it might have produced. The burning of the New Testaments last Thursday by yeshiva students was regrettable and unplanned, said Deputy Mayor Uzi Aharon of the central Israeli town Or Yehuda to The Jerusalem Post on Tuesday. Aharon had initially defiantly defended the students' action when news broke out about the Bible burning. He had described their action to various media outlets as "purging the evil among us," fighting those that break the law by trying to convert Jews, and following the "commandment." But by the time he spoke to The Jerusalem Post, which publishes a monthly Christian edition, he changed his tone and said he was very sorry for the book burning, that it was unplanned, and that he was unaware the event may have caused damage to Christian-Jewish relations. "I wasn't even on the scene when the boys rounded up all the Bibles and brought them all to one place [near the synagogue in Neveh Rabin]," Aharon claimed to the Post. "They started burning them before I got there. Once I arrived the most I could do was pull a Bible out of the fire. I put it in nylon and its now in my car. I am really sorry for the book burning, but I did not organize it, it was a spontaneous thing by the yeshiva boys," Aharon said. He added, "We respect all religions as we expect others to respect ours. I am very sorry that the New Testament was burned, we mean it no harm and I'm sorry that we hurt the feelings of others." However, the Or Yehuda deputy mayor also declared that Israel cannot allow messianic Jews to "come into our homes and incite against our religion, and turn our children away from Judaism. That is against the law." Aharon, a strong anti-missionary activist, admits he had initially organized "three or four" yeshiva students from the town's Michtav M'Eliahu Yeshiva to go to apartments in a part of town with many Ethiopian Jews to collect packages recently given to them by local messianic Jews, according to the Post. The packages contained a New Testament and pamphlets, which Aharon claims encouraged going against Judaism. The New Testament burning is the latest incident revealing escalating tension between Orthodox Jews and messianic Jews as well as any Christian trying to share the Gospel with Jews in Israel. "What worries me is that nobody has stood up against this," said Kalisher, the son of Holocaust survivors, to the Post. "It seems there is a war against messianic Jews in Israel." Kalisher argues that Bibles are not forced on anybody or into any homes, contrary to what many Orthodox Jews claim about Christian evangelism. "The book has never harmed anyone, you can choose to read it or choose not to read it," he said. "If this happened to Jewish books overseas we would be screaming anti-Semitism." He acknowledged the increased tension between the two communities, noting bombs that have been sent to messianic Jews, "and now books have been burned." "This cannot be allowed to happen here," said the messianic Jew. Calev Myers, a lawyer representing messianic Jews in Israel, not only condemned the Or Yehuda incident, but he called it an "illegal act" and part of growing institutionalized discrimination against messianic Jews in Israel. The lawyer is waiting to see if Or Yehuda police will open an investigation into the New Testament burning incident, but if the do not, he said he will file a petition. "I expect the police to investigate everyone who was involved in the book burning, including those who incited the youths to the act, even if that includes Mr. Aharon," Myers said. "Israelis have to understand something: Messianic Jews here have strong ties to American evangelical Christians, and there are hundreds of millions of people in the world who see the burning of the New Testament as a very serious issue. The New Testament is believed in by hundreds of millions of people. It is not in Israel's national interest to allow the burning of their holy book," Myers said. On a larger scale, various groups throughout Israel have increasingly tried to prevent Christians from sharing their faith with Jews. In September, Israeli rabbis had urged Jews to boycott a massive Christian tourism event to avoid attempts to convert them to Christianity. Earlier that same year, Israel's interior ministry officials said an evangelical pastor and his wife – who had lived in Israel for nearly 20 years – had to leave the country within two weeks because their application for permanent residency was rejected. Officials said the decision resulted from suspicion that the two were involved in missionary work, which Israel bans. Another incident occurred in July, when the country's cable television company pulled the plug on a major Christian TV Network, which has programs offering biblical teachings from the New Testament as well as infomercials that targets a Jewish audience with the message of Jesus. The International Christian Embassy Jerusalem, which has in the past resisted criticism of Israel, has called the burning of the Christian Holy Book "unacceptable" and "offensive to most Christians."
<reponame>lstyles/nsgflowlogsbeat<filename>vendor/github.com/elastic/beats/vendor/gopkg.in/jcmturner/rpc.v1/ndr/union.go package ndr import ( "errors" "fmt" "reflect" ) // Union interface must be implemented by structs that will be unmarshaled into from the NDR byte stream union representation. // The union's discriminating tag will be passed to the SwitchFunc method. // The discriminating tag field must have the struct tag: `ndr:"unionTag"` // If the union is encapsulated the discriminating tag field must have the struct tag: `ndr:"encapsulated"` // The possible value fields that can be selected from must have the struct tag: `ndr:"unionField"` type Union interface { SwitchFunc(t interface{}) string } // Union related constants such as struct tag values const ( unionSelectionFuncName = "SwitchFunc" TagEncapsulated = "encapsulated" TagUnionTag = "unionTag" TagUnionField = "unionField" ) func (dec *Decoder) isUnion(field reflect.Value, tag reflect.StructTag) (r reflect.Value) { ndrTag := parseTags(tag) if !ndrTag.HasValue(TagUnionTag) { return } r = field // For a non-encapsulated union, the discriminant is marshalled into the transmitted data stream twice: once as the // field or parameter, which is referenced by the switch_is construct, in the procedure argument list; and once as // the first part of the union representation. if !ndrTag.HasValue(TagEncapsulated) { dec.r.Discard(int(r.Type().Size())) } return } // unionSelectedField returns the field name of which of the union values to fill func unionSelectedField(union, discriminant reflect.Value) (string, error) { if !union.Type().Implements(reflect.TypeOf(new(Union)).Elem()) { return "", errors.New("struct does not implement union interface") } args := []reflect.Value{discriminant} // Call the SelectFunc of the union struct to find the name of the field to fill with the value selected. sf := union.MethodByName(unionSelectionFuncName) if !sf.IsValid() { return "", fmt.Errorf("could not find a selection function called %s in the unions struct representation", unionSelectionFuncName) } f := sf.Call(args) if f[0].Kind() != reflect.String || f[0].String() == "" { return "", fmt.Errorf("the union select function did not return a string for the name of the field to fill") } return f[0].String(), nil }
def bdev_nvme_opal_init(client, nvme_ctrlr_name, password): params = { 'nvme_ctrlr_name': nvme_ctrlr_name, 'password': password, } return client.call('bdev_nvme_opal_init', params)
<filename>inference-engine/src/inference_engine/ngraph_ops/proposal_ie.cpp //***************************************************************************** // Copyright 2017-2019 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. //***************************************************************************** #include <memory> #include "proposal_ie.hpp" #include "ngraph/op/constant.hpp" using namespace std; using namespace ngraph; op::ProposalIE::ProposalIE(const std::shared_ptr<Node>& class_probs, const std::shared_ptr<Node>& class_logits, const std::shared_ptr<Node>& image_shape, const ProposalAttrs& attrs) : Op(check_single_output_args({class_probs, class_logits, image_shape})) , m_attrs(attrs) { constructor_validate_and_infer_types(); } void op::ProposalIE::validate_and_infer_types() { set_input_is_relevant_to_shape(2); const auto& class_probs_pshape = get_input_partial_shape(0); const auto& class_logits_pshape = get_input_partial_shape(1); const auto& image_shape_pshape = get_input_partial_shape(2); if (class_probs_pshape.is_static() && class_logits_pshape.is_static() && image_shape_pshape.is_static()) { const Shape class_probs_shape{class_probs_pshape.to_shape()}; const Shape class_logits_shape{class_logits_pshape.to_shape()}; const Shape image_shape_shape{image_shape_pshape.to_shape()}; NODE_VALIDATION_CHECK( this, class_probs_shape.size() == 4, "Proposal layer shape class_probs input must have rank 4 (class_probs_shape: ", class_probs_shape, ")."); NODE_VALIDATION_CHECK( this, class_logits_shape.size() == 4, "Proposal layer shape class_logits_shape input must have rank 4 (class_logits_shape: ", class_logits_shape, ")."); NODE_VALIDATION_CHECK( this, image_shape_shape.size() == 2, "Proposal layer image_shape input must have rank 2 (image_shape_shape: ", image_shape_shape, ")."); NODE_VALIDATION_CHECK( this, image_shape_shape[1] >= 3 && image_shape_shape[1] <= 4, "Image_shape 1D tensor must have => 3 and <= 4 elements (image_shape_shape[1]", image_shape_shape[1], ")."); auto batch_size = class_probs_shape[0]; set_output_type(0, get_input_element_type(0), Shape{batch_size * m_attrs.post_nms_topn, 5}); } else { set_output_type(0, get_input_element_type(0), PartialShape::dynamic()); } } shared_ptr<Node> op::ProposalIE::copy_with_new_args(const NodeVector& new_args) const { check_new_args_count(this, new_args); return make_shared<ProposalIE>(new_args.at(0), new_args.at(1), new_args.at(2), m_attrs); }
A Literature Review on the Impact of Games on Learning English Vocabulary to Children Digital games play a significant role in the life of the new generation. Although there are many criticisms, many studies focus on the importance of digital games in improving learners vocabulary in the target language. Researchers have begun conductingseveral researches on how using games in the class can foster vocabulary learning. The aim of this paper is to investigate the impacts of digital games on childrens vocabulary learning depending on a literature review. Many studies focus on the impacts of digital games on different aspects of education. This conceptual paper aims to shed light on some games' benefits, and challenges which educators and children face in the use of digital games. The findings of this paper show that Games are used not only for making children successful in EFL classes but more importantly, for motivating them and increasing the cooperation among children. In addition,the findings state that there are advantages as well as disadvantages in using games for learning English vocabulary.
Investment under uncertainty with implementation delay One of the major characteristics of the capital budgeting process is the delay existing between the investment decision and its implementation. This paper analyses investment decisions under uncertainty with implementation delay in a unified analytical framework. We provide closed-form solutions relating the value of the investment opportunity and the optimal investment threshold to the size of the delay. We show that the implementation lag creates an embedded option for the investor: the option to abandon the project during this delay. We de- rive the value of this option for various exercise policies corresponding to different levels of freedom with respect to the abandonment of the project and analyze its effects on the investment policy of the firm.
The Detroit Pistons were the reigning NBA champs and the team that had crushed Jordan's championship dreams three years in a row. Michael Jordan exacted revenge with this insane dunk from the free-throw line over Bill Laimbeer during Game 2 of the Eastern Conference Finals. Detroit: You lose.
Volunteer hiring, organizational form and the provision of mission-oriented goods Mission-oriented organizations, such as nonprofit organizations and NGOs, rely critically on volunteer recruitment to achieve their organizational goals. Besides serving as an outlet of altruistic motives, volunteering often acts as a stepping-stone for a paid position in the nonprofit sector. This paper provides an explanation for the fact that nonprofit employers are uniquely able to attract such volunteers with social concerns and career aspirations and for the related observation that nonprofits figure prominently in mission-related activities. Our theory is predicated on that - by committing to not distributing profits - nonprofit incorporation relaxes the incentive constraint that employers face when implicitly contracting with volunteers, without relying on ex ante differences in workers' preferences over the employer's identity or inherent asymmetries between nonprofit and for-profit providers. The not-for-profit commitment is shown to be effective only in activities where producers, who can choose to be for-profit or nonprofit, care about the level or quality of the service being provided. Thus, in the equilibrium of the model developed here nonprofit entry in sectors where missions play a defining role and the hiring of volunteers arise endogenously due to economic forces. This equilibrium outcome has some desirable welfare properties. Keywords; volunteers, nonprofit institutions, privately provided public goods
ALBUQUERQUE, N.M. — New Mexico became the seventeenth state in the U.S. in December to surpass the 1,000-megawatt mark for installed wind energy capacity, following the startup of a 250-megawatt wind farm in Roosevelt County. New Mexico is now generating 1,112 MW of electricity from a dozen utility-scale wind installations, or enough electricity to power 190,000 homes every year, according to a recent report from the American Wind Energy Association. New Mexico’s growth is part of a trend blowing across the country. Wind accounted for more than 40 percent of all new electric generation added to the grid last year, reflecting, in part, a rapid decline in prices. Costs for wind generation have fallen by about 66 percent over the last five years. All told, wind generation reached nearly 75,000 MW of installed capacity as of March. That represents enough electricity to power about 20 million average homes, accounting for about 5 percent of all the country’s electricity. The wind industry is also helping spur economic development, with about $128 billion invested to date in wind projects, and more than 88,000 people currently employed in wind-related jobs. In New Mexico, wind developers have invested about $1.8 billion, employing about 2,000 people as of year-end 2015. And the state has capacity for a lot more wind generation, particularly on New Mexico’s gusty central and eastern plains. For that to happen, the state needs more transmission infrastructure, something local and national developers are working on. But even without new transmission lines, more wind farms are in the works. That includes the 298 MW El Cabo Wind Farm in Torrance County, which Oregon-based developer Iberdrola Renewables expects to bring online next year. Once operating, El Cabo will be the largest wind farm in the state. For now, that record belongs to the Roosevelt Wind Project, a 250 MW farm that California-based developer EDF Renewable Energy brought online in December. That new farm, located about 18 miles southwest of Portales, will supply all its electricity to Southwest Public Service Co., which serves customers in eastern New Mexico and West Texas. EDF also brought a second, 50 MW wind farm in Roosevelt County online in March to sell electricity through the Southwest Power Pool.
. OBJECTIVE To evaluate the effect of probiotics (bifidobacterium breve and lactobacillus acidophilus) on serum lipid, serum insulin and insulin resistance in high-fat diet (HFD)-induced obese rats. METHODS Fifty male Sprague-Dawley rats were randomly assigned to a control (n=10) and a high fat diet groups (n=40) and were fed with standard diet and HFD respectively. Four weeks later, thirty-six HFD-induced obese rats were randomly administered with normal saline (NS), bifidobacterium breve and lactobacillus acidophilus daily (n=12 each). Four weeks later, body lengths, body weights and abdomen circumference of rats were measured, blood lipid, glucose and insulin levels were measured, and Lee's index and insulin resistance index were calculated. RESULTS Body weight, abdomen circumference, Lee's index, fasting glucose, triglyceride (TG), total cholesterol (TC), low density lipoprotein (LDL) in the NS-treated HFD group were significantly higher than the control group (P<0.05). The bifidobacterium breve and lactobacillus acidophilus-treated groups had significantly lower levels of body weight, abdomen circumference, Lee's index, fasting glucose, TC, TG and LDL than the NS-treated HFD group (P<0.05), but the levels of the parameters in the bifidobacterium breve and lactobacillus acidophilus-treated groups were significantly higher than the control group (P<0.05). High density lipoprotein (HDL) and insulin sensitivity index in the NS-treated HFD group were significantly lower than the control group (P<0.05). Bifidobacterium breve and lactobacillus acidophilus treatment dramatically increased HDL levels and insulin sensitivity index compared with the NS-treated HFD group (P<0.05), although the levels of the two parameters did not reach to the levels of the control group. There were significant differences in the levels of fasting insulin, insulin resistance index and insulin secretion index between the bifidobacterium breve and lactobacillus acidophilus groups (P<0.05). CONCLUSIONS Lactobacillus acidophilus and bifidobacterium breve can decrease serum levels of lipid and glucose and improve insulin resistance in obese rats. Bifidobacterium breve seems to be more effective on attenuating insulin resistance than lactobacillus acidophilus.
Sitedirected mutagenesis, expression, purification and translesion synthesis analysis of human DNA polymerase mutations found in xeroderma pigmentosum variant and melanoma patients The variant form of human syndrome Xeroderma Pigmentosum (XPV) is caused by mutations in DNA polymerase (hpol). XPV patients are deficient in repairing the DNA damage caused by ultraviolet (UV) light in the form of cyclobutanepyrimidine dimers (CPD). Many missense mutations in hpol catalytic core (1432aa) have been identified in XPV patients, and mutations have also been implicated in Melanoma. The aim of current research is to confirm that the catalytic core of hpol is 1432aa. Hpol (1432aa) has been constructed. It will be expressed in E.coli and tested in primer extension assays to assess its effectiveness during translesion synthesis (TLS). Several of the point mutations have been successfully introduced in to hpol (1432aa) by sitedirected mutagenesis. Those mutants are expressed in E.coli cells and will be examined for their activity during translesion synthesis (TLS). Source of research support: Student research grant to Mukesh Kumar, Department of Chemistry, TTU, Cookeville, TN, Faculty grant to Xiaohua Jiang, College of Arts and Sciences, TTU, Cookeville, TN
/** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "no ActiveX", IE = "<![CDATA[child-cdata]]><!--child-comment--><child-element/>" + "<child-element2><grand-child-element/></child-element2>child-text") public void xml() throws Exception { final String test = "" + "var cdata = doc.createCDATASection('child-cdata');\n" + "fragment.appendChild(cdata);\n" + "var comment = doc.createComment('child-comment');\n" + "fragment.appendChild(comment);\n" + "var element = doc.createElement('child-element');\n" + "fragment.appendChild(element);\n" + "var element2 = doc.createElement('child-element2');\n" + "fragment.appendChild(element2);\n" + "var element2a = doc.createElement('grand-child-element');\n" + "element2.appendChild(element2a);\n" + "var text = doc.createTextNode('child-text');\n" + "fragment.appendChild(text);\n" + "var fragment2 = doc.createDocumentFragment();\n" + "fragment.appendChild(fragment2);\n" + "log(fragment.xml);\n"; tester(test); }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { StartupStudentsComponent } from './modules/startup-students/startup-students.component'; import { MainComponent } from './pages/main/main.component'; import { AbiturMapComponent } from './modules/abitur-map/abitur-map.component'; import { AbiturientComponent } from './pages/abiturient/abiturient.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatExpansionModule} from '@angular/material/expansion'; import { StartupStudentsLessComponent } from './modules/startup-students-less/startup-students-less.component'; import { ProjectsMiriteamComponent } from './modules/projects-miriteam/projects-miriteam.component'; import { AdditionalEducationComponent } from './modules/additional-education/additional-education.component'; import { PeopleLeaveComponent } from './modules/people-leave/people-leave.component'; import { PartnersComponent } from './modules/partners/partners.component'; import { DetailsPartnersComponent } from './modules/details-partners/details-partners.component'; import { LeftPageBarComponent } from './modules/left-page-bar/left-page-bar.component'; import { GlingOneComponent } from './modules/gling-one/gling-one.component'; import { GlinfTwoComponent } from './modules/glinf-two/glinf-two.component'; import { NewsComponent } from './modules/news/news.component'; import { ImpinfComponent } from './modules/impinf/impinf.component'; import { GrantComponent } from './modules/grant/grant.component'; import { GrantsComponent } from './modules/grants/grants.component'; import { AdditionalInnovationComponent } from './modules/additional-innovation/additional-innovation.component'; import { DisciplinesComponent } from './modules/disciplines/disciplines.component'; import { StudlifeComponent } from './modules/studlife/studlife.component'; import { DemandComponent } from './modules/demand/demand.component'; import { UsefullinfComponent } from './modules/usefullinf/usefullinf.component'; import { FieldsstudyComponent } from './modules/fieldsstudy/fieldsstudy.component'; import { NewsPageComponent } from './pages/news-page/news-page.component'; import {MatPaginatorModule} from '@angular/material/paginator'; import { GrantspComponent } from './pages/grantsp/grantsp.component'; import { ProjectsPComponent } from './pages/projects-p/projects-p.component'; import { KafPComponent } from './pages/kaf-p/kaf-p.component'; import { GlinfThreeComponent } from './modules/glinf-three/glinf-three.component'; import { DirectionComponent } from './modules/direction/direction.component'; @NgModule({ declarations: [ AppComponent, StartupStudentsComponent, MainComponent, AbiturMapComponent, AbiturientComponent, StartupStudentsLessComponent, ProjectsMiriteamComponent, AdditionalEducationComponent, PeopleLeaveComponent, PartnersComponent, DetailsPartnersComponent, LeftPageBarComponent, GlingOneComponent, GlinfTwoComponent, NewsComponent, ImpinfComponent, GrantComponent, GrantsComponent, AdditionalInnovationComponent, DisciplinesComponent, StudlifeComponent, DemandComponent, UsefullinfComponent, FieldsstudyComponent, NewsPageComponent, GrantspComponent, ProjectsPComponent, KafPComponent, GlinfThreeComponent, DirectionComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatExpansionModule, MatPaginatorModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
package ru.spec.java1.lecFinal; import java.awt.AWTException; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Window; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Date; import javax.imageio.ImageIO; import javax.swing.JFrame; import com.sun.glass.events.KeyEvent; public class UserTest { public static void main(String[] args) throws AWTException, IOException, InterruptedException { Robot r = new Robot(); //r.mouseMove(0, 0); //r.keyPress(KeyEvent.VK_Z); //r.keyRelease(KeyEvent.VK_Z);//zz // int dx=0, dy = 0; // for (int i=0;i<100;i++) { // Point p = MouseInfo.getPointerInfo().getLocation(); // dx=(int)(Math.random()*7)-3; // dy=(int)(Math.random()*7)-3; // // r.mouseMove(p.x+dx, p.y+dy); // Thread.sleep(20); // } // JFrame frame = new JFrame("my app"); frame.setBounds(300,300,500,500); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Window w= new Window(null); w.setBounds(200, 200, 500, 500); w.setVisible(true); w.setAlwaysOnTop(true); Thread.sleep(1000); Date date = new Date(); String d=date.toString(); String path = "c:/java/screen.png"; w.getGraphics().drawImage(ImageIO.read(new File (path)), 0, 0, null); BufferedImage img = r.createScreenCapture(new Rectangle(0, 0, 2500, 1500));// не работает быстро int height = img.getHeight(); int width = img.getWidth(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = img.getRGB(x, y); img.setRGB(x, y, ~rgb);// инвертирование цвета } } System.out.println(date); ImageIO.write(img, "png", new File(path)); } }
//generateChannelUIObjects -- To generate channel user input objects for all the channels func (c ChannelUIObject) generateChannelUIObjects(channel inputStructs.Channel, organizations []inputStructs.Organization, tls, action, ordererChannel string) []ChannelUIObject { var channelObjects []ChannelUIObject if channel.ChannelPrefix != "" && channel.NumChannels > 0 { channelObjects = c.createChannelObjectIfChanPrefix(channel, organizations, tls, action, ordererChannel) return channelObjects } orgNames := strings.Split(channel.Organizations, ",") channelObjects = c.createChannelConfigObjects(orgNames, channel.ChannelName, channel.ChannelTxPath, channel.AnchorPeerTxPath, tls, action, ordererChannel, organizations) return channelObjects }
package com.sunstar.weatherdemo; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.sunstar.weatherdemo.helper.JsonHelper; import com.sunstar.weatherdemo.helper.SimpleOkHttpHelper; import com.sunstar.weatherdemo.javabean.HeWeather; import com.sunstar.weatherdemo.service.AutoUpdateService; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import static android.preference.PreferenceManager.getDefaultSharedPreferences; public class WeatherActivity extends AppCompatActivity { private ScrollView id_sv_weather_all_layout; private TextView id_tv_title; private TextView id_tv_right_time; private TextView id_tv_degree; private TextView id_tv_info; private LinearLayout id_ll_forecast; private TextView id_tv_aqi; private TextView id_tv_pm25; private TextView id_tv_comfort; private TextView id_tv_car_wash; private TextView id_tv_sport; private SwipeRefreshLayout id_srl_refresh; private ImageView id_iv_bg; private String weatheridStr = "CN101210102"; private Button id_btn_home; private DrawerLayout id_drawer_layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); //状态栏 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } id_btn_home = (Button) findViewById(R.id.id_btn_home); id_drawer_layout = (DrawerLayout) findViewById(R.id.id_drawer_layout); //菜单 /*getSupportFragmentManager() .beginTransaction() .replace(R.id.id_left_drawer_content, ChoseAreaFragment.newInstance("", "")) .commit();*/ id_btn_home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { id_drawer_layout.openDrawer(GravityCompat.START); } }); // id_srl_refresh = (SwipeRefreshLayout) findViewById(R.id.id_srl_refresh); id_srl_refresh.setColorSchemeResources(R.color.colorPrimary); id_iv_bg = (ImageView) findViewById(R.id.id_iv_bg); id_sv_weather_all_layout = (ScrollView) findViewById(R.id.id_sv_weather_all_layout); id_sv_weather_all_layout.setVisibility(View.GONE); id_tv_title = (TextView) findViewById(R.id.id_tv_title); id_tv_right_time = (TextView) findViewById(R.id.id_tv_right_time); id_tv_degree = (TextView) findViewById(R.id.id_tv_degree); id_tv_info = (TextView) findViewById(R.id.id_tv_info); id_ll_forecast = (LinearLayout) findViewById(R.id.id_ll_forecast); id_tv_aqi = (TextView) findViewById(R.id.id_tv_aqi); id_tv_pm25 = (TextView) findViewById(R.id.id_tv_pm25); id_tv_comfort = (TextView) findViewById(R.id.id_tv_comfort); id_tv_car_wash = (TextView) findViewById(R.id.id_tv_car_wash); id_tv_sport = (TextView) findViewById(R.id.id_tv_sport); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); final String bing_pic = sharedPreferences.getString("bing_pic", null); if (bing_pic == null) { String reqImageUrlApi = "http://guolin.tech/api/bing_pic"; SimpleOkHttpHelper.reqHttp(reqImageUrlApi, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { //Toast.makeText(WeatherActivity.this, "获取图片数据失败", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String imageUrl = response.body().string(); SharedPreferences sharedPreferences = getDefaultSharedPreferences(WeatherActivity.this); sharedPreferences.edit().putString("bing_pic", imageUrl).commit(); runOnUiThread(new Runnable() { @Override public void run() { Glide.with(WeatherActivity.this).load(imageUrl).into(id_iv_bg); } }); } }); } else { Glide.with(this).load(bing_pic).into(id_iv_bg); } String cacheWeatherJson = sharedPreferences.getString("weather", null); if (cacheWeatherJson == null) { if (getIntent() != null) { weatheridStr = getIntent().getStringExtra("weatherid"); } reqWeather(); } else { //有缓存 HeWeather heWeather = JsonHelper.parseWeather(cacheWeatherJson); HeWeather.HeWeatherBean hwb = heWeather.getHeWeather().get(0); //赋值 weatheridStr = hwb.getBasic().getId(); configAllView(hwb); } id_srl_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { reqWeather(); } }); } private void reqWeather() { id_srl_refresh.setRefreshing(true); // String url = String.format("http://guolin.tech/api/weather?cityid=%s&key=0fb8fe4a211a4b6cac088aba556b3375", weatheridStr); SimpleOkHttpHelper.reqHttp(url, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { id_srl_refresh.setRefreshing(false); Toast.makeText(WeatherActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String result = response.body().string(); final HeWeather hw = JsonHelper.parseWeather(result); runOnUiThread(new Runnable() { @Override public void run() { id_srl_refresh.setRefreshing(false); if (hw != null) { HeWeather.HeWeatherBean hwb = hw.getHeWeather().get(0); if (hwb != null && hwb.getStatus().equals("ok")) { //缓存下来 SharedPreferences sp = getDefaultSharedPreferences(WeatherActivity.this); sp.edit().putString("weather", result).commit(); // configAllView(hwb); // AutoUpdateService.stareMe(WeatherActivity.this); } else { Toast.makeText(WeatherActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(WeatherActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show(); } } }); } }); } private void configAllView(HeWeather.HeWeatherBean heWeatherBean) { id_tv_title.setText(heWeatherBean.getBasic().getCity()); id_tv_right_time.setText(heWeatherBean.getBasic().getUpdate().getLoc()); id_tv_degree.setText(heWeatherBean.getNow().getTmp() + "℃"); id_tv_info.setText(heWeatherBean.getNow().getCond().getTxt()); if (heWeatherBean.getAqi()!=null&&heWeatherBean.getAqi().getCity()!=null) { id_tv_aqi.setText(heWeatherBean.getAqi().getCity().getAqi()); id_tv_pm25.setText(heWeatherBean.getAqi().getCity().getPm25()); } id_tv_comfort.setText(heWeatherBean.getSuggestion().getComf().getTxt()); id_tv_car_wash.setText(heWeatherBean.getSuggestion().getCw().getTxt()); id_tv_sport.setText(heWeatherBean.getSuggestion().getSport().getTxt()); id_ll_forecast.removeAllViews(); for (int i = 0; i < heWeatherBean.getDaily_forecast().size(); i++) { View itemView = LayoutInflater.from(this).inflate(R.layout.forecast_item, null, false); TextView id_tv_data = (TextView) itemView.findViewById(R.id.id_tv_data); TextView id_tv_info_2 = (TextView) itemView.findViewById(R.id.id_tv_info_2); TextView id_tv_max = (TextView) itemView.findViewById(R.id.id_tv_max); TextView id_tv_min = (TextView) itemView.findViewById(R.id.id_tv_min); id_tv_data.setText(heWeatherBean.getDaily_forecast().get(i).getDate()); id_tv_info_2.setText(heWeatherBean.getDaily_forecast().get(i).getCond().getTxt_d()); id_tv_max.setText(heWeatherBean.getDaily_forecast().get(i).getTmp().getMax()); id_tv_min.setText(heWeatherBean.getDaily_forecast().get(i).getTmp().getMin()); id_ll_forecast.addView(itemView); } id_sv_weather_all_layout.setVisibility(View.VISIBLE); } public static void stareMe(Context context, String weatherid) { Intent intent = new Intent(context, WeatherActivity.class); intent.putExtra("weatherid", weatherid); context.startActivity(intent); } public static void stareMe(Context context) { Intent intent = new Intent(context, WeatherActivity.class); context.startActivity(intent); } public void changeArea(String weatherid) { id_drawer_layout.closeDrawers(); weatheridStr = weatherid;//更新赋值 reqWeather(); } }
from library import * from lib_attack import * import sys import numpy as np inputs, outputs, traces = parse(sys.argv[1], left=650000, right=700000) normalize(traces) smooth(traces, 25) align(traces, range(-5000, 15000)) if 1: traces = traces[:,0:40000] normalize(traces) align(traces, range(-50, 50)) if 0: traces = traces[:, 8000:9500] normalize(traces) align(traces, range(-20, 20)) save_traces(sys.argv[2], inputs, outputs, traces)
// // TKLayerView.h // TKComponent // // Created by liubao on 14-11-15. // Copyright (c) 2014年 liubao. All rights reserved. // #import <Foundation/Foundation.h> #import "TKMBProgressHUD.h" /** 位置 */ typedef enum { /** * 顶部 */ TKLayerPosition_Top, /** * 中间 */ TKLayerPosition_Center, /** * @Author 刘宝, 2016-03-01 18:03:20 * * 底部 */ TKLayerPosition_Bottom }TKLayerPosition; /** * 相关弹层组件 */ @interface TKLayerView:NSObject /** * @Author 刘宝, 2015-01-04 14:01:32 * * 是否显示加深的背景色 */ @property(nonatomic,assign)BOOL isDimBackground; /** * 显示缓冲等待层 * * @param content 显示文本 */ -(void)showLoading:(NSString *)content; /** * 显示缓冲等待层 */ -(void)showLoading; /** * 隐藏缓冲等待层 */ -(void)hideLoading; /** * 显示短消息提示 * * @param content 提示的信息 */ -(void)showTip:(NSString *)content; /** * 显示短消息提示 * * @param content 提示的信息 */ -(void)showTip:(NSString *)content position:(TKLayerPosition)position; /** * @Author 刘宝, 2015-01-04 14:01:10 * * 显示文本提示 * * @param content 内容 */ -(void)showText:(NSString *)content; /** * @Author 刘宝, 2015-01-04 14:01:17 * * 显示进度条,记得用完要隐藏进度条 * * @return */ -(TKMBProgressHUD *)showProgressHUD; /** * 弹出确认框 * * @param content 内容 * @param title 标题 * @param confirmAction 确认动作 * @param cancelAction 取消动作 */ -(void)showConfirm:(NSString *)content title:(NSString *)title confirmAction:(void(^)())confirmAction cancelAction:(void(^)())cancelAction; /** * @Author 刘宝, 2015-05-06 22:05:01 * * 弹出确认框 * * @param content 内容 * @param title 标题 * @param confirmAction 确认动作 * @param cancelAction 取消动作 * @param confirmBtn 确认按钮 * @param cancelBtn 取消按钮 */ -(void)showConfirm:(NSString *)content title:(NSString *)title confirmAction:(void(^)())confirmAction cancelAction:(void(^)())cancelAction confirmBtn:(NSString *)confirmBtn cancelBtn:(NSString *)cancelBtn; /** * 弹出提示框 * * @param content 内容 * @param title 标题 * @param closeAction 关闭动作 */ -(void)showAlert:(NSString *)content title:(NSString *)title closeAction:(void(^)())closeAction; /** * 弹出提示框 * * @param content 内容 * @param title 标题 * @param closeAction 关闭动作 * @param isClose 是否关闭 */ -(void)showAlert:(NSString *)content title:(NSString *)title closeAction:(void(^)())closeAction isClose:(BOOL)isClose; /** * 弹出提示框 * * @param content 内容 * @param title 标题 * */ -(void)showAlert:(NSString *)content title:(NSString *)title; /** * 弹出提示框 * * @param content 内容 * @param title 标题 * @param buttonText 按钮文本 * @param closeAction 关闭动作 */ -(void)showAlert:(NSString *)content title:(NSString *)title buttonText:(NSString *)buttonText closeAction:(void(^)())closeAction; /** * 弹出提示框 * * @param content 内容 * @param title 标题 * @param buttonText 按钮文本 * @param closeAction 关闭动作 * @param isClose 是否关闭 */ -(void)showAlert:(NSString *)content title:(NSString *)title buttonText:(NSString *)buttonText closeAction:(void(^)())closeAction isClose:(BOOL)isClose; /** * 初始化弹出组件 * * @param frame 区域范围 * @param contentView 操作内容面板 * @param btnTextColor 按钮文字颜色 * * @return */ -(id)initContentView:(UIView *)contentView withBtnTextColor:(NSString *)btnTextColor; /** * 初始化弹出组件 * * @param frame 区域范围 * @param contentView 操作内容面板 * @param btnTextColor 按钮文字颜色 * @param cancelBtnTextColor 取消按钮文字颜色 * * @return */ -(id)initContentView:(UIView *)contentView withBtnTextColor:(NSString *)btnTextColor cancelBtnTextColor:(NSString *)cancelBtnTextColor; /** * @Author 刘宝, 2015-06-10 20:06:49 * * 设置弹出层的最大宽度和最大宽度 * * @param maxWidth 最大宽度 * @param maxHeight 最大高度 */ -(void)setAlertConfirmMaxWidth:(CGFloat)maxWidth maxHeight:(CGFloat)maxHeight; @end
A case report on mother-to-child transmission of Brucella in human, China Background Human brucellosis is endemic in China and commonly occurs through contact with infected animals from working with livestock or consumption of unpasteurized dairy products. Although rare, human-to-human, and possible sexual transmission, of Brucella has been reported. In this report, we describe a case of likely mother-to-child transmission of Brucella in Hunan Province, China. Case presentation Between June and October 2016, a 28-year old man sought care for testicular swelling and pain at several health facilities. His 26-year old wife developed intermittent fever along with right thigh and hip pain between November 2016 and February 2017 respectively. On April 5, 2017, the female patient delivered a male neonate at 34weeks of gestation through natural labor. The childs venal blood sample was cultured on April 5, 2017. Brucella was isolated and identified on April 12, 2017. On the same date, serum antibodies of the father and mother were above 1:100 (based on the serum agglutination test ). The strains isolated from the mother and neonate were identified as Brucella melitensis biotype 1. Conclusions This report highlights a family cluster of brucellosis. Culture results strongly support mother-to-child transmission, and a high probability of sexual transmission from husband to wife. Background Human brucellosis remains an important zoonotic infection in China and is endemic in several provinces including Inner Mongolia, Shanxi, Heilongjiang, Hebei and Xinjiang. Predominant strains include B. melitensis bv 3, B. abortus bv 1 and 3, B. suis bv 1 and 3. Human Brucellosis can range from asymptomatic infections to severe symptoms with fever, fatigue, loss of appetite, and joint-muscle and back pain. Brucella orchitis is reported among approximately 7% of male patients with brucellosis. Symptom onset may occur between 5 days to 5 months following infection and may disappear and return several weeks or months later. A suspect case of brucellosis is defined as a person with clinical symptoms and epidemiologic risk factors for infection. The serum (tube) agglutination test (SAT) is used to detect Brucella antibodies in China. Suspect cases with serum titers 1:100 and above are considered laboratory confirmed. Culture and isolation can be performed at a few provincial-level laboratories and the national Brucella laboratory in Beijing. Persons with suspect and laboratory confirmed Brucellosis are treated with Rifampin, Doxycycline or Streptomycin for 21 days. Inappropriate treatment, poor adherence to treatment, or late diagnosis can lead to chronic infections. Chronic infections involve complex treatment and can last for several years. Although transmission is commonly associated with contact with livestock (cattle, sheep, goats, and swine) and consumption of unpasteurized dairy products, sexual transmission has been previously reported. In this report, we describe a case of likely mother-to-child transmission of Brucella in Hunan Province, China. Case presentation In June 2016, a 28-year old male sought health care at People's Hospital in Anhua County, Hunan Province for testicular swelling and pain. An ultrasound scan was performed and determined to be inconclusive; no treatment was provided. The patient subsequently developed a fever and received outpatient care at a local private clinic. In October 2016, the patient experienced recurrent swelling of the right testicle and again sought hospital care. He was treated for 7 days with Ciprofloxacin and Rifampicin. The patient improved and was discharged without a diagnosis. In November 2016, a 26-year female, the wife of the 28-year old male patient and X months pregnant, developed a fever without obvious cause. She was diagnosed with acute nephritis at a local hospital, and, based on her complete blood count (CBC), was treated with Penicillin and Ampicillin for 3 days. In December 2016, the female patient sought care for a recurring fever and right thigh and hip pain. She was again diagnosed with acute nephritis and treated with Penicillin and Ampicillin for 15 days. In February 2017, the patient reported additionally unexplained right thigh and buttock pain and improved following analgesic therapy at home for 3 days. On 5 April, 2017, the patient delivered a male neonate at 34 weeks of gestation through natural labor at People's Hospital in Anhua County. At birth the neonate weighed 2500 g, with a length of 50 cm, but was in poor health (Apgar = 4) with a temperature of 37.6°C along with an enlarged liver and spleen. The neonate was initially treated with a six-day course of Penicillin and Ampicillin. The clinical events of this family cluster of brucellosis are shown in Fig. 1. Laboratory diagnostics The blood sample collected at the time of the neonate's birth on 7 April was culture positive for Brucella on 12 April 2017 at People's Hospital in Anhua County. Follow-up testing of blood samples from the father, mother, and neonate were also culture positive for Brucella on 12 April 2017 at Hunan People's Hospital, Hunan Province. SAT results indicated that the father and mother had serum antibody titers above 1:100. The neonate's white blood cell (WBC) count, platelet count and high sensitivity C reactive protein were higher than the normal; no serum antibody was detected. The strains isolated from the mother and the neonate were identified as Brucella melitensis biotype 1 and belonged to same genotype by MLVA genotyping (multi-locus variable-number tandem repeat analysis). The neonate was treated with Rifampicin and Doxycycline for one month at Hunan People's Hospital. His parents were treated with Rifampicin and Doxycycline for a onemonth period. All three patients -the father, mother, and neonate -were symptom-free at the end of the treatment period. Retrospective epidemiological survey The family resided in urban housing, and the father's worked in shipment of fruit from local farmers to urban markets, requiring travel throughout the province. The mother was not exposed to live livestock during pregnancy. The family regularly visited local markets for purchasing meat and dairy products for cooking; all identified dairy products were pasteurized. According to human surveillance data for the county, the risk of brucellosis was low and limited to B. melitensis biotype 3 from Chinese surveillance. On April 18, 2017, an investigation was conducted for five close contacts of the family cluster of brucellosis. All contacts were asymptomatic and blood samples were culture and SAT negative for brucella and serum antibodies, respectively (Table 1). Discussion and conclusions The male patient described in this case report developed symptoms in June 2016. The patient was inadequately treated until receiving a Brucella diagnosis on 12 April 2017 following confirmatory SAT results. The patient's wife and neonate were culture positive for Brucella melitensis biotype 1 and belonged to same genotype, suggesting mother-to-child transmission. The three patients were diagnosed as a family cluster of brucellosis. Neither the male or female patient had previous travel to a brucellosis epidemic region, nor reported contact with sheep or other livestock. The family often consumed dairy products, including milk; however, no other cases were linked to the same these diary products. Although the male patient presented with typical symptoms at his initial contact with the health care system, the late diagnosis and inappropriate treatment led to a chronic brucella infection. The wife became pregnant in Fig. 1 The clinical events on a family aggregation cases of brucellosis August 2016, a time between the male patient's two disease episodes in June 2016 and November 2016. Because no other risk factors were identified, the wife was probably infected with Brucella through sexual transmission. Brucellosis transmission has occurred following blood transfusions or bone-marrow transplants. Although uncommon, brucellosis has also been transmitted from suspicious person-to-person. The female patient developed clinical symptoms during pregnancy but was not successfully treated until after the birth of her son. Brucellosis causes fewer spontaneous abortions in humans than animals, primarily due to the absence of erythritol in the human placenta and fetus. The presence of anti-brucella activity in human amniotic fluid may also play a role. The MLVA-16 assays, which can differentiate closely related brucella isolates, revealed that the strains from the mother and her neonate had same genotype -B. melitensis biotype 1which is rare in China and the first detection of this strain in Hunan Province, a low risk are for brucellosis. Since the infant did not have any other possible exposures, these findings strongly support mother-to-child transmission of Brucellosis. The neonate's negative test results for brucella antibodies may suggest an immature system unable to mount a detectable immune response from our previous test results. Our report describes likely transmission of brucella from mother-to-child and probable sexual transmission from father to mother. Although these events are rare, this report highlights the importance of improving clinical awareness. Brucellosis should be considered for persons presenting with fever, fatigue, and joint-muscle pain not associated with other infections. Early and appropriate treatment is essential. With therapy during pregnancy, the overall success rate resulting in normal delivery is 90%.
Complex aspects of clinical-functional evaluation and ambulatory therapeutic-rehabilitation approach in a young patient with post stroke - spasticity and peroneal nerve palsy Introduction. Spasticity, a common post-stroke complication associated with signs and symptoms of upper motor neuron syndrome, occurs with a 35% prevalence one year after brain injury and can be severely disabling in young patients, regarding locomotor dysfunction and also regarding the quality of life. Stroke incidence in young patients increased in the last decades, being correlated with the increasing substance abuse and sedentariness, excessive alcohol consumption, and smoking. Peroneal nerve palsy is the most common cause of neuropathy of the lower limb and, in most cases, is caused due to nerve lesion in the fibula head area. Material and method. We present the complex case of a young male patient, former alcohol and narcotics user, who suffered an ischemic stroke in the right middle cerebral artery teritory along with a posttraumatic paresis of the right peroneal nerve. The patient presents motor deficit right spastic hemiplegia, right foot drop, locomotion and self-care disorders. Results and discussions. The patient followed medical treatment (antiepileptic, neurotrophic factors, vitamins, antiplatelet) and rehabilitation treatment adapted to the current clinical-functional status (thermotherapy, lasertherapy, magnetotherapy and individual kinesiotherapy), with slow favorable evolution of the improvement of locomotion and quality of life disorders. Conclusions. Therapeutic-rehabilitation management of the spastic patient with disability due to brain injury and peripheral traumatic neuropathy represents a challenge because it doesnt exist a miraculous treatement (yet) to cure completely these nervous injuries. Keywords: post stroke spasticity, peroneal nerve palsy, rehabilitation,
Effects of exercise training on coronary collateralization and control of collateral resistance. Coronary collateral vessels serve as a natural protective mechanism to provide coronary flow to ischemic myocardium secondary to critical coronary artery stenosis. The innate collateral circulation of the normal human heart is typically minimal and considerable variability occurs in extent of collateralization in coronary artery disease patients. A well-developed collateral circulation has been documented to exert protective effects upon myocardial perfusion, contractile function, infarct size, and electrocardiographic abnormalities. Thus therapeutic augmentation of collateral vessel development and/or functional adaptations in collateral and collateral-dependent arteries to reduce resistance into the ischemic myocardium represent a desirable goal in the management of coronary artery disease. Tremendous evidence has provided documentation for the therapeutic benefits of exercise training programs in patients with coronary artery disease (and collateralization); mechanisms that underlie these benefits are numerous and multifaceted, and currently under investigation in multiple laboratories worldwide. The role of enhanced collateralization as a major beneficial contributor has not been fully resolved. This topical review highlights literature that examines the effects of exercise training on collateralization in the diseased heart, as well as effects of exercise training on vascular endothelial and smooth muscle control of regional coronary tone in the collateralized heart. Future directions for research in this area involve further delineation of cellular/molecular mechanisms involved in effects of exercise training on collateralized myocardium, as well as development of novel therapies based on emerging concepts regarding exercise training and coronary artery disease.
<gh_stars>100-1000 // Copyright 2021 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package kubeclient import ( "bytes" "encoding/hex" "net/url" "k8s.io/apimachinery/pkg/runtime/schema" restclient "k8s.io/client-go/rest" "go.pinniped.dev/internal/plog" ) // defaultServerUrlFor was copied from k8s.io/client-go/rest/url_utils.go. //nolint: golint func defaultServerUrlFor(config *restclient.Config) (*url.URL, string, error) { hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0 hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0 defaultTLS := hasCA || hasCert || config.Insecure host := config.Host if host == "" { host = "localhost" } if config.GroupVersion != nil { return restclient.DefaultServerURL(host, config.APIPath, *config.GroupVersion, defaultTLS) } return restclient.DefaultServerURL(host, config.APIPath, schema.GroupVersion{}, defaultTLS) } // glogBody logs a body output that could be either JSON or protobuf. It explicitly guards against // allocating a new string for the body output unless necessary. Uses a simple heuristic to determine // whether the body is printable. func glogBody(prefix string, body []byte) { if plog.Enabled(plog.LevelAll) { if bytes.IndexFunc(body, func(r rune) bool { return r < 0x0a }) != -1 { plog.Debug(prefix, "body", hex.Dump(body)) } else { plog.Debug(prefix, "body", string(body)) } } }