content
stringlengths 7
2.61M
|
---|
Philippe Cousteau is the CEO of EarthEcho International and the grandson of famed ocean explorer Jacques Yves Cousteau.
The sun was coming up when we drove away from the hotel in New Orleans, bound for my 5th trip to Grand Isle. The projected low for the day was 88 degrees, a new record and a bad sign for hurricane season ahead, but by now I was getting used to the heat. The next few days would see us retrace our steps from the weekend with a day in Grand Isle, LA, and one in Alabama. I was asked by the producers at Larry King Live to host the field segments for a two-hour telethon that they are producing to raise money for the communities and wildlife impacted by the disaster that has spread through the Gulf for more than 50 days. I was delighted when they informed us of their plans because while other disasters often attract huge outpourings of charity in this country, people have been slow to realize that there is tremendous suffering going on in our back yard and an equally tremendous need for the nation to unite in order to help.
We pulled into Grand Isle and boarded the small boat that would take us out into Barataria Bay. As we headed out into the Bay the now familiar smell of oil wafted over the bow and the silhouette of shrimp boats retrofitted for their job of skimming oil flashed past us. Already their oily catch was collecting behind them as they moved in unison, a phalanx of soldiers desperately trying to collect as much oil as possible. These are the lucky few, people who have found employment to replace a livelihood that is now out of reach for them. Over the past 6 weeks, I have seen this disaster unfolding first hand from below the surface and the impact on the environment and the local communities at the surface. As nature itself goes, so goes these communities, the fate of both is inextricably linked to the other. As I thought about it over the past few days, seeing now familiar faces struggling to come to grips with this disaster I have become more and more frustrated for those fighting on the ground.
As Casi Callaway, executive director of the Mobile Baykeeper, a member of the Waterkeeper Alliance puts it “We had no budget for this, we are struggling to deal with this disaster mobilizing people on the ground to save our environment and our communities both in the short and long term.” Incidentally, the Gulf coast Waterkeeper Alliance has a website www.saveourgulf.org where you can support the groups on the front lines of this disaster.
Mark Twain once wrote, “A man’s first duty is to his conscience and his honor.” As this recent expedition from the shores of Grand Isle to the beaches of Alabama reminded me, there is no honor in this catastrophe and its consequences are unconscionable, but nor is there honor in the circumstances that created it. As one local businessman reminded me, “I hate what has happened here but I still need oil to power my boat to take people fishing.” He is right and summed up what many of us have been saying all along. That while BP, Halliburton, MMS, and Transocean all share immediate blame, as a country we must take the necessary steps to cut our addiction to oil.
Many claim that we cannot afford to do it…I say we cannot afford not to.
While it is true that climate change is perhaps our greatest threat, remember that NASA has reported an average decline of sea ice per decade since 1979 of almost 10% (even doubters would do well to remember the precautionary principle) we must also pay attention to the other costs to our health and our security.
From foreign wars to other environmental crisis like ocean acidification and growing droughts which are causing human crisis such as the genocide in Darfur, our addiction to fossil fuels is literally killing us. Take for example a recent report by the American Academy of Allergy, Asthma and Immunology; from 1980-1994, the prevalence of asthma increased 75% in the US population. Amongst children under the age of five it increased more than 160%.
There is real need on the ground in the short term for this country to support social organizations that provide financial support to families, social support to communities, fund critical research and conservation activities all of which would have to wait months and file difficult legal claims to possibly get funding at some point in the future. But there is also a real need for us as a nation to realize that our fast food burgers cost a lot more than 99 cents, our gas much more than the 2-3 dollars a gallon advertised at the pump, our cars and houses much more than what we pay on the for sale sign. The cost of all these things is nothing less than a crippled economy that indebts our nation’s future, foreign policy that puts our armed forces in harm’s way and industries that poison our air and water and ultimately a world that we should be ashamed to pass on to our children.
This catastrophe is not an opportunity, there is no silver lining, to say so would be extraordinarily insensitive and naïve but I hope that it is a wake-up call, that it reminds us, as Dr. Martin Luther King Jr. once said, “we have no time for the tranquilizing drug of gradualism.” We must act now to support the groups on the ground who are fighting this crisis every day and then challenge ourselves to build a future that we can be proud to pass on to our children.
Maybe the gulf they are looking at roman catholic church, spanish, and BP isd looking at anglican or church of England. Whose bible? yours or mine.? The CEO does not seem to care about the oil spill. Too many "I don't recall".
Oil rigs have poor safety records.
Shrimp fisheries have come a long way. There are jumbo, large, medium and small shrimp sizes. The technology to freeze the shrimp is developed. Shrimp in market is fresh and good. Mexican cantinas serve shrimp cocktail. Thai restaurants serve crystal shrimp dish and chinese have shrimp noodle soup. I bought medium shrimp from Ecuador at $2.00/ib. from asian market.
Crude Oil Spills = Ecocide, there is no positive spin on that. Poisonous to breathe, Poisonous to eat, Poisonous to drink, Poisonous to swim in, Poisonous to your skin. Poisonous to aquatic life, Poisonous to mammals, Poisonous to birds, Poisonous to the water table.
If these 'Gulf Keepers' and Environmental Keepers of the Gulf of Mexico want to actually 'save' the Dead and Dieing Gulf of Mexico region, they would in Force, Demand a Moratorium to Oil Drilling in the Gulf of Mexico. There is no safe Oil Well in the Ocean, there is no impossibility of another enormous Oil Spill. The Only question is 'WHEN' the next immense Oil Spill is going to occur.
Philippe's father Jacques was, and is, one of my heroes. The oceans were his life and love and he took us to places we could never possibly visit and showed us the beauty and teeming life below the surface. I am a tallship sailor and have long appreciated the ocean. Humans gather on beaches to watch sunsets or simply to look out and let thoughts roam free. The sight of the oil soaked Pelicans is heartbreaking, their lifespan is 35 years and they are defenseless against oil spills, dying slowly and painfully. Each and every one of us can do something to help.
Thank you Larry King, Thank you Anderson Cooper, Thank you CNN, Thank you Soledad Obrien, Thank you Kira Phillips for bringin this truth home to all of us across the nation – if not for you, we would not see, we would not know.
God help us all if this disaster does not awaken us to what is going on in this greedy world. The pain and suffering of the animals, the environment and humanity will never be the same. We must all start conserving, and call for the shut down of all oil rigs offshore immediately before this can happen again. We have to get on our bikes, make fewer trips in the car, start walking, visit with neighbors by foot. Go green right now. No more excuses.
Thank you for helping to safeguard the ocean "trails" that Jacques blazed and for blazing new ones now for the world's sake.
I have donated to Global Green USA to help the Gulf Coast build a strong Green economy. Long after all victims have been paid what will be left for people there? A strong Green economy based on alternative clean energy is a good long range plan for the region.
They have been trying to develop alternative energy like wind farms and water turbines but federal funding was not there for them. Help Global Green USA secure that funding for the region and continue their good works there for a responsible and sustainable future.
It seems that our main concern should be how to get the oil to STOP spilling into the Gulf of Mexico... does anyone know who is in charge of making this happen and what options are being considered on a daily basis? I hear reports that it is chaos! It seems to me that it needs to be decared a national disaster area and our military and the best American engineers and geologists need to be making these decisions – not BP. How can we clean up anything if the oil is still spilling???
Here's the reason I watch Fox News, your station is THE most biased news media on the air lately, your portrayal of General Petraius as being against the President if offending; that man begged for help from Obama months ago, while our men were being slaughtered, he has every reason to be upset and, probably sarcastic. I can understand why he passed out during a congressional hearing. Why is it that the people who are trying to HELP our country are being blackballed? This President is not doing his best to help our country, yet he takes the time to have a beer with a police officer (who did the right thing) and one of his (I say lightly, Professor friends). We are not stupid, we watch and we analyze. Cnn is off limits and will always be, as far as I am concerned. Keep on doing a lousy job by protecting the wrong people and you will all find yourselves out of a job...like you did with Lou Dobbs!! What happened to real journalism, instead of predjudicial views!! Helen Nordo P.
Capt. Ben Williams who is a Charter fisherman in the summer , trying to work his way thru college. It was heart breaking to see the saddness in his face as you asked him questions, his 18 year-old passion for fishing has been halted and his spirit crushed to witness all the destruction. thanks for allowing him to express a voice.
OK I have to give credit to CNN for covering the oil spill, good work; however, I made a comment earlier concerning your handling of the "scandalous" remarks made by General McChrystal at a time when he, obviously, was feeling despondent over events in Afghanistan; this is not an ordinary war, although perhaps that is the wrong term, the country is not helping, it seems our soldiers are doing all the work and losing their lives to a failing system. We are replacing Generals one after the other, so something is not right, perhaps the white house should respond to Generals when they state they are in need of more troops, the President keeps changing his mind as to how many troops to send, whether they should send "financial aid" to the "GOVERNMENT" money, money, money does not always get us out of a mess. Russia could not do it, it is rough terrain and I feel sorry for those men, who obviously are told "Please be gentle with the population, do not shoot unless necessary.." No wonder the Generals are fainting and shooting off their mouths, they are obviously under pressure. If the President keeps unloading our generals, what will the bad guys think? The worst thing this general could have done was apologize, and the President should not have expected him to..This isn't the President's war, these men aren't dying for the President, they are, actually, fighting a losing war..and putting pressure on the generals certainly is a bad maneuver. Let these remarks go, be a man and don't ask for an apology...The President is a man, not a God, we have watered down the CIA, we are giving rights to terrorists and we are taking away the power from important men that protect our country...look, we can't even handle an oil spill (which should have been anticipated in such deep water) I feel the President is shaming this man to draw attention away from his recent poor handling of the Presidency. This man will go down in history for the mishandling and endangerment of our country, economically and logistically. God Bless America, we need his blessing!! Helen Nordo P.
And how many do realize the real dimension of all that's going on, "oil spill" (or whatever it is) included.
All the money in the world – whether from BP or telethons – will not heal this ongoing disaster in the Gulf.
PLUG THE DAMN LEAK. I can't BELIEVE there is no plan in place. We don't need more laws, we need to enforce the ones we have. There are more controls in place for my menial, unimportant job. Could there be politics behind not capping the well???
The Gulf area will be a dead zone for years to come and it makes me angry and sad to think of the animal and human suffering, to see the marshes and formerly beautiful beaches saturated with oil. In addition to the enviro-disaster, it will wreak havoc on our nations' already shaky economy, not just in the location of the spill, but throughout the US.
"Green Energy" sounds like a great (although idealistic) solution, but is nothing we can transition to easily. Since the world isn't going to get over its' oil "addiction" any time soon, without effecting so many peoples livlihoods, we'd better figure out a way to make it safe. |
OK, I don’t know if he is pounded meat royalty, but the boss at Schnitzel & Things is a proud member of the new wave of food truck vendors who are serving up specific and sometimes gourmet cuisine on street corners. People love the good eats at a cheap price. Vendors get their American dream — owning their own business. Some restaurants hate it and are trying to ban the competition. There are turf wars. Even the Food Network is holding a contest to find the best food truck in the U.S. Perhaps my favorite truck I’ve seen recently, just yesterday in fact, was this one, the Big Gay Ice Cream Truck.
The bloggers at Big Girls, Small Kitchen share five recipes that are sure to impress even the scroogiest of partygoers.
The bloggers at Big Girls, Small Kitchen share eight easy tips for throwing a party this holiday season.
A cabbage shortage sparks a national crisis. |
A multiple cavity malignancy involving the renal capsule, pleura and meninges: A case report and review of the literature Malignant renal subcapsular effusions commonly arise from primary or metastatic renal neoplasms. The current case report presents a rare case of malignancy with a massive renal subcapsular effusion accompanied by a malignant pleural effusion of an unknown primary site, which underwent progression to carcinomatous meningitis during chemotherapy. The type of adenocarcinoma present was determined by effusion cytology. Intravenous chemotherapy (docetaxel plus oxaliplatin and gemcitabine plus cisplatin) were administered; however, the disease still progressed. Time to progression was 9 months during treatment of gefitinib. Comprehensive therapies, including intracavity chemotherapy, immunotherapy and gefitinib, were shown to be effective and prolonged the patients survival time. Introduction Cancer of unknown primary site (CUP) is a category of malignancy with undetectable primary site upon diagnosis. It is characterized by diverse clinical manifestations and poor prognosis. The histological types include adenocarcinoma, squamous cell carcinoma, neuroendocrine tumors and carcinoma not otherwise specified. Adenocarcinoma of unknown primary site accounts for 60-70% of all cases of CUP and is commonly identified in the liver, lung, bone and lymph nodes. Metastatic adenocarcinoma of unknown primary site, first presenting with malignant renal subcapsular effusions, is extremely rare and has not been analyzed in previous studies. The current case report presents a patient with adenocarcinoma of unknown primary site that initially presented with renal subcapsular and pleural effusion followed by carcinomatous meningitis. The treatment of this specific type of carcinoma is subsequently discussed. Written informed consent was obtained from the patient. Case report Patient presentation and diagnosis. A 45-year-old female was admitted to The Comprehensive Cancer Center, Drum Tower Hospital (Nanjing, China) on April 9, 2006 with flank pain, cough and dyspnea. One month prior to admission, the patient had suffered from left flank pain. Abdominal ultrasonography at the patient's local hospital revealed a subcapsular effusion, a small cyst in the left kidney and a calculus of 0.8 cm in diameter in the upper right ureter. The patient was treated for lithiasis for ~1 month with no amelioration and subsequently developed a cough and dyspnea. A computed tomography (CT) scan revealed right pleural and subcapsular effusions in the left kidney (Fig. 1A). A thorough examination of the individual was performed, including an intravenous urogram, mammography, gynecological ultrasonography, whole gastrointestinal barium contrast imaging and colonoscopy, however, no abnormalities were identified. Upon admission, a physical examination revealed high blood pressure (160/100 mmHg), lowered respiratory sounds in the right lung and a mass in the left loin. Blood tests showed an elevated level of serum creatinine (196 mol/l) and serum tumor markers, cancer antigen (CA)125 (168 U/ml; reference range, <35 U/ml), carcinoembryonic antigen (CEA; 15.3 ng/ml; reference range, <5.0 ng/ml) and CA153 (68 U/ml; reference range, <25 U/ml) and a urine test was negative. The cytopathological examination of the pleural effusion was positive for poorly-differentiated adenocarcinoma cells. To identify the primary tumor site, the patient received a systemic positron emission tomography (PET)/CT scan, which identified a small nodule measuring 7x12x9 mm in the upper lobule of the right lung and right pleural ( Fig. 1B and C) and subcapsular effusions of the kidneys (Fig. 1D), with normal 18 F-fluorodeoxyglucose (FDG) uptake. Due to its size and site, a fine-needle biopsy of the lung nodule was not performed and therefore, the patient was diagnosed with a carcinoma of unknown primary site. A multiple cavity malignancy involving the renal capsule, pleura and meninges: A case report and review of the literature Treatment and clinical course. Chemotherapy was initiated and agents with high renal toxicity were excluded to avoid the deterioration of the patient's kidney function. Intravenous docetaxel (40 mg/m 2 on days 1 and 8, every 3 weeks) plus oxaliplatin (75 mg/m 2 on days 1 and 8, every 3 weeks) and intrapleural interleukin-2 (1x10 9 U on days 3 and 10, every 3 weeks) was administered. The pleural effusion subsided after being drained three times and intrapleural interleukin-2 administration. Following the initial course of chemotherapy, the cough and dyspnea ameliorated and serum levels of creatinine and tumor markers decreased. Following three cycles of chemotherapy, the CT scan showed no change in the pulmonary nodule ( Fig. 2B and D) or subcapsular effusion ( Fig. 2A and C). Next, renal subcapsular drainage was performed and ~330 and 960 ml stale hematoid fluid was aspirated from the left and right sides, respectively. The levels of CA125, CA199 and CA153 tumor markers were significantly elevated in the drained fluid and adenocarcinoma cells were evident upon analysis of the drainage cytology (Fig. 1E). Following sequential treatments of interleukin-2 and bleomycin administered intrasubcapsularly, the amount of drained fluid decreased ( Fig. 2C and E) and turned yellow and clear. The abdominal symptoms were ameliorated and the patient's blood pressure and serum creatinine level returned to normal; however, no clear changes to the lung nodule were observed (Fig. 2F). Subsequently, the patient received an additional three cycles of systemic chemotherapy with gemcitabine (1,000 mg/m 2 on days 1 and 8, every 3 weeks) plus cisplatin (25 mg/m 2 daily for 3 days ). The patient's condition was stable prior to an intense headache that developed three weeks after the final administration of gemcitabine plus cisplatin. The individual exhibited no vomiting or blurred vision, the blood pressure remained normal and the brain and spinal MRI scans were negative. A lumber puncture was performed and the cerebrospinal fluid was positive for a large number of adenocarcinoma cells (Fig. 1F). Immunostaining was positive for epithelial membrane antigen and pan-cytokeratin, but negative for vimentin, glial fibrillary acidic protein, cluster of differentiation (CD)3, CD20, CD30 and CD68. Meningeal metastasis and carcinomatous meningitis were diagnosed and the patient received 10 mg intrathecal methotrexate weekly, but refused cranial and spinal cord radiation therapy. Following a total of 40 mg intrathecal methotrexate chemotherapy, the patient's headache was ameliorated and the cerebrospinal fluid was negative for tumor cells. The individual was administered with 250 mg gefitinib daily for the following nine months, during which the disease status was stable. However, following this, the patient developed paroxysmal syncope and epileptic seizures. No abnormalities were identified in the cranial MRI. Following an additional four months of treatment, the patient succumbed to carcinoma of unknown primary site on March 20, 2008, ~23.5 months after the initial diagnosis. An autopsy was not performed according to the wishes of the patient's family. Discussion CUP comprises 2-5% of all diagnosed tumors. It represents a heterogeneous group of metastatic tumors that share unique clinical features, including early dissemination, a clinical absence of a primary tumor, unpredictable metastatic patterns and aggressiveness, and patients tend to have an unfavorable prognosis. Adenocarcinoma of unknown primary site commonly presents in the liver, lungs, lymph nodes and bones and is rarely identified with malignant pleural or peritoneal effusions. A malignant renal subcapsular effusion of unknown primary site is extremely rare and has not been analyzed in previous studies. The current case report presents an unusual manifestation of CUP with massive malignant renal subcapsular and pleural effusions and subsequent carcinomatous meningitis. No solid metastasis was identified during a thorough examination. Renal subcapsular effusions may be hydroceles or hematoceles, and various mechanisms, including venous, lymphatic and urine regurgitation, may contribute to a subcapsular hydrocele of the kidney. However, a hematocele is likely to be caused by trauma, a renal tumor, vascular disease, infection, nephritis, blood dyscrasias, calculus or hydronephrosis. With an incidence rate of 57.7%, spontaneous subcapsular or perirenal hematomas are commonly associated with primary renal neoplasms, of which 33.4% are malignant with renal cell carcinoma predominance and 24.3% are benign with angiomyolipoma predominance. In addition, tumors occasionally arise from metastasis of extrarenal primary tumors to the kidney. In the present case report, the subcapsular effusion was hematoid and positive for adenocarcinoma cells. The renal parenchyma was negative for any discernible lesions with the exception of a cyst in the left kidney, which did not resemble a common entity of a metastasis of adenocarcinoma cells and did not change throughout the duration of the treatment process. In addition, the urine test was negative for tumor cells or hematuria. As the effusion was bilateral, subcapsular metastasis from the extrarenal site was hypothesized. No consensus has been made with regard to the standard therapy for CUP and particularly for multiple malignant cavity effusions. Empiric chemotherapy with 5-fluorouracil, doxorubicin or cisplatin-based regimens have previously produced relatively low response rates and few complete responses. Broad spectrum antineoplastic agents, including taxanes, topoisomerase I inhibitors, gemcitabine and vinorelbine, have been investigated in epithelial CUP, and platinum and taxane combination therapy is now widely used in clinical practice. However, a previous meta-analysis showed that no types of chemotherapy have been confirmed to prolong survival in patients with CUP. Paclitaxel/docetaxel-containing combination regimens have been used in specific phase II trials and the preliminary results have shown response rates between 23 and 38.7%. Briasoulis et al reported encouraging results from phase II data on carboplatin and paclitaxel combination therapy for patients with CUP. The overall response rate by an intention-to-treat analysis was 38.7% and the median overall survival time was 13 months with a median follow-up of 28 months. A recent randomized study compared empiric therapy with paclitaxel/carboplatin/etoposide against gemcitabine/irinotecan, each followed by single-agent gefitinib, and subsequently identified a comparable efficacy. However, gemcitabine/irinotecan therapy revealed a more favorable toxicity profile. In the current case report, the docitaxel/oxiplatin and gemcitabine/cisplatin regimens were administered to the patient successively, but the efficacy was limited since the tumor rapidly metastasized to the meninges and caused carcinomatous meningitis. As a maintenance therapy, gefitinib was effective and the patient's condition was stabilized for nine months despite metastasis of the tumor to the meninges and subsequent carcinomatous meningitis, for which the median survival time is 2-3 months. Patients untreated or unresponsive to treatment exhibit a median survival of 4-6 weeks. Overexpression of epidermal growth factor receptor (EGFR) has been observed frequently in a large subset of CUP and gefitinib is effective in a broad spectrum of tumor types. Although no previous randomized studies have analyzed the effect of gefitinib in CUP, a previous prospective study reported that the combination of vascular endothelial growth factor receptor inhibitor (bevacizumab) and EGFR inhibitor (erlotinib) in CUP has a better median survival than previously reported with second-line chemotherapy and is similar to the results of a number of first-line therapies. Gefitinib maintenance therapy was also included in a recent prospective randomized trial. The role of gefitinib in adenocarcinoma with CUP is promising and must be analyzed in future studies. In conclusion, the current case report presents the case of a patient with a malignant effusion in multiple cavities and demonstrates the intracavity administration of chemotherapeutic agents. Interleukin-2 appeared to be effective for controlling the effusion, however, systemic chemotherapy with docetaxel plus oxaliplatin, followed with gemcitabine plus cisplatin, appeared non-effective and the patient exhibited disease progression with involvement of the central nervous system, indicating the refractory entity and poor prognosis of this type of carcinoma. The overall survival time of the patient was ~24 months, which was considerably higher than the normal median survival of individuals with CUP. Gefitinib was identified to be promising for maintenance therapy and was shown to prolong the patient's survival. |
class JsonPath:
"""Represents a JSONPath variable in request/response body.
:param path: JSONPath to desired data in state input data
"""
path: jsonpath_rw.JSONPath = attr.ib(validator=instance_of(jsonpath_rw.JSONPath), converter=_convert_path)
def __str__(self):
return str(self.path)
def to_dict(self) -> str:
"""Serialize path for use in serialized state machine definition."""
return str(self) |
/**
* Information about {@link RenderedImage} (sources, layout, properties).
* The {@link #image} property value is shown as the root of a tree of images,
* with image {@linkplain RenderedImage#getSources() sources} as children.
* When an image is selected, its layout (image size, tile size, <i>etc.</i>) is described in a table.
* Image {@linkplain RenderedImage#getPropertyNames() properties} are also available in a separated table.
*
* <p>This widget is useful mostly for debugging purposes or for advanced users.
* For displaying a geospatial raster as a GIS application, see {@link CoverageCanvas} instead.</p>
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.2
* @since 1.1
* @module
*/
public class ImagePropertyExplorer extends Widget {
/**
* The root image to describe. This image will be the root of a tree;
* children will be image {@linkplain RenderedImage#getSources() sources}.
*
* <div class="note"><b>API note:</b>
* We do not provide getter/setter for this property; use {@link ObjectProperty#set(Object)}
* directly instead. We omit the "Property" suffix for making this operation more natural.</div>
*/
public final ObjectProperty<RenderedImage> image;
/**
* Implementation of {@link #image} property.
*/
private final class ImageProperty extends ObjectPropertyBase<RenderedImage> {
/** Returns the bean that contains this property. */
@Override public Object getBean() {return ImagePropertyExplorer.this;}
@Override public String getName() {return "image";}
/** Sets this property to the given value with no sub-region. */
@Override public void set(RenderedImage newValue) {setImage(newValue, null);}
/** Do the actual set operation without invoking {@link ImagePropertyExplorer} setter method. */
void assign(RenderedImage newValue) {super.set(newValue);}
}
/**
* Image region which is currently visible, or {@code null} if unspecified.
* Conceptually this field and {@link #image} should be set together. But we have not defined
* a container object for those two properties. So we use that field as a workaround for now.
*
* @see #setImage(RenderedImage, Rectangle)
*/
private Rectangle visibleImageBounds;
/**
* Whether {@link #visibleImageBounds} applies to the coordinate system of an image.
* This is initially {@code true} for an image specified by {@link CoverageCanvas} and become {@code false}
* after a {@link ResampledImage} is found. Images not present in this map are implicitly associated to the
* {@code false} value.
*
* <p>This map is also opportunistically used for avoiding never-ending recursivity
* during the traversal of image sources.</p>
*
* @see #setImage(RenderedImage, Rectangle)
*/
private final Map<RenderedImage,Boolean> imageUseBoundsCS;
/**
* Whether to update {@code ImagePropertyExplorer} content when the {@link #image} changed.
* This is usually {@code true} unless this {@code ImagePropertyExplorer} is hidden,
* in which case it may be useful to temporary disable updates for saving CPU times.
*
* <div class="note"><b>Example:</b>
* if this {@code ImagePropertyExplorer} is shown in a {@link TitledPane}, one can bind this property
* to {@link TitledPane#expandedProperty()} for updating the content only if the pane is visible.
* </div>
*
* Note that setting this property to {@code false} may have the effect of discarding current content
* when the {@link #image} change. This is done for allowing the garbage collector to reclaim memory.
* The content is reset to {@link #image} properties when {@code updateOnChange} become {@code true} again.
*
* <div class="note"><b>API note:</b>
* We do not provide getter/setter for this property; use {@link BooleanProperty#set(boolean)}
* directly instead. We omit the "Property" suffix for making this operation more natural.</div>
*/
public final BooleanProperty updateOnChange;
/**
* Whether to notify {@code ImagePropertyExplorer} about {@link #image} changes.
* This may become {@code false} after {@link #updateOnChange} (not at the same time),
* and reset to {@code true} when {@code updateOnChange} become {@code true} again.
*
* @see #updateOnChange
* @see #startListening()
*/
private boolean listening;
/**
* The root {@link #image} and its sources as a tree. The root value may be {@code null} and the children
* removed if the tree needs to be rebuilt after an {@linkplain #image} change and this rebuild has been
* deferred ({@link #updateOnChange} is {@code false}).
*/
private final TreeItem<RenderedImage> sourcesRoot;
/**
* The selected item in the sources tree.
*
* @see #getSelectedImage()
*/
private final ReadOnlyObjectProperty<TreeItem<RenderedImage>> selectedImage;
/**
* The rows in the table showing layout information (image size, tile size, image position, <i>etc</i>).
* This list should be considered read-only.
*/
private final ObservableList<LayoutRow> layoutRows;
/**
* A row in the table showing image layout. The inherited {@link String} property is the label to show in
* the first column. That label never change, contrarily to the {@link #xp} and {@link #yp} property values
* which are updated every time that we need to update the content for a new image.
*/
private static final class LayoutRow extends ImmutableObjectProperty<String> {
/**
* Row indices where {@link LayoutRow} instances are shown, when all rows are present.
* Rows {@link #DISPLAYED_SIZE} and {@link #MIN_VISIBLE} may be absent, in which case
* next rows have their position shifted.
*/
static final int IMAGE_SIZE = 0, DISPLAYED_SIZE = 1, TILE_SIZE = 2, NUM_TILES = 3,
MIN_PIXEL = 4, MIN_VISIBLE = 5, MIN_TILE = 6;
/**
* Creates all rows.
*/
static LayoutRow[] values(final Vocabulary vocabulary, final Resources resources) {
final LayoutRow[] rows = new LayoutRow[7];
rows[IMAGE_SIZE] = new LayoutRow(true, vocabulary.getString(Vocabulary.Keys.ImageSize));
rows[DISPLAYED_SIZE] = new LayoutRow(false, resources .getString(Resources .Keys.DisplayedSize));
rows[TILE_SIZE] = new LayoutRow(true, vocabulary.getString(Vocabulary.Keys.TileSize));
rows[NUM_TILES] = new LayoutRow(true, vocabulary.getString(Vocabulary.Keys.NumberOfTiles));
rows[MIN_PIXEL] = new LayoutRow(true, resources .getString(Resources .Keys.ImageStart));
rows[MIN_VISIBLE] = new LayoutRow(false, resources .getString(Resources .Keys.DisplayStart));
rows[MIN_TILE] = new LayoutRow(true, resources .getString(Resources .Keys.TileIndexStart));
return rows;
}
/** Size or position along x and y axes, to show in second and third columns. */
final IntegerProperty xp, yp;
/**
* Whether this property is a core property to keep always visible.
*/
private final boolean core;
/** Creates a new row with the given label in first column. */
private LayoutRow(final boolean core, final String label) {
super(label);
this.core = core;
xp = new SimpleIntegerProperty();
yp = new SimpleIntegerProperty();
}
/**
* Updates {@link #xp} and {@link #yp} property values for the given image.
* The index <var>i</var> is the row index when no filtering is applied.
*/
final void update(final RenderedImage image, final Rectangle visibleImageBounds, final int i) {
int x = 0, y = 0;
if (image != null) switch (i) {
case IMAGE_SIZE: x = image.getWidth(); y = image.getHeight(); break;
case TILE_SIZE: x = image.getTileWidth(); y = image.getTileHeight(); break;
case NUM_TILES: x = image.getNumXTiles(); y = image.getNumYTiles(); break;
case MIN_TILE: x = image.getMinTileX(); y = image.getMinTileY(); break;
case MIN_PIXEL: x = image.getMinX(); y = image.getMinY(); break;
case MIN_VISIBLE: if (visibleImageBounds != null) {
x = visibleImageBounds.x;
y = visibleImageBounds.y;
}
break;
case DISPLAYED_SIZE: if (visibleImageBounds != null) {
x = visibleImageBounds.width;
y = visibleImageBounds.height;
}
break;
}
xp.set(x);
yp.set(y);
}
/**
* Filter for excluding the rows that need a non-null {@code visibleImageBounds} argument.
*/
static Predicate<LayoutRow> EXCLUDE_VISIBILITY = (r) -> r.core;
}
/**
* The predicate for filtering {@link #layoutRows}.
*
* @see LayoutRow#EXCLUDE_VISIBILITY
*/
private final ObjectProperty<Predicate<? super LayoutRow>> layoutFilter;
/**
* The rows in the tables showing property values.
* Rows in the list will be added and removed when the image changed.
*
* @see #updatePropertyList(RenderedImage)
*/
private final ObservableList<PropertyRow> propertyRows;
/**
* The selected item in the table of properties.
*/
private final ReadOnlyObjectProperty<PropertyRow> selectedProperty;
/**
* A row in the table showing image properties. The inherited {@link String} property is the property name.
* The property value is fetched from the given image and can be updated for the value of a new image.
* Updating an existing {@code PropertyRow} instead of creating a new instance is useful for keeping
* the selected row unchanged if possible.
*/
private static final class PropertyRow extends ImmutableObjectProperty<String> {
/**
* Image property value.
*/
final ObjectProperty<Object> value;
/**
* Creates a new row for the given property in the given image.
*/
PropertyRow(final RenderedImage image, final String property) {
super(property);
value = new SimpleObjectProperty<>(getProperty(image, property));
}
/**
* If this property can be updated to a value for the given image, performs
* the update and returns {@code true}. Otherwise returns {@code false}.
*/
final boolean update(final RenderedImage image, final String property) {
if (property.equals(super.get())) {
value.set(getProperty(image, property));
return true;
}
return false;
}
/**
* Returns a property value of given image, or the exception if that operation failed.
*/
private static Object getProperty(final RenderedImage image, final String property) {
try {
return image.getProperty(property);
} catch (RuntimeException e) {
return e;
}
}
/**
* Returns a human-readable variation of the property name for use in graphic interface.
*/
@Override
public String get() {
final String property = super.get();
return CharSequences.camelCaseToSentence(property.substring(property.lastIndexOf('.') + 1)).toString();
}
}
/**
* The tab where to show details about a property value. The content of tab may be different kinds
* of node depending on the class of the property to be show.
*
* @see #propertyDetails
* @see #updatePropertyDetails(Rectangle)
*/
private final Tab detailsTab;
/**
* Viewer of property value. The different components of this viewer are created when first needed.
*
* @see #updatePropertyDetails(Rectangle)
*/
private final PropertyView propertyDetails;
/**
* The view containing all visual components.
* The exact class may change in any future version.
*/
private final TabPane view;
/**
* Creates an initially empty explorer.
*/
public ImagePropertyExplorer() {
this(null, null);
}
/**
* Creates a new explorer.
*
* @param background the image background color, or {@code null} if none.
*/
ImagePropertyExplorer(final Locale locale, final ObjectProperty<Background> background) {
final Vocabulary vocabulary = Vocabulary.getResources(locale);
final Resources resources = Resources.forLocale(locale);
// Following variables could be class fields, but are not yet needed outside this constructor.
final TreeView<RenderedImage> sources;
final TableView<LayoutRow> layout;
final NumberFormat integerFormat;
final TableView<PropertyRow> properties;
image = new ImageProperty();
imageUseBoundsCS = new IdentityHashMap<>(4);
updateOnChange = new SimpleBooleanProperty(this, "updateOnChange", true);
listening = true;
/*
* Tree of image sources. The root is never changed after construction. All children nodes can
* be created, removed or updated to new value at any time. At most one image can be selected.
*/
{
sourcesRoot = new TreeItem<>();
sources = new TreeView<>(sourcesRoot);
selectedImage = sources.getSelectionModel().selectedItemProperty();
sources.setCellFactory(SourceCell::new);
selectedImage.addListener((p,o,n) -> {
RenderedImage selected = null;
if (n != null) selected = n.getValue();
imageSelected(selected != null ? selected : image.get());
});
}
/*
* Table of image layout built with a fixed set of rows: no row will be added or removed after
* construction. Instead property values of existing rows will be modified when a new image is
* selected. Row selection are not allowed since we have nothing to do with selected rows.
*/
{
final FilteredList<LayoutRow> filtered;
layoutRows = FXCollections.observableArrayList(LayoutRow.values(vocabulary, resources));
filtered = new FilteredList<>(layoutRows);
layout = new TableView<>(filtered);
layoutFilter = filtered.predicateProperty();
integerFormat = NumberFormat.getIntegerInstance();
layout.setSelectionModel(null);
final TableColumn<LayoutRow, String> label = new TableColumn<>(resources.getString(Resources.Keys.SizeOrPosition));
final TableColumn<LayoutRow, Number> xCol = new TableColumn<>(resources.getString(Resources.Keys.Along_1, "X"));
final TableColumn<LayoutRow, Number> yCol = new TableColumn<>(resources.getString(Resources.Keys.Along_1, "Y"));
final Callback<TableColumn<LayoutRow, Number>,
TableCell<LayoutRow, Number>> cellFactory = (column) -> new LayoutCell(integerFormat);
xCol .setCellFactory(cellFactory);
yCol .setCellFactory(cellFactory);
xCol .setCellValueFactory((cell) -> cell.getValue().xp);
yCol .setCellValueFactory((cell) -> cell.getValue().yp);
label.setCellValueFactory((cell) -> cell.getValue());
layout.getColumns().setAll(label, xCol, yCol);
layout.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
layout.getColumns().forEach((c) -> {
c.setReorderable(false);
c.setSortable(false);
});
}
/*
* Table of image properties. Contrarily to the layout table, the set of rows in
* this property table may change at any time. At most one row can be selected.
* We do not register a listener on the row selection; instead we wait for the
* details pane to become visible.
*/
{
properties = new TableView<>();
propertyRows = properties.getItems();
selectedProperty = properties.getSelectionModel().selectedItemProperty();
final TableColumn<PropertyRow, String> label = new TableColumn<>(vocabulary.getString(Vocabulary.Keys.Property));
final TableColumn<PropertyRow, Object> value = new TableColumn<>(vocabulary.getString(Vocabulary.Keys.Value));
label.setCellValueFactory((cell) -> cell.getValue());
value.setCellValueFactory((cell) -> cell.getValue().value);
value.setCellFactory((column) -> new PropertyCell(locale));
properties.getColumns().setAll(label, value);
properties.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
properties.getColumns().forEach((c) -> c.setReorderable(false));
}
/*
* Tab where to show details about the currently selected property value.
* The tab content is updated when it become visible. We can do that because
* the property selection is done in another tab.
*/
{
detailsTab = new Tab(vocabulary.getString(Vocabulary.Keys.Details));
selectedProperty.addListener((p,o,n) -> clearPropertyValues(false));
propertyDetails = new PropertyView(locale, detailsTab.contentProperty(), background);
detailsTab.selectedProperty().addListener((p,o,n) -> {
if (n) updatePropertyDetails(getVisibleImageBounds(getSelectedImage()));
});
}
/*
* The view containing all visual components. In current version the sources is a tab like others.
* A previous version was showing the sources on top (using SlidePane), so we could navigate easily
* in the properties of different sources. It has been removed for simplifying the layout, but the
* listeners are still updating layout and property panes immediately when a new source is selected.
*/
view = new TabPane(
new Tab(vocabulary.getString(Vocabulary.Keys.Source), sources),
new Tab(vocabulary.getString(Vocabulary.Keys.Layout), layout),
new Tab(vocabulary.getString(Vocabulary.Keys.Properties), properties),
detailsTab);
view.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
updateOnChange.addListener((p,o,n) -> {if (n) startListening();});
}
/**
* Invoked when {@link #updateOnChange} became {@code true}.
* This method updates the visual components for current image.
*
* <p>Note: there is no {@code stopListening()} method because setting {@link #listening} flag
* to {@code false} will be done by the {@link #setImage(RenderedImage, Rectangle)} method.</p>
*/
private void startListening() {
listening = true;
if (sourcesRoot.getValue() == null) {
setTreeRoot(image.get());
refreshTables();
}
}
/**
* Sets the image to show together with the coordinates of the region currently shown.
* If {@link #updateOnChange} is true, then the tree view is updated.
* Otherwise we will wait for the tree view to become visible before to update it.
*
* @param newValue the new image, or {@code null} if none.
* @param visibleBounds image region which is currently visible, or {@code null} if unspecified.
*/
final void setImage(final RenderedImage newValue, final Rectangle visibleBounds) {
visibleImageBounds = visibleBounds;
((ImageProperty) image).assign(newValue);
if (listening) {
final boolean immediate = updateOnChange.get();
setTreeRoot(immediate ? newValue : null);
if (immediate) {
refreshTables();
} else {
clearPropertyValues(true);
listening = false;
}
}
}
/**
* Returns the currently selected image. If no image is explicitly selected,
* returns the root {@linkplain #image} (which may be null).
*/
private RenderedImage getSelectedImage() {
final TreeItem<RenderedImage> item = selectedImage.get();
if (item != null) {
final RenderedImage selected = item.getValue();
if (selected != null) return selected;
}
return image.get();
}
/**
* Refresh all visual components except the tree of sources. This includes the table of
* image layouts, the table of property values and the details of selected property value.
*/
private void refreshTables() {
imageSelected(getSelectedImage());
}
/**
* Invoked when an image is selected in the tree of image sources. The selected image
* is not necessarily the {@link #image} property value; it may be one of its sources.
* If no image is explicitly selected, defaults to the root image.
*/
private void imageSelected(final RenderedImage selected) {
final Rectangle bounds = getVisibleImageBounds(selected);
final int n = layoutRows.size();
for (int i=0; i<n; i++) {
layoutRows.get(i).update(selected, bounds, i);
}
layoutFilter.set(bounds != null ? null : LayoutRow.EXCLUDE_VISIBILITY);
updatePropertyList(selected);
/*
* The selected property value may have changed as a result of above.
* If the details tab is visible, update immediately. Otherwise we will
* wait for that tab to become visible.
*/
if (detailsTab.isSelected()) {
updatePropertyDetails(bounds);
}
}
/**
* Returns the pixel coordinates of the region shown on screen,
* or {@code null} if none or does not apply to the currently selected image.
*/
final Rectangle getVisibleImageBounds(final RenderedImage selected) {
return Boolean.TRUE.equals(imageUseBoundsCS.get(selected)) ? visibleImageBounds : null;
}
/**
* Sets the root image together with its tree of sources.
*/
private void setTreeRoot(final RenderedImage newValue) {
imageUseBoundsCS.clear();
setTreeNode(sourcesRoot, newValue, imageUseBoundsCS, visibleImageBounds != null);
/*
* Remove entries associated to value `false` since our default value is `false`.
* The intent is to avoid unnecessary `RenderedImage` references for reducing the
* risk of memory retention.
*/
imageUseBoundsCS.values().removeIf((b) -> !b);
}
/**
* Invoked when tree under {@link #sourcesRoot} node needs to be updated. This method is not necessarily invoked
* immediately after an {@linkplain #image} change; the update may be deferred until the tree become visible.
*
* @param imageUseBoundsCS the {@link #imageUseBoundsCS} as an initially empty map. This map is
* populated by this method and opportunistically used for avoiding infinite recursivity.
*/
private static void setTreeNode(final TreeItem<RenderedImage> root, final RenderedImage image,
final Map<RenderedImage,Boolean> imageUseBoundsCS, Boolean boundsApplicable)
{
root.setValue(image);
if (imageUseBoundsCS.putIfAbsent(image, boundsApplicable) == null) {
final ObservableList<TreeItem<RenderedImage>> children = root.getChildren();
if (image != null) {
final List<RenderedImage> sources = image.getSources();
if (sources != null) {
/*
* If the image is an instance of `ResampledImage`, then its
* source is presumed to use a different coordinate system.
*/
if (image instanceof ResampledImage) {
boundsApplicable = Boolean.FALSE;
}
final int numSrc = sources.size();
final int numDst = children.size();
final int n = Math.min(numSrc, numDst);
int i;
for (i=0; i<n; i++) {
setTreeNode(children.get(i), sources.get(i), imageUseBoundsCS, boundsApplicable);
}
for (; i<numSrc; i++) {
final TreeItem<RenderedImage> child = new TreeItem<>();
setTreeNode(child, sources.get(i), imageUseBoundsCS, boundsApplicable);
children.add(child);
}
if (i < numDst) {
children.remove(i, numDst);
}
return;
}
}
children.clear();
}
}
/**
* Creates the renderer of cells in the tree of image sources.
*/
private static final class SourceCell extends TreeCell<RenderedImage> {
/**
* Invoked by the cell factory (must have this exact signature).
*/
SourceCell(final TreeView<RenderedImage> tree) {
}
/**
* Invoked when a new image is shown in this cell node. This method also tests image consistency.
* If an inconsistency is found, the line is shown in red (except for "width" and "height") with
* a warning message. We do not use a red color for "width" and "height" because the mismatch may
* be normal.
*/
@Override protected void updateItem(final RenderedImage image, final boolean empty) {
super.updateItem(image, empty);
String text = null;
Color fill = Styles.NORMAL_TEXT;
if (image != null) {
text = getClassName(image.getClass());
if (image instanceof PlanarImage) {
final String check = ((PlanarImage) image).verify();
if (check != null) {
text = Resources.format(Resources.Keys.InconsistencyIn_2, text, check);
if (!(check.equals("width") || check.equals("height"))) {
fill = Styles.ERROR_TEXT;
}
}
}
}
setText(text);
setTextFill(fill);
}
}
/**
* Gets a simple top-level class name for an image class. If the given type is an enclosed class,
* searches for a parent class instead because enclosed class names are often not very informative.
* For example {@code ImageRenderer.Untitled} which is a {@code BufferedImage} subclass:
* the enclosing class name is not suitable in that example.
*/
private static String getClassName(Class<?> type) {
while (type.getEnclosingClass() != null) {
type = type.getSuperclass();
}
return type.getSimpleName();
}
/**
* Creates the renderer of cells in the table of image layout information.
*/
private static final class LayoutCell extends TableCell<LayoutRow,Number> {
/**
* The formatter to use for numerical values in the table.
*/
private final NumberFormat integerFormat;
/**
* Invoked by the cell factory.
*/
LayoutCell(final NumberFormat integerFormat) {
this.integerFormat = integerFormat;
setAlignment(Pos.CENTER_RIGHT);
}
/**
* Invoked when a new value is shown in this table cell.
*/
@Override protected void updateItem(final Number value, final boolean empty) {
super.updateItem(value, empty);
setText(value != null ? integerFormat.format(value) : null);
}
}
/**
* Creates the renderer of cells in the table of image properties.
*/
private static final class PropertyCell extends TableCell<PropertyRow,Object> {
/**
* The formatter to use for producing a short string representation of a property value.
*/
private final ValueFormat format;
/** {@link PropertyCell#format} implementation. */
private static final class ValueFormat extends PropertyFormat {
/** The locale to use for objects such as international strings. */
private final Locale locale;
/** Creates a new formatter which will write in the given buffer. */
ValueFormat(final Locale locale, final StringBuilder buffer) {
super(buffer);
this.locale = locale;
}
/** Returns the locale specified at construction time. */
@Override public Locale getLocale() {return locale;}
/** Invoked by {@link PropertyFormat} for values of unrecognized type. */
@Override protected String toString(final Object value) {
if (value instanceof Number || value instanceof Date) { // See super-class javadoc.
return value.toString();
}
return getClassName(value.getClass()) + "[…]";
}
}
/**
* Temporary buffer user when formatting property values.
*/
private final StringBuilder buffer;
/**
* Invoked by the cell factory.
*/
PropertyCell(final Locale locale) {
buffer = new StringBuilder();
format = new ValueFormat(locale, buffer);
}
/**
* Invoked when a new value is shown in this table cell.
*/
@Override protected void updateItem(final Object value, final boolean empty) {
super.updateItem(value, empty);
String text = null;
if (!empty) try {
buffer.setLength(0);
format.appendValue(value);
format.flush();
text = buffer.toString();
} catch (IOException e) { // Should never happen since we write in a StringBuilder.
text = e.toString();
}
setText(text);
}
}
/**
* Update the list of properties for the given image.
* The {@link #propertyRows} are updated with an effort for reusing existing items when
* the property name is the same. The intent is to keep selection unchanged if possible
* (because removing a selected row may make it unselected).
*/
private void updatePropertyList(final RenderedImage selected) {
if (selected != null) {
final String[] properties = selected.getPropertyNames();
if (properties != null) {
int insertAt = 0;
nextProp: for (final String property : properties) {
if (property != null) {
for (int i=insertAt; i < propertyRows.size(); i++) {
if (propertyRows.get(i).update(selected, property)) {
propertyRows.remove(insertAt, i);
insertAt = i + 1;
continue nextProp;
}
}
propertyRows.add(insertAt++, new PropertyRow(selected, property));
}
}
propertyRows.remove(insertAt, propertyRows.size());
return;
}
}
propertyRows.clear();
}
/**
* Updates the {@link #detailsTab} with the value of currently selected property.
* This method may be invoked after the selection changed (but not immediately),
* or after the selected image changed (which indirectly changes the properties).
*
* @param bounds {@link #visibleImageBounds} or {@code null} if it does not apply to current image.
*/
private void updatePropertyDetails(final Rectangle bounds) {
final PropertyRow row = selectedProperty.get();
propertyDetails.set((row != null) ? row.value.get() : null, bounds);
}
/**
* Clears the table of property values and the content of {@link #detailsTab}.
* We do that when the tab became hidden and the image changed, in order to give
* a chance to the garbage collector to release memory.
*
* @param full whether to clears also the table in the "properties" tab (in addition of clearing the
* "details" tab). This parameter should be {@code false} if the properties tab is still visible.
*/
private void clearPropertyValues(final boolean full) {
if (propertyDetails != null) {
propertyDetails.clear();
detailsTab.setContent(null);
}
if (full) {
propertyRows.clear();
}
}
/**
* Returns the view of this explorer. The subclass is implementation dependent
* and may change in any future version.
*
* @return this explorer view.
*/
@Override
public Region getView() {
return view;
}
/**
* Returns the locale for controls and messages.
*
* @since 1.2
*/
@Override
public final Locale getLocale() {
return propertyDetails.getLocale();
}
} |
<gh_stars>1-10
# Generated by Django 2.1.3 on 2019-08-20 04:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('result', '0003_auto_20190820_1253'),
]
operations = [
migrations.AlterModelOptions(
name='cname',
options={'ordering': ('last_name',)},
),
migrations.RenameField(
model_name='cname',
old_name='student_name',
new_name='first_name',
),
migrations.AddField(
model_name='cname',
name='last_name',
field=models.CharField(blank=True, max_length=30, null=True),
),
]
|
<reponame>PaulJWright/sunkit-dem-sandbox
"""
Single Gaussian Model
"""
from sunkit_dem import GenericModel
import astropy.units as u
import numpy as np
from astropy.modeling.models import Gaussian1D
from scipy.optimize import minimize
import warnings
__all__ = ["SingleGaussian"]
class SingleGaussian(GenericModel):
def _model(self, dem0=1e23 / (u.cm ** 5 * u.K), logT0=None, delta_logT=None):
# Predefine some quantities
delta_T_kernel = (
np.diff(self.temperature_bin_edges) * self.kernel_matrix
).value
logT_centers = np.log10(self.temperature_bin_centers.value)
uncertainty = np.array(
[
c.uncertainty.array.squeeze() if c.uncertainty is not None else 1
for c in self.data
]
)
initial_conditions = (
dem0.value,
logT_centers.mean() if logT0 is None else logT0,
np.diff(logT_centers)[0] if delta_logT is None else delta_logT,
)
# Define chi-squared between model and data
N_free = self.wavelength.shape[0] - 3
def func(x):
g = Gaussian1D(*x)
data_model = (delta_T_kernel * g(logT_centers)).sum(axis=1)
return np.sqrt(
(((self.data_matrix.value - data_model) / uncertainty) ** 2).sum()
/ N_free
)
# Run minimization
res = minimize(func, initial_conditions, method="Nelder-Mead",)
if not res.success:
warnings.warn(res.message)
unit = (
self.data_matrix.unit
/ self.temperature_bin_edges.unit
/ self.kernel_matrix.unit
)
dem = Gaussian1D(*res.x)(logT_centers) * unit
return {
"dem": Gaussian1D(*res.x)(logT_centers) * unit,
"uncertainty": None,
}
@classmethod
def defines_model_for(cls, *args, **kwargs):
return kwargs.get("model") == "single_gaussian"
|
<reponame>leomrocha/mix_nlp<filename>utf8/sparse_encoders.py
"""
This file contains the functions that execute every aspect of the paper,
each function contains the chosen configuration values and is done like that mostly for reproducibility WITHOUT the need
of an external configuration file, so it is purposely written with hardcoded values instead of depending on an external
file.
Many things might (and will be) done in a non-optimal code or production-level code in this file for the sake of clarity
and/or idea separation.
Code is single threaded single process, this is to measure build and run times and compare results (also parallel code
can be slightly or much more complex to run and debug)
"""
from itertools import combinations
import os
import pickle
import numpy as np
import scipy as sp
import scipy.sparse
import time
import unicodedata
import unidecode
import torch.nn.functional as F
try:
from .utf8_encoder import *
from .constants import *
except:
# to solve issue with ipython executing this import
from utf8_encoder import *
from constants import *
SEGMENTS = [1, 2, 3, 4]
NCODES = [128, 1984, 59328, 1107904]
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
def create_measure_tables():
elapsed_times = []
tables = []
shapes = []
# exceptions = []
sizes = []
matrix_sizes = []
sparse_sizes = []
paths = []
base_name = "codes/utf8_codes-{}seg.pkl"
matrix_name = "codes/utf8_codes_matrix-{}seg.npy"
sparse_matrix_name = "codes/utf8_codes_sparse_matrix-{}seg.npy"
for i in range(1, 5):
t_init = time.time()
t = create_tables(segments=i)
t = add_mappings(t)
tables.append(t)
# Save the shape of the matrices
shapes.append(t[0].shape)
# Save tables
name = base_name.format(i)
paths.append(name)
with open(name, 'wb') as f:
pickle.dump(t, f, pickle.HIGHEST_PROTOCOL)
# Save matrix alone
mname = matrix_name.format(i)
np.save(mname, t[0])
# Save Sparse matrix alone
smname = sparse_matrix_name.format(i)
spcodes = sp.sparse.coo_matrix(t[0])
np.save(smname, spcodes)
# Measure size in disk in MB
mb = os.path.getsize(name) / (1024 ** 2)
sizes.append(mb)
# Dense Matrix
mmb = os.path.getsize(mname) / (1024 ** 2)
matrix_sizes.append(mmb)
# Sparse Matrix
smmb = os.path.getsize(smname) / (1024 ** 2)
sparse_sizes.append(smmb)
t_end = time.time()
el = t_end - t_init
elapsed_times.append(el)
col = "| Segments | exec_time (sec) | matrix_shape | Size in Disk (MB): | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {:.3f} | {} | {:.2f} | {:.2f} | {:.2f} | {} |"
print(col)
for i, et, sh, si, ms, ss, p in zip(range(1, 5), elapsed_times, shapes, sizes, matrix_sizes, sparse_sizes, paths):
print(row.format(i, et, sh, si, ms, ss, p))
def overfit_tests():
pass
def sparse_Nk_dimension_analysis():
# find the minimum N and k for which the condition is filled for the different codes
results = []
for code_points in NCODES:
for k in range(2, 7):
for N in range(10, 256):
v = int(np.prod(list(range(N, N - k, -1))) / np.prod(list(range(1, k + 1))))
if v > code_points:
# print("code_size={}; N={},k={}".format(v, N, k))
results.append((code_points, v, N, k, '{:.3f}'.format(k / N)))
break
return results
def sparse_code_Nk(code_size, N, k):
# get the indices for the ones
comb = combinations(list(range(N)), k) # iterator
# limit to code size
comb = np.array(list(comb))[:code_size]
# compute referential as flat index to be able to use for
comb = comb + np.array(range(code_size))[:comb.shape[0]].reshape([-1, 1]) * N
# convert indices to dense binary matrix
sc = np.zeros([code_size, N], dtype=bool)
np.put(sc, comb, 1)
return sc
def create_sparse_Nk_codes():
col = "| Segments | code size | Vector Size | N | k |exec_time (sec) | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {} | {} | {} | {} | {:.3f} | {:.2f} | {:.2f} | {} |"
base_name = "codes/utf8_sparse_codes-{}_N-{}_k-{}_seg"
sparse_matrix_name = "codes/utf8_sparse_codes-{}_N-{}_k-{}_seg_sparse-matrix"
params = [(NCODES[0], 17, 2), (NCODES[1], 24, 3), (NCODES[2], 37, 4), (NCODES[3], 45, 5)]
codes = []
print(col)
for i, p in enumerate(params):
t_init = time.time()
nc, N, k = p
scode = sparse_code_Nk(nc, N, k)
codes.append(scode)
# Save matrix alone
mname = base_name.format(i + 1, N, k)
np.save(mname, scode)
# Save Sparse matrix alone
smname = sparse_matrix_name.format(i + 1, N, k)
spcodes = sp.sparse.coo_matrix(scode)
np.save(smname, spcodes)
msize = os.path.getsize(mname + ".npy") / (1024 ** 2)
# Sparse Matrix
smsize = os.path.getsize(smname + ".npy") / (1024 ** 2)
t_end = time.time()
el = t_end - t_init
print(row.format(i + 1, nc, scode.shape, N, k, el, msize, smsize, mname))
return codes
def multihot_primes_conf_finder():
all_codes = []
for i in range(2, 5):
arr = list(combinations(PRIMES, i))
for a in arr:
ll = len(a)
ncodes = np.prod(a)
vsize = np.sum(a)
sparsity = round(i / vsize, 3)
all_codes.append((a, ll, sparsity, vsize, ncodes))
all_codes = sorted(all_codes, key=lambda x: x[-2])
codes_1seg = [i for i in all_codes if i[-1] > NCODES[0] and i[-1] < NCODES[3] * 2]
codes_2seg = [i for i in all_codes if i[-1] > NCODES[1] and i[-1] < NCODES[3] * 2]
codes_3seg = [i for i in all_codes if i[-1] > NCODES[2] and i[-1] < NCODES[3] * 2]
codes_4seg = [i for i in all_codes if i[-1] > NCODES[3] and i[-1] < NCODES[3] * 2]
return all_codes, codes_1seg, codes_2seg, codes_3seg, codes_4seg
def generate_multihot_prime_code(ncodes, subcode_list):
eyes = [np.eye(c).astype(bool) for c in subcode_list]
# TODO
# stack each and cut to the ncodes size
cols = [np.tile(e, ((ncodes // e.shape[0]) + 1, 1))[:ncodes] for e in eyes]
code = np.hstack(cols)
return code
def all_multihot_primes():
col = "| Segments | code size | Vector Size | primes |exec_time (sec) | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {} | {} | {} | {:.3f} | {:.2f} | {:.2f} | {} |"
base_name = "codes/utf8_coprime_codes-{}_primes-{}_{}_seg"
sparse_matrix_name = "codes/utf8_coprime_codes-{}_primes-{}_{}_seg_sparse-matrix"
# the codes already were selected by hand from the ones and are:
code_config = [(NCODES[0], (3, 5, 11)),
(NCODES[1], (3, 5, 11, 13)),
(NCODES[2], (11, 13, 19, 23)),
(NCODES[3], (23, 31, 37, 43))]
codes = []
print(row)
for i, cc in enumerate(code_config):
t_init = time.time()
code = generate_multihot_prime_code(*cc)
codes.append(code)
# Save matrix alone
mname = base_name.format(cc[0], str(cc[1]), i + 1)
np.save(mname, code)
# Save Sparse matrix alone
smname = sparse_matrix_name.format(cc[0], str(cc[1]), i + 1)
spcodes = sp.sparse.coo_matrix(code)
np.save(smname, spcodes)
msize = os.path.getsize(mname + ".npy") / (1024 ** 2)
# Sparse Matrix
smsize = os.path.getsize(smname + ".npy") / (1024 ** 2)
t_end = time.time()
el = t_end - t_init
print(row.format(i + 1, cc[0], code.shape, cc[1], el, msize, smsize, mname))
return codes
def create_choose_Nk_coprimes_codes():
col = "| Segments | code size | Vector Size | N | k | primes |exec_time (sec) | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {} | {} | {} | {} | {} | {:.3f} | {:.2f} | {:.2f} | {} |"
base_name = "codes/utf8_N-{}k-{}-coprime_codes-{}_primes-{}_{}_seg"
sparse_matrix_name = "codes/utf8_N-{}k-{}-coprime_codes-{}_primes-{}_{}_seg_sparse-matrix"
# N choose k + coprime multihot
# code dim, N,k,target dim, prime dim, primes
config = [(NCODES[0], 17, 2, 32, 15, (3, 5, 7)),
(NCODES[1], 24, 3, 48, 24, (5, 8, 11)),
(NCODES[2], 37, 4, 64, 27, (3, 5, 8, 11)),
(NCODES[3], 45, 5, 96, 51, (3, 7, 11, 13, 17))]
codes = []
print(col)
for i, (cs, N, k, tgts, ms, coprimes) in enumerate(config):
t_init = time.time()
nk = sparse_code_Nk(cs, N, k)
cp = generate_multihot_prime_code(cs, coprimes)
code = np.hstack([nk, cp])
codes.append(code)
# Save matrix alone
mname = base_name.format(N, k, cs, str(coprimes), i + 1)
np.save(mname, code)
# Save Sparse matrix alone
smname = sparse_matrix_name.format(N, k, cs, str(coprimes), i + 1)
spcodes = sp.sparse.coo_matrix(code)
np.save(smname, spcodes)
msize = os.path.getsize(mname + ".npy") / (1024 ** 2)
# Sparse Matrix
smsize = os.path.getsize(smname + ".npy") / (1024 ** 2)
t_end = time.time()
el = t_end - t_init
print(row.format(i + 1, cs, code.shape, N, k, coprimes, el, msize, smsize, mname))
return codes
def create_coprimes_choose_Nk_codes():
col = "| Segments | code size | Vector Size | N | k | primes |exec_time (sec) | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {} | {} | {} | {} | {} | {:.3f} | {:.2f} | {:.2f} | {} |"
base_name = "codes/utf8_coprime_codes-{}_primes-{}_N-{}k-{}_{}-seg"
sparse_matrix_name = "codes/utf8_coprime_codes-{}_primes-{}_N-{}k-{}_{}-seg_sparse-matrix"
# coprime multihot + N choose k
# code dim, primes, (N, k)
config = [(NCODES[0], (3, 5, 11), (13, 3)),
(NCODES[1], (3, 5, 11, 13), (32, 3)),
(NCODES[2], (11, 13, 19, 23), (30, 4)),
(NCODES[3], (23, 31, 37, 43), (58, 5))]
codes = []
print(col)
for i, (cs, coprimes, (N, k)) in enumerate(config):
t_init = time.time()
nk = sparse_code_Nk(cs, N, k)
nk = np.tile(nk, ((cs // nk.shape[0]) + 1, 1))[:cs]
cp = generate_multihot_prime_code(cs, coprimes)
code = np.hstack([cp, nk])
codes.append(code)
# Save matrix alone
mname = base_name.format(cs, str(coprimes), N, k, i + 1)
np.save(mname, code)
# Save Sparse matrix alone
smname = sparse_matrix_name.format(cs, str(coprimes), N, k, i + 1)
spcodes = sp.sparse.coo_matrix(code)
np.save(smname, spcodes)
msize = os.path.getsize(mname + ".npy") / (1024 ** 2)
# Sparse Matrix
smsize = os.path.getsize(smname + ".npy") / (1024 ** 2)
t_end = time.time()
el = t_end - t_init
print(row.format(i + 1, cs, code.shape, N, k, coprimes, el, msize, smsize, mname))
return codes
def create_specific_redundant_codes():
col = "| Segments | code size | Vector Size | N | k | primes |exec_time (sec) | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {} | {} | {} | {} | {} | {:.3f} | {:.2f} | {:.2f} | {} |"
base_name = "codes/utf8_coprime_codes-{}_primes-{}_N-{}k-{}_{}-seg"
sparse_matrix_name = "codes/utf8_coprime_codes-{}_primes-{}_N-{}k-{}_{}-seg_sparse-matrix"
# coprime multihot + N choose k
# code dim, primes, (N, k)
config = [(NCODES[0], (3, 5, 11), (13, 3)),
(NCODES[1], (3, 5, 11, 13), (32, 3)),
(NCODES[2], (11, 13, 19, 23), (30, 4)),
(NCODES[3], (23, 31, 37, 43), (58, 5))]
codes = []
print(col)
for i, (cs, coprimes, (N, k)) in enumerate(config):
t_init = time.time()
nk = sparse_code_Nk(cs, N, k)
nk = np.tile(nk, ((cs // nk.shape[0]) + 1, 1))[:cs]
cp = generate_multihot_prime_code(cs, coprimes)
code = np.hstack([cp, nk])
codes.append(code)
# Save matrix alone
mname = base_name.format(cs, str(coprimes), N, k, i + 1)
np.save(mname, code)
# Save Sparse matrix alone
smname = sparse_matrix_name.format(cs, str(coprimes), N, k, i + 1)
spcodes = sp.sparse.coo_matrix(code)
np.save(smname, spcodes)
msize = os.path.getsize(mname + ".npy") / (1024 ** 2)
# Sparse Matrix
smsize = os.path.getsize(smname + ".npy") / (1024 ** 2)
t_end = time.time()
el = t_end - t_init
print(row.format(i + 1, cs, code.shape, N, k, coprimes, el, msize, smsize, mname))
return codes
# FIXME
# The cycle code generator is WRONG and MUST be corrected, I'll just not use it for the moment and that's it.
# WARNING this is NOT working, DO NOT USE
def create_single_cycle_code(code_size, sizes):
"""
:param code_size: number of elements in the code
:param sizes: iterable of vector sizes to include in the code
:return: a multi-hot (or one-hot) vector of shape=(code_size, sum(sizes)) with the codes
"""
codes = []
for s in sizes:
# compute index of the value '1'
idx = np.arange(1, code_size + 1)
idx = idx // s
# idx = idx % s
# convert indices to dense binary matrix
sc = np.zeros([code_size, s], dtype=bool)
np.put(sc, idx, 1)
codes.append(sc)
ret = np.hstack(codes)
return ret
def create_codematrix_from_conf(config=[]):
"""
The codes are N choose k + coprime + filling with single cycle method giving redundancy and 2
complete representations
There are only done for 2 and 3 segments, the cycles are arbitrarilly chosen to fill the gaps to the next interesting
dimension (64/128
:return:
"""
col = "| Segments | code size | Vector Size | N | k | primes | cycles | exec_time (sec) | Matrix Size in Disk (MB): \
| Sparse Matrix Size in Disk (MB): |code path"
row = "| {} | {} | {} | {} | {} | {} | {} | {:.3f} | {:.2f} | {:.2f} | {} |"
base_name = "codes/utf8_{}-seg_{}-codepoints_{}-dim_N-{}-k{}_coprimes-{}_cycles-{}_dense"
sparse_matrix_name = "codes/utf8_{}-seg_{}-codepoints_{}-dim_N-{}-k{}_coprimes-{}_cycles-{}_sparse"
if len(config) <= 0:
config = [
# segment, number of code-points, (n,k), (coprimes), (cycles), dimension, sparcity
(2, NCODES[1], (24, 3), (3, 5, 11, 13), (6, 2), 64, 9 / 64),
# (2, 1916, (24, 3), (3, 5, 11, 13), (6, 2), 64, 9 / 64),
(3, NCODES[2], (37, 4), (11, 13, 19, 23), (11, 7, 4, 3), 128, 12 / 128),
]
codes = []
print(col)
for seg, codepoints, (N, k), coprimes, cycles, dim, sparcity in config:
t_init = time.time()
nk = sparse_code_Nk(codepoints, N, k)
nk = np.tile(nk, ((codepoints // nk.shape[0]) + 1, 1))[:codepoints]
cp = generate_multihot_prime_code(codepoints, coprimes)
cc = create_single_cycle_code(codepoints, cycles)
code = np.hstack([cp, nk, cc])
codes.append(code)
# Save matrix alone
mname = base_name.format(seg, codepoints, dim, N, k, str(coprimes), str(cycles))
np.save(mname, code)
# Save Sparse matrix alone
smname = sparse_matrix_name.format(seg, codepoints, dim, N, k, str(coprimes), str(cycles))
spcodes = sp.sparse.coo_matrix(code)
np.save(smname, spcodes)
msize = os.path.getsize(mname + ".npy") / (1024 ** 2)
# Sparse Matrix
smsize = os.path.getsize(smname + ".npy") / (1024 ** 2)
t_end = time.time()
el = t_end - t_init
print(row.format(seg, codepoints, code.shape, N, k, coprimes, cycles, el, msize, smsize, mname))
return codes
# BAD BAD these configurations go together ... need to do an automation system to compute them
# CHARSET_PATH = "codes/all_chars.chars"
# CONFIG = (2, 1916, (24, 3), (3, 5, 11, 13), (6, 2), 64, 9 / 64)
# OFNAME = "codes/adhoc-codebook-1916.pkl"
CHARSET_PATH = "codes/all_chars.chars"
CONFIG = (2, 1871, (24, 3), (3, 5, 11, 13), (4, 6, 8, 10, 12), 96, 13 / 96)
OFNAME = "codes/adhoc-codebook-1871.pkl"
def create_codebook(charset, config=CONFIG,
ofname=OFNAME,
special_codes=SPECIAL_CODES,
nul_row_is_zero=True,
reserved_spaces=RESERVED_CODE_SPACE
):
"""
:param charset_fpath: file path where the set of characters is available
:param config: list of tuples: (segment, number of code-points, (n,k), (coprimes), (cycles), dimension, sparcity)
:param ofname: Where to save the codebook
:param special_codes: special codes mapping for the output dictionary
:param nul_row_is_zero: if the first row (the NUL one) should be zeros or the given code
:param reserved_spaces: the reserved spaces at the beginning of the codebook, 32 is the default as is the number of
control codes in utf-8. This later is used for remapping reserved SPECIAL_CODES, IS 32
:return:
"""
# TODO this code is ugly but works wiht the right configuration, for the moment
# TODO make the configuration selection automatic from some config points and the charset
codes = create_codematrix_from_conf([config])[0]
if nul_row_is_zero:
# assume nul row is the first one
codes[0, :] = 0
# create dict
char2int = OrderedDict()
int2char = OrderedDict()
# add the number of reserved chars at the beginning
for i in range(reserved_spaces): # Warning, must be <128
# use utf-8 codepoints
c = str(bytes([i]), 'utf-8')
char2int[c] = i
# for the reverse mapping, to avoid issues on decoding, leave them unassigned UNASSIGNED='◁???▷'
# could use UNK but I'd rather have it be obviously different, leaving unassigned is an issue
int2char[i] = c # UNASSIGNED
# overwrite the indices of the reverse mapping for the special codes
for c, i, c_alt in special_codes:
# Take into account this will duplicate the char2int mapping having 2 chars and the alternative code
# mapping to the same int
char2int[c] = i
# char2int[c_alt] = i
# but the int reverse index will be overwritten
int2char[i] = c
for i, c in enumerate(list(charset)):
# forward the index
j = i + reserved_spaces
char2int[c] = j
int2char[j] = c
# pickle all together
codebook = (codes, char2int, int2char)
with open(ofname, 'wb') as f:
print("saving file {} with codes.shape {} | char2int {} | int2char {}".format(
ofname, codes.shape, len(char2int), len(int2char)))
pickle.dump(codebook, f, pickle.HIGHEST_PROTOCOL)
return codebook
##############################################################
# Last codes created that handle compositional codes.
# characters are
def create_base_codebook(charset, special_codes=SPECIAL_CODES, code_size=2145 + 33,
N=24, k=3,
subcode_list=(2, 5, 9, 11, 13), # subcode_list=(2,3,5,11,13),
# cycle_list=(2, 3), # (4,6,10,12), # WARNING< DO NOT USE < bug in the cycle code generator
nul_row_is_zero=True, reserved_spaces=RESERVED_CODE_SPACE
):
"""
:param charset:
:param special_codes:
:param code_size:
:param N:
:param k:
:param subcode_list: configuration for the prime configuration
:param special_codes: special codes mapping for the output dictionary
:param nul_row_is_zero: if the first row (the NUL one) should be zeros or the given code
:param reserved_spaces: the reserved spaces at the beginning of the codebook, 32 is the default as is the number of
control codes in utf-8. This later is used for remapping reserved SPECIAL_CODES, IS 32
:return:
"""
# TODO this code is ugly but works with the right configuration, for the moment
# TODO make the configuration selection automatic from some config points and the charset
codes = [
sparse_code_Nk(code_size, N, k),
generate_multihot_prime_code(code_size, subcode_list),
# create_single_cycle_code(code_size, cycle_list), # this code generator is only for redundancy
]
if nul_row_is_zero:
# assume nul row is the first one
for code in codes:
code[0, :] = 0
# create dict
char2int = OrderedDict()
int2char = OrderedDict()
# add the number of reserved chars at the beginning
for i in range(reserved_spaces): # Warning, must be <128
# use utf-8 codepoints
c = str(bytes([i]), 'utf-8')
char2int[c] = i
# for the reverse mapping, to avoid issues on decoding, leave them unassigned UNASSIGNED='◁???▷'
# could use UNK but I'd rather have it be obviously different, leaving unassigned is an issue
int2char[i] = c # UNASSIGNED
# overwrite the indices of the reverse mapping for the special codes
for c, i, c_alt in special_codes:
# Take into account this will duplicate the char2int mapping having 2 chars and the alternative code
# mapping to the same int
char2int[c] = i
# char2int[c_alt] = i
# but the int reverse index will be overwritten
int2char[i] = c
for i, c in enumerate(list(set(charset))):
# forward the index
j = i + reserved_spaces
char2int[c] = j
int2char[j] = c
# pickle all together
codebook = (codes, char2int, int2char)
# with open(ofname, 'wb') as f:
# print("saving file {} with codes.shape {} | char2int {} | int2char {}".format(
# ofname, codes.shape, len(char2int), len(int2char)))
# pickle.dump(codebook, f, pickle.HIGHEST_PROTOCOL)
return codebook
# from
# https://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
def get_code_item(c, codebook, padded_codebook, circ_padded_codebook, char2int):
"""
Converts a char sequence to a code dictionary for compositional code generation
The idea behind the scenes is to generate several codes from convolutional and sum of the characters.
The final code is decided by a post-processing step.
The codebook for the input should be able to encode ALL values given as input, in this idea there is no exception
handling and an exception is expected if a symbol is not present.
:param c:
:param codebook:
:param padded_codebook:
:param circ_padded_codebook:
:param char2int:
:return:
"""
# convert to lowercase for the symbol representation
#
c_len = len(c)
c = unicodedata.normalize('NFKD', c)
nc = c.lower()
ac = remove_accents(nc)
nc_vecs = [codebook[char2int[i]] for i in nc]
ac_vecs = [codebook[char2int[i]] for i in ac]
# padded version to be able to convolve later
nc_padded = [padded_codebook[char2int[i]] for i in nc]
ac_padded = [padded_codebook[char2int[i]] for i in ac]
nc_cpadded = [circ_padded_codebook[char2int[i]] for i in nc]
ac_cpadded = [circ_padded_codebook[char2int[i]] for i in ac]
# circular convolution -> keeps order of elements in token
nc_conv = nc_padded[0] if len(nc_padded) > 0 else codebook[0]
if len(nc_padded) > 1:
# print(nc_conv.shape)
for cpadded in nc_cpadded[1:]:
# print(c, padded.shape, nc_conv.shape)
olen = nc_conv.shape[0] # original vector length before
nc_conv = np.convolve(nc_conv, cpadded, mode='same')
#
nc_conv = nc_conv if nc_conv.shape[0] == olen else nc_conv[olen // 2:-olen // 2]
ac_conv = ac_padded[0] if len(ac_padded) > 0 else codebook[0]
if len(ac_conv) > 1:
for cpadded in ac_cpadded[1:]:
olen = ac_conv.shape[0] # original vector length before
ac_conv = np.convolve(ac_conv, cpadded, mode='same')
ac_conv = ac_conv if ac_conv.shape[0] == olen else ac_conv[olen // 2:-olen // 2]
# vector sum, keeps the values only but don't keep order
nc_sum = nc_vecs[0]
for v in nc_vecs[1:]:
nc_sum = np.add(nc_sum, v)
ac_sum = ac_vecs[0] if len(ac_vecs) > 0 else codebook[0]
if len(ac_vecs) > 1:
for v in ac_vecs[1:]:
ac_sum = np.add(ac_sum, v)
# case representation -> dim = 3
islower_case = c.islower()
isupper_case = c.isupper()
notcase = not (c.lower() or c.upper()) # only true if is not all upper or lower
# starts with uppercase or not -> dim = 2 10|01
istitle = c.istitle()
# if all elements are numeric (does not understand decimals) -> dim = 3
isnum = c.isnumeric() # takes into account other things like exponents, japanese and chinese numeric characters
isalnum = c.isalnum()
isalpha = c.isalpha()
# TODO implement is_float (check if floating point)
# TODO implement: beginning and of word, prefixes and suffixes
code_dict = {
'token': c, # Normalized NFKD token
'complete_conv': nc_conv,
'non_accent_conv': ac_conv,
'complete_sum': nc_sum, # bag of words
'non_accent_sum': ac_sum, # bag of words lowercase
'casing': [isupper_case, islower_case, notcase, istitle],
'alnum': [isnum, isalnum, isalpha],
'len': c_len, # length -> I can encode it with Fourier approximations, a few sine waves should suffice
}
return code_dict
# CHAR_FPATH = "/home/leo/projects/Datasets/text/wiki-unicode/selected_sources_small/selected_chars.chars"
CHAR_FPATH = "./charsets/selected_chars.chars"
def compositional_code_main(fpath=CHAR_FPATH, reserved_codespace=RESERVED_CODE_SPACE, size_factor=2):
"""
:param fpath: path to the char vocabulary
:param reserved_codespace: code spaces to NOT touch, reserved
:param size_factor: the size factor for the circular convolution composition
:return: dictionary of the codes
"""
# recover source of the chars to encode
with open(fpath, "r") as f:
chars = f.read()
# complete the symbols checking that there are upper and lowercase, ensure that they are encoded in
# the right normalization
all_chars = []
first_symbols = []
# print("chars len = ", len(chars))
# print("1 first_symbols len = ", len(first_symbols))
for c in chars:
# need to normalize the basic code to avoid later normalization mismatch with NFKD
cc = unicodedata.normalize('NFKC', c)
all_chars.append(cc.upper())
all_chars.append(cc.lower())
nc = unicodedata.normalize('NFKD', c)
for i in nc:
# be sure all cases are represented in the set
first_symbols.append(i.upper())
first_symbols.append(i.lower())
break
# print("1 all_chars len = ", len(all_chars))
all_chars = sorted(list(set(all_chars)))
# print("2 all_chars len = ", len(all_chars))
# print("2 first_symbols len = ", len(first_symbols))
# sort and take out a few symbols that I don't want and couldn't set in the filter of the original file
first_symbols = sorted(list(set(first_symbols).difference({'҈', '҉'})))
# print("3 first_symbols len = ", len(first_symbols))
all_base_chars = sorted(list(set(first_symbols + list(unicodedata.normalize('NFKD', ''.join(chars))))))
# print("all_base_chars len = ", len(all_base_chars))
# create the base codebook from which the composition will be created
codes, char2int, int2char = create_base_codebook(all_base_chars, code_size=len(all_base_chars) + reserved_codespace,
# N=24, k=3, subcode_list=(2, 5, 7, 11, 13)
N=22, k=3, subcode_list=(2, 5, 7, 11, 13)
)
# print("all_base_chars len = ", len(all_base_chars))
# create the base matrices for the compositions
codematrix = np.concatenate(codes, axis=1).astype('float16')
# padding for circular convolution
padded_codematrix = np.zeros((codematrix.shape[0], codematrix.shape[1] * size_factor)).astype('float16')
pad_dim = (padded_codematrix.shape[1] - codematrix.shape[1]) // 2
# pad_dim = codematrix.shape[1] // 2
padded_codematrix[:, pad_dim:-pad_dim] = codematrix
# circular padding to make circular convolution a reality with numpy.convolve
# is done here to do it only once and with matrix operations
circ_padded_codematrix = np.concatenate([padded_codematrix, padded_codematrix], axis=1)
# create now all the charcodes dictionaries from which all compositional codes will be derived
charcodes = [get_code_item(c, codematrix, padded_codematrix, circ_padded_codematrix, char2int) for c in all_chars]
# print("charcodes len = ", len(charcodes))
# charcodes now can be used as a database
return charcodes
def charcodes_dict2codebook(charcodes, fields=('complete_conv', 'non_accent_sum', 'casing', 'alnum'), dtype='int8'):
"""
Converts a list of charcode dicts to a codebook and assignation mapping dicts for the encoding to be used
:param charcodes: a list containing the charcodes with the format output of get_code_item function
:param fields: the fields to use for the final codebook charcode MUST be the among the following fields:
'complete_conv', 'non_accent_conv', 'complete_sum', 'non_accent_sum', 'casing', 'alnum', 'len'
:param dtype: datatype for the output codebook. Default int8 as we don't need more for small convolutions
:return: a tuple (codebook, symbol2int, int2symbol)
"""
charcodes = sorted(charcodes, key=lambda k: k['token'])
codes = []
symbol2int = OrderedDict()
int2symbol = OrderedDict()
for i in range(len(charcodes)):
c = charcodes[i]
symbol = c['token']
symbol2int[symbol] = i
int2symbol[i] = symbol
vecs = []
for f in fields:
vecs.append(np.array(c[f], dtype=dtype))
code = np.concatenate(vecs)
codes.append(code)
codes = np.stack(codes)
return codes, symbol2int, int2symbol
|
package com.javamaster.b2c.cloud.test.learn.java.java8.model;
/**
* Created on 2019/1/8.<br/>
*
* @author yudong
*/
public interface Resizable {
int getWidth();
int getHeight();
void setWidth(int width);
void setHeight(int height);
void setAbsoluteSize(int width, int height);
default void setRelativeSize(int wFactor, int hFactor) {
setAbsoluteSize(getWidth() / wFactor, getHeight() / hFactor);
}
}
|
import axios from "../../../utils/AxiosBase";
import getErrorMessage from "../../../utils/GetErrorMessage";
import { getUserSuccess } from "../../user/get/getUserActions";
import { resetAuthReducer } from "../authActions";
import {
signupUserFailure,
signupUserRequest,
signupUserSuccess,
} from "./signupActions";
const signupUser = (values: object) => {
return (dispatch: any) => {
dispatch(signupUserRequest());
axios
.post("/signup", values)
.then((res) => {
dispatch(signupUserSuccess(res.data));
dispatch(getUserSuccess(res.data));
setTimeout(() => dispatch(resetAuthReducer()), 1000);
})
.catch((err) => {
const errorMessage = getErrorMessage(err);
dispatch(signupUserFailure(errorMessage));
});
};
};
export default signupUser;
|
BLymphoproliferative disorders: A Proposed unified pathogenetic pathway The clinical features of lymphoproliferative diseases associated with paraproteinemia are briefly reviewed and correlated with current immunologic concepts in an effort to clarify the pathophysiology of Blymphocyte disorders. Blymphocyte maturation proceeds in a predictable manner from the PreB cell to the formation of idiotype specific plasma cells and memory Blymphocytes. The immunoglobulin isotype produced by the mature plasma cell is determined by a site specific process of gene switching which proceeds from to a production. Lymphoproliferative diseases are the result of disordered B cell maturation and their clinical features can be explained by identifying the locus of the maturational defect. |
The Mafia series hasn't been quite as massively popular as Grand Theft Auto - also under Take-Two Interactive's umbrella - but it's been rightly praised for creating interesting, era-appropriate worlds to tackle a bit of criminal activity within.
Given that, we're excited to hear more about Mafia III, which was just properly revealed yesterday at Gamescom. The two previous entries were set in the 1930s and 1940s, respectively, but this new Xbox One, PlayStation 4, and PC adventure shifts the action ahead to New Orleans in 1968.
It should be an intriguing setting for an open-world action affair, but Mafia III's appeal comes from more than just location. Moving past the tried-and-true Italian organized crime stories of the past, this entry features a returned Vietnam War veteran named Lincoln Clay who gets tangled up in the black mob. In fact, it's the Italian mob they're fighting against. |
/*====================================================================*
*
* void readitem (struct item * item, char const * string);
*
* encode a slave structure with infomation specified by a string
* specification has the following production:
*
* <spec> := <mac_addr>
* <spec> := <spec>,<vlan_id>
*
* basically, encode slave->MAC_ADDR then encode slave->VLANID[]
* with hexadecimal VLANID values; we allow 10 VLANID values but
* only 8 are legal;
*
* the idea is to read multiple input strings and call this function
* to initialize one or more slave structures; it is possible to fit
* up to 128 slave structures in one message frame;
*
*
*--------------------------------------------------------------------*/
static void readitem (struct item * item, char const * string)
{
register uint8_t * origin = (uint8_t *)(item->MAC_ADDR);
register uint8_t * offset = (uint8_t *)(item->MAC_ADDR);
size_t extent = sizeof (item->MAC_ADDR);
memset (item, 0, sizeof (* item));
while ((extent) && (*string))
{
unsigned radix = RADIX_HEX;
unsigned field = sizeof (uint8_t) + sizeof (uint8_t);
unsigned value = 0;
unsigned digit = 0;
if ((offset != origin) && (*string == HEX_EXTENDER))
{
string++;
}
while (field--)
{
if ((digit = todigit (*string)) < radix)
{
value *= radix;
value += digit;
string++;
continue;
}
error (1, EINVAL, "bad MAC address: ...[%s] (1)", string);
}
*offset = value;
offset++;
extent--;
}
if (extent)
{
error (1, EINVAL, "bad MAC address: ...[%s] (2)", string);
}
while (isspace (*string))
{
string++;
}
if ((*string) && (*string != ','))
{
error (1, EINVAL, "bad MAC address: ...[%s] (3)", string);
}
while (*string == ',')
{
unsigned radix = RADIX_DEC;
unsigned digit = 0;
unsigned value = 0;
do
{
string++;
}
while (isspace (*string));
while ((digit = todigit (*string)) < radix)
{
value *= radix;
value += digit;
string++;
}
while (isspace (*string))
{
string++;
}
if (item->NUM_VLANIDS < (sizeof (item->VLANID) / sizeof (uint16_t)))
{
item->VLANID [item->NUM_VLANIDS++] = value;
}
}
while (isspace (*string))
{
string++;
}
if (*string)
{
error (1, EINVAL, "bad VLAN ID: ...[%s]", string);
}
return;
} |
Demoicracy, Transnational Partisanship and the EU Advocates of demoicracy dismiss the proposal to transform the EU into a supranational democracy on the grounds that there is no pan-European demos. This article examines several arguments that have been advanced to that effect and, noting some problems left outstanding, goes on to suggest that demoicrats who endorse the no-demos thesis fail to consider the possibility that citizens themselves may seek to europeanize the identities of Europeans. If we take this possibility seriously, it not only follows that the no-demos thesis is not a knockdown objection to supranational democracy. We are also provided with an alternative normative vision for transforming the EU into a legitimate supranational democratic order, one that turns upon the transformative potential of citizens who associate across borders in pursuit of shared political goals. The article concludes by examining this vision under the heading of transnational partisanship. |
ASSESSMENT OF THE SEVERE OF THE PATIENTS CONDITION IS AN INTEGRAL COMPONENT OF THE TREATMENT PROCESS FOR PATIENTS WITH ABDOMINAL SEPSIS Abstract. To date, numerous studies continue to identify factors that significantly affect the outcome of treatment of intraperitoneal infections. The proposed work: to improve existing systems for assessing the severity of the patients condition by modification aimed at adapting to the capabilities of most domestic clinics. Material and methods. Based on the analysis of clinical and laboratory data obtained in 183 patients with acute peritonitis and abdominal sepsis, a scale for assessing the severity of patients was developed. Results. The developed scale of assessment of the severity of patients (OTSP) coincides with the most widespread system (Acute Physiology And Chronic Health Evaluation) II. Some changes and additions are related to the transfer of indicators to the international system of SI measurements, the use of regulatory data adopted in Ukraine, as well as the introduction of two new parameters. The scale system is based on numerical evaluation of clinical, physiological, laboratory and other parameters. The presence of clinical symptoms or deviations of physiological, biochemical parameters from the norm is determined by the number and values relating to one patient, added to the general scale. Conclusion. The proposed scale for assessing the severity of the patients condition is available and informative enough for use in patients with acute peritonitis and abdominal sepsis. |
The effects of dietary omega-3 and omega-6 fatty acids glucose tolerance and pancreatic insulin concentration in C57BL/KSJ db/db mice The effects of dietary omega-3 and omega-6 fatty acids glucose tolerance and pancreatic insulin concentration in C57BL/KSJ db/db mice Suraj, Rohini, "The effects of dietary omega-3 and omega-6 fatty acids glucose tolerance and pancreatic insulin concentration in C57BL/KSJ db/db mice". CUNY Academic Works. ACKNOWLEDGMENTS Special thanks to Dr. Ronald W. Schwizer for being my sponsor and for the use of his laboratory. His patience, encouragement and assistance was of immense help to me throughout this study. Thanks to the Baruch College Fund for providing necessary funds, and also to Dr. Norman Fainstein, Dean, School of Liberal Arts and Sciences, who provided the money to repair a vital piece of equipment necessary for this study. Thanks to Sean Pickering and Michael Dempsey for their assistance with laboratory work and animal care during this study. I would also like to thank Mr. Dalchand Rampaul, Senior College Laboratory Technician, for the use of his computer and office during the preparation of this paper. Fig. 1 Major metabolites of linoleic (omega-6) and linolenic (omega-3) fatty acids Fig. 2 Changes in body weight during 8 weeks of dietary supplementation and a) db/+ and b) db/db mice Fig. 3 Plasma glucose concentration during 8 weeks of dietary supplementation in a) db/+ and b) db/db mice Fig. 4 Pancreatic insulin concentration after 8 weeks of dietary supplementation in db/+ and db/db mice Fig. 5 The effects of 8 weeks of dietary supplementation on plasma glucose concentration during a 2-hour glucose tolerance test |
<reponame>nxgtw/confluent-kafka-go<filename>kafka/consumer.go<gh_stars>10-100
package kafka
/**
* Copyright 2016 Confluent Inc.
*
* 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.
*/
import (
"fmt"
"math"
"time"
"unsafe"
)
/*
#include <stdlib.h>
#include <librdkafka/rdkafka.h>
static rd_kafka_topic_partition_t *_c_rdkafka_topic_partition_list_entry(rd_kafka_topic_partition_list_t *rktparlist, int idx) {
return idx < rktparlist->cnt ? &rktparlist->elems[idx] : NULL;
}
*/
import "C"
// RebalanceCb provides a per-Subscribe*() rebalance event callback.
// The passed Event will be either AssignedPartitions or RevokedPartitions
type RebalanceCb func(*Consumer, Event) error
// Consumer implements a High-level Apache Kafka Consumer instance
type Consumer struct {
events chan Event
handle handle
eventsChanEnable bool
readerTermChan chan bool
rebalanceCb RebalanceCb
appReassigned bool
appRebalanceEnable bool // config setting
}
// Strings returns a human readable name for a Consumer instance
func (c *Consumer) String() string {
return c.handle.String()
}
// getHandle implements the Handle interface
func (c *Consumer) gethandle() *handle {
return &c.handle
}
// Subscribe to a single topic
// This replaces the current subscription
func (c *Consumer) Subscribe(topic string, rebalanceCb RebalanceCb) error {
return c.SubscribeTopics([]string{topic}, rebalanceCb)
}
// SubscribeTopics subscribes to the provided list of topics.
// This replaces the current subscription.
func (c *Consumer) SubscribeTopics(topics []string, rebalanceCb RebalanceCb) (err error) {
ctopics := C.rd_kafka_topic_partition_list_new(C.int(len(topics)))
defer C.rd_kafka_topic_partition_list_destroy(ctopics)
for _, topic := range topics {
ctopic := C.CString(topic)
defer C.free(unsafe.Pointer(ctopic))
C.rd_kafka_topic_partition_list_add(ctopics, ctopic, C.RD_KAFKA_PARTITION_UA)
}
e := C.rd_kafka_subscribe(c.handle.rk, ctopics)
if e != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(e)
}
c.rebalanceCb = rebalanceCb
c.handle.currAppRebalanceEnable = c.rebalanceCb != nil || c.appRebalanceEnable
return nil
}
// Unsubscribe from the current subscription, if any.
func (c *Consumer) Unsubscribe() (err error) {
C.rd_kafka_unsubscribe(c.handle.rk)
return nil
}
// Assign an atomic set of partitions to consume.
// This replaces the current assignment.
func (c *Consumer) Assign(partitions []TopicPartition) (err error) {
c.appReassigned = true
cparts := newCPartsFromTopicPartitions(partitions)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
e := C.rd_kafka_assign(c.handle.rk, cparts)
if e != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(e)
}
return nil
}
// Unassign the current set of partitions to consume.
func (c *Consumer) Unassign() (err error) {
c.appReassigned = true
e := C.rd_kafka_assign(c.handle.rk, nil)
if e != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(e)
}
return nil
}
// commit offsets for specified offsets.
// If offsets is nil the currently assigned partitions' offsets are committed.
// This is a blocking call, caller will need to wrap in go-routine to
// get async or throw-away behaviour.
func (c *Consumer) commit(offsets []TopicPartition) (committedOffsets []TopicPartition, err error) {
var rkqu *C.rd_kafka_queue_t
rkqu = C.rd_kafka_queue_new(c.handle.rk)
defer C.rd_kafka_queue_destroy(rkqu)
var coffsets *C.rd_kafka_topic_partition_list_t
if offsets != nil {
coffsets = newCPartsFromTopicPartitions(offsets)
defer C.rd_kafka_topic_partition_list_destroy(coffsets)
}
cErr := C.rd_kafka_commit_queue(c.handle.rk, coffsets, rkqu, nil, nil)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cErr)
}
rkev := C.rd_kafka_queue_poll(rkqu, C.int(-1))
if rkev == nil {
// shouldn't happen
return nil, newError(C.RD_KAFKA_RESP_ERR__DESTROY)
}
defer C.rd_kafka_event_destroy(rkev)
if C.rd_kafka_event_type(rkev) != C.RD_KAFKA_EVENT_OFFSET_COMMIT {
panic(fmt.Sprintf("Expected OFFSET_COMMIT, got %s",
C.GoString(C.rd_kafka_event_name(rkev))))
}
cErr = C.rd_kafka_event_error(rkev)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newErrorFromCString(cErr, C.rd_kafka_event_error_string(rkev))
}
cRetoffsets := C.rd_kafka_event_topic_partition_list(rkev)
if cRetoffsets == nil {
// no offsets, no error
return nil, nil
}
committedOffsets = newTopicPartitionsFromCparts(cRetoffsets)
return committedOffsets, nil
}
// Commit offsets for currently assigned partitions
// This is a blocking call.
// Returns the committed offsets on success.
func (c *Consumer) Commit() ([]TopicPartition, error) {
return c.commit(nil)
}
// CommitMessage commits offset based on the provided message.
// This is a blocking call.
// Returns the committed offsets on success.
func (c *Consumer) CommitMessage(m *Message) ([]TopicPartition, error) {
if m.TopicPartition.Error != nil {
return nil, Error{ErrInvalidArg, "Can't commit errored message"}
}
offsets := []TopicPartition{m.TopicPartition}
offsets[0].Offset++
return c.commit(offsets)
}
// CommitOffsets commits the provided list of offsets
// This is a blocking call.
// Returns the committed offsets on success.
func (c *Consumer) CommitOffsets(offsets []TopicPartition) ([]TopicPartition, error) {
return c.commit(offsets)
}
// StoreOffsets stores the provided list of offsets that will be committed
// to the offset store according to `auto.commit.interval.ms` or manual
// offset-less Commit().
//
// Returns the stored offsets on success. If at least one offset couldn't be stored,
// an error and a list of offsets is returned. Each offset can be checked for
// specific errors via its `.Error` member.
func (c *Consumer) StoreOffsets(offsets []TopicPartition) (storedOffsets []TopicPartition, err error) {
coffsets := newCPartsFromTopicPartitions(offsets)
defer C.rd_kafka_topic_partition_list_destroy(coffsets)
cErr := C.rd_kafka_offsets_store(c.handle.rk, coffsets)
// coffsets might be annotated with an error
storedOffsets = newTopicPartitionsFromCparts(coffsets)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return storedOffsets, newError(cErr)
}
return storedOffsets, nil
}
// Seek seeks the given topic partitions using the offset from the TopicPartition.
//
// If timeoutMs is not 0 the call will wait this long for the
// seek to be performed. If the timeout is reached the internal state
// will be unknown and this function returns ErrTimedOut.
// If timeoutMs is 0 it will initiate the seek but return
// immediately without any error reporting (e.g., async).
//
// Seek() may only be used for partitions already being consumed
// (through Assign() or implicitly through a self-rebalanced Subscribe()).
// To set the starting offset it is preferred to use Assign() and provide
// a starting offset for each partition.
//
// Returns an error on failure or nil otherwise.
func (c *Consumer) Seek(partition TopicPartition, timeoutMs int) error {
rkt := c.handle.getRkt(*partition.Topic)
cErr := C.rd_kafka_seek(rkt,
C.int32_t(partition.Partition),
C.int64_t(partition.Offset),
C.int(timeoutMs))
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(cErr)
}
return nil
}
// Poll the consumer for messages or events.
//
// Will block for at most timeoutMs milliseconds
//
// The following callbacks may be triggered:
// Subscribe()'s rebalanceCb
//
// Returns nil on timeout, else an Event
func (c *Consumer) Poll(timeoutMs int) (event Event) {
ev, _ := c.handle.eventPoll(nil, timeoutMs, 1, nil)
return ev
}
// Events returns the Events channel (if enabled)
func (c *Consumer) Events() chan Event {
return c.events
}
// ReadMessage polls the consumer for a message.
//
// This is a conveniance API that wraps Poll() and only returns
// messages or errors. All other event types are discarded.
//
// The call will block for at most `timeout` waiting for
// a new message or error. `timeout` may be set to -1 for
// indefinite wait.
//
// Timeout is returned as (nil, err) where err is `kafka.(Error).Code == Kafka.ErrTimedOut`.
//
// Messages are returned as (msg, nil),
// while general errors are returned as (nil, err),
// and partition-specific errors are returned as (msg, err) where
// msg.TopicPartition provides partition-specific information (such as topic, partition and offset).
//
// All other event types, such as PartitionEOF, AssignedPartitions, etc, are silently discarded.
//
func (c *Consumer) ReadMessage(timeout time.Duration) (*Message, error) {
var absTimeout time.Time
var timeoutMs int
if timeout > 0 {
absTimeout = time.Now().Add(timeout)
timeoutMs = (int)(timeout.Seconds() * 1000.0)
} else {
timeoutMs = (int)(timeout)
}
for {
ev := c.Poll(timeoutMs)
switch e := ev.(type) {
case *Message:
if e.TopicPartition.Error != nil {
return e, e.TopicPartition.Error
}
return e, nil
case Error:
return nil, e
default:
// Ignore other event types
}
if timeout > 0 {
// Calculate remaining time
timeoutMs = int(math.Max(0.0, absTimeout.Sub(time.Now()).Seconds()*1000.0))
}
if timeoutMs == 0 && ev == nil {
return nil, newError(C.RD_KAFKA_RESP_ERR__TIMED_OUT)
}
}
}
// Close Consumer instance.
// The object is no longer usable after this call.
func (c *Consumer) Close() (err error) {
if c.eventsChanEnable {
// Wait for consumerReader() to terminate (by closing readerTermChan)
close(c.readerTermChan)
c.handle.waitTerminated(1)
close(c.events)
}
C.rd_kafka_queue_destroy(c.handle.rkq)
c.handle.rkq = nil
e := C.rd_kafka_consumer_close(c.handle.rk)
if e != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(e)
}
c.handle.cleanup()
C.rd_kafka_destroy(c.handle.rk)
return nil
}
// NewConsumer creates a new high-level Consumer instance.
//
// Supported special configuration properties:
// go.application.rebalance.enable (bool, false) - Forward rebalancing responsibility to application via the Events() channel.
// If set to true the app must handle the AssignedPartitions and
// RevokedPartitions events and call Assign() and Unassign()
// respectively.
// go.events.channel.enable (bool, false) - Enable the Events() channel. Messages and events will be pushed on the Events() channel and the Poll() interface will be disabled. (Experimental)
// go.events.channel.size (int, 1000) - Events() channel size
//
// WARNING: Due to the buffering nature of channels (and queues in general) the
// use of the events channel risks receiving outdated events and
// messages. Minimizing go.events.channel.size reduces the risk
// and number of outdated events and messages but does not eliminate
// the factor completely. With a channel size of 1 at most one
// event or message may be outdated.
func NewConsumer(conf *ConfigMap) (*Consumer, error) {
err := versionCheck()
if err != nil {
return nil, err
}
// before we do anything with the configuration, create a copy such that
// the original is not mutated.
confCopy := conf.clone()
groupid, _ := confCopy.get("group.id", nil)
if groupid == nil {
// without a group.id the underlying cgrp subsystem in librdkafka wont get started
// and without it there is no way to consume assigned partitions.
// So for now require the group.id, this might change in the future.
return nil, newErrorFromString(ErrInvalidArg, "Required property group.id not set")
}
c := &Consumer{}
v, err := confCopy.extract("go.application.rebalance.enable", false)
if err != nil {
return nil, err
}
c.appRebalanceEnable = v.(bool)
v, err = confCopy.extract("go.events.channel.enable", false)
if err != nil {
return nil, err
}
c.eventsChanEnable = v.(bool)
v, err = confCopy.extract("go.events.channel.size", 1000)
if err != nil {
return nil, err
}
eventsChanSize := v.(int)
cConf, err := confCopy.convert()
if err != nil {
return nil, err
}
cErrstr := (*C.char)(C.malloc(C.size_t(256)))
defer C.free(unsafe.Pointer(cErrstr))
C.rd_kafka_conf_set_events(cConf, C.RD_KAFKA_EVENT_REBALANCE|C.RD_KAFKA_EVENT_OFFSET_COMMIT|C.RD_KAFKA_EVENT_STATS|C.RD_KAFKA_EVENT_ERROR)
c.handle.rk = C.rd_kafka_new(C.RD_KAFKA_CONSUMER, cConf, cErrstr, 256)
if c.handle.rk == nil {
return nil, newErrorFromCString(C.RD_KAFKA_RESP_ERR__INVALID_ARG, cErrstr)
}
C.rd_kafka_poll_set_consumer(c.handle.rk)
c.handle.c = c
c.handle.setup()
c.handle.rkq = C.rd_kafka_queue_get_consumer(c.handle.rk)
if c.handle.rkq == nil {
// no cgrp (no group.id configured), revert to main queue.
c.handle.rkq = C.rd_kafka_queue_get_main(c.handle.rk)
}
if c.eventsChanEnable {
c.events = make(chan Event, eventsChanSize)
c.readerTermChan = make(chan bool)
/* Start rdkafka consumer queue reader -> events writer goroutine */
go consumerReader(c, c.readerTermChan)
}
return c, nil
}
// rebalance calls the application's rebalance callback, if any.
// Returns true if the underlying assignment was updated, else false.
func (c *Consumer) rebalance(ev Event) bool {
c.appReassigned = false
if c.rebalanceCb != nil {
c.rebalanceCb(c, ev)
}
return c.appReassigned
}
// consumerReader reads messages and events from the librdkafka consumer queue
// and posts them on the consumer channel.
// Runs until termChan closes
func consumerReader(c *Consumer, termChan chan bool) {
out:
for true {
select {
case _ = <-termChan:
break out
default:
_, term := c.handle.eventPoll(c.events, 100, 1000, termChan)
if term {
break out
}
}
}
c.handle.terminatedChan <- "consumerReader"
return
}
// GetMetadata queries broker for cluster and topic metadata.
// If topic is non-nil only information about that topic is returned, else if
// allTopics is false only information about locally used topics is returned,
// else information about all topics is returned.
// GetMetadata is equivalent to listTopics, describeTopics and describeCluster in the Java API.
func (c *Consumer) GetMetadata(topic *string, allTopics bool, timeoutMs int) (*Metadata, error) {
return getMetadata(c, topic, allTopics, timeoutMs)
}
// QueryWatermarkOffsets returns the broker's low and high offsets for the given topic
// and partition.
func (c *Consumer) QueryWatermarkOffsets(topic string, partition int32, timeoutMs int) (low, high int64, err error) {
return queryWatermarkOffsets(c, topic, partition, timeoutMs)
}
// OffsetsForTimes looks up offsets by timestamp for the given partitions.
//
// The returned offset for each partition is the earliest offset whose
// timestamp is greater than or equal to the given timestamp in the
// corresponding partition.
//
// The timestamps to query are represented as `.Offset` in the `times`
// argument and the looked up offsets are represented as `.Offset` in the returned
// `offsets` list.
//
// The function will block for at most timeoutMs milliseconds.
//
// Duplicate Topic+Partitions are not supported.
// Per-partition errors may be returned in the `.Error` field.
func (c *Consumer) OffsetsForTimes(times []TopicPartition, timeoutMs int) (offsets []TopicPartition, err error) {
return offsetsForTimes(c, times, timeoutMs)
}
// Subscription returns the current subscription as set by Subscribe()
func (c *Consumer) Subscription() (topics []string, err error) {
var cTopics *C.rd_kafka_topic_partition_list_t
cErr := C.rd_kafka_subscription(c.handle.rk, &cTopics)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cErr)
}
defer C.rd_kafka_topic_partition_list_destroy(cTopics)
topicCnt := int(cTopics.cnt)
topics = make([]string, topicCnt)
for i := 0; i < topicCnt; i++ {
crktpar := C._c_rdkafka_topic_partition_list_entry(cTopics,
C.int(i))
topics[i] = C.GoString(crktpar.topic)
}
return topics, nil
}
// Assignment returns the current partition assignments
func (c *Consumer) Assignment() (partitions []TopicPartition, err error) {
var cParts *C.rd_kafka_topic_partition_list_t
cErr := C.rd_kafka_assignment(c.handle.rk, &cParts)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cErr)
}
defer C.rd_kafka_topic_partition_list_destroy(cParts)
partitions = newTopicPartitionsFromCparts(cParts)
return partitions, nil
}
// Committed retrieves committed offsets for the given set of partitions
func (c *Consumer) Committed(partitions []TopicPartition, timeoutMs int) (offsets []TopicPartition, err error) {
cparts := newCPartsFromTopicPartitions(partitions)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_committed(c.handle.rk, cparts, C.int(timeoutMs))
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cerr)
}
return newTopicPartitionsFromCparts(cparts), nil
}
// Pause consumption for the provided list of partitions
//
// Note that messages already enqueued on the consumer's Event channel
// (if `go.events.channel.enable` has been set) will NOT be purged by
// this call, set `go.events.channel.size` accordingly.
func (c *Consumer) Pause(partitions []TopicPartition) (err error) {
cparts := newCPartsFromTopicPartitions(partitions)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_pause_partitions(c.handle.rk, cparts)
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(cerr)
}
return nil
}
// Resume consumption for the provided list of partitions
func (c *Consumer) Resume(partitions []TopicPartition) (err error) {
cparts := newCPartsFromTopicPartitions(partitions)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_resume_partitions(c.handle.rk, cparts)
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return newError(cerr)
}
return nil
}
|
// Fix for JDK-4802633 on Java 6 and Apache Harmony-based Android
@Override
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index, size());
throw uoe();
} |
import React from 'react'
import styled from 'styled-components'
import { useTranslation } from 'react-i18next'
import { useStaticQuery, graphql } from 'gatsby'
import Img, { FluidObject } from 'gatsby-image'
import { Container } from 'components/Container'
import { backgroundColors, colors } from 'styles/colors'
import { displayWidth } from 'styles/width'
import { mobileAfterBorder } from 'styles/mobileAfterBorder'
import { Title } from 'components/TitleComponent'
import { getDataByLanguage } from 'utils/getDataByLanguage'
import { LocalizedLinkAnchor } from 'i18n/LocalizedLink'
import { Button } from 'components/Button'
import { JumpingArrow } from 'components/JumpingArrow'
import { indent } from 'styles/indent'
import { sendEvent } from 'tracking'
import { imagesDataProp } from 'pages/promo'
import { getImageByImageName } from 'utils/getImageByImageName'
const Visualization3dWrapper = styled.div`
display: flex;
justify-content: center;
width: 100%;
background-color: ${backgroundColors.project};
position: relative;
border-bottom: 1px solid ${colors.dark};
${mobileAfterBorder}
`
const SubTitle = styled.h3`
font-weight: normal;
font-size: 16px;
line-height: 26px;
text-align: center;
letter-spacing: 0.4px;
color: ${colors.dark};
margin: 20px ${indent.heroColumnDesktop};
@media (min-width: ${displayWidth.tablet}) {
margin: 0 ${indent.heroColumnTablet} 48px;
text-align: left;
}
@media (min-width: ${displayWidth.desktop}) {
margin: 0 ${indent.heroColumnDesktop} 48px;
}
`
const HeroColumn = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
padding-bottom: 32px;
align-items: center;
border-bottom: 1px solid ${colors.dark};
@media (min-width: ${displayWidth.tablet}) {
border-bottom: none;
padding: 0 0 32px;
border-right: 1px solid ${colors.dark};
}
`
const ImgStyled = styled(Img)<{ fluid: FluidObject }>`
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 0 16px;
align-self: center;
@media (min-width: ${displayWidth.tablet}) {
max-width: calc((100vw - 160px) * 0.6666);
padding: 0;
}
@media (min-width: ${displayWidth.desktop}) {
width: 793px;
}
`
const ImgWrapper = styled.div`
padding: 0 16px;
@media (min-width: ${displayWidth.tablet}) {
padding: 0;
}
`
const LocalizedLinkStyled = styled(LocalizedLinkAnchor)`
text-decoration: none;
`
const ButtonStyled = styled(Button)`
width: 264px;
margin: 0 auto 50px;
z-index: 3;
@media (max-width: 330px) {
width: 250px;
}
@media (min-width: ${displayWidth.tablet}) {
width: 220px;
}
@media (min-width: ${displayWidth.desktop}) {
width: 264px;
}
`
export const Project3D = ({ imagesData }: { imagesData: imagesDataProp }) => {
const { i18n } = useTranslation()
const data = useStaticQuery(graphql`
query {
allProject3DYaml {
edges {
node {
title
subTitle
buttonText
parent {
... on File {
name
}
}
}
}
}
}
`)
const project3DYaml = getDataByLanguage(
data.allProject3DYaml,
i18n.language
)
const image = getImageByImageName(
imagesData.allImageSharp,
'picture3D.webp'
)
const { title, subTitle, buttonText } = project3DYaml
return (
<Visualization3dWrapper>
<Container columns={'1fr'} tabletColumns={'1fr 2fr'}>
<HeroColumn>
<Title>{title}</Title>
<SubTitle>{subTitle}</SubTitle>
<LocalizedLinkStyled
to={'/promo/#project3dAdvantages'}
onClick={() => {
sendEvent('Click', {
eventCategory: 'ShowMoreButton',
placement: 'Project3D',
target: 'Advantages3D',
})
}}
>
<ButtonStyled>{buttonText}</ButtonStyled>
</LocalizedLinkStyled>
<JumpingArrow />
</HeroColumn>
<ImgWrapper>
<ImgStyled fluid={image.fluid} loading="eager" />
</ImgWrapper>
</Container>
</Visualization3dWrapper>
)
}
|
Publishing and consuming GLUE v2.0 resource information in XSEDE XSEDE users, science gateways, and services need a variety of accurate information about XSEDE resources so that they can use those resources effectively. They need information to decide which resources to use, to track their usage of resources, and to provide services to their users. To support this, XSEDE is deploying a new system to gather and publish static and dynamic resource information. This paper gives an overview of the resource information available with this new system, describes the design and performance of the software and services that make up this system, and finally provides examples of how to use this new resource information. |
<filename>src/lib.rs
//! This contains thin wrappers around `memfd_create` and the associated file sealing API.
//!
//! The [`MemFile`] struct represents a file created by the `memfd_create` syscall.
//! Such files are memory backed and fully anonymous, meaning no other process can see them (well... except by looking in `/proc` on Linux).
//!
//! After creation, the file descriptors can be shared with child processes, or even sent to another process over a Unix socket.
//! The files can then be memory mapped to be used as shared memory.
//!
//! This is all quite similar to `shm_open`, except that files created by `shm_open` are not anoynmous.
//! Depending on your application, the anonymous nature of `memfd` may be a nice property.
//! Additionally, files created by `shm_open` do not support file sealing.
//!
//! # File sealing
//! You can enable file sealing for [`MemFile`] by creating them with [`CreateOptions::allow_sealing(true)`][CreateOptions::allow_sealing].
//! This allows you to use [`MemFile::add_seals`] to add seals to the file.
//! You can also get the list of seals with [`MemFile::get_seals`].
//!
//! Once a seal is added to a file, it can not be removed.
//! Each seal prevents certain types of actions on the file.
//! For example: the [`Seal::Write`] seal prevents writing to the file, both through syscalls and memory mappings,
//! and the [`Seal::Shrink`] and [`Seal::Grow`] seals prevent the file from being resized.
//!
//! This is quite interesting for Rust, as it is the only guaranteed safe way to map memory:
//! when a file is sealed with [`Seal::Write`] and [`Seal::Shrink`], the file contents can not change, and the file can not be shrinked.
//! The latter is also important, because trying to read from a memory mapping a of file that was shrinked too far will raise a `SIGBUS` signal
//! and likely crash your application.
//!
//! Another interesting option is to first create a shared, writable memory mapping for your [`MemFile`],
//! and then add the [`Seal::FutureWrite`] and [`Seal::Shrink`] seals.
//! In that case, only the existing memory mapping can be used to change the contents of the file, even after the seals have been added.
//! When sharing the file with other processes, it prevents those processes from shrinking or writing to the file,
//! while the original process can still change the file contents.
//!
//! # Example
//! ```
//! # fn main() -> std::io::Result<()> {
//! use memfile::{MemFile, CreateOptions, Seal};
//! use std::io::Write;
//!
//! let mut file = MemFile::create("foo", CreateOptions::new().allow_sealing(true))?;
//! file.write_all(b"Hello world!")?;
//! file.add_seals(Seal::Write | Seal::Shrink | Seal::Grow)?;
//! // From now on, all writes or attempts to created shared, writable memory mappings will fail.
//! # Ok(())
//! # }
//! ```
use std::ffi::CStr;
use std::fs::File;
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
mod sys;
mod seal;
pub use seal::{Seal, Seals};
/// A memory backed file that can have seals applied to it.
///
/// The struct implements [`AsRawFd`], [`IntoRawFd`] and [`FromRawFd`].
/// When using [`FromRawFd::from_raw_fd`], you must ensure that the file descriptor is a valid `memfd`.
#[derive(Debug)]
pub struct MemFile {
file: File,
}
impl MemFile {
/// Create a new [`MemFile`] with the given options.
///
/// The `name` argument is purely for debugging purposes.
/// On Linux it shows up in `/proc`, but it serves no other purpose.
/// In particular, multiple files can be created with the same name.
///
/// The close-on-exec flag is set on the created file descriptor.
/// If you want to pass it to a child process, you should use [`libc::dup2`] or something similar *after forking*.
/// Disabling the close-on-exec flag before forking causes a race condition with other threads.
pub fn create(name: &str, options: CreateOptions) -> std::io::Result<Self> {
let file = sys::memfd_create(name, options.as_flags())?;
Ok(Self { file })
}
/// Create a new [`MemFile`] with the given options.
///
/// This is identical to [`Self::create`], except that it takes the name as [`CStr`] to avoid allocations.
/// See that function for more information.
pub fn create_cstr(name: &CStr, options: CreateOptions) -> std::io::Result<Self> {
let file = sys::memfd_create_cstr(name, options.as_flags())?;
Ok(Self { file })
}
/// Create a new [`MemFile`] with default options.
///
/// Sealing is not enabled for the created file.
///
/// See [`Self::create`] for more information.
pub fn create_default(name: &str) -> std::io::Result<Self> {
Self::create(name, CreateOptions::default())
}
/// Create a new [`MemFile`] with file sealing enabled.
///
/// Sealing is enabled for the created file.
/// All other options are the same as the defaults.
///
/// See [`Self::create`] for more information.
pub fn create_sealable(name: &str) -> std::io::Result<Self> {
Self::create(name, CreateOptions::new().allow_sealing(true))
}
/// Create a new [`MemFile`] that shares the same underlying file handle.
///
/// The clones [`MemFile`] has a new file descriptor,
/// but reads, writes, and seeks will affect both [`MemFile`] instances simultaneously.
pub fn try_clone(&self) -> std::io::Result<Self> {
let file = self.file.try_clone()?;
Ok(Self { file })
}
/// Wrap an already-open file as [`MemFile`].
///
/// This function returns an error if the file was not created by `memfd_create`.
///
/// If the function succeeds, the passed in file object is consumed and the returned [`MemFile`] takes ownership of the file descriptor.
/// If the function fails, the original file object is included in the returned error.
pub fn from_file<T: AsRawFd + IntoRawFd>(file: T) -> Result<Self, FromFdError<T>> {
match sys::memfd_get_seals(file.as_raw_fd()) {
Ok(_) => {
let file = unsafe { File::from_raw_fd(file.into_raw_fd()) };
Ok(Self { file })
},
Err(error) => Err(FromFdError { error, file }),
}
}
/// Convert this [`MemFile`] into an [`std::fs::File`].
///
/// This may be useful for interoperability with other crates.
pub fn into_file(self) -> std::fs::File {
self.file
}
/// Query metadata about the underlying file.
///
/// Note that not all information in the metadata is not very meaningfull for a `memfd`.
/// The file type is particularly useless since it is always the same.
/// Some information, like the file size, may be useful.
pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
self.file.metadata()
}
/// Truncate or extend the underlying file, updating the size of this file to become size.
///
/// If the size is less than the current file's size, then the file will be shrunk.
/// If it is greater than the current file's size, then the file will be extended to size and have all of the intermediate data filled in with 0s.
/// The file's cursor isn't changed.
/// In particular, if the cursor was at the end and the file is shrunk using this operation, the cursor will now be past the end.
pub fn set_len(&self, size: u64) -> std::io::Result<()> {
self.file.set_len(size)
}
/// Get the active seals of the file.
pub fn get_seals(&self) -> std::io::Result<Seals> {
let seals = sys::memfd_get_seals(self.as_raw_fd())?;
Ok(Seals::from_bits_truncate(seals as u32))
}
/// Add a single seal to the file.
///
/// If you want to add multiple seals, you should prefer [`Self::add_seals`] to reduce the number of syscalls.
///
/// This function will fail if the file was not created with sealing support,
/// if the file has already been sealed with [`Seal::Seal`],
/// or if you try to add [`Seal::Write`] while a shared, writable memory mapping exists for the file.
///
/// Adding a seal that is already active is a no-op.
pub fn add_seal(&self, seal: Seal) -> std::io::Result<()> {
self.add_seals(seal.into())
}
/// Add multiple seals to the file.
///
/// This function will fail if the file was not created with sealing support,
/// if the file has already been sealed with [`Seal::Seal`],
/// or if you try to add [`Seal::Write`] while a shared, writable memory mapping exists for the file.
///
/// Adding seals that are already active is a no-op.
pub fn add_seals(&self, seals: Seals) -> std::io::Result<()> {
sys::memfd_add_seals(self.as_raw_fd(), seals.bits() as std::os::raw::c_int)
}
}
impl FromRawFd for MemFile {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
let file = File::from_raw_fd(fd);
Self { file }
}
}
impl AsRawFd for MemFile {
fn as_raw_fd(&self) -> RawFd {
self.file.as_raw_fd()
}
}
impl IntoRawFd for MemFile {
fn into_raw_fd(self) -> RawFd {
self.file.into_raw_fd()
}
}
impl std::os::unix::fs::FileExt for MemFile {
fn read_at(&self, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
self.file.read_at(buf, offset)
}
fn write_at(&self, buf: &[u8], offset: u64) -> std::io::Result<usize> {
self.file.write_at(buf, offset)
}
}
impl std::io::Write for MemFile {
fn flush(&mut self) -> std::io::Result<()> {
self.file.flush()
}
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.file.write(buf)
}
}
impl std::io::Read for MemFile {
fn read(&mut self, buf: &mut[u8]) -> std::io::Result<usize> {
self.file.read(buf)
}
}
impl std::io::Seek for MemFile {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.file.seek(pos)
}
}
impl From<MemFile> for std::process::Stdio {
fn from(other: MemFile) -> Self {
other.file.into()
}
}
/// Options for creating a [`MemFile`].
///
/// Support for options depend on platform and OS details.
/// Refer to your OS documentation for `memfd_create` for more information.
#[derive(Copy, Clone, Debug, Default)]
pub struct CreateOptions {
allow_sealing: bool,
huge_table: Option<HugeTlb>,
}
impl CreateOptions {
/// Get the default creation options for a [`MemFile`].
///
/// Initially, file sealing is not enabled no no huge TLB page size is configured.
///
/// Note that the close-on-exec flag will always be set on the created file descriptor.
/// If you want to pass it to a child process, you should use [`libc::dup2`] or something similar *after forking*.
/// Disabling the close-on-exec flag before forking causes a race condition with other threads.
pub fn new() -> Self {
Self::default()
}
/// Create a new [`MemFile`]` with the current options.
///
/// This is a shorthand for [`MemFile::create`].
/// See that function for more details.
pub fn create(&self, name: &str) -> std::io::Result<MemFile> {
MemFile::create(name, *self)
}
/// Create a new [`MemFile`]` with the current options.
///
/// This is identical to [`Self::create`], except that it takes the name as [`CStr`] to avoid allocations.
/// See [`MemFile::create`] for more details.
pub fn create_cstr(&self, name: &CStr) -> std::io::Result<MemFile> {
MemFile::create_cstr(name, *self)
}
/// Allow sealing operations on the created [`MemFile`].
pub fn allow_sealing(mut self, value: bool) -> Self {
self.allow_sealing = value;
self
}
/// Create the file in a `hugetlbfs` filesystem using huge pages for the translation look-aside buffer.
///
/// Support for this feature and specific sizes depend on the CPU and kernel configuration.
/// See also: <https://www.kernel.org/doc/html/latest/admin-guide/mm/hugetlbpage.html>
pub fn huge_tlb(mut self, value: impl Into<Option<HugeTlb>>) -> Self {
self.huge_table = value.into();
self
}
/// Get the options as raw flags for `libc::memfd_create`.
fn as_flags(&self) -> std::os::raw::c_int {
let mut flags = sys::flags::MFD_CLOEXEC;
if self.allow_sealing {
flags |= sys::flags::MFD_ALLOW_SEALING;
}
#[cfg(target_os = "linux")]
if let Some(size) = self.huge_table {
flags |= sys::flags::MFD_HUGETLB | size as u32 as std::os::raw::c_int;
}
flags
}
}
/// Page size for the translation look-aside buffer.
///
/// Support for specific sizes depends on the CPU and kernel configuration.
/// See also: <https://www.kernel.org/doc/html/latest/admin-guide/mm/hugetlbpage.html>
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(u32)]
#[non_exhaustive]
pub enum HugeTlb {
Huge64KB = sys::flags::MFD_HUGE_64KB as u32,
Huge512KB = sys::flags::MFD_HUGE_512KB as u32,
Huge1MB = sys::flags::MFD_HUGE_1MB as u32,
Huge2MB = sys::flags::MFD_HUGE_2MB as u32,
Huge8MB = sys::flags::MFD_HUGE_8MB as u32,
Huge16MB = sys::flags::MFD_HUGE_16MB as u32,
Huge32MB = sys::flags::MFD_HUGE_32MB as u32,
Huge256MB = sys::flags::MFD_HUGE_256MB as u32,
Huge512MB = sys::flags::MFD_HUGE_512MB as u32,
Huge1GB = sys::flags::MFD_HUGE_1GB as u32,
Huge2GB = sys::flags::MFD_HUGE_2GB as u32,
Huge16GB = sys::flags::MFD_HUGE_16GB as u32,
}
/// Error returned when the file passed to [`MemFile::from_file`] is not a `memfd`.
///
/// This struct contains the [`std::io::Error`] that occurred and the original value passed to `from_file`.
/// It is also directly convertible to [`std::io::Error`], so you can pass it up using the `?` operator
/// from a function that returns an [`std::io::Result`].
pub struct FromFdError<T> {
error: std::io::Error,
file: T,
}
impl<T> FromFdError<T> {
/// Get a reference to the I/O error.
pub fn error(&self) -> &std::io::Error {
&self.error
}
/// Get a reference to the original file object.
pub fn file(&self) -> &T {
&self.file
}
/// Consume the struct and return the I/O error and the original file object as tuple.
pub fn into_parts(self) -> (std::io::Error, T) {
(self.error, self.file)
}
/// Consume the struct and return the I/O error.
pub fn into_error(self) -> std::io::Error {
self.error
}
/// Consume the struct and return the original file object.
pub fn into_file(self) -> T {
self.file
}
}
impl<T> From<FromFdError<T>> for std::io::Error {
fn from(other: FromFdError<T>) -> Self {
other.into_error()
}
}
|
DropoutNet: Addressing Cold Start in Recommender Systems Latent models have become the default choice for recommender systems due to their performance and scalability. However, research in this area has primarily focused on modeling user-item interactions, and few latent models have been developed for cold start. Deep learning has recently achieved remarkable success showing excellent results for diverse input types. Inspired by these results we propose a neural network based latent model called DropoutNet to address the cold start problem in recommender systems. Unlike existing approaches that incorporate additional content-based objective terms, we instead focus on the optimization and show that neural network models can be explicitly trained for cold start through dropout. Our model can be applied on top of any existing latent model effectively providing cold start capabilities, and full power of deep architectures. Empirically we demonstrate state-of-the-art accuracy on publicly available benchmarks. Code is available at https://github.com/layer6ai-labs/DropoutNet. |
CanadianIrish dermatological meeting perforated by the smaller cutaneous vessels or through fascial splits. The usual differential diagnosis is varicosities. A young woman aged 20 years presented with the condition. She worked as a canteen worker (standing all day). She gave a 14-month history of lower leg discomfort particularly towards the end ofthe day. Discomfort was associated with the appearance of two lumps over the antero-lateral aspect of both lower legs. On examination, although nothing abnormal was visible on standing, when she sat with her knees crossed two almost symmetrical soft swellings were palpable over each lower leg anterolaterally (Fig. i). The lower herniation was situated about 15 cm above the lateral malleolus on the left and 13 cm above the lateral malleolus on the right. The upper herniation was both higher and more medially situated than the lower one on each leg and the distance between them was about 4 cm greater on the right than on the left leg. Elastic support stockings were recommended. This condition, in which single or multiple unilateral or bilateral herniae may occur, has been welldescribed (Ihde, 1929; Kitchin & Richmond, 1943; Obermayer & Wilson, 1951) but may be unfamiliar to many dermatologists. |
package com.self.blocking.queue;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* ReentrantLock操作是先调用lock(),操作完成后调用unlock()
* Condition ReentrantLock.newCondition() 调用await(),调用singalAll()唤醒
* @author Administrator
*
*/
public class MyQueue {
private LinkedList<String> linkedList = new LinkedList<String>();
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private int max = 5;
public String add(String str) throws InterruptedException {
lock.lock();
while (linkedList.size() == max) {
condition.await();
}
linkedList.add(str);
condition.signalAll();
lock.unlock();
return str;
}
public String removeFirst() throws InterruptedException {
lock.lock();
while (linkedList.size() == 0) {
condition.await();
}
String removeFirst = linkedList.removeFirst();
condition.signalAll();
lock.unlock();
return removeFirst;
}
public int getSize() {
lock.lock();
int size = linkedList.size();
lock.unlock();
return size;
}
} |
<gh_stars>0
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FacilityType } from 'src/models/facility-types/entities/facility-type.entity';
import { Repository } from 'typeorm';
import * as facilityTypes from './facility-type.data.json';
@Injectable()
export class FacilityTypeSeederService {
constructor(
@InjectRepository(FacilityType)
private readonly facilityTypeRepository: Repository<FacilityType>,
) {}
async create(): Promise<Promise<FacilityType>[]> {
try {
return facilityTypes.map(async (facilityType) => {
const newFacilityType = this.facilityTypeRepository.create({
name: facilityType.name,
});
return await this.facilityTypeRepository.save(newFacilityType);
});
} catch (error) {
console.log(error);
}
}
}
|
// createOSID creates the osID, as used in the `--os` flag of the CLI tools. An empty string is
// return when unable to determine the osID.
func (c *osVersionCheck) createOSID(originalMajor string, originalMinor string, r *report) string {
major, minor := originalMajor, originalMinor
switch c.osInfo.ShortName {
case "":
r.Info("Unable to determine OS.")
return ""
case osinfo.Linux:
r.Info("Detected generic Linux system.")
return ""
case osinfo.Windows:
r.Info("Detected Windows system.")
windowsMajor, windowsMinor, err :=
distro.WindowsServerVersionforNTVersion(originalMajor, originalMinor)
if err == nil {
major, minor = windowsMajor, windowsMinor
}
}
release, err := distro.FromComponents(c.osInfo.ShortName, major, minor, c.osInfo.Architecture)
if err != nil {
r.Info(err.Error())
return ""
}
osID := release.AsGcloudArg()
if osID != "" {
return osID
}
if c.osInfo.ShortName != osinfo.Linux && c.osInfo.ShortName != "" && c.osInfo.Version != "" {
return fmt.Sprintf("%s-%s", c.osInfo.ShortName, c.osInfo.Version)
}
return ""
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@class NSString;
@protocol NXEngineJSAPIHandler;
@interface PLDEngineConfig : NSObject
{
NSString *_jsfmSource;
NSString *_jsfmVersion;
NSString *_jsfmPath;
id <NXEngineJSAPIHandler> _jsAPIHandler;
}
@property(retain, nonatomic) id <NXEngineJSAPIHandler> jsAPIHandler; // @synthesize jsAPIHandler=_jsAPIHandler;
@property(copy, nonatomic) NSString *jsfmPath; // @synthesize jsfmPath=_jsfmPath;
@property(copy, nonatomic) NSString *jsfmVersion; // @synthesize jsfmVersion=_jsfmVersion;
@property(copy, nonatomic) NSString *jsfmSource; // @synthesize jsfmSource=_jsfmSource;
- (void).cxx_destruct;
- (id)jsSource;
@end
|
<reponame>Zweihander-Main/lordliverpool.com<gh_stars>0
export const baseSize: string;
export const baseLineHeight: string;
export const scaleRatio: string;
export const headerFont: string;
export const bodyFont: string;
export const letterSpacing: string;
export const cardWidth: string;
export const outer: string;
export const isActive: string;
export const inner: string;
export const close: string;
export const retailersList: string;
export const retailer: string;
export const showRetailer: string;
export const retailerLink: string;
export const logo: string;
export const flag: string;
export const menu: string;
export const menuSelection: string;
export const menuLabel: string;
export const radioOptionsContainer: string;
export const radioOption: string;
export const radioLabel: string;
export const unselect: string;
export const showUnselect: string;
|
Blockchain Technology and Healthcare Applications 1 Office of Superintendent, St. Joseph's Hospital, Yunlin, Taiwan 2 Nursing Administration, Graduate Institute of Medical Sciences, Chang Jung Christian University, Tainan, Taiwan 3 University of Texas at Austin, Austin, Texas, USA 4 Department of Otolaryngology-Head and Neck Surgery, Taoyuan Armed Forces General Hospital, Taoyuan, Taiwan 5 Institute of Brain Science, National Yang-Ming University School of Medicine, Taipei, Taiwan 6 Department of Otolaryngology-Head and Neck Surgery, Tri-Service General Hospital, Taipei, Taiwan 7 Department of Otolaryngology-Head and Neck Surgery, National Defense Medical Center, Taipei, Taiwan INTRODUCTION A bockchain consists of a chain of blocks containing information. The chain is stored on nodes of computers that work collectively to maintain a shared ledger of information. The blocks record all transactions that take place in the system. It is the basis of cryptocurrencies, of which the most famous is the Bitcoin. Electronic cryptocurrencies are trusted and secure because encryption and validation are used to control the units and their transfer. Amendments can be made only according to a strict protocol. The blockchain ledger is kept up to date on different nodes or computers. Bitcoin's blockchain ledger, for instance, prevents errors and double-spending, and keeps continuous track of transactions securely. The records are on linked blocks and stored on an encrypted digital ledger, spread across a network of synchronised replicated databases. Users can only update the block they have access to. The system works without a central administrator, but since control is spread across the network, there are no chances of error. Because of its unprecedented security, a currency has been created that is not controlled by a central bank. Events are recorded in each block that is authenticated using a protocol of operation. This mechanism ensures that information stored on the blockchain is trusted as reliable, since the network validates the blocks posted to the ledger as per the rules. The transaction data is thus replicated consistently across the network. Any mistake will be rejected as it will not be validated by the network. The blockchain is said to be the most important creation since the advent of the Internet. Its design, based on a public, shared, tamperproof and trusted ledger, makes it open for a number of different applications. One such area is that of medical care. BLOCKCHAIN IN MEDICAL CARE The blockchain technology can be very helpful in integrating of health care information, which is currently scattered, with a range of service providers. Since it is a distributed network, blockchain-based systems can be useful for integration of several intermediaries in the medical care system. Such systems can be used in storing longitudinal patient histories that can be used by consumers, companies, and medical service providers. One of its major advantages is interoperability among institutions and service providers. Blockchains can result in improved data integrity, decentralization and help in reducing transaction costs. They can also help in delivering precision medicine, improving patient care and outcomes, and the connecting medical records across a nation. This could be a boon in emergency situations as hospitals can easily access data rather than collect medical histories from individual patients. By combining these functions, blockchains can result in real-time patient monitoring and updating patient data by tracking different nodes using Internet of Things (IoT). Combined with a database, it can be used by medical care providers and a range of intermediaries. In this way, it allows for quick way of accessing patient records across service providers, thereby reducing costs, and improving collaboration between health institutions. Blockchains can form the basis of Health Information Exchange (HIE) and the Integrating the Health care Enterprise (IHE). Further, by linking the system across functions such as insurance companies, financial and operational services, revenue cycles and supply chains, back-office data input and maintenance costs can be significantly reduced. Data accuracy and security are added benefits. Countries could ultimately develop their nation-wide health information systems based on a seamless sharing of data. The benefits of integrating the medical network will also yield low cost solutions and virtual health systems in the long run. In summary, blockchain technology can be used in several key data-driven healthcare areas, including health care records, health claims, interoperability, patient access, and supply chains. Health Care Records Blockchains allow collection of health records of a patient's lifetime. This longitudinal data can be stored on blocks, which can yield invaluable insight not only with regard to individual patients but for various population segments. A distributed network can be used to improve care coordination among various services providers. For instance, a futuristic scenario has been described in which a technician can simply swipe patients' interactive wristbands to get their medical history. This would be of great help in medical emergencies, because as soon as the wristband is used, the patient's details are broadcast in real-time to the hospital and doctor, who use the blockchain to obtain access health care accounts with the details as recorded by the attending technician. Using IoT, wearable sensors make medical care seamless no matter where the patient is. Furthermore, by combining health data from mobile applications with genomics can yield invaluable information about sub-populations who may be susceptible to a particular disease or who respond to certain kinds of treatment. Health Claims Another area for seamless integration is the area of health claims and insurance. Such claims, linked to a blockchain, can be easily and quickly processed, saving time and cost. Interoperability standards and application programming interfaces can provide an almost real-time claim settlement since patients' bank and health savings accounts would be linked through the blockchain. Interoperability Health care records are traditionally disjointed and stored in silos of service providers. This is because Electronic Health Records (EHRs) were generated on an episode basis without taking into account linkages required for lifetime PERSPECTIVES 2 of 2 records or different service providers, and hence suffer from a lack of linkages, common architectures and standards. There is also no system of transfer of patients' information among stakeholders and even to the patient. Thus, a patient's common clinical data cannot be updated in a central pool each time a medical service is provided. Interoperability is of great help that will help patients and medical service providers alike. Data interoperability allows systems that support population health initiatives, and the blockchain can be used to collect massive amounts of patient data to aid such large-scale initiatives. Patient Access Another benefit of an open ledger is that patients also gain access to their own medical records. This depends on health care data interoperability, which can be achieved after meeting regulatory and legal requirements. In addition, a health care blockchain can be linked to the latest medical research to help suggest the latest treatments for patients. Patients could thus be better informed and discuss the best treatment with their doctors based on research rather than accepted methods. The blockchain technology is thus useful for health care data interoperability by creating secure and trusted health record data, linking transactional data, and providing access to patients and recording their consent. |
Gut morphology and metallothionein immunoreactivity in Liza aurata from different heavy metal polluted environments A critical analysis was made as to whether changes in morphology and histomorphology of fish intestinal mucosa could be appropriate for rapid application in field monitoring programs for heavy metal pollution. Equivalent gut samples of the gold grey mullet Liza aurata from different polluted environments were simultaneously treated using morphological, histomorphological and immunohistochemical methods. The morphological aspects of the mucosal folds and the characteristics of the mucous goblet cells seemed to vary according to the environmental pollution, as well as to the presence and distribution of metallothionein immunoreactivity. On the basis of these findings, the use of the gut fold morphology test is suggested as an expertiseindependent, costeffective and rapid prognostic biomarker for field heavy metal monitoring programs. |
<filename>src/ts/gmailSend.d.ts
declare module "gmail-send";
|
/**
* This event is fired when a player request the informations of faction. You
* can customize the displayed informations.
*
* @author BrokenSwing
*
*/
public class FactionInfoEvent extends Event {
private final Faction faction;
private ArrayList<String> informations;
public FactionInfoEvent(final Faction faction, final ArrayList<String> informations) {
this.faction = faction;
this.informations = informations;
}
/**
* Returns a list containing the lines which will be displayed to the player.
*
* @return a list of String
*/
public ArrayList<String> getInformations() {
return informations;
}
/**
* Changes the informations which will be displayed to the player.
*
* @param informations
* The new informations
*/
public void setInformations(final ArrayList<String> informations) {
this.informations = informations;
}
/**
* The faction which is concerned by the informations.
*
* @return the faction
*/
public Faction getFaction() {
return faction;
}
} |
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2017 SignifAI Inc
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 nagios
import (
"errors"
"github.com/intelsdi-x/snap-plugin-lib-go/v1/plugin"
"os"
"time"
)
const (
Name = "Nagios"
Namespace = "nagios"
Version = 1
)
var (
HostStateCode2String = map[string]string{
"0": "UP",
"1": "DOWN",
}
ServiceStateCode2String = map[string]string{
"0": "OK",
"1": "WARNING",
"2": "CRITICAL",
"3": "UNKNOWN",
}
)
type NagiosPlugin struct {
statusFile string
}
func (NagiosPlugin) GetConfigPolicy() (plugin.ConfigPolicy, error) {
policy := plugin.NewConfigPolicy()
policy.AddNewStringRule([]string{"nagios"},
"status_file",
true)
return *policy, nil
}
func (nagios NagiosPlugin) GetMetricTypes(pluginConfig plugin.Config) ([]plugin.Metric, error) {
metricDefinitions := []plugin.Metric{}
// Host State
metricDefinitions = append(metricDefinitions, plugin.Metric{
Description: "A host's state (supercedes service state)",
Namespace: plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname for the service").AddStaticElement("state"),
Unit: "string",
Version: Version,
})
// Service State
metricDefinitions = append(metricDefinitions, plugin.Metric{
Description: "A service's state",
Namespace: plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname for the service").AddStaticElement("services").AddDynamicElement("service_name", "The service's name").AddStaticElement("state"),
Unit: "string",
Version: Version,
})
// Acknowledgement (host)
metricDefinitions = append(metricDefinitions, plugin.Metric{
Description: "A host's acknowledgment status",
Namespace: plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname being acknowledged").AddStaticElement("acknowledged"),
Unit: "boolean",
Version: Version,
})
// Acknowledgement (service)
metricDefinitions = append(metricDefinitions, plugin.Metric{
Description: "A service's acknowledgment status",
Namespace: plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname of the host for which the service is acknowledged").AddStaticElement("services").AddDynamicElement("service_name", "The service's name").AddStaticElement("acknowledged"),
Unit: "boolean",
Version: Version,
})
// Host Plugin Long Output
metricDefinitions = append(metricDefinitions, plugin.Metric{
Description: "A host's check's long plugin output",
Namespace: plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname for the service").AddStaticElement("long_plugin_output"),
Unit: "string",
Version: Version,
})
// Service Plugin Long Output
metricDefinitions = append(metricDefinitions, plugin.Metric{
Description: "A service's check's long plugin output",
Namespace: plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname for the service").AddStaticElement("services").AddDynamicElement("service_name", "The service's name").AddStaticElement("long_plugin_output"),
Unit: "string",
Version: Version,
})
return metricDefinitions, nil
}
func HostStatusToMetric(hostname string, valueOf string, status map[string]string) (plugin.Metric, error) {
var metricValue interface{}
var stateVar string
var tags map[string]string
if status["state_type"] == "0" {
// Soft -- use last_hard_state to avoid flapping too much...
stateVar = "last_hard_state"
} else {
stateVar = "current_state"
}
var exists bool
switch valueOf {
case "state":
metricValue, exists = HostStateCode2String[status[stateVar]]
if !exists {
metricValue = "UNKNOWN"
}
case "acknowledged":
metricValue = status["problem_has_been_acknowledged"]
if metricValue.(string) == "0" {
metricValue = false
} else {
metricValue = true
}
case "long_plugin_output":
metricValue = status["long_plugin_output"]
tags = make(map[string]string)
tags["service_state"], exists = ServiceStateCode2String[status[stateVar]]
if !exists {
tags["service_state"] = "UNKNOWN"
}
}
metricName := plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname for the service").AddStaticElement(valueOf)
metricName[1].Value = hostname
return plugin.Metric{
Namespace: metricName,
Data: metricValue,
Timestamp: time.Now(),
Version: Version,
Tags: tags,
}, nil
}
func HostServiceStatusToMetric(hostname string, service string, valueOf string, status map[string]string) (plugin.Metric, error) {
var metricValue interface{}
var stateVar string
var tags map[string]string
if status["state_type"] == "0" {
// Soft -- use last_hard_state to avoid flapping too much...
stateVar = "last_hard_state"
} else {
stateVar = "current_state"
}
var exists bool
switch valueOf {
case "state":
metricValue, exists = ServiceStateCode2String[status[stateVar]]
if !exists {
metricValue = "UNKNOWN"
}
case "acknowledged":
metricValue = status["problem_has_been_acknowledged"]
if metricValue.(string) == "0" {
metricValue = false
} else {
metricValue = true
}
case "long_plugin_output":
metricValue = status["long_plugin_output"]
tags = make(map[string]string)
tags["service_state"], exists = ServiceStateCode2String[status[stateVar]]
if !exists {
tags["service_state"] = "UNKNOWN"
}
}
metricName := plugin.NewNamespace("nagios").AddDynamicElement("hostname", "The hostname for the service").AddStaticElement("services").AddDynamicElement("service_name", "The service's name").AddStaticElement(valueOf)
metricName[1].Value = hostname
metricName[3].Value = service
return plugin.Metric{
Namespace: metricName,
Data: metricValue,
Timestamp: time.Now(),
Version: Version,
Tags: tags,
}, nil
}
func (nagios NagiosPlugin) CollectMetrics(metrics []plugin.Metric) (returnedMetrics []plugin.Metric, err error) {
statusFilename, err := metrics[0].Config.GetString("status_file")
statusFile, err := os.Open(statusFilename)
hoststatuses, servicestatuses, err := NagiosStatusMaps(statusFile)
if err == nil {
for _, metric := range metrics {
var hostname, serviceName, valueOf string
var isService bool = false
for _, namePart := range metric.Namespace {
if namePart.IsDynamic() {
switch namePart.Name {
case "hostname":
hostname = namePart.Value
case "service_name":
serviceName = namePart.Value
isService = true
}
} else {
switch namePart.Value {
case "acknowledged":
valueOf = "acknowledged"
case "state":
valueOf = "state"
case "long_plugin_output":
valueOf = "long_plugin_output"
}
}
}
if valueOf != "" {
if isService {
if hostname == "*" {
for _hostname, serviceMap := range servicestatuses {
if serviceName == "*" {
for _serviceName, serviceData := range serviceMap {
newMetric, err := HostServiceStatusToMetric(_hostname, _serviceName, valueOf, serviceData)
if err == nil {
returnedMetrics = append(returnedMetrics, newMetric)
}
}
} else {
if serviceData, ok := serviceMap[serviceName]; ok {
newMetric, err := HostServiceStatusToMetric(_hostname, serviceName, valueOf, serviceData)
if err == nil {
returnedMetrics = append(returnedMetrics, newMetric)
}
}
}
}
} else {
if serviceName == "*" {
for _serviceName, serviceData := range servicestatuses[hostname] {
newMetric, err := HostServiceStatusToMetric(hostname, _serviceName, valueOf, serviceData)
if err == nil {
returnedMetrics = append(returnedMetrics, newMetric)
}
}
} else {
newMetric, err := HostServiceStatusToMetric(hostname, serviceName, valueOf, servicestatuses[hostname][serviceName])
if err == nil {
returnedMetrics = append(returnedMetrics, newMetric)
}
}
}
} else {
// TODO: Make more efficient? It's just funny I'm doing the same thing
// both times, but one's in an iteration and the other is a one-off.
if hostname == "*" {
for _hostname, hostMetrics := range hoststatuses {
newMetric, err := HostStatusToMetric(_hostname, valueOf, hostMetrics)
if err == nil {
returnedMetrics = append(returnedMetrics, newMetric)
}
}
} else {
if hostMetrics, ok := hoststatuses[hostname]; ok {
newMetric, err := HostStatusToMetric(hostname, valueOf, hostMetrics)
if err == nil {
returnedMetrics = append(returnedMetrics, newMetric)
}
}
}
}
} else {
err = errors.New("Missing valueOf for host [" + hostname + "], service [" + serviceName + "]")
break
}
}
}
return returnedMetrics, err
}
|
<gh_stars>1-10
"""
Smart predictor module
"""
from shapash.utils.check import check_consistency_model_features, check_consistency_model_label
from shapash.utils.check import check_model, check_preprocessing, check_preprocessing_options
from shapash.utils.check import check_label_dict, check_mask_params, check_ypred, check_contribution_object,\
check_features_name
from .smart_state import SmartState
from .multi_decorator import MultiDecorator
import pandas as pd
from shapash.utils.transform import adapt_contributions
from shapash.utils.shap_backend import check_explainer, shap_contributions
from shapash.manipulation.select_lines import keep_right_contributions
from shapash.utils.model import predict_proba
from shapash.utils.io import save_pickle
from shapash.utils.transform import apply_preprocessing, apply_postprocessing
from shapash.manipulation.filters import hide_contributions
from shapash.manipulation.filters import cap_contributions
from shapash.manipulation.filters import sign_contributions
from shapash.manipulation.filters import cutoff_contributions
from shapash.manipulation.filters import combine_masks
from shapash.manipulation.mask import init_mask
from shapash.manipulation.mask import compute_masked_contributions
from shapash.manipulation.summarize import summarize
from shapash.decomposition.contributions import rank_contributions, assign_contributions
class SmartPredictor :
"""
The SmartPredictor class is an object lighter than SmartExplainer Object with
additionnal consistency checks.
The SmartPredictor object is provided to deploy the summary of local explanation
for the operational needs.
Switching from SmartExplainer to SmartPredictor, allows users to reproduce
the same results automatically on datasets with right structure.
SmartPredictor is designed to make new results understandable:
- It checks consistency of all parameters
- It applies preprocessing and postprocessing
- It computes models contributions
- It makes predictions
- It summarizes local explainability
This class allows the user to automatically summarize the results of his model
on new datasets (prediction, preprocessing and postprocessing linking,
explainability).
The SmartPredictor has several methods described below.
The SmartPredictor Attributes :
features_dict: dict
Dictionary mapping technical feature names to domain names.
model: model object
model used to check the different values of target estimate predict_proba
explainer: explainer object
explainer must be a shap object (TreeExplainer, LinearExplainer, KernelExplainer)
columns_dict: dict
Dictionary mapping integer column number (in the same order of the trained dataset) to technical feature names.
features_types: dict
Dictionary mapping features with the right types needed.
label_dict: dict (optional)
Dictionary mapping integer labels to domain names (classification - target values).
preprocessing: category_encoders, ColumnTransformer, list or dict (optional)
The processing apply to the original data.
postprocessing: dict (optional)
Dictionary of postprocessing modifications to apply in x_pred dataframe.
_case: string
String that informs if the model used is for classification or regression problem.
_classes: list, None
List of labels if the model used is for classification problem, None otherwise.
mask_params: dict (optional)
Dictionary that specify how to summarize the explainability.
How to declare a new SmartPredictor object?
Example
-------
>>> predictor = SmartPredictor(features_dict=my_features_dict,
>>> model=my_model,
>>> explainer=my_explainer,
>>> columns_dict=my_columns_dict,
>>> features_types=my_features_type_dict,
>>> label_dict=my_label_dict,
>>> preprocessing=my_preprocess,
>>> postprocessing=my_postprocess)
or the most common syntax
>>> predictor = xpl.to_smartpredictor()
xpl, explainer: object
SmartExplainer instance to point to.
"""
def __init__(self, features_dict, model,
columns_dict, explainer, features_types,
label_dict=None, preprocessing=None,
postprocessing=None,
mask_params = {"features_to_hide": None,
"threshold": None,
"positive": None,
"max_contrib": None
}
):
params_dict = [features_dict, features_types, label_dict, columns_dict, postprocessing]
for params in params_dict:
if params is not None and isinstance(params, dict) == False:
raise ValueError(
"""
{0} must be a dict.
""".format(str(params))
)
self.model = model
self._case, self._classes = self.check_model()
self.explainer = self.check_explainer(explainer)
check_preprocessing_options(preprocessing)
self.preprocessing = preprocessing
self.check_preprocessing()
self.features_dict = features_dict
self.features_types = features_types
self.label_dict = label_dict
self.check_label_dict()
self.columns_dict = columns_dict
self.mask_params = mask_params
self.check_mask_params()
self.postprocessing = postprocessing
check_consistency_model_features(self.features_dict, self.model, self.columns_dict,
self.features_types, self.mask_params, self.preprocessing,
self.postprocessing)
check_consistency_model_label(self.columns_dict, self.label_dict)
def check_model(self):
"""
Check if model has a predict_proba method is a one column dataframe of integer or float
and if y_pred index matches x_pred index
Returns
-------
string:
'regression' or 'classification' according to the attributes of the model
"""
_case, _classes = check_model(self.model)
return _case, _classes
def check_preprocessing(self):
"""
Check that all transformation of the preprocessing are supported.
"""
return check_preprocessing(self.preprocessing)
def check_label_dict(self):
"""
Check if label_dict and model _classes match
"""
if self._case != "regression":
return check_label_dict(self.label_dict, self._case, self._classes)
def check_mask_params(self):
"""
Check if mask_params given respect the expected format.
"""
return check_mask_params(self.mask_params)
def add_input(self, x=None, ypred=None, contributions=None):
"""
The add_input method is the first step to add a dataset for prediction and explainability.
add_input applies to x parameter :
- consistencies checks
- preprocessing and postprocessing specified during the initialisation
- features reordering with the right order for the model
If you don't specify ypred or contributions, add_input compute them.
It's possible to not specified one parameter if it has already been defined before.
For example, if the user want to specified an ypred without reinitialize the dataset x already defined.
If the user declare a new input x, all the parameters stored will be cleaned.
Example
--------
>>> predictor.add_input(x=xtest_df)
>>> predictor.add_input(ypred=ytest_df)
Parameters
----------
x: dict, pandas.DataFrame (optional)
Raw dataset used by the model to perform the prediction (not preprocessed).
ypred: pandas.DataFrame (optional)
User-specified prediction values.
contributions: pandas.DataFrame (regression) or list (classification) (optional)
local contributions aggregated if the preprocessing part requires it (e.g. one-hot encoding).
"""
if x is not None:
x = self.check_dataset_features(self.check_dataset_type(x))
self.data = self.clean_data(x)
self.data["x_postprocessed"] = self.apply_postprocessing()
try :
self.data["x_preprocessed"] = self.apply_preprocessing()
except BaseException :
raise ValueError(
"""
Preprocessing has failed. The preprocessing specified or the dataset doesn't match.
"""
)
else:
if not hasattr(self,"data"):
raise ValueError ("No dataset x specified.")
if ypred is not None:
self.data["ypred_init"] = self.check_ypred(ypred)
if contributions is not None:
self.data["ypred"], self.data["contributions"] = self.compute_contributions(contributions=contributions)
else:
self.data["ypred"], self.data["contributions"] = self.compute_contributions()
def check_dataset_type(self, x=None):
"""
Check if dataset x given respect the expected format.
Parameters
----------
x: dict, pandas.DataFrame (optional)
Raw dataset used by the model to perform the prediction (not preprocessed).
Returns
-------
x: pandas.DataFrame
Raw dataset used by the model to perform the prediction (not preprocessed).
"""
if not (type(x) in [pd.DataFrame, dict]):
raise ValueError(
"""
x must be a dict or a pandas.DataFrame.
"""
)
else :
x = self.convert_dict_dataset(x)
return x
def convert_dict_dataset(self, x):
"""
Convert a dict to a dataframe if the dataset specified is a dict.
Parameters
----------
x: dict
Raw dataset used by the model to perform the prediction (not preprocessed).
Returns
-------
x: pandas.DataFrame
Raw dataset used by the model to perform the prediction (not preprocessed).
"""
if type(x) == dict:
if not all([column in self.features_types.keys() for column in x.keys()]):
raise ValueError("""
All features from dataset x must be in the features_types dict initialized.
""")
try:
x = pd.DataFrame.from_dict(x, orient="index").T
for feature, type_feature in self.features_types.items():
x[feature] = x[feature].astype(type_feature)
except BaseException:
raise ValueError(
"""
The structure of the given dict x isn't at the right format.
"""
)
return x
def check_dataset_features(self, x):
"""
Check if the features of the dataset x has the expected types before using preprocessing and model.
Parameters
----------
x: pandas.DataFrame (optional)
Raw dataset used by the model to perform the prediction (not preprocessed).
"""
assert all(column in self.columns_dict.values() for column in x.columns)
if not all([type(key) == int for key in self.columns_dict.keys()]):
raise ValueError("columns_dict must have only integers keys for features order.")
features_order = []
for order in range(min(self.columns_dict.keys()), max(self.columns_dict.keys()) + 1):
features_order.append(self.columns_dict[order])
x = x[features_order]
assert all(column in self.features_types.keys() for column in x.columns)
if not all([str(x[feature].dtypes) == self.features_types[feature] for feature in x.columns]):
raise ValueError("Types of features in x doesn't match with the expected one in features_types.")
return x
def check_ypred(self, ypred=None):
"""
Check that ypred given has the right shape and expected value.
Parameters
----------
ypred: pandas.DataFrame (optional)
User-specified prediction values.
"""
return check_ypred(self.data["x"],ypred)
def choose_state(self, contributions):
"""
Select implementation of the smart predictor. Typically check if it is a
multi-class problem, in which case the implementation should be adapted
to lists of contributions.
Parameters
----------
contributions : object
Local contributions. Could also be a list of local contributions.
Returns
-------
object
SmartState or SmartMultiState, depending on the nature of the input.
"""
if isinstance(contributions, list):
return MultiDecorator(SmartState())
else:
return SmartState()
def adapt_contributions(self, contributions):
"""
If _case is "classification" and contributions a np.array or pd.DataFrame
this function transform contributions matrix in a list of 2 contributions
matrices: Opposite contributions and contributions matrices.
Parameters
----------
contributions : pandas.DataFrame, np.ndarray or list
Returns
-------
pandas.DataFrame, np.ndarray or list
contributions object modified
"""
return adapt_contributions(self._case, contributions)
def validate_contributions(self, contributions):
"""
Check len of list if _case is "classification"
Check contributions object type if _case is "regression"
Check type of contributions and transform into (list of) pd.Dataframe if necessary
Parameters
----------
contributions : pandas.DataFrame, np.ndarray or list
Returns
-------
pandas.DataFrame or list
"""
check_contribution_object(self._case, self._classes, contributions)
return self.state.validate_contributions(contributions, self.data["x_preprocessed"])
def check_contributions(self, contributions):
"""
Check if contributions and prediction set match in terms of shape and index.
"""
if not self.state.check_contributions(contributions, self.data["x"], features_names=False):
raise ValueError(
"""
Prediction set and contributions should have exactly the same number of lines
and number of columns. the order of the columns must be the same
Please check x, contributions and preprocessing arguments.
"""
)
def clean_data(self, x):
"""
Clean data stored if x is defined and not None.
Parameters
----------
x: pandas.DataFrame
Raw dataset used by the model to perform the prediction (not preprocessed).
Returns
-------
dict of data stored
"""
return {"x" : x,
"ypred_init": None,
"ypred" : None,
"contributions" : None,
"x_preprocessed": None,
"x_postprocessed": None
}
def check_explainer(self, explainer):
"""
Check if explainer class correspond to a shap explainer object
"""
return check_explainer(explainer)
def predict_proba(self):
"""
The predict_proba compute the probabilities predicted for each x row defined in add_input.
Returns
-------
pandas.DataFrame
A dataset with all probabilities of each label if there is no ypred data or a dataset with ypred and the associated probability.
Example
--------
>>> predictor.add_input(x=xtest_df)
>>> predictor.predict_proba()
"""
return predict_proba(self.model, self.data["x_preprocessed"], self._classes)
def compute_contributions(self, contributions=None):
"""
The compute_contributions compute the contributions associated to data ypred specified.
Need a data ypred specified in an add_input to display detail_contributions.
Parameters
-------
contributions : object (optional)
Local contributions, or list of local contributions.
Returns
-------
pandas.DataFrame
Data with contributions associated to the ypred specified.
pandas.DataFrame
ypred data with right probabilities associated.
"""
if not hasattr(self, "data"):
raise ValueError("add_input method must be called at least once.")
if self.data["x"] is None:
raise ValueError(
"""
x must be specified in an add_input method to apply detail_contributions.
"""
)
if self.data["ypred_init"] is None:
self.predict()
if contributions is None:
contributions, explainer = shap_contributions(self.model,
self.data["x_preprocessed"],
self.explainer)
adapt_contrib = self.adapt_contributions(contributions)
self.state = self.choose_state(adapt_contrib)
contributions = self.validate_contributions(adapt_contrib)
contributions = self.apply_preprocessing_for_contributions(contributions,
self.preprocessing
)
self.check_contributions(contributions)
proba_values = self.predict_proba() if self._case == "classification" else None
y_pred, match_contrib = keep_right_contributions(self.data["ypred_init"], contributions,
self._case, self._classes,
self.label_dict, proba_values)
return y_pred, match_contrib
def detail_contributions(self, contributions=None):
"""
The detail_contributions method associates the right contributions with the right data predicted.
(with ypred specified in add_input or computed automatically)
Parameters
-------
contributions : object (optional)
Local contributions, or list of local contributions.
Returns
-------
pandas.DataFrame
A Dataset with ypred and the right associated contributions.
Example
--------
>>> predictor.add_input(x=xtest_df)
>>> predictor.detail_contributions()
"""
y_pred, detail_contrib = self.compute_contributions(contributions=contributions)
return pd.concat([y_pred, detail_contrib], axis=1)
def apply_preprocessing_for_contributions(self, contributions, preprocessing=None):
"""
Reconstruct contributions for original features, taken into account a preprocessing.
Parameters
----------
contributions : object
Local contributions, or list of local contributions.
preprocessing : object
Encoder taken from scikit-learn or category_encoders
Returns
-------
object
Reconstructed local contributions in the original space. Can be a list.
"""
if preprocessing:
return self.state.inverse_transform_contributions(
contributions,
preprocessing
)
else:
return contributions
def save(self, path):
"""
Save method allows users to save SmartPredictor object on disk using a pickle file.
Save method can be useful: you don't have to recompile to display results later.
Load_smartpredictor method allow to load your SmartPredictor object saved. (See example below)
Parameters
----------
path : str
File path to store the pickle file
Example
--------
>>> predictor.save('path_to_pkl/predictor.pkl')
>>> from shapash.utils.load_smartpredictor import load_smartpredictor
>>> predictor_load = load_smartpredictor('path_to_pkl/predictor.pkl')
"""
dict_to_save = {}
for att in self.__dict__.keys():
if (isinstance(getattr(self, att), (list, dict, pd.DataFrame, pd.Series, type(None))) or att == "model"
or att == "explainer" or att == "preprocessing") and not att == "data" :
dict_to_save.update({att: getattr(self, att)})
save_pickle(dict_to_save, path)
def apply_preprocessing(self):
"""
Apply preprocessing on new dataset input specified.
"""
return apply_preprocessing(self.data["x"], self.model, self.preprocessing)
def filter(self):
"""
The filter method is an important method which allows to summarize the local explainability
by using the user defined mask_params parameters which correspond to its use case.
"""
mask = [init_mask(self.summary['contrib_sorted'], True)]
if self.mask_params["features_to_hide"] is not None:
mask.append(
hide_contributions(
self.summary['var_dict'],
features_list=self.check_features_name(self.mask_params["features_to_hide"])
)
)
if self.mask_params["threshold"] is not None:
mask.append(
cap_contributions(
self.summary['contrib_sorted'],
threshold=self.mask_params["threshold"]
)
)
if self.mask_params["positive"] is not None:
mask.append(
sign_contributions(
self.summary['contrib_sorted'],
positive=self.mask_params["positive"]
)
)
self.mask = combine_masks(mask)
if self.mask_params["max_contrib"] is not None:
self.mask = cutoff_contributions(mask=self.mask, k=self.mask_params["max_contrib"])
self.masked_contributions = compute_masked_contributions(
self.summary['contrib_sorted'],
self.mask
)
def summarize(self):
"""
The summarize method allows to display the summary of local explainability.
This method can be configured with modify_mask method to summarize the explainability to suit needs.
If the user doesn't use modify_mask, the summarize method uses the mask_params parameters specified during
the initialisation of the SmartPredictor.
In classification case, The summarize method summarizes the explainability which corresponds to :
- the predicted values specified by the user or automatically computed (with add_input method)
- the right probabilities from predict_proba associated to the right predicted values
- the right contributions ranked and filtered as specify with modify_mask method
Returns
-------
pandas.DataFrame
- selected explanation of each row for classification case
Examples
--------
>>> summary_df = predictor.summarize()
>>> summary_df
pred proba feature_1 value_1 contribution_1 feature_2 value_2 contribution_2
0 0 0.756416 Sex 1.0 0.322308 Pclass 3.0 0.155069
1 3 0.628911 Sex 2.0 0.585475 Pclass 1.0 0.370504
2 0 0.543308 Sex 2.0 -0.486667 Pclass 3.0 0.255072
>>> predictor.modify_mask(max_contrib=1)
>>> summary_df = predictor.summarize()
>>> summary_df
pred proba feature_1 value_1 contribution_1
0 0 0.756416 Sex 1.0 0.322308
1 3 0.628911 Sex 2.0 0.585475
2 0 0.543308 Sex 2.0 -0.486667
"""
# data is needed : add_input() method must be called at least once
if not hasattr(self, "data"):
raise ValueError("You have to specify dataset x and y_pred arguments. Please use add_input() method.")
self.summary = assign_contributions(
rank_contributions(
self.data["contributions"],
self.data["x_postprocessed"]
)
)
# Apply filter method with mask_params attributes parameters
self.filter()
# Summarize information
self.data['summary'] = summarize(self.summary['contrib_sorted'],
self.summary['var_dict'],
self.summary['x_sorted'],
self.mask,
self.columns_dict,
self.features_dict)
# Matching with y_pred
return pd.concat([self.data["ypred"], self.data['summary']], axis=1)
def modify_mask(
self,
features_to_hide=None,
threshold=None,
positive=None,
max_contrib=None
):
"""
This method allows the users to modify the mask_params values.
Each parameter is optional, modify_mask method modifies only the values specified in parameters.
This method has to be used to configure the summary displayed with summarize method.
Parameters
----------
features_to_hide : list, optional (default: None)
List of strings, containing features to hide.
threshold : float, optional (default: None)
Absolute threshold below which any contribution is hidden.
positive: bool, optional (default: None)
If True, hide negative values. False, hide positive values
If None, hide nothing.
max_contrib : int, optional (default: None)
Maximum number of contributions to show.
Examples
--------
>>> predictor.modify_mask(max_contrib=1)
>>> summary_df = predictor.summarize()
>>> summary_df
pred proba feature_1 value_1 contribution_1
0 0 0.756416 Sex 1.0 0.322308
1 3 0.628911 Sex 2.0 0.585475
2 0 0.543308 Sex 2.0 -0.486667
"""
Attributes = {"features_to_hide": features_to_hide,
"threshold": threshold,
"positive": positive,
"max_contrib": max_contrib}
for label, attribute in Attributes.items() :
if attribute is not None:
self.mask_params[label] = attribute
def predict(self):
"""
The predict method compute the predicted values for each x row defined in add_input.
Returns
-------
pandas.DataFrame
A dataset with predicted values for each x row.
Example
--------
>>> predictor.add_input(x=xtest_df)
>>> predictor.predict()
"""
if not hasattr(self, "data"):
raise ValueError("add_input method must be called at least once.")
if self.data["x_preprocessed"] is None:
raise ValueError(
"""
x must be specified in an add_input method to apply predict.
"""
)
if hasattr(self.model, 'predict'):
self.data["ypred_init"] = pd.DataFrame(
self.model.predict(self.data["x_preprocessed"]),
columns=['ypred'],
index=self.data["x_preprocessed"].index)
else:
raise ValueError("model has no predict method")
return self.data["ypred_init"]
def apply_postprocessing(self):
"""
Modifies x Dataframe according to postprocessing modifications, if exists.
Parameters
----------
postprocessing: Dict
Dictionnary of postprocessing modifications to apply in x.
Returns
-------
pandas.Dataframe
Returns x_pred if postprocessing is empty, modified dataframe otherwise.
"""
if self.postprocessing:
return apply_postprocessing(self.data["x"], self.postprocessing)
else:
return self.data["x"]
def check_features_name(self, features):
"""
Convert a list of feature names (string) or features ids into features ids.
Features names can be part of columns_dict or features_dict.
Parameters
----------
features : List
List of ints (columns ids) or of strings (business names)
Returns
-------
list of ints
Columns ids compatible with var_dict
"""
return check_features_name(self.columns_dict, self.features_dict, features)
|
<filename>server/src/router/users.router.ts
import express from "express";
import {
getUsers,
getUserById,
insertUser,
updateUser,
deleteUser,
} from "../controllers/users.controller";
export const UserRouter = express.Router();
/**
* @openapi
* /api/users:
* get:
* tags:
* - "users"
* summary: "return all users"
* description: "users description"
* produces:
* - "application/json"
* responses:
* "200":
* description: "Successful"
* "500":
* description: "Server error"
*/
UserRouter.get("/", getUsers);
/**
* @openapi
* /api/users/:id:
* get:
* tags:
* - "users"
* summary: "return all users"
* description: "users description"
* produces:
* - "application/json"
* responses:
* "200":
* description: "Successful"
* "500":
* description: "Server error"
*/
UserRouter.get("/:id", getUserById);
/**
* @openapi
* /api/users:
* post:
* tags:
* - "users"
* summary: "insert a user"
* description: "Insert a new user into the DB"
* produces:
* - "application/json"
* requestBody:
* description: User object that needs to be added to the store
* content:
* application/json:
* schema:
* application/xml:
* schema:
* required: true
* responses:
* "201":
* description: "created"
* "500":
* description: "Server error"
*/
UserRouter.post("/", insertUser);
/**
* @openapi
* /api/users:
* put:
* tags:
* - "users"
* summary: "insert a user"
* description: "Insert a new user into the DB"
* produces:
* - "application/json"
* requestBody:
* description: User object that needs to be added to the store
* content:
* application/json:
* schema:
* application/xml:
* schema:
* required: true
* responses:
* "201":
* description: "created"
* "500":
* description: "Server error"
*/
UserRouter.put("/:id", updateUser);
/**
* @openapi
* /api/users:
* delete:
* tags:
* - "users"
* summary: "insert a user"
* description: "Insert a new user into the DB"
* produces:
* - "application/json"
* requestBody:
* description: User object that needs to be added to the store
* content:
* application/json:
* schema:
* application/xml:
* schema:
* required: true
* responses:
* "201":
* description: "created"
* "500":
* description: "Server error"
*/
UserRouter.delete("/:id", deleteUser);
|
package web;
import model.URL;
import org.mongodb.morphia.query.FindOptions;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import util.DatabaseDriver;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@SpringBootApplication
@EnableScheduling
public class Application {
static String SEED_FILE_NAME;
static int MAX_DOUCMENTS_COUNT, NUMBER_OF_THREADS;
/**
* The main method for the application as a whole.
*
* @param args Commandline arguments, must adhere to the restrictions specified
*/
public static void main(String[] args) throws InterruptedException, FileNotFoundException {
if (args.length != 3) {
System.err.println("Usage: CrawlerMan <seed_file> <max_URLs_count> <number_of_threads>");
System.exit(-1);
}
SEED_FILE_NAME = args[0];
MAX_DOUCMENTS_COUNT = Integer.parseInt(args[1]);
NUMBER_OF_THREADS = Integer.parseInt(args[2]);
util.DatabaseDriver.initializeDatabase();
SpringApplication.run(Application.class);
}
static void update(String seedFileName, int maxURLsCount, int numberOfThreads) throws InterruptedException, FileNotFoundException {
// Run Crawler
Thread crawlerThread = new Thread(() -> {
try {
crawler.Crawler.crawl(seedFileName, maxURLsCount, numberOfThreads);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
});
// Run Indexer
Thread indexerThread = new Thread(indexer.Indexer::index);
// Waiting for them to finish
crawlerThread.start();
indexerThread.start();
crawlerThread.join();
indexerThread.join();
// Update seeds
List<URL> urls = DatabaseDriver.datastore.createQuery(model.URL.class).order("urlRank").asList(new FindOptions().limit(maxURLsCount / 4));
try (PrintWriter file = new PrintWriter(seedFileName)) {
for (URL url : urls) {
file.println(url.getURL());
}
}
}
}
|
A Review of The Optimization of The Manual Picking System The warehouse operations play a decisive role in the service quality performance of logistics service supply chain. Currently, many small and medium-sized warehouses still adopt manual picking systems. Picking, therefore, becomes the most workload among the whole warehouse operational processes. Study on the improvement of the manual picking system still has a great significance. This study first reviews the main problems that affect the efficiency of the picking system regarding two categories: strategical and operational issues. With the investigation among reviewed research works, the study proposes suggestions on the improvement of the manual picking systems for SMEs.. |
import { Subject } from 'rxjs/Subject';
import { NgProgressState } from '../models/progress.state';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/takeWhile';
export declare class NgProgress {
/** Initial state */
initState: NgProgressState;
/** Progress state */
state: BehaviorSubject<NgProgressState>;
/** Trickling stream */
trickling: Subject<{}>;
progress: number;
maximum: number;
minimum: number;
speed: number;
trickleSpeed: number;
constructor();
/** Start */
start(): void;
/** Done */
done(): void;
/** Increment the progress */
inc(amount?: any): void;
/** Set the progress */
set(n: any): void;
/**
* Is progress started
* @return {boolean}
*/
isStarted(): boolean;
/** Update the progress */
private updateState(progress, isActive);
}
|
<gh_stars>0
package com.freakybyte.accedo.controller.score.di;
import com.freakybyte.accedo.controller.score.ui.ScoreActivity;
import com.freakybyte.accedo.di.component.SqliteComponent;
import com.freakybyte.accedo.di.module.WidgetModule;
import com.freakybyte.accedo.di.scope.ActivityScoped;
import dagger.Component;
/**
* Created by <NAME> in FreakyByte on 26/06/16.
*/
@ActivityScoped
@Component(dependencies = SqliteComponent.class, modules = {ScoreModule.class, WidgetModule.class})
public interface ScoreComponent {
void inject(ScoreActivity activity);
}
|
The present invention pertains to trailers intended to be towed by a motor vehicle. These trailers may be used for a variety of purposes including transporting luggage, materials, or sports machines. Such trailers are generally made from metal beams cut to the correct length and welded together. These operations, particularly the welding operation, require welding stations and qualified personnel. Such operations can only be conducted in workshops equipped with specific tooling. Often this tooling is expensive and requires trained workers to operate the tooling. The trailers must then be transported to consumers in an assembled state, which is difficult and costly. It is therefore desired to design a new trailer which requires a minimum number of tools for assembly. It is further desired to design a new trailer which does not require skilled workers, such as welders, to assemble the trailer. It is further desired to design a new trailer which can be assembled on site at the point of sale to reduce the logistical problems associated with transporting the trailers in their assembled configuration. |
Density-matrix renormalization study of the frustrated fermions on the triangular lattice We show that the two-dimensional density-matrix renormalization analysis is useful to detect the symmetry breaking in the fermionic model on a triangular lattice. Under the cylindrical boundary conditions with chemical potentials on edge sites, we find that the open edges work as perturbation to select the strongest correlations {\it only in the presence of a long range order}. We also demonstrate that the ordinary size scaling analysis on the charge gap as well as that of the local charge density under this boundary condition could determine the metal-insulator phase boundary, which scales almost perfectly with the density of states and the exact solutions in the weak and strong coupling region, respectively. We show that the two-dimensional density-matrix renormalization analysis is useful to detect the symmetry breaking in the fermionic model on a triangular lattice. Under the cylindrical boundary conditions with chemical potentials on edge sites, we find that the open edges work as perturbation to select the strongest correlations only in the presence of a long range order. We also demonstrate that the ordinary size scaling analysis on the charge gap as well as that of the local charge density under this boundary condition could determine the metal-insulator phase boundary, which scales almost perfectly with the density of states and the exact solutions in the weak and strong coupling region, respectively. Geometrically frustrated lattices sometimes provide particular situation where the strong correlation between particles or spins works effectively to give rise to exotic states. The numerical approach to such systems made remarkable progress in recent years; quantum monte carlo method (QMC) is applied to clarify the supersolid state on a triangular and square lattices 1,2, plaquette state on a quantum dimer model, the nematic orders in the ring exchanged ladders 3. Also the exact diagonalization by the symmetry analysis gave much information on the low-energy excitation of the Kagome lattice 4, nematic orders in the frustrated square lattice 5, and so on. In the present paper we apply the density matrix renormalization group (DMRG) method to the two-dimensional(2D) frustrated system. So far, we understand that the systematic treatment to 2D-DMRG is not known to such system where a competition between several orders exists. We give a prototype analysis on how to determine the translational symmetry breaking, to detect the metal-insulator transition and so on. We choose as a representative frustrated system a fermionic system on the triangular lattice. Since the QMC is quite hopeless to such system due to the minus sign problem, the 2D-DMRG approach is useful instead, which can cope with much bigger sizes compared to the exact diagonalization. However, it is relatively quite difficult to get a reasonable results in DMRG when the system is critical or in higher dimension than one, which is demonstrated in the t-J model on a square lattice 6. Recent 2D-DMRG analysis with the cylindrical boundary condition is given by systematically varying the aspect ratio of the finite cluster, which successfully determined the magnetization of the Nel order in the square lattice Heisenberg model 7. However, the same analysis for the triangular lattice Heisenberg model turned out to be far difficult. In the present paper, we adopt the same cylindrical boundary condition, and demonstrate that the triangular lattice geometry combined with this boundary condition is useful to detect the symmetry breaking in an unbiased manner, which is also possible in the case of other lattices, e.g., the bipartite square lattice. We mention in advance that even though the present analysis turned out to be successful, there are only few cases where the 2D-DMRG is reasonably adopted; in detecting the Ising type of long range orders (with quantum fluctuation) when the ground state candidates are elucidated, when the numerous number of states (more than the order of ∼ 10000) are kept by e.g., using the parallel computing system 8, analysis on metallic state away from the phase boundary. Still, the difficulty depends on what quantity we measure, and the numerically rigorous data provided by the DMRG would be of help in many occasions as in the present case which is one of the examples of case. We choose as the simplest fermionic model the t-V model whose Hamiltonian given as, Here c j (c j ) are creation (annihilation) operators of fermions and n j (=c j c j ) are number operators. The interactions act only between neighboring sites ij. Anisotropies of the hopping amplitudes and repulsion strengths are all positive and are given by (t ij, V ij ) = (t, V ) for the vertical bond and (t, V ) for the remaining bond directions, as shown in Fig. 1(a)-(c). We focus on half-filling where we have competitive orders due to the commensulability of charges, namely one charge per two sites. We take t = 1 as the unit of energy and fix t = 1 if not otherwise stated. The overall ground state phase diagram of the t-V model is presented by part of the authors based on the exact diagonalization on a 4 6 cluster and on a strong coupling analysis 9. When the interaction is enough large, the phase diagram is characterized by the three different phases according to the anisotropy of V and V as shown schematically in Fig. 1(d). Around the regular triangular geometry of the interactions, V ∼ V, we have a partially charge ordered liquid called a "pinball liquid". This phase breaks the translational symmetry as characterized by the wave vector number, k = ±( 2 3, 2 3 ), and it originates from the long range order of "pins", while still retains a coherent metallic property. If one enters the anisotropic region, V > V, one finds an insulator where the particles align in stripes in the horizontal (or diagonal) direction in order to avoid the energy rise by the stronger interaction, V. We also have similar stripes in V < V which extends along the vertical direction. The weakly coupled to intermediate coupling region is, however, not clarified yet, which will be focused in the present paper. The 2D-DMRG calculation is performed on a N = N x N y cluster shown in Fig. 1(a)-(c). We keep up to 3200 basis for each DMRG block and undergo ∼ 20 sweeps until the ground-state energy converges within an error of ∼ 10 −10 t. Here, we adopt the open (OBC) and periodic (PBC) boundary condition in x-and y-direction, respectively as shown schematically in Figs. 1(a)-(c). It is well known that if all the boundaries are taken as periodic, the translational symmetry of charge density is always preserved at finite system size since the wave function is the superposition of all the degenerate states with equal weight. However, if we take the the cylindrical topology of the triangular lattice system and opens part of the boundaries, it gives rise to the lifting of the degenerate wave functions in the DMRG calculation. Therefore, we can easily detect translational-symmetry breaking charge-ordered states shown in Fig. 1 FIG. 2: (Color online) Charge density at sites indexed by numbers 1 to 6 in the cluster Fig.1(a), where the parameters are taken as (a) The calculations are given on 8 6 cluster ( Fig.1(a)) with periodic boundary in the y-direction and open boundary in the x-directions. OBC. Usually, in the exact diagonalization and other finite size methods, we figure out what kind of structural factor the state has by analyzing the two-point correlation functions. If the considered structure has a true long range order, the amplitude of the structural factor shall remain finite in the thermodynamic limit after the finite scaling analysis. However, in the present 2D-DMRG calculation, each of these phases are detected more simply by the spatial structure of the charge density as follows; as in Fig. 1(a) we take the PBC on one of the V -bond directions. Then, the other two open bonds with different interactions, V and V, artificially lifts the degeneracy of the finite size ground state and enables us to distinguish several translational symmetry broken and also the unbroken phases. Figure 2 shows the charge density of each characteristic state for sites indexed by numbers 1 to 6 in Fig. 1(a). The two-fold periodic structure in Fig. 2(a) and (c) indicate the diagonal and vertical stripes, respectively. We also detect the three fold periodic rich-rich-poor density of charges (denoted as A-A-B structure) in the pinball liquid state in Fig. 2(b). In contrast to those phases, the metallic phase at small V or V has almost uniform charge density along this periodic boundary. Therefore, the way we assign the boundary conditions should be the one that could efficiently detect the differences between ordered states. Here, we must note that the horizontal stripe, which is another possible two-fold periodic structure at V > V, is not realized if we take the boundary conditions as in Fig. 1(a). Therefore, we consider another type of cluster shown in Fig. 1(b) where both the diagonal and horizontal stripes are compatible, and compare their energies. The calculations on the 6 8 cluster confirm that the horizontal order is always the ground state in the insulating phase at at V > V and the diagonal order belongs to a higher state with small excitation energy. We now present the phase diagram on the plane of V and V in Fig. 3. As mentioned earlier we find three characteristic phases in the strong interaction region; the pinball liquid phase is sandwiched between two different stripes. As has been discussed in Ref., the width of the pinball liquid phase is determined by the absolute value of t and t, e.g. 3t for t < t. Since these three phases breaks the translational symmetry with different characteristic wave numbers the transition between them are of first order. In the strongly interacting region, the phase boundaries show excellent agreement with the one found in the exact diagonalization. The similar phase diagram has been obtained by the same 2D-DMRG method for t-U -V model 11, and by the variational monte carlo (VMC) method 12. The physics of the charge ordering is essentially the same but the pinball-liquid phase is replaced by the three-fold charge-ordered metallic phase with doubly occupied sites. In one dimension, the open boundary is regarded as impurities which induces a Friedel oscillation in metals and can be used to analyze the wave number and critical exponent of the Tomonaga-Luttinger liquid 13,14. These Friedel oscillations are not a true long range order and shall be suppressed if the proper chemical potentials are placed on open edges. On the other hand, if the system has a true long range order with particular symmetry k = 0, the OBC actually lifts the degeneracy of wave functions, regardless of whether the chemical potentials is present or not. We take advantage of this fact in 2D and use the partially open edges which would give rise to the spatial structure of the local quantities (charge density) only when we have long range order. The partially opened edge must be compatible in geometry with the symmetry of the orders to get rid of the the translated counterpart components. We note that the chemical potentials not only suppresses the Friedel oscillation but also helps the variational states not to fall into the local minimum in the case of the Ising-type of orders. Even if we adopt this method to the square lattice system, such breaking of symmetry will also appear. This is because the translational symmetry is broken in a direction with open ends and concomitantly the breaking of symmetry in the other direction which is periodic occurs. From these results, we may argue that the analysis based on the cylindrical boundary condition are useful to detect the breaking of translational symmetry in the two-dimensional lattices. We also confirmed that the same analysis is well adopted to the the Kagome lattice as well 15. In the above analysis, we only considered the fixed cluster size. However, the phase boundary is usually overestimated by the small system size, particularly when we have finite but long correlation length compared to the size of the cluster. Thus one cannot really discriminate the short range order from the true long range order without the proper size scaling analysis. In order to get the more quantitative information, we give the scaling analysis on these local quantities by using the L4 cluster shown in Fig. 1(c). We focus on the four different sites placed at the center of the cluster (see the sites marked by numbers 1-4 in Fig. 1(c)) which are the least influenced by the open boundary. Figure 4(a) shows the deviation from the average charge density of these sites as a function of inverse system length L −1 in the pinball liquid phase at V = V. Here we take L = 6n with integer n, which is a period compatible with both the two-fold and three-fold periodicities. As we can see, at V = V < 6 the deviation of charge density is extrapolated to zero, while over V = V ≥ 6 they change the slope significantly and become finite. This means that the translational symmetry is broken at V = V ∼ 6, and a three-fold periodic long range order appears. This phase boundary is smaller than the one estimated from the VMC simulations on the same model, V c ∼ 12t 16. The VMC estimation based on the Fermi sea slater wave function is an upper bound, and the present results lie just in between the Hartree-Fock estimation and the VMC one. We also estimate the charge gap, ∆ c, of the three-fold periodic phase. The charge gap at each system size N and particle number N e = N/2 is given as, ∆(N e, N x, N y ) = E(N e + 1, N x, N y ) + E(N e − 1, N x, N y ) − 2E(N e, N x, N y ), where E(N e, N x, N y ) is the energy of the corresponding cluster. Figure 4(b) shows the extrapolation of ∆(N e, N x, N y ) towards N x = L, L → ∞ with N y = 4. We see that the system can be regarded as gapless in the thermodynamic limit, which is consistent with the previous study 10. The estimated phase boundary quantitatively agrees with the one by the charge den- 5: (Color online) Finite size scaling of the expectation value of (a) charge density after extracting the mean charge density at the center four sites of the system, and (b) the charge gap at V = 0 and t = t = 1. In panel (c), the gap and the charge density disproportionation in the bulk limit is presented as a function of V /t. sity in Fig. 2 and guarantees the present analysis on the local quantities. Now we focus on the weak coupling region of the phase diagram which is not well studied yet. In the horizontal stripe phase at V > V, the charge gap opens due to the staggered long range order of particles in the anisotropic direction. The gap is well estimated by extrapolating the system size in that direction. Figure 5(a) shows the L −1 -dependence of the gap for several choices of V /t with the fixed V = 0. The same scaling of the center site charge density is given in Fig. 5(b). As plotted in Fig. 5(c), the smooth opening of the extrapolated gap suggests the second order transition, while the extrapolated charge density shows a sharp development at the transition point. These are common behaviors in charge ordering induced by long-range interactions 17. However, the transition point itself shows an excellent agreement between these two quantities. We note that the L-dependence of the gap is very small in the insulating state, which reflects the localized character of the wave function. Resultantly, although the phase boundary of Fig. 3 shifts somewhat to a smaller V -or V region after the scaling, the correction is less than ∼ 0.5t. The charge gap in the bulk limit at V = 0 as a function of V for the several choices of t /t. The finite size scaling is given in the same way as those in Fig.4. (b) t /t-dependence of the phase boundary between the normal weak coupling Fermi liquid phase and the horizontal stripe insulator, VMI. The inset shows the t /t-dependence of t /VMI for the same data. Next, by performing the same analysis, we investigate the effect of varying the geometry of transfer integrals, t /t. Figure 6(a) shows the extrapolated charge gap for several choices of t /t. By fitting the V -dependences, the metal-insulator (MI) phase boundary is detected. Here, the gap opens linearly which makes the estimate precise. The t /t-dependence of V MI is plotted in Fig. 6(b). Just off the non-interacting point, V = 0, V ∼ 0, the gap opens since the shape of the Fermi surface at half-filling is a regular square and the perfect nesting takes place. Therefore the obtained insulator is a typical charge-density-wave state with a small gap. The value of V MI significantly changes at 0 ≤ t /t ≤ 0.5, and then saturates to V MI ∼ 3. At t /t ≫ 1, the system is regarded as the onedimensional chain, where the exact solution of the charge gap is given as V MI /t = 2 18. This can be more easily understood in the V MI /t-t /t plot in the inset, where the value of V MI /t shows a clear crossover from the V MI -linear term to the constant value at around V MI ∼ 3. We now try to understand the characteristic t /t-linear behavior of V MI /t in the weak coupling region. Figure 7 shows the t /t-dependence of the non-interacting density of states of the anisotropic triangular lattice at the Fermi level at halffilling, D(E F ). We find that t /D(E F ) scales almost linearly with t /t in the wide region, 0.25 ≤ t /t ≤ 1.5, which is exactly the region where we find the same linear relation in the inset of Fig. 6(b). By interpolating these two characteristic relations, we obtain the following relation, where = 0.04, = 0.06. The two different linear relations found in Fig. 5(c) indicates that the MI transition changes its character from the weak to the strong coupling ones, i.e. from the charge-density-wave to the charge ordered insulator, at t /t ≃ 1.6, which is also the point where the van Hove singularity touches the Fermi level at half-filling. To summarize we performed the 2D-DMRG analysis on the fermionic system on an anisotropic triangular lattice. We showed that in the triangular lattice the cylindrical bound-ary condition with chemical potentials on open edge site, the translational symmetry breaking is detected by measuring the local quantity in a reasonable accuracy. Also the finite scaling analysis is found to give a further quantitative estimation on the phase boundaries. The demonstration is given on the determination of the metal-insulator phase boundary as a function of the degree of the transfer integral, t /t. It is found that at relatively small t the phase boundary is scaled by the non-interacting density of states at the Fermi level, which indicates that the phase transition is regarded as a charge-densitywave transition due to the instability if the Fermi surface. On the other hand, at t ≥ 1.6t, the phase boundary is scaled to V c = 2t, which means that the system undergoes the phase transition to the charge ordered state in the one-dimensional manner. The role of t /t on the metal-insulator transition has been discussed previously in some articles related to organic compounds based on the mean-field approach 19. Recently, it is proved by the uniaxial strain experiment that the MI transition temperature of the -ET 2 CsZn(SCN) 4 into the horizontal charge ordered state significantly increases when the geometry of the transfer integral varies as t /t = 0 − 0.5 20. The tendency that the insulator is stabilized due to t /t is contrary to what we get in the present analysis. This might be because the present model deals with the half-filled charge density wave, while the experiments should be better explained in the 3/4filled extended Hubbard model (which has a different Fermi level and a Fermi surface) instead. We expect that even in this latter model the V MI will be scaled by the density of states. The present paper shows for the first time that the 2D-DMRG provides a reliable way to cope with the difficult parameter region where the electronic correlation and kinetic energy compete with each other, and presented the clear crossover from the weak to strong coupling. |
Morally Illicit Cells in Medical Research The Catholic Church missed an opportunity to be more proactive and change the course of secular biotechnology when unethical cell lines were first introduced several decades ago. No ethical alternative human cell lines to the HEK293, WI-38, and MRC-5 have been generally accepted by the scientific community. While some animal cell lines are used in creating safe alternative vaccines, no alternative human cell lines for producing vaccines, biologics, or gene therapy have met the scientific rigor of efficacy and safety of these cell lines. It is both possible and within reach to create ethical human cell lines to replace current morally objectionable lines used for producing biologics (proteins and vaccines), but it will take considerable research that requires financial support. Dignitas personae should be backed by leadership and supported by stakeholders. |
def fully_ordered(wrap_iter: Iterable) -> Iterable[Tuple[int, Any]]:
epoch = 0
for item in wrap_iter:
yield (epoch, item)
epoch += 1 |
. Physical therapy is the most important element of naturopathy. In old age conditions accumulate that can be readily treated with physical therapy. It is possible to save on simultaneous drug treatment, and the risk of side effects can be reduced. The prescription of physical therapy in old age should not be regarded as restrictive. |
// Copyright 2009-2018 Information & Computational Sciences, JHI. All rights
// reserved. Use is subject to the accompanying licence terms.
package jhi.flapjack.analysis;
import jhi.flapjack.data.GTViewSet;
import jhi.flapjack.data.MarkerInfo;
import jhi.flapjack.data.StateTable;
import scri.commons.gui.SimpleJob;
public class FilterHeterozygousMarkers extends SimpleJob
{
private GTViewSet viewSet;
private boolean[] selectedChromosomes;
private int cutoff;
private int count;
public FilterHeterozygousMarkers(GTViewSet viewSet, boolean[] selectedChromosomes, int cutoff)
{
this.viewSet = viewSet;
this.selectedChromosomes = selectedChromosomes;
this.cutoff = cutoff;
}
public int getCount()
{ return count; }
public void runJob(int index)
throws Exception
{
AnalysisSet as = new AnalysisSet(viewSet)
.withViews(selectedChromosomes)
.withSelectedLines()
.withSelectedMarkers();
for (int i = 0; i < as.viewCount(); i++)
maximum += as.markerCount(i);
StateTable stateTable = viewSet.getDataSet().getStateTable();
for (int view = 0; view < as.viewCount(); view++)
{
boolean isSpecialChromosome = as.getGTView(view).getChromosomeMap().isSpecialChromosome();
// For each marker...
for (int i = as.markerCount(view)-1; i >= 0 && okToRun; i--)
{
int allelesCount = 0;
int hetCount = 0;
// Count how many alleles are heterozygous across all the lines...
for (int j = 0; j < as.lineCount() && okToRun; j++)
{
if (stateTable.isHet(as.getState(view, j, i)))
hetCount++;
allelesCount++;
}
// And if the percentage of heterozygous ones is >= cutoff, then
// remove it from the visible set
if ((hetCount / (float)allelesCount)*100 >= cutoff)
{
MarkerInfo mi = as.getMarker(view, i);
as.getGTView(view).hideMarker(mi);
if (isSpecialChromosome == false)
count++;
}
progress++;
}
}
}
} |
<gh_stars>0
package io.sphere.sdk.categories;
import io.sphere.sdk.categories.commands.CategoryCreateCommand;
import io.sphere.sdk.categories.commands.CategoryDeleteCommand;
import io.sphere.sdk.categories.queries.CategoryQuery;
import io.sphere.sdk.client.BlockingSphereClient;
import io.sphere.sdk.models.*;
import io.sphere.sdk.queries.PagedQueryResult;
import io.sphere.sdk.utils.SphereInternalLogger;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static io.sphere.sdk.test.SphereTestUtils.*;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Locale.ENGLISH;
public class CategoryFixtures {
private static final SphereInternalLogger LOGGER = SphereInternalLogger.getLogger("categories.fixtures");
public static void withPersistentCategory(final BlockingSphereClient client, final Consumer<Category> user) {
final String externalId = "persistent-category-id";
final Optional<Category> fetchedCategory = client.executeBlocking(CategoryQuery.of().byExternalId(externalId)).head();
final Category category = fetchedCategory.orElseGet(() -> {
final LocalizedString name = en("name persistent-category-id");
final CategoryDraftBuilder catSupplier = CategoryDraftBuilder.of(name, name.slugified()).externalId(externalId);
return client.executeBlocking(CategoryCreateCommand.of(catSupplier.build()));
});
user.accept(category);
}
public static void withCategory(final BlockingSphereClient client, final Supplier<? extends CategoryDraft> creator, final Consumer<Category> user) {
final CategoryDraft categoryDraft = creator.get();
final String slug = englishSlugOf(categoryDraft);
final PagedQueryResult<Category> pagedQueryResult = client.executeBlocking(CategoryQuery.of().bySlug(Locale.ENGLISH, slug));
pagedQueryResult.head().ifPresent(category -> client.executeBlocking(CategoryDeleteCommand.of(category)));
final Category category = client.executeBlocking(CategoryCreateCommand.of(categoryDraft));
LOGGER.debug(() -> "created category " + category.getSlug() + " id: " + category.getId());
try {
user.accept(category);
} finally {
final PagedQueryResult<Category> res = client.executeBlocking(CategoryQuery.of().byId(category.getId()));
//need to update because category could be changed
client.executeBlocking(CategoryDeleteCommand.of(res.head().get()));
LOGGER.debug(() -> "deleted category " + category.getId());
}
}
public static void withCategories(final BlockingSphereClient client, final List<Supplier<? extends CategoryDraft>> creator, final Consumer<List<Category>> user) {
List<Category> categories = creator.stream().map(singleCreator -> {
final CategoryDraft categoryDraft = singleCreator.get();
final String slug = englishSlugOf(categoryDraft);
final PagedQueryResult<Category> pagedQueryResult = client.executeBlocking(CategoryQuery.of().bySlug(Locale.ENGLISH, slug));
pagedQueryResult.head().ifPresent(
category -> client.executeBlocking(CategoryDeleteCommand.of(category))
);
final Category category = client.executeBlocking(CategoryCreateCommand.of(categoryDraft));
return category;
}).collect(Collectors.toList());
try {
user.accept(categories);
} finally {
categories.forEach(category -> {
client.executeBlocking(CategoryDeleteCommand.of(category));
});
}
}
public static void withCategoryAndParentCategory(final BlockingSphereClient client, final BiConsumer<Category, Category> consumer) {
withCategory(client, parent ->
withCategory(client, CategoryDraftBuilder.of(randomSlug(), randomSlug()).key(randomKey()).parent(parent), category -> {
consumer.accept(category, parent);
})
);
}
public static void withCategory(final BlockingSphereClient client, final Consumer<Category> consumer) {
final CategoryDraftBuilder catSupplier = categorySupplier();
CategoryFixtures.withCategory(client, catSupplier, consumer);
}
public static void withCategoryHavingAssets(final BlockingSphereClient client, final Consumer<Category> consumer) {
final CategoryDraftBuilder catSupplier = categorySupplier();
catSupplier.assets(asList(getAssetDraft1(), getAssetDraft2()));
CategoryFixtures.withCategory(client, catSupplier, consumer);
}
public static Category createCategory(final BlockingSphereClient client) {
final CategoryDraft categoryDraft = CategoryDraftBuilder.of(randomSlug(), randomSlug()).build();
return client.executeBlocking(CategoryCreateCommand.of(categoryDraft));
}
public static void deleteAll(final BlockingSphereClient client) {
delete(client, CategoryQuery.of().byIsRoot());
delete(client, CategoryQuery.of());
}
private static void delete(final BlockingSphereClient client, final CategoryQuery categoryQuery) {
client.executeBlocking(categoryQuery.withLimit(500)).getResults().forEach(cat -> {
client.executeBlocking(CategoryDeleteCommand.of(cat));
});
}
private static CategoryDraftBuilder categorySupplier() {
final LocalizedString slug = randomSlug();
return CategoryDraftBuilder.of(en(slug.get(ENGLISH) + " name"), slug).externalId(randomKey());
}
private static AssetDraft getAssetDraft1() {
final AssetSource assetSource1 = AssetSourceBuilder.ofUri("https://commercetools.com/binaries/content/gallery/commercetoolswebsite/homepage/cases/rewe.jpg")
.key(randomKey())
.contentType("image/jpg")
.dimensionsOfWidthAndHeight(1934, 1115)
.build();
final LocalizedString name = LocalizedString.ofEnglish("REWE show case");
final LocalizedString description = LocalizedString.ofEnglish("screenshot of the REWE webshop on a mobile and a notebook");
return AssetDraftBuilder.of(singletonList(assetSource1), name)
.description(description)
.tags("desktop-sized", "jpg-format", "REWE", "awesome")
.build();
}
private static AssetDraft getAssetDraft2() {
final AssetSource assetSource1 = AssetSourceBuilder.ofUri("http://dev.commercetools.com/assets/img/CT-logo.svg")
.key(randomKey())
.contentType("image/svg+xml")
.build();
final LocalizedString name = LocalizedString.ofEnglish("commercetools logo");
return AssetDraftBuilder.of(singletonList(assetSource1), name)
.tags("desktop-sized", "svg-format", "commercetools", "awesome")
.build();
}
}
|
package dockerclient
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/Dataman-Cloud/crane/src/model"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/swarm"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestInspectNodeError(t *testing.T) {
body := `{"Id":"e90302"}`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
}
_, err = client.InspectNode("test")
assert.NotNil(t, err)
}
func TestInspectNode(t *testing.T) {
body := `
{
"ID":"1t6jojzasio4veexyubvic4j2",
"Version":{
"Index":26607
},
"CreatedAt":"2016-08-26T08:00:24.466491891Z",
"UpdatedAt":"2016-09-08T05:23:49.697933079Z",
"Spec":{
"Labels":{
"dm.reserved.node.endpoint":"http://192.168.59.103:2376"
},
"Role":"worker",
"Availability":"active"
},
"Description":{
"Hostname":"192.168.59.013",
"Platform":{
"Architecture":"x86_64",
"OS":"linux"
},
"Resources":{
"NanoCPUs":2000000000,
"MemoryBytes":3975561216
},
"Engine":{
"EngineVersion":"1.12.0",
"Plugins":[
{
"Type":"Network",
"Name":"bridge"
},
{
"Type":"Network",
"Name":"host"
},
{
"Type":"Network",
"Name":"null"
},
{
"Type":"Network",
"Name":"overlay"
},
{
"Type":"Volume",
"Name":"local"
}
]
}
},
"Status":{
"State":"down"
}
}
`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
_, err = client.InspectNode("test")
assert.Nil(t, err)
}
func TestCreateNodeRoleManager(t *testing.T) {
fakeClusterWithID := func(ID string) func(ctx *gin.Context) {
fakeCluster := func(ctx *gin.Context) {
var body swarm.Swarm
body.JoinTokens.Manager = "FakeManagerToken"
ctx.JSON(http.StatusOK, body)
}
return fakeCluster
}
fakeNodeInfo := func(addr string, nodeID string) func(ctx *gin.Context) {
nodeInfo := func(ctx *gin.Context) {
body := types.Info{
Swarm: swarm.Info{
NodeAddr: addr,
NodeID: nodeID,
},
}
ctx.JSON(http.StatusOK, body)
}
return nodeInfo
}
fakeSwarmNodeInfo := func(addr string, nodeID string) func(ctx *gin.Context) {
swarmNodeInfo := func(ctx *gin.Context) {
body := swarm.Node{
ID: nodeID,
ManagerStatus: &swarm.ManagerStatus{
Addr: addr,
},
}
ctx.JSON(http.StatusOK, body)
}
return swarmNodeInfo
}
fakeNodeUpdate := func(ctx *gin.Context) {
body := ``
ctx.JSON(http.StatusOK, body)
}
fakeSwarmJoin := func(ctx *gin.Context) {
body := ``
ctx.JSON(http.StatusOK, body)
}
fakeManagerID := "FakeManagerID"
fakeJoiningNodeID := "FakeJoiningNodeID"
joiningNodeRouter := gin.New()
joiningNodeRouter.POST("/swarm/join", fakeSwarmJoin)
joiningNodeRouter.GET("/info", fakeNodeInfo("FakeAddr", fakeJoiningNodeID))
joiningNode := httptest.NewServer(joiningNodeRouter)
defer joiningNode.Close()
managerRouter := gin.New()
managerRouter.GET("/swarm", fakeClusterWithID(fakeManagerID))
managerRouter.GET("/info", fakeNodeInfo("FakeAddr", fakeManagerID))
managerRouter.GET("/nodes/"+fakeManagerID, fakeSwarmNodeInfo("FakeAddr", fakeManagerID))
managerRouter.GET("/nodes/"+fakeJoiningNodeID, fakeSwarmNodeInfo(joiningNode.URL, fakeJoiningNodeID))
managerRouter.POST("/nodes/"+fakeJoiningNodeID+"/update", fakeNodeUpdate)
manager := httptest.NewServer(managerRouter)
defer manager.Close()
joiningNodeRoleManager := model.JoiningNode{
Role: swarm.NodeRoleManager,
Endpoint: joiningNode.URL,
}
httpClient, err := NewHttpClient()
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: manager.URL,
}
err = client.CreateNode(joiningNodeRoleManager)
assert.Nil(t, err)
}
func TestCreateNodeRoleWorker(t *testing.T) {
fakeClusterWithID := func(ID string) func(ctx *gin.Context) {
fakeCluster := func(ctx *gin.Context) {
var body swarm.Swarm
body.JoinTokens.Worker = "FakeWorkerToken"
ctx.JSON(http.StatusOK, body)
}
return fakeCluster
}
fakeNodeInfo := func(addr string, nodeID string) func(ctx *gin.Context) {
nodeInfo := func(ctx *gin.Context) {
body := types.Info{
Swarm: swarm.Info{
NodeAddr: addr,
NodeID: nodeID,
},
}
ctx.JSON(http.StatusOK, body)
}
return nodeInfo
}
fakeSwarmNodeInfo := func(addr string, nodeID string) func(ctx *gin.Context) {
swarmNodeInfo := func(ctx *gin.Context) {
body := swarm.Node{
ID: nodeID,
ManagerStatus: &swarm.ManagerStatus{
Addr: addr,
},
}
ctx.JSON(http.StatusOK, body)
}
return swarmNodeInfo
}
fakeNodeUpdate := func(ctx *gin.Context) {
body := ``
ctx.JSON(http.StatusOK, body)
}
fakeSwarmJoin := func(ctx *gin.Context) {
body := ``
ctx.JSON(http.StatusOK, body)
}
fakeManagerID := "FakeManagerID"
fakeJoiningNodeID := "FakeJoiningNodeID"
joiningNodeRouter := gin.New()
joiningNodeRouter.POST("/swarm/join", fakeSwarmJoin)
joiningNodeRouter.GET("/info", fakeNodeInfo("FakeAddr", fakeJoiningNodeID))
joiningNode := httptest.NewServer(joiningNodeRouter)
defer joiningNode.Close()
managerRouter := gin.New()
managerRouter.GET("/swarm", fakeClusterWithID(fakeManagerID))
managerRouter.GET("/info", fakeNodeInfo("FakeAddr", fakeManagerID))
managerRouter.GET("/nodes/"+fakeManagerID, fakeSwarmNodeInfo("FakeAddr", fakeManagerID))
managerRouter.GET("/nodes/"+fakeJoiningNodeID, fakeSwarmNodeInfo(joiningNode.URL, fakeJoiningNodeID))
managerRouter.POST("/nodes/"+fakeJoiningNodeID+"/update", fakeNodeUpdate)
manager := httptest.NewServer(managerRouter)
defer manager.Close()
joiningNodeRoleWorker := model.JoiningNode{
Role: swarm.NodeRoleWorker,
Endpoint: joiningNode.URL,
}
httpClient, err := NewHttpClient()
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: manager.URL,
}
err = client.CreateNode(joiningNodeRoleWorker)
assert.Nil(t, err)
}
func TestCreateNodeWithInvalidRole(t *testing.T) {
body := `{"Id":"e90302"}`
swarmManager := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer swarmManager.Close()
joiningNodeWithInvalidRole := model.JoiningNode{
Role: "invalidRole",
Endpoint: "invalid",
}
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: swarmManager.URL,
}
err = client.CreateNode(joiningNodeWithInvalidRole)
assert.NotNil(t, err)
}
func TestListNodeError(t *testing.T) {
body := `{"Id":"e90302"}`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
_, err = client.ListNode(types.NodeListOptions{})
assert.NotNil(t, err)
}
func TestListNode(t *testing.T) {
body := `
[
{
"ID":"1t6jojzasio4veexyubvic4j2",
"Version":{
"Index":26607
},
"CreatedAt":"2016-08-26T08:00:24.466491891Z",
"UpdatedAt":"2016-09-08T05:23:49.697933079Z",
"Spec":{
"Labels":{
"dm.reserved.node.endpoint":"http://192.168.59.103:2376"
},
"Role":"worker",
"Availability":"active"
},
"Description":{
"Hostname":"192.168.59.013",
"Platform":{
"Architecture":"x86_64",
"OS":"linux"
},
"Resources":{
"NanoCPUs":2000000000,
"MemoryBytes":3975561216
},
"Engine":{
"EngineVersion":"1.12.0",
"Plugins":[
{
"Type":"Network",
"Name":"bridge"
},
{
"Type":"Network",
"Name":"host"
},
{
"Type":"Network",
"Name":"null"
},
{
"Type":"Network",
"Name":"overlay"
},
{
"Type":"Volume",
"Name":"local"
}
]
}
},
"Status":{
"State":"down"
}
},
{
"ID":"dbspw1g0sjee8ja1khx2w0xtt",
"Version":{
"Index":26603
},
"CreatedAt":"2016-08-26T07:59:50.685235915Z",
"UpdatedAt":"2016-09-08T05:23:36.061728082Z",
"Spec":{
"Labels":{
"dm.reserved.node.endpoint":"192.168.59.104:2376"
},
"Role":"manager",
"Availability":"active"
},
"Description":{
"Hostname":"localhost",
"Platform":{
"Architecture":"x86_64",
"OS":"linux"
},
"Resources":{
"NanoCPUs":2000000000,
"MemoryBytes":3975561216
},
"Engine":{
"EngineVersion":"1.12.0",
"Plugins":[
{
"Type":"Network",
"Name":"bridge"
},
{
"Type":"Network",
"Name":"host"
},
{
"Type":"Network",
"Name":"null"
},
{
"Type":"Network",
"Name":"overlay"
},
{
"Type":"Volume",
"Name":"local"
}
]
}
},
"Status":{
"State":"ready"
},
"ManagerStatus":{
"Leader":true,
"Reachability":"reachable",
"Addr":"192.168.59.104:2377"
}
}
]
`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
nodes, err := client.ListNode(types.NodeListOptions{})
assert.Nil(t, err)
assert.Equal(t, len(nodes), 2)
assert.Equal(t, nodes[0].ID, "1t6jojzasio4veexyubvic4j2")
assert.Equal(t, nodes[1].ID, "dbspw1g0sjee8ja1khx2w0xtt")
}
func TestRemoveNode(t *testing.T) {
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/nodes/test" {
w.WriteHeader(http.StatusOK)
w.Write([]byte("success"))
} else {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("failed"))
}
return
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
err = client.RemoveNode("tessst")
assert.NotNil(t, err)
err = client.RemoveNode("test")
assert.Nil(t, err)
}
func TestNodeRole(t *testing.T) {
badRole, err := json.Marshal("test")
assert.Nil(t, err)
_, err = nodeRole(badRole)
assert.NotNil(t, err)
worker, err := json.Marshal("worker")
assert.Nil(t, err)
role, err := nodeRole(worker)
assert.Nil(t, err)
assert.Equal(t, role, swarm.NodeRoleWorker)
manager, err := json.Marshal("manager")
assert.Nil(t, err)
role, err = nodeRole(manager)
assert.Nil(t, err)
assert.Equal(t, role, swarm.NodeRoleManager)
}
func TestNodeAvailability(t *testing.T) {
badAvailability, err := json.Marshal("test")
assert.Nil(t, err)
_, err = nodeAvailability(badAvailability)
assert.NotNil(t, err)
active, err := json.Marshal("active")
assert.Nil(t, err)
availability, err := nodeAvailability(active)
assert.Nil(t, err)
assert.Equal(t, swarm.NodeAvailabilityActive, availability)
pause, err := json.Marshal("pause")
assert.Nil(t, err)
availability, err = nodeAvailability(pause)
assert.Nil(t, err)
assert.Equal(t, swarm.NodeAvailabilityPause, availability)
drain, err := json.Marshal("drain")
assert.Nil(t, err)
availability, err = nodeAvailability(drain)
assert.Nil(t, err)
assert.Equal(t, swarm.NodeAvailabilityDrain, availability)
}
func TestGetDaemonUrlByIdErrorKey(t *testing.T) {
body := `
{
"ID":"1t6jojzasio4veexyubvic4j2",
"CreatedAt":"2016-08-26T08:00:24.466491891Z",
"UpdatedAt":"2016-09-08T05:23:49.697933079Z",
"Spec":{
"Labels":{
"dm.reserved.node.endpoint":"http://192.168.59.103:2376"
},
"Role":"worker",
"Availability":"active"
},
"Description":{
"Hostname":"192.168.59.013",
"Platform":{
"Architecture":"x86_64",
"OS":"linux"
},
"Resources":{
"NanoCPUs":2000000000,
"MemoryBytes":3975561216
},
"Engine":{
"EngineVersion":"1.12.0",
"Plugins":[
{
"Type":"Network",
"Name":"bridge"
}
]
}
}
}
`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
_, err = client.GetDaemonUrlById("test")
assert.NotNil(t, err)
}
func TestGetDaemonUrlById(t *testing.T) {
body := `
{
"ID":"1t6jojzasio4veexyubvic4j2",
"CreatedAt":"2016-08-26T08:00:24.466491891Z",
"UpdatedAt":"2016-09-08T05:23:49.697933079Z",
"Spec":{
"Labels":{
"crane.reserved.node.endpoint":"http://192.168.59.103:2376"
},
"Role":"worker",
"Availability":"active"
},
"Description":{
"Hostname":"192.168.59.013",
"Platform":{
"Architecture":"x86_64",
"OS":"linux"
},
"Resources":{
"NanoCPUs":2000000000,
"MemoryBytes":3975561216
},
"Engine":{
"EngineVersion":"1.12.0",
"Plugins":[
{
"Type":"Network",
"Name":"bridge"
}
]
}
}
}
`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
_, err = client.GetDaemonUrlById("test")
assert.Nil(t, err)
}
func TestGetNodeIdByUrl(t *testing.T) {
body := `
{
"Swarm":{
"NodeID":"dbspw1g0sjee8ja1khx2w0xtt"
}
}
`
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(body))
}))
defer server1.Close()
httpClient, err := NewHttpClient()
assert.Nil(t, err)
client := &CraneDockerClient{
sharedHttpClient: httpClient,
swarmManagerHttpEndpoint: server1.URL,
}
u, err := url.Parse(server1.URL)
assert.Nil(t, err)
var returnedNodeId string
matchedNodeUrlWithSchemeTcp := u
matchedNodeUrlWithSchemeTcp.Scheme = "tcp"
returnedNodeId, err = client.getNodeIdByUrl(matchedNodeUrlWithSchemeTcp)
assert.Nil(t, err)
assert.Equal(t, returnedNodeId, "dbspw1g0sjee8ja1khx2w0xtt")
matchedNodeUrlWithSchemeHttp := u
matchedNodeUrlWithSchemeHttp.Scheme = "http"
returnedNodeId, err = client.getNodeIdByUrl(matchedNodeUrlWithSchemeHttp)
assert.Nil(t, err)
assert.Equal(t, returnedNodeId, "dbspw1g0sjee8ja1khx2w0xtt")
matchedNodeUrlWithoutScheme := u
matchedNodeUrlWithoutScheme.Scheme = ""
returnedNodeId, err = client.getNodeIdByUrl(matchedNodeUrlWithoutScheme)
assert.NotNil(t, err)
assert.Equal(t, returnedNodeId, "")
misMatchedNodeUrl := u
misMatchedNodeUrl.Host = misMatchedNodeUrl.Host + "mis-match"
returnedNodeId, err = client.getNodeIdByUrl(misMatchedNodeUrl)
assert.NotNil(t, err)
assert.Equal(t, returnedNodeId, "")
}
|
General insights on obstacles to dog vaccination in Chad on community and institutional level Domestic dogs are responsible for 95% of all human rabies cases worldwide and continue to be the main reservoir for this fatal virus in African and Asian countries. Interrupting the spread of the disease in the domestic dog population is therefore necessary for long-term, sustainable rabies control. Chad has been recognized as a rabies-endemic country since 1961, but no national control strategy is in place to date and dog vaccination coverage is very low. This qualitative, descriptive study aims to describe the main barriers to dog vaccination on both the community and the institutional level from a socio-anthropological point of view in Chad. The study was embedded in an overall project conducted from 2016 to 2018, to determine rabies burden and vaccine demand in West and Central Africa, funded by GAVI, the vaccine alliance. Data collection was conducted on the occasion of the project's closing workshops with stakeholders organized between August to September 2018 in the four project areas: Logone Occidental, Ouadda, Hadjer Lamis and Chari Baguirmi. We conducted interviews and focus group discussions (FGD) among veterinary officers and dog owners. Participants were selected purposively based on their place of residence (dog owners) or work place (veterinary officers) and their previous contact with the project through reporting (dog owner) or management (veterinary officers) of a suspect dog rabies case. In each region, one FGD was organized with dog owners, and one FGD with heads of veterinary posts. At the end of the FGDs, a few participants were randomly selected for interviews. In addition, in each region an interview was conducted with the head of the livestock sector, the chief district medical officers and the head of a civil society association. The identified barriers to dog vaccination access are grouped into three main aspects: the economic, the socio-cultural and the institutional level. Economic constraints encountered relate to the cost of the vaccine itself and the expenses for transporting the dogs to the vaccination site. The cultural belief that the vaccine will have an impact on the therapeutic properties of dog meat for consumers (observed in Southern Chad), and the fact that dogs are considered impure animals in Muslim faith, which prohibits handling of dogs, are obstacles identified on the sociocultural level. At the institutional level, the unavailability of vaccines in veterinary services, the lack of communication about the law on dog vaccination, the absence of rabies in the training curricula of veterinary agents, and the lack of intersectoral collaboration limit vaccination coverage. In order to improve vaccination coverage and rabies surveillance with a view to eradicate rabies by 2030, communication strategies that are adapted to the context and that take cultural obstacles into account must be put in place in a synergy of interdisciplinary action. In addition, factors such as affordability, geographical access and availability of dog rabies vaccines needs to be addressed throughout the country. Although our study design did not allow a detailed analysis of obstacles related to socio-economic level, gender and age the broad insights gained can provide general guidance for future interventions in Chad and similar countries. Domestic dogs are responsible for % of all human rabies cases worldwide and continue to be the main reservoir for this fatal virus in African and Asian countries. Interrupting the spread of the disease in the domestic dog population is therefore necessary for long-term, sustainable rabies control. Chad has been recognized as a rabies-endemic country since, but no national control strategy is in place to date and dog vaccination coverage is very low. This qualitative, descriptive study aims to describe the main barriers to dog vaccination on both the community and the institutional level from a socio-anthropological point of view in Chad. The study was embedded in an overall project conducted from to, to determine rabies burden and vaccine demand in West and Central Africa, funded by GAVI, the vaccine alliance. Data collection was conducted on the occasion of the project's closing workshops with stakeholders organized between August to September in the four ( ) project areas: Logone Occidental, Ouadda, Hadjer Lamis and Chari Baguirmi. We conducted interviews and focus group discussions (FGD) among veterinary o cers and dog owners. Participants were selected purposively based on their place of residence (dog owners) or work place (veterinary o cers) and their previous contact with the project through reporting (dog owner) or management (veterinary o cers) of a suspect dog rabies case. In each region, one FGD was organized with dog owners, and one FGD with heads of veterinary posts. At the end of the FGDs, a few participants were randomly selected for interviews. In addition, in each region an interview was conducted with the head of the livestock sector, the chief district medical o cers and the head of a civil society association. The identified barriers to dog vaccination access are grouped into three main aspects: the economic, the socio-cultural and the institutional level. Economic constraints encountered relate to the cost of the vaccine itself and the expenses for transporting the dogs to the vaccination site. The cultural belief that the vaccine will have an impact on the therapeutic properties of dog meat for consumers (observed in Southern Chad), and the fact that dogs are considered impure animals in Muslim faith, which prohibits handling of dogs, are obstacles Introduction Rabies, a lethal zoonotic disease, is mostly transmitted to humans by infected dogs and mainly affects marginalized communities in Africa and Asia. In many low-income countries, the classical rabies virus (RABV) is endemically present in dog populations. At the same time most of the dogs are free roaming leading to frequent human to dog contact. Humans usually get infected accidentally through a bite, scratch, or lick of excoriated skin by a rabid animal and tragically, children are disproportionally affected. The disease is almost invariably fatal once clinical signs appear. Timely administration of rabies vaccine to bite victims can prevent the onset of rabies, but this measure called Post-Exposure-Prophylaxis (PEP) is very costly, hard to access for marginalized communities and most importantly does not reduce overall exposure risk for those communities. With 25,000 deaths per year, Africa is one of the continents most affected by rabies. The recognized most cost-effective control measure that also holds the potential for elimination of dog-mediated human rabies is large-scale vaccination of dogs. Rabies control became a flagship of the One Health approach because it illustrates very well the added value of intervention in animals to improve health not only in animals but for humans and the ecosystem overall, which is the core idea behind this concept. The feasibility of dog vaccination to reduce the burden of human rabies is proven by the success of this intervention to eliminate canine rabies from large parts of Latin America and by many successful local interventions in Africa and Asia. However, the same studies point out the need for sustained control measures, the necessity for locally adapted methods and the importance of accurate sensitization through local awareness campaigns. For example in the case of N'Djamena, the capital city of Chad, two consecutive mass vaccination campaigns were sufficient to temporarily eliminate rabies from the city, but after the interventions, rabies was reintroduced from the rural area. During the same vaccination intervention, considerable differences were noted between the achieved vaccination coverage in different quarters of the town depending on the socioeconomic and cultural context. In a similar intervention in Bamako, Mali, vaccination coverage did not achieve the level needed to interrupt rabies transmission in the dog population. This indicates that sociocultural factors determine the accessibility of dogs to vaccination because they determine adequacy and acceptance of the intervention measures, as described by Obrist et al.. Local economic and socio-cultural context also determines the most effective tools and strategies for awareness raising. Therefore, it is important to study human attitudes and practices toward dogs and rabies in order to better plan and undertake dog vaccination campaigns. To achieve sustainability, dog vaccination campaigns need to be institutionalized and taken over by the governmental veterinary services. Therefore, institutional factors also influence the long-term success of vaccination interventions. Finally, accessibility of dog vaccination is heavily impacted by affordability, especially in the context of livelihood insecurity faced by many dog owners in endemic areas. In Chad, as in many other low-income countries, the accessibility of health facilities is often challenging which has a large impact on access to PEP. At the same time incidence of rabies in the dog population is observed to be high in areas where surveillance is implemented. Therefore, it would be all the more important to decrease exposure risk through dog vaccination. However, veterinary services are even more neglected than human health services and are mostly Dog keeping households are widespread in Chad, and dogs are used for many purposes, ranging from protection to hunting and breeding. Dog ownership is most common in the predominantly Christian southern regions of the country, but is also observed in Muslim areas. According to Anyiam et al., Chad's dog population is estimated at 1,205,361 dogs. Only around 10% of the overall dog population in Chad are stray (ownerless) dogs, but most of the owned dogs roam freely due to lack of means to adequately feed the animals. Dogs supplement their diet from food scraps in the environment such as human feces, wildlife, slaughter offal, and other waste. This creates a lot of contact with people, especially children, who are often unsupervised. Challenges are noted on many levels and show that rabies is a topic that deserves special attention. This paper aims to contribute to the knowledge basis for future planning of control programs in Chad through identification of the socio-economic, socio-cultural and institutional barriers that limit access to dog vaccination in the various cultural contexts of the country. These are very diverse and range from regions dominated by sedentary farmers with a Christian background to regions with a predominantly pastoralist population and a mainly Muslim rooted culture. Study background The qualitative study presented in this paper is part of a large-scale research project implemented in Chad, Cte d'Ivoire and Mali, to estimate the burden of rabies and vaccine demand in West and Central Africa, funded by GAVI, the vaccine alliance (GAVI-project). In Chad, this research project lasted from January 2016 to September 2018 and was implemented in three study areas belonging to four administrative provinces ( Figure 1). The provinces were selected based on their various demographic and socio-cultural characteristics to cover the range of backgrounds in the country. The quantitative studies undertaken during the project are already published in different papers. They included a household survey on bite occurrence, a health facility-based study on reporting of bite cases, PEP access and follow-up and extension of animal surveillance to the project areas. The quantitative studies combined revealed a high occurrence of dog rabies in Chad and in consequence, a high dog to human transmission risk that calls for urgent control measures such as dog vaccination. At the same time, the study team members encountered differences in attitudes toward dogs and practices for rabies prevention across the study areas that might hamper future control interventions, in particular dog vaccination. Therefore, we identified the need to investigate on these differences through a qualitative study, which for the first time, would provide some broad insights on the influence of socio-cultural factors on rabies control in Chad. Data collection for the study was conducted during the closing workshops of the project conducted for each study area. The study's aim is to gain a general overview of obstacles to dog vaccination against rabies in Chad combining the perspectives of different cultural and socio-economic contexts on the population/client side with institutional perspectives of the dog vaccination service provider side (in our case governmental veterinary services). It is a socio-anthropological study, based on a qualitative approach with focus group discussions (FGD) and individual semi-structured interviews. Such a research design allows gaining real life examples of how dogs are perceived and treated, the practices the population and animal health professionals. /fvets.. adopt regarding dogs in the context of rabies prevention as well as the underlying institutional factors influencing these practices. A detailed analysis of different socio-demographic characteristics, gendered analysis at household level or a deeper investigation into the dynamics at play in government institutions were beyond the scope of this study. Description of study areas The first study area includes the province Logone Occidentale, with the city of Moundou, the economic capital and second largest town of Chad ( Figure 1). Logone Occidentale is the smallest province in southwestern Chad and is populated mostly by Christians and animist communities. Outside of the regional capital in the rural areas, people live mostly on small-scale farming. The population of the Logone Occidentale province is estimated at 790,694 inhabitants with a human density of 88.68 inhabitants per square kilometer. The second zone covers the sparsely populated Ouadda region in the northeast, with a predominantly Muslim population. Its regional capital is Abch situated very close to the Sudanese border in the northeast of Chad ( Figure 1). In 2009, Ouadda had a population of over 700,000 with a density of 24 inhabitants per square kilometer. In the vast rural areas of this province, people are mainly pastoralists. The third study area is defined by a 100-kilometer radius around the capital city of N'Djamena situated in the central-west of the country. It includes parts of the province Chari Baguirmi to the south of the capital, and parts of the province Hadjer Lamis to the north of the capital ( Figure 1). These two administrative provinces have a culturally mixed population of sedentary farmers and pastoralists. The population density is about 18 inhabitants per square kilometer. The study areas were broadly divided into urban and rural strata: The provincial capitals (Moundou and Abch) are considered urban and the rest of the respective province is considered rural. The study area covering parts of Chari Baguirmi and Hadjer Lamis was considered rural. Target population, recruitment, and participants' background Based on the experience form the various quantitative studies of the GAVI project, we identified the following stakeholder groups to be interviewed: Community level: -Dog owners -Heads of the regional civil society association Institutional level -veterinary officers (heads of veterinary posts) -administrative authorities of the study regions (heads of district veterinary delegations, heads of regional livestock sectors and chief medical district officers). For the purpose of the study a dog owner is defined as a person that keeps one or more dogs at his household for which he provides care to some extent (food, shelter etc.) and to which he attributes a role (watchdog, guard dog, etc.). Dog owners were selected in a purposive manner with the help of veterinary officers. Most of them had no formal employment and were farmers, herders, informal traders, housewives or students. The only selection criteria for the institutional representatives was the prior participation in the extended animal surveillance and bite reporting activities of the overall GAVI-project. Public veterinary officers in Chad most often do not have a university degree in veterinary science, but are graduated livestock technicians. Veterinary officers and dog owners came from various districts in rural and urban settings of the respective regions. In total, the study gathered 42 participants in 6 different FGDs and conducted 21 individual interviews. The discussion points of the FGDs and the interview guides are provided in the Supplementary Document (S1). Two thirds of the institutional representatives were Muslims and the other third Christians. Study participants representing the population and dog owners included 13 Christians and 11 Muslim. It is important to note that local belief systems based on a rich ethnic background persist in the population, even if people go to church or pray at the mosque. Furthermore, formal education with a Francophone heritage add to the cultural complexity. As mentioned above the aim of the study was not to analyze the different socio-cultural profiles in detail, but to identify major trends about beliefs and practices concerning dogs, their vaccination, rabies and institutional shortcomings. Considering the rather broad level of analysis that we aimed at (rather than depth), we did not pay particular attention to gender, neither age (see Table 1 below). However, both demographic characteristics are mentioned to provide some information to the reader about the positionality of the different quotes. Three languages were used depending on the region and characteristics of the interviewees to allow everyone to participate in the discussion. French was used to talk to service providers in all regions. To talk to dog owners in the Logone Occidental region in southern Chad, Ngambay was used, whereas in rural N'Djamena and the Ouadda region, Arabic was used in interviews and FGDs. In a society that values seniority, the constitutions of groups in relation to age always has an influence on how participants of FGD express themselves. Therefore, individual interviews were added to complement the data Frontiers in Veterinary Science frontiersin.org. /fvets.. sources (triangulation). Men and women were mixed in FGDs of dog owners. This choice was taken based on the focus on economic, religio-social and institutional factors (rather than gender). For the client vs. provider perspective adopted in this article, it was crucial not to mix service providers with the client (dog owner) side, as this may have limited dog owners from expressing their views on the service received out of fear of disadvantages in case of future consultations. Before the discussions and interviews, each participant signed an informed written consent. Table 1 describes the number of FGD and interviews by study site and the study participants' backgrounds. Data collection techniques and tools This qualitative data collection was conducted on the occasion of the above mentioned stakeholder workshop, during which the results of the quantitative studies undertaken during the GAVI-project were shared. The workshops were held between August to September 2018 distributed as follows: from August 22 to 23, 2018 in Abch, from August 27 to 28, 2018 in Moundou and on September 10, 2018 in N'Djamena. Data were collected by FGDs and by direct semi-structured interviews using an interview guide (S1). With dog owners, veterinary officers and heads of livestock delegations both indepth interviews and FGDs were conducted. With heads of civil society associations, district medical officers and heads of livestock sectors only individual interviews were conducted. The FGDs were held separately for community representatives and the institutional representatives (see Table 1). This allows to juxtapose perspectives on dog vaccination from the client's point of view (the dog owners) with the institutional point of view, as well as to compare formal rules with actual vaccination practices. There were seven participants per FGD. In average, the FGD lasted about 45 min. The interview guide was structured along the following thematic aspects: Economic and socio-cultural factors affecting access to dog vaccination and institutional factors that hinder access to dog vaccination. The interviews lasted about 30 minutes each. Data processing and analysis With the participants from the institutional level, interviews were conducted in French. With the dog owners, Arabic and Sara was used, in addition to French. The lead author who did the field research speaks all three languages fluently. The data collected through the FGDs and individual interviews were translated into French if needed and transcribed and entered into Word version 2010 and then processed using MAXQDA version 2018 software. The data was analyzed using content analysis. Coding was done inductively. The text broken down into thematic paragraphs and coded with the help of the software. The first and second author of this paper were members of the local GAVI-project team and as such involved on all levels of the quantitative data collection: Household survey, bite case reporting and animal rabies case surveillance. In addition, the main author was responsible for the free hotline established during the project to facilitate communication between the animal health and human health workers and reporting of bites or animal rabies incidents by the public. Together with the main author's participation in prior rabies research studies in Chad, the presence in the field and close contact with both the community and the institutions during the GAVIproject period has allowed him to gain the needed experience to appropriately interpret the FGDs and interviews. Ethical considerations Ethical approval for the overall study, covering research activities in the three GAVI-project countries (Mali, Cte Results The data presented here address the obstacles to dog vaccination in Logone Occidentale (LO) province, in Ouaddai (O) province and rural Ndjamena (Chari Baguirmi (CB) and Hadjer-Lamis (HL) provinces) of Chad. It is structured in two sections: The first section presents the economic and sociocultural factors that constitute obstacles to dog vaccination on the population side, and the second point deals with the institutional factors that prevent dogs from being vaccinated on the provider/veterinary side. At the end of the result section, we summarize the topics discussed in a table to give a general overview ( Table 2). Economic and socio-cultural factors a ecting access to dog vaccination Economic and sociocultural factors that hinder dog vaccination include: the high cost of the vaccine; Dimension Variables Obstacles Propositions Economic Cost of the vaccine The cost of the animal rabies vaccine varies between 10,000 and 15,000 CFA francs (15 to 23 Euros) depending on the locality in Chad. The majority of respondents found the price of the vaccine very expensive. With a Gross Domestic Product (GDP) of less than one Euro (<500 CFA francs) per day (https://www.data.worldbank.org/country/chad), most people were unable to pay for vaccines. Respondents from all focus groups in the different regions said that the high cost and local unavailability of the vaccine prevent them from vaccinating their dogs. Some study participants even say: "We don't have money to pay for bread and you ask us to pay for vaccine that is expensive for dog only." (Dog owner, Christian, W, 41, CB) "The vaccine costs are too much, the state must give it for free. We want to vaccinate our dogs well, but with this price, we can't." Geographical accessibility of the vaccine The distance between homes and veterinary facilities that might provide vaccine is a major concern for our study participants. In all four regions of the study, rabies vaccines are stored in the regional capitals (Moundou, Abch, Massakory, and Massenya), because of the lack of electricity for storage at veterinary district levels. In Logone Occidental, the distance between the district veterinary office and the provincial livestock delegation that manages the vaccines is between 60 and 80 km. In Ouadda, it is between 150 and 200 km. The one of Chari-Baguirmi is in the range of 80-100 km away and in Hadjer Lamis, the provincial delegation in Massakory is located between 100 and 150 km from the district offices of the region. Thus, when in need, people are obliged to travel at least 60 km to have their animals vaccinated and some up to 200 km. The average cost of a single trip for transportation between the districts and the regional livestock delegation is 3,000 to 6,000 FCFA "It must be recognized that the rabies vaccines are only available in Moundou. And we who are in the other localities, do not have the possibility to keep them because we do not have the electricity to keep them. When someone wants to vaccinate their dog, they are directed to Moundou and because of the distance, they refuse to go." (Veterinary officer, Christian, M, 58, LO) "We have problems with vaccine supply. When it rains, the road is cut by rainwater and we are isolated. It takes 3 to 4 months for our roads to be cleared. Under these conditions, access to vaccine is difficult" (Veterinary officer, Muslim, M, 46, HL) Our district is very far from the regional hospital in Abch and sometimes in Abch itself, we cannot find vaccine for the dogs. If needed, we are sent all the way to Ndjamena, more than 1,000 kilometers to get the vaccines." ( Dog owner, Muslim, M, 39, O) During the focus groups, respondents expressed themselves in these terms: "There are no vaccines in the veterinary station at our home in Abdi. If someone wants to vaccinate their dog, we send them to Abeche. But as the journey is long, the owners of the dogs refuse to go. We have no way to store the vaccines here." (Dog owner, Muslim, M, 53, O) "We can't transport the dogs more than 150 kilometers for vaccination. One has to send the vaccines to the districts." Means of transporting dogs to the vaccination post One of the difficulties raised by our respondents is the lack of means to transport the dog to the vaccination site. In this regard, about three quarters of the respondents stated that it is impossible to drag the dog on foot for miles to vaccinate it. Since most of the dogs are free roaming taking the dog on foot for vaccination entail the risks for dogto-dog aggression. In addition, there is the risk that the dog might aggress other people in the street. The cost of transporting dogs in a public vehicle (between 2,000 and 3,000 CFA francs, or 3 to 5 Euros) makes it difficult to travel longer distances to access the vaccine. Furthermore, in the case of public transport, some truck owners refuse to transport dogs, because according to their belief the dog is an animal of misfortune whose presence in the truck can cause accidents. Some of the comments made in the interview were: Frontiers in Veterinary Science frontiersin.org. /fvets.. "When you bring your dog somewhere, the other dogs chase you and the dogs fight." (Dog owner, Christian, M, 54, HL) "The dog is a complicated animal. If you take it somewhere, the other dogs will follow you and fight, or even bite you. If you take him in the truck, he attacks the other passengers. That's why we can't get our dogs vaccinated." (Dog owner and head of social civil society association, Christian, M, 31, LO) "I would like to vaccinate my dog, but I do not know how to transport it to the vaccination site. If the vaccine is in our district, we will get our dogs vaccinated. But we have to go all the way to Moundou. We don't know how to transport our dogs." (Dog owner, Muslim, W, 39, HL) "Transporting dogs to the vaccination site is always a problem in our communities. We need to organize door-todoor vaccination. We don't know how to transport the dogs to the vaccination ." (Dog owner, Muslim, M, 46, O) "We have no means of transporting the dogs to Ndjamena for vaccination. And the vehicle owners refuse to take the dogs, because they will cause an accident." (Dog owner, Muslim, M, 60, CB) Social value and perception of the dog In addition to its value as a guardian and pet, many male respondents of the Logone Occidental, region of southern Chad mentioned that they eat dogs due to its ascribed therapeutic properties. This cultural practice of dog meat consumption persists in Christian communities in southern Chad and is not practiced among Muslims. Several research participants mentioned that the vaccination of dogs could destroy the virtues contained in the dog. The statements about this specific function and perception of the dog are as follows: "The meat of the dog is a medicine for us. It preserves against bad spells, evil spirits and rejuvenates the cells of the body." (Dog owner, Christian, M, 59, LO) "We raise the dog to eat. When you hear the dog howling at night like a wolf, it means it has seen a spirit. So we eat the dog's meat to protect ourselves from evil spirits. But when you vaccinate the dog, it loses all these virtues and it has no longer any effect." (Dog owner, youth Association Leader, Christian, M, 43, LO). "The dog is used for hunting in our country. But when it dies, we make medicine with its flesh against disease. That's why we don't want to vaccinate it." (Dog owner, Christian, M, 39, CB) To the contrary, research participants with a predominantly Muslim background in the Ouadda region, consider the dog as an impure animal that should not be approached according to the religious and cultural practices. According to our study participants, even if a dog owner is willing to handle the dog and bring it to a vaccination location, the community's negative perception of someone handling a dog is an obstacle for owners to bring their dogs to vaccination. "The dog is not appreciated in our community. Those who approach the dog are also hated. I can't take my dog to vaccination because of the community's view." (Dog owner, Muslim, M, 41, O). "At home, if you are seen handling the dog or touching the dog, people do not greet you, and do not eat with you in the same dish. You are considered dirty, unclean. We don't accept the dog near us. Even if we raise it for our own safety, it stays in the front yard and we give it food, but it does not come near the family because it is too dirty." Institutional factors that hinder access to dog vaccination This section focuses on institutional factors that limit access to vaccination. These include the absence of vaccines at veterinary posts, lack of communication about the Animal Health Law, lack of awareness of rabies among veterinary officers, and lack of intersectoral collaboration. Unavailability of vaccines at veterinary posts When asked if the vaccine is available at the veterinary posts, more than half of our respondents said that there is no vaccine at the posts, which confirms the experiences shared by the dog owners. In the district of Moundou, which is the vaccine storage center, cases of vaccine shortages have been noted. In this regard, the shortages are noted during certain periods as a result of lacking supply chain management, as the respondents stated during the interviews: "When we order the vaccine, it takes time to reach us and this can create the shortages." (Veterinary officer, Muslim, M, 34, O) "We looked for the vaccine in all the districts of the region, but we did not find it. We are told that only the district of Moundou has the vaccine. I went there but they tell me there is a break" (Dog owner, Christian, M, 51, LO) The absence of rabies vaccines at local veterinary posts results in the barriers to accessing dog vaccination Lack of communication about the dog vaccination law Regarding knowledge of the law that requires owners to vaccinate their pets and report cases of mandatory rabies, almost all were unaware of it. The interviews yielded the following statements: "There is no law for dog vaccination in this country." (Dog owner, Muslim, W, 43, O) "Nobody told us that there is a law that obliges dog owners to vaccinate them. But when your dog bites someone and if it dies, you are arrested in prison." (Head of civil society association, Christian, M, 55, LO) "Although this law on the vaccination of dogs exists but it needs to be popularized to the public. We don't have the means to raise awareness." (Head of district veterinary delegation, Christian, M, 39,CB) We note from the opinion of the respondents that the majority is not informed of the law on dog vaccination and mandatory reporting of suspected animal bites. This situation is due to the lack of communication and awareness of the population by the authorities in charge of animal health and rabies. Absence of rabies in the training curricula of veterinary o cers The data collected from our respondents regarding their knowledge and practice of rabies reveal that animal health professionals do not have a good understanding of rabies. The majority of them stated that rabies was not part of their training, as some of them testified: "In our training, we have never heard of rabies. We do not know the manifestations or clinical symptoms of this disease in dogs." (Veterinary officer, Christian, M, 48, LO) "Rabies is considered a neglected disease by our authorities and no one cares about this disease. Yet, it kills many children. The state must develop a plan to fight this disease." (Head of livestock sector, Muslim, M, 57, HL) According to them, this lack of training in rabies control is due to the negligence of the authorities in charge of animal health. The lack of knowledge of rabies by veterinary officers does not allow them to organize an awareness or communication campaign about rabies. In order to effectively communicate the danger of rabies to the population, agents must be well-trained about the subject. The absence of this training result in an access barrier related to lacking knowledge about the disease in the community as a whole. Lack of intersectoral collaboration Another important factor for access to dog vaccination is collaboration between human and animal health services. According to the data collected, the majority of our respondents stated that there is no collaboration between these two sectors: "We don't have collaboration as such with the human health sector. Sometimes, we meet at workshops but afterwards, each one goes its own way." (Veterinary officer, Muslim, M, 49, LO) "Since we have been practicing, we have no relationship with human health workers. Everyone evolves on their own and in case of rabies, it is difficult for us to communicate." (Head of livestock sector, Christian, M, 38, CB) "Collaboration with human health was non-existent. It is from the GAVI study that we had collaboration in the monitoring and diagnosis of the biting animal." (Veterinary officer, Christian, M, 43, LO) Indeed, when there is a case of rabies, the two services must work together to adequately treat the victim, but also to follow up on the bitten animal to stop the spread of rabies. The lack of collaboration also results in inadequate notification of cases and in consequence, the burden of rabies is underestimated and authorities do not perceive the need for a national action plan. Discussion The studies objective was to combine perspectives on the community and institutional level to gain a first overview of where some of the main obstacles to dog vaccination in Chad might lie. The results reveal several economic, sociocultural and institutional factors that prevent access to dog vaccination in Chad. Some of them have been observed in other studies, but to our knowledge this is the first qualitative study that brings together insights from both the population and the service provider level. These insights will be valuable to overcome barriers to vaccination in future planning of rabies control measures. Like for other goods, access to dog vaccination is subject to the dynamics between availability and demand. Both positive and negative factors associated to dog vaccination on the community level thus influence the factors on the institutional level and vice versa, forming an access cycle. If for example animal health professionals are not well-trained on rabies prevention and control, they are not able to provide adequate sensitization to the public to increase awareness among the community and hence demand by dog owners will remain low. On the other hand low purchasing. power and limited geographical access on the community level results in low demand by dog owners and in turn, availability will remain low on the institutional level due to the unprofitability of providing dog vaccination. These examples show that the combined perspective allows us to better understand drivers or barriers influencing this access cycle. In our study we have only looked at the provision of vaccine in public veterinary facilities, but we assume that the interplay between availability and demand will be even more negatively affect in the private veterinary sector due to the higher need for profitability. In Senegal for example the public sector funded through the government provides livestock vaccine free of charge and farmers pay only a service fee, whereas in the private distribution system, herders bear the full cost of the vaccine. The study took place in four provinces of Chad that together represent the two major religio-cultural backgrounds. Moreover, the study covered the rural and urban context. The results of this study can thus provide guidance to implementation of a rabies control program at the national level. In Chadian communities, dogs are kept for a variety of reasons, ranging from protection of premises and livestock, to hunting and even consumption. Accordingly, the perception and role of the dog varies from one community to another based on the ethno-cultural and religious context. Despite the general picture, we are able to provide by looking at the two main religio-cultural contexts, our study has limitations. The breadth (sample size) and depth (detail) of data did not allow us to deepen the analysis of perceptions and practices that would enable us to distinguish between different ethno-linguistic groups, socio-demographic and socio-economic characteristics. Such a study could be a next step helping to design locally tailored measures to increase acceptability of interventions. Nonetheless, the main access barriers identified here can already be useful to prepare a general national action plan for rabies control. A first issue to address would be the cost of the vaccine. Chad remains one of the poorest countries in the world with a Human Development Index (HDI) of 0.401 (187th out of 189 countries). The majority of study participants representing the population have low monthly incomes (<60,000 CFA francs or 90 Euros) and have no formal employment, with low purchasing power. In N'Djamena, a free mass dog vaccination campaign achieved the required level of 70% coverage, whereas a previous campaign in the same setting that charged around 4 USD for vaccinating a dog achieved only a coverage of 24%. Studies from Uganda and Peru also show that poverty influences not only vaccination coverage, but also dog keeping practices. Another previous study in Chad shows that lack of financial means for vaccination or to pay for PEP in a case of a bite even influences the decision to raise a dog. Indeed, when a rabid dog bites individuals, it is the dog owner's responsibility to take care of these victims regardless of the number of victims. Given the unavailability and cost of human rabies vaccine, some dog owners end up in prison, or social ties with their neighbors or the community are weakened after a dog bite incident, because they are unable to pay for PEP . Risks and cost related to transport of a dog to distant veterinary facilities with vaccine in stock highlight the need for localized approaches to improve availability of services. Distance and transport were also identified to be major barriers for dog vaccination in Ethiopia and Tanzania. Free public rabies vaccine and bringing veterinary posts closer to communities could improve motivation of dog owners to vaccinate their animal, but our results also show that such measures alone might not be sufficient due to lack of disease awareness and socio-cultural barriers observed. A study in Ethiopia found that a dog owner's knowledge of rabies is a significant predictor of the level of intention to vaccinate a dog. A finding that is supported by a study in Cte d'Ivoire reporting that low vaccine access appears to be influenced by ignorance and negligence. Overall these findings are not new since already back in 2010 a study conducted in several developing countries, where canine rabies is endemic, the most common reasons for dog owners not to vaccinate their dogs are lack of knowledge about the disease burden and prevention, vaccination costs, and ease of catching dogs. In fact, the neglect of rabies in sub-Saharan Africa is largely attributed to a lack of recognition of the infection as a significant public health threat. Our qualitative data confirm the hypothesis derived from quantitative data on vaccine coverage and dog population estimates in Chad, that ethnic beliefs influence dog breeding/keeping in some localities. Some respondents believe that the consumption of dog meat protects them against evil spirits and helps to cure certain diseases. This power is according to them destroyed by the vaccine and therefore this aspect constitutes an obstacle to rabies control. The Christian religion considers the dog as a companion that deserves care and affection. According to Akakpo, a Christian priest points out that "on the day of the last judgment, all the animals rescued by your care will come to testify in your favor." In the Muslim communities, dogs are less appreciated. This conception is also reported in Senegal. Leye had stated that in Senegal, "it is common to hear that the Muslim should not raise a dog, because it is an impure animal." Indeed, some Hadiths of Islam cited by Migan teach the following: "The angel does not enter the room where there is a dog"; "The black dog is a Satan (demon)"; "If the dog licks the dish, it must be washed 6 times in natural water and the 7th time with soap." It should be noted that in the Muslim community in Chad, the dog is called "khleb" which means (impure, dirty, hated, smells bad) to the point where someone who is hated by society is called "wadam khleb" which translated means "damned dog." This concept leads the. /fvets.. community to chase dogs off their premises and even keeps a dog, it is held in the front yard to ensure their safety, but the dogs are not allowed in the house. Such dogs that are not close to their owners and not used to be handled are difficult to reach during vaccination campaigns. In Bamako, Mali, for example, the inability to handle aggressive dogs was an important reason for non-participation in a centralized vaccination campaign. However, the situation is paradoxical in Pikine (a suburb of Dakar in Senegal) where the Muslim community is the one that owns most dogs. At a closer look the topic is more complex that commonly thought. According to cited hadiths in Migan, the Prophet Mohammed also said: "the best dog is the one who guards the herd and the house. He also promised paradise to the believer who quenched a dog's thirst by giving it a drink from his shoe." In any case, in spite of religious or ethnic prohibitions, confronted with the problem of insecurity, in the cities and the countryside alike, people with different beliefs decide to keep a dog to ensure their safety. An element that we were unfortunately not able to address with our study, is the effect of gender-dynamics on dog vaccination access. We did not particularly pay attention to gender balance during recruitment of participants and the fact that FGD were mixed certainly had an influence on the way women participated. Two new studies highlight the importance of adopting a gender sensitive approach when identifying obstacles to vaccination in the field of livestock vaccines. The role of managing and controlling livestock diseases in these communities was culturally ascribed to men. This is also the case for dog keeping in Chad and the decision power on whether to vaccinate or not lies almost inclusively in the hands of the male representative of the household. Moreover, dog meat consumption is limited to men (main author's experience). Even in cases where women are the primary caretakers, for example in the case of poultry farming in Senegal, there are cultural and social barriers to their ability to access vaccination services. Similarly, children are most often those that can handle their household dogs very well to bring to vaccination posts, but they depend on the decision of their parent. Further, more fine-grained studies of the social dynamics related to age and gender at household level would certainly provide valuable insight into gender or age related differences to access. Obstacles also result from the low involvement of the authorities in dog vaccination campaigns. The majority of our respondents cited ignorance of the law on health police organizing dog vaccination (Law No. 04-009 2004-05-19 PR of 19 May 2004). According to this law, dog vaccination is mandatory in Chad, and sanctions are provided for all those who do not respect this law. The lack of knowledge of the law by the majority of owners is explained by the lack of awareness in the community, lack of knowledge of animal and human health providers and low priorization of rabies control by concerned authorities resulting from a virtually absent rabies surveillance system. Results from a global study on rabies surveillance shows that Chad is not an exception in this regard. In fact, a very recent article reflecting on the factors hampering advances on the road to zero dog mediated human rabies cases by 2030 identified these very obstacles described here on the institutional and socio-cultural level. Intersectoral collaboration between human health and veterinary workers is a key factor in rabies control. Lack of collaboration and lack of expertise in rabies control is a challenge for the organization of vaccination campaigns. A Knowledge Attitude and Practices (KAP) study in human and veterinary health workers conducted during the GAVI-project revealed a considerable lack of knowledge about rabies and recommended treatment among the participants and confirms the negligence of the rabies topic by the training curricula of both sectors. The need for cross-sectoral collaboration of actors in a synergistic transdisciplinary way highlights the usefulness of a "One Health" approach for rabies control. This approach gives an important role to animal health professionals and animal owners as well as to people in regular contact with domestic and wild fauna and the environment. To be effective, control actions must address all levels of society, all political, religious or associative groups. Although it primarily concerns the Ministries of Health and Agriculture or Livestock, rabies control also requires the involvement of the Ministries of the Interior, Education and Communication, and Research. All stakeholders, including universities, learned societies and associations of physicians, pharmacists and animal health professionals, all schools, the media, local authorities and religious groups, and even neighborhood communities, must be sensitized and involved in the fight against rabies if the disease is to be defeated in the near future. Conclusion Socio-cultural and institutional factors influence a dogs' access to vaccination. Therefore, these factors, which may constitute barriers to rabies control, must be addressed and eliminated through context-specific communication strategies to improve vaccination and surveillance coverage. In Chad, this study demonstrated three major problems that impede dog vaccination. These obstacles are economic (cost of vaccines), sociocultural (belief of loss of valued characteristics of dog meat in case of vaccination on the one hand and stigmatization of dogs on the other), and institutional (unavailability of vaccine and lack of knowledge and communication of the law on dog vaccination). To achieve efficient control and ultimately elimination of rabies the collaboration of several actors intervening in the field of human and animal health, safety, education, communication, /fvets.. research, environment, etc. is crucial. These actors need to have sufficient resources to respond to the existing demand for dog vaccine but also to engage in awareness raising to increase demand by dog owners. Data availability statement The raw data supporting the conclusions of this article will be made available by the authors, without undue reservation. Ethics statement The studies involving human participants were reviewed and approved by Ethics Committee of Northern and Central Switzerland (EKNZ). Written informed consent for participation was not required for this study in accordance with the national legislation and the institutional requirements. Author contributions NM: sociologist, study design, data collection and analysis, and manuscript writing. AM: health geographer, study codesign, data collection, and analysis support. DA: sociologist, methodological, and analysis support. PN: veterinarian and manuscript writing support. JZ: veterinarian, one health expert, and overall study PI. KH-T: sociologist, methodological support, and manuscript revision. ML: veterinarian and rabies expert, study coordination, data collection, supervision, and manuscript revision. All authors contributed to the article and approved the submitted version. Funding This research is part of a project conducted under the DELTAS Africa Initiative and the Global Vaccine Alliance (GAVI) learning agenda (Exhibit A-3 PP46311015A3C). Africa One-ASPIRE was funded by a consortium of donors including the African Academy of Sciences (AAS), the Alliance for Accelerated Scientific Excellence in Africa (AESA), the New Partnership for Africa's Development (NEPAD) Planning and Coordinating Agency, the Welcome Trust , and the UK government. |
Spatiotemporal Variations of Precipitation in the Southern Part of the Heihe River Basin (China), 19842014 : Local precipitation variations in the context of global warming are a hot topic in the climate change research community. Using daily precipitation data spanning from 1984 to 2014 from 25 meteorological stations, the spatiotemporal variations of precipitation were analyzed for the southern part of Heihe River Basin (HRB), which is the second-largest inland river basin in Northwest China. Linear trend analysis, empirical orthogonal function (EOF) analysis, the MannKendall test, and the moving t -test were employed in the study. Results showed that the regional annual precipitation exhibited an increasing trend with a slope of 13.1 mm per decade from 1984 to 2014. The increasing trend was detected at 21 sites and the first EOF illustrating the regional increasing trend explained 51.8% of the total variance. The increasing trend of annual precipitation was mainly due to an increase in autumn precipitation, while summer precipitation exhibited a weak declining trend and springwinter precipitation remained unchanged. Moreover, the increasing precipitation trend was mainly caused by an abrupt increase around 1997, when the global warming hiatus occurred. Through 1997, the atmospheric circulation and physical structure, such as vertical upward motion, vapor transmission, and its convergence changed to be more favorable for precipitation in autumn, but unfavorable for precipitation in summer in the HRB. Introduction As the only source of water in the inland watershed of an arid area, precipitation not only determines the categories and spatial distribution of natural ecosystem, but also plays a crucial role in agricultural yield, economic development, and societal statues. Therefore, studies on inland watersheds of arid areas are very valuable. The Heihe River, which is located in arid and semi-arid regions of Northwest China, is the second-largest inland river of China, with a length of 821 km and drainage area of 130,000 km 2. Geographic conditions exhibit large spatial differences within the Heihe River Basin (HRB). From south to north, there are three major geomorphological sub-regions. In the southern part, there is the Qilian Mountains, with remarkable vertical zonality. It is the water source of HRB and the elevation of the area ranges from 2000 m to 5500 m. In the middle, there is Hexi Corridor, where the elevation decreases from 2000 m to 1000 m. It is located between the Qilian Mountains and the Beishan Mountains. In the northern part, there is the Alxa high-plain. It is mainly occupied by bare Gobi, with a mean altitude of about 1000 m. The seasonal distribution of precipitation within one year was characterized by the maximum in summer, followed by spring and autumn, and minimum in winter. The economy, agriculture, and human living conditions in the HRB are highly dependent on the streamflow of the Heihe River. The shortage of water resources is the most pressing issue for the survival and development of the HRB. Hence, the precipitation variations in the HRB have been the subject of many studies. Previous studies have focused on the temporal and spatial variations of the precipitation and the factors determining precipitation in the HRB. For instance, Ding et al. reported that from 1959 to 1999 precipitation tended to increase across the entire HRB, but with differences between alpine and plains areas. It was also found that 1959-1999 was divided into two stages at 1980. Before that there was a strong increasing trend and thereafter precipitation tended to decrease markedly. Based on 10 meteorological stations within the HRB, Wang and Niu reported that precipitation exhibited a slightly increasing trend in the upstream mountain area and a decreasing trend for both the agricultural area in the middle reach and the desert area in the lower reach since 1950. By synthesizing the existing achievements, it was found that on the whole the annual average values of precipitation, which increased slightly during the last several decades, were still between 50 and 500 mm, and the distribution of precipitation was very uneven spatially, with more in the southeast and less in the northwest. However, almost all of these studies are based on station data from the last century, and most of them on no more than 10 sites. Due to the shortage of observed data in West China, the knowledge on the spatiotemporal variations of precipitation in the HRB may be limited. Additionally, to date, there are few studies investigating the changes in atmospheric circulations leading to precipitation in the HRB. From the late 1990s to the early 2010s, global mean surface temperature has increased more slowly than in the preceding two decades. In the wake of the release of the Working Group I contribution to the 5th Assessment Report of the Intergovernmental Panel on Climate Change (IPCC AR5), there has been much attention in the media and scientific community devoted to the so-called hiatus. In the context of global warming and its hiatus, the regional temperature of HRB exhibited strong warming from the 1960s to the 1990s and very weak warming, which is like the hiatus, from the late 1990s to the early 2010s. There have been many studies on local/regional precipitation variations as a response to climate warming. So far, the responses of regional/local climate within China to climate warming and its hiatus have been little studied. In this study, the spatial and temporal variations of precipitation over the HRB were examined using observational precipitation data from 25 meteorological stations from 1984 to 2014. In addition, the changes in atmospheric circulation leading to precipitation from 1984 to 2014 were investigated to understand the cause of precipitation changes. These results are expected to improve our understanding of the regional climate changes of HRB, especially in the context of the global warming hiatus. Data This study used rain gauge measurements of precipitation from meteorological stations. Following the stipulation that daily measurements from January 1984 to December 2014 had to be exactly consecutive without missing values, 25 meteorological stations within the HRB were selected (see Table 1 for details). Figure 1 shows that all stations were located in the southern part of the HRB, referring to the upper and middle reaches of the Heihe River. Such uneven distribution is mainly derived from the spatial variability of precipitation. Within the HRB, precipitation mostly occurs in the upper and middle reaches and there is very little precipitation in the lower reach. As a result, there are plenty of water resources and a high population in the upper and middle reaches, and less water and a lower population in the lower reach. Additionally, due to the complex terrain of the upper reach, there is a higher population in the middle reach than in the upper reach. So, as we can see, there are many meteorological stations in Hexi Corridor along the foothills of the Qilian Mountains. Meanwhile, the measurements from these meteorological stations generally represent the regional precipitation of HRB, since the precipitation mostly occurs in the upper and middle reaches. Table 1 for details). This study also used the reanalysis data from the European Centre for Medium-Range Weather Forecasts (ECMWF) Interim from 1984 to 2014. The monthly mean geopotential height, temperature, wind, vertical velocity, water vapor flux, and its divergence fields from the ECMWF Interim were analyzed. The ECMWF Interim reanalysis data has a spatial resolution of 1 (latitude) 1 (longitude). Methodology This study disclosed the spatiotemporal characters of precipitation variations in the southern part of the HRB from 1984 to 2014, and analyzed the potential physical mechanisms leading to the precipitation changes. The spatiotemporal character of the precipitation variations were disclosed through three aspects: linear trend of precipitation and its spatial variability; dominant spatiotemporal modes of precipitation variations; and abrupt change of precipitation. Firstly, with the least squares method, the linear trend of precipitation was fitted. This study disclosed the linear trend of precipitation amount and number of days with precipitation (NDP), respectively, for each station and for the mean of the 25 stations from 1984 to 2014. Here, the precipitation amount refers to the sum of daily precipitation within a certain period, such as annually, seasonally, or monthly. A day with precipitation was defined as daily precipitation greater than 0.1 mm. Second, to extract the dominant spatiotemporal modes of precipitation variations, we conducted an empirical orthogonal function (EOF) analysis. EOF analysis is actually principal component analysis (PCA), which operates on the spatial-temporal matrix. One station is treated as one variable and one time point is treated as one observation. In detail, before the EOF analysis, the annual precipitation series from 1984 to 2014 were normalized for each station. The normalized precipitation series from the 25 stations were grouped into a matrix P MN where M and N denote the station numbers and total years, respectively. Using Equation, the correlation coefficient matrix R MM was built. In the matrix R, the component r i,j records the correlation coefficient of annual precipitation between site i and site j. Next, with the Jacobian method, the eigenvalue V{v 1, v 2,..., v M } and eigenvectors E{e 1, e 2,..., e M } of the matrix R were calculated. The v i and E i(M1) denote the i-th eigenvalue and eigenvector, respectively. Next, using Equation, the time coefficient, namely PC, was calculated. Following the structure of P MN, in which spatial samples are row vectors, the components of e i corresponded to stations one by one. So, the e i could be expressed as a map that illustrates the spatial pattern of precipitation variations, namely EOF. The PC illustrates the temporal characters of EOF. Generally, the first several EOFs contain mostly variations of precipitation. The variation of each EOF could be quantified by the weighting coefficient, which was calculated by Equation. Therefore, only the first several EOF and PC were analyzed in practice. where P MN denotes the precipitation from M stations and N years; P T denotes the transposition of P MN and E denotes the eigenvectors matrix. where v i denotes the i-th eigenvalue. Third, to detect the abrupt changes of annual precipitation from 1984 to 2014, the Mann-Kendall (M-K) test and moving t-test were conducted. The sequential M-K test, as a non-parametric test, is widely used to detect the monotonic trend in a series of environmental data, climate data, and hydrological data. In detail, following Equation, an order serial S k was built using the original precipitation series. Then, following Equation, the serial UF k was built using the order serial S k. These definitions implicated that UF k represented the trend of temporal serial from begin to the time k. Next, we reversed the order of the P i series and calculated Equations and again. There would be a new UF k serial. Here, we defined UB k = −1 UF k and k = n − k + 1. The UB k represents the reverse trend of series from end to the time n − k + 1. As a result, the intersection points of UF k and UB k denote the reverse trend to the original precipitation series, and were hence treated as abrupt change points. where a ij = 1, P i > P j 0, P i < P j, P i is the precipitation in i year. where The moving t-test is actually the Student's t-test on two consecutive windows of precipitation series. By building t-statistic model, the significance of the differences of the mean values of two consecutive windows was tested. In this study, the window size was defined as five years and a confidence level of 0.05 was applied. Once the differences of the mean values of two consecutive windows were significant, abrupt change was considered to be occurring. Though the methodologies of the moving t-test and M-K test were different, the abrupt changes detected with the two methods may be comparable with each other, as the large trend reverse of UF and UB series generally co-occurs with a large change in mean values. Final, to understand the physical mechanisms leading to the precipitation changes, the changes of atmospheric circulation corresponding to the precipitation changes was investigated. According to the results of the M-K test and moving t-test, the study period of 1984-2014 was divided into two periods, 1984-1997 and 1998-2014. The differences of average geopotential height, temperature, and wind at a pressure level of 500 hPa between the two periods were analyzed. These differences represented the atmospheric circulation changes. In addition, we analyzed the differences of average temperature and vertical velocity on the vertical cross section, the column integrated water vapor flux, and its divergence between the two periods. Figure 2 shows that both the annual mean precipitation amount and NDP exhibited a general declining trend from southeast to northwest. The mean annual precipitation amount and NDP of the 25 stations for the 1984-2014 were 259.6 mm and 72.4 days, respectively. Among the station-based measurements, the annual precipitation reached as high as 532.9 mm at Maying Station in the southeast but was only 62.8 mm at Yuanyangchi Station in the northwest. Correspondingly, the annual NDP was as high as 101.2 days at Maying Station and was only 32.5 days at Yuanyangchi Station. Spatial and Temporal Patterns of Precipitation Variations in the HRB Due to a lack of ground stations in the Qilian Mountains, the general spatial variability in the mountain areas was derived from spatial interpolation ( Figure 2). However, the spatial variability derived from interpolation and that derived from dynamics-based climate modeling could be comparable with each other. For instance, the several years of high-resolution (3-5 km) simulations with Weather Research and Forecast (WRF) model also show that the western part of the Qilian Mountain has less precipitation than the southeastern part It is noted that simulated precipitation is significantly larger than the station measurements in the mountainous area due to the high sensitivity of the micro-physical parameters of the WRF model to complex terrain. The precipitation of HRB also exhibit seasonal cycles (Figure 3). There is more precipitation and NDP in summer with a maximum in July and less precipitation and NDP in winter with the minimum in January. In the summer, the monthly mean precipitation amount and NDP of 25 stations for 1984-2014 were in the ranges of 45-55 mm and 14-18 days, respectively. In the spring and autumn, they are 5-35 mm and 5-12 days, respectively. In the winter, they are only around 5 mm and five days. (Table 2), respectively. It can be concluded that the increase in annual precipitation, as shown by Figure 4, was mainly due to the increase in autumn precipitation. EOF Analysis of Precipitation in the HRB The cumulative variance explained by the first two EOFs reached about 67.3% (Table 3). Hence, the first two EOFs explained most of the precipitation variation of 25 stations from 1984 to 2014. The first EOF explained 51.8% of the total variance of annual precipitation. Figure 6 show that this EOF exhibits uniform behavior across the study area. Such a spatial pattern suggests that precipitation changes would be in the same phase across the entire region. The corresponding PC exhibited high values in 2007, 2010, 1993, and 1998; and low values in 1997, 1985, 1991, and 2001. These high and low values suggest that there would be more and less precipitation across the entire region, respectively. Thereby, these high and low values explained the positive and negative anomaly of regional mean precipitation ( Figure 4B), respectively. Additionally, PC1 exhibited a positive trend, which suggests a regional increase in annual precipitation. Hence, such a positive trend may also explain the increasing trend of regional mean precipitation ( Figure 4B). The uniform behavior of EOF1 indicates that such spatial-temporal variation of precipitation may be induced by a large-scale weather system. The second EOF explained 15.5% of the total variance. This EOF exhibits an approximately dipole structure ( Figure 6). There was a negative center in the southeast and a positive center in the northwest, respectively. Such a spatial pattern suggests that the precipitation variations in the southwest would be out of phase with those in the northwest. Additionally, PC2 exhibited a slight increasing trend, which may indicate increasing precipitation in the northwest and decreasing precipitation in the southeast from 1984 to 2014. Such a reverse trend suggests weakening precipitation differences between the southeast and northwest. Figure 7A shows that the UF series mostly remained positive, without exceeding the significance level line. It is suggested that precipitation showed a slight increase in HRB from 1984 to 2014. There were two intersections between the UF and UB series in 1997 and 2012 ( Figure 7A), respectively. The intersections suggest that the precipitation might have changed abruptly around 1997 and 2012. Abrupt Change of the Time Series The moving t-test shows a significant breaking point in 1997 at a confidence level of 0.05 ( Figure 7B). Such statistical detection indicates that there was a precipitation uplift around 1997. The mean precipitation was 252 mm in 1993-1997 and increased to 259 mm in 1998-2002. Thereby, the M-K test and moving t-test suggest that there was a sudden increase in precipitation around 1997. The mean precipitation was 251 mm in 1984-1997 and increased to 268 mm in 1998-2014. As shown in Figure 4, the abrupt increase was mainly caused by autumn precipitation, which increased from 37 mm in 1984-1997 to 58 mm in 1998-2014. The abrupt change corresponded to the beginning of the climate warming hiatus. The regional precipitation increased, especially in the autumn. Differences in Circulation Characteristics The abovementioned findings demonstrate that the precipitation in summer and autumn changed greatly. To understand the potential mechanisms leading to the precipitation changes, the changes of atmospheric circulation from 1984-1997 to 1998-2014 were analyzed for summer and autumn, respectively. Figure 8 shows that in summer time a geopotential height of 500 hPa in the middle and high latitudes exhibited a low-pressure anomaly in 1984-1997( Figure 8A). However, there was a high-pressure anomaly over that area in 1998-2014( Figure 8B). Due to conversion from low-pressure anomaly to high-pressure anomaly, the cyclonic circulation anomaly in 1984-1997 over that area was replaced by the anticyclonic circulation anomaly in 1998-2014. Furthermore, the atmospheric circulation situation also changed from convergence to weak divergence. Since divergence is unfavorable for precipitation, the changes in atmospheric circulation from convergence to weak divergence may have led to the declining precipitation trend from 1984 to 2014. For the autumn, the geopotential height of 500 hPa was characterized by high-pressure anomaly over Mongolia and low-pressure anomaly over the Sea of Japan in 1984-1997 ( Figure 8C,D). Over the HRB, the upper air was dominanted by anti-cyclone circulation and dry-cold northwest wind. Such circulation is unfavorable for precipitation. In 1998-2014, the anomaly of geopotential height of 500 hPa was completely different than that in 1984-1997. Over the HRB, there was a dominant moist southwest wind from the ocean or an anomaly cyclonic. Such circulation is favorable for precipitation. The abovementioned changes in circulations at a pressure level of 500 hPa explained the decrease in summer precipitation and increase in autumn precipitation from 1984 to 2014. Vertical movement and water vapor transmission are also necessary conditions to induce precipitation. Figure 9 shows the changes of vertical movement from 1984-1997 to 1998-2014. It can be seen that, within the range of 98E-102E, the airflow has an ascending motion between the 700 hPa and 400 hPa height layers in autumn. In the summer, airflow showed upward movement in the eastern region, while there was downward movement in the western region. This finding illustrates that, compared with 1984-1997, the vertical upward movement of airflow was significantly stronger in 1998-2014, especially in the autumn. However, the vertical profiles of temperature changes demonstrate that thermal conditions were likely unfavorable for vertical upward movement, since warming was gradually intensified from the bottom to the top of the atmosphere. Hence, the strengthened upward movement may be caused by large-scale changes in dynamic conditions, rather than changes in local thermal conditions. Figure 10 shows that the difference in vertically integrated column water vapor flux through 1998-2014 subtracted 1984-1997 was positive in autumn, whereas it was negative in summer for the whole study area. This finding suggests that there was more water vapor in autumn in 1998-2014 than in 1984-1997. However, for the summer, the water vapor in 1998-2014 was less than that in 1984-1997. Meanwhile, the divergence of water vapor flux was negative, which suggests the convergence of water vapor. The convergence of water vapor is favorable for precipitation. These findings demonstrate that both the increase in water vapor flux and the dynamic conditions of convergence were favorable for precipitation in autumn from 1984 to 2014. For the summer, the dynamic condition of convergence was favorable for precipitation, but the decrease in water vapor flux may offset the positive contribution of convergence. As a result, the summer precipitation exhibited a weak declining trend from 1984 to 2014. Figure 10A,B, and the shadow indicates water vapor flux divergence (unit: 10 −7 g s −1 cm −2 hPa −1 ) in Figure 10C,D. Discussion Based on the observation data of daily precipitation during 1984-2014, the spatiotemporal patterns of precipitation variations in the HRB were disclosed in the study. On the whole, the precipitation exhibits a spatial variability, characterized by a declining trend from southeast to northwest. The annual precipitation in the southeast could be up to eight times that in the northwest areas, and as much as five times higher for the number of NDP. Our results were consistent with existing studies that found that the precipitation tended to increase from the northwest to southeast, with the changes of altitude and terrain. Such spatial variability might be derived from the different characteristics of natural terrain, altitude, and vapor resources in the study area. The terrain of the study area is very complex as multiple natural landscapes coexist: snow cover and permafrost in the mountainous regions in the upper reaches; forests and oases in the middle reaches; and Gobi and desert in the lower reaches. In the same climate conditions, the geographical distribution of precipitation may be significantly affected by local terrains (slope and elevation). The precipitation generally increased along with elevation under the same atmospheric circulation conditions. Wang et al. found that annual precipitation increased by an average of 4.55% with a 100-m increase in altitude. The uneven terrain distribution also led to variation in sensitive water resources and climate change. Analogously, the difference of vapor source between east and west may be divided at 99.5 E, possibly leading to a difference between the eastern and the western areas of the catchment. The abovementioned reasons may contribute to the spatial variability of precipitation in HRB. The EOF analysis demonstrates that the first EOF displayed the main features of the temporal variability in the whole basin. The increasing trend of precipitation from 1984 to 2014 may be mainly derived from changes in large-scale weather systems, which were mainly influenced by atmospheric circulation. For most stations, a slight but noticeable increasing trend was also detected in precipitation at an annual scale. It was reported that the water vapor over the northwest region exhibited an increasing trend since the late 1980s, and the high-altitude wind field in Northwest China has been favorable for the transmission of water vapor from south to north in recent years. Weakened by the Ural Mountains ridge and the East Asian trough, the westerly wind is weaker and the south wind is stronger in Northwest China. Such circulation is favorable for the northward transmission of southern moisture from the Indian Ocean and the Western Pacific. This may be the main cause of the increase in precipitation in the HRB. The second EOF displayed approximately symmetric characteristics of precipitation between the northeast and the southwest region, and it can be inferred that the opposite tendency became more and more obvious from 1984 to 2014. The main reason for this may be the impact of small-and medium-scale weather systems. However, when compared with a large-scale weather system, the effect on precipitation was less significant. Previous studies also found that precipitation in the western region to the northwest of the HRB increased significantly under global warming and accelerating water circulation. In addition, Shi et al. found that the climate was basically characterized by the development of warm and wet weather from the end of the Little Ice Age until the 1980s, especially in Northwest China. However, the cause of the second EOF has yet to be determined. Qu et al. reported that as a response to climate warming status after 1998, there was a decreasing trend in the number of extreme high-temperature events in Northwest China during the last 20 years. In the HRB, there was weakened climate warming, which is like the hiatus, from the late 1990s to the early 2010s. Here, our findings suggest that precipitation changes in HRB also responded to the climate warming hiatus. There was a rise in precipitation, especially in the autumn, in the HRB around 1997, which approximately corresponded to the beginning of the hiatus. The changes in atmospheric circulation and physical structures, such as temperature, vertical upward motion, vapor transmission, and its convergence from 1984 to 2014 were all favorable for autumn precipitation. First, from 1984-1997 to 1998-2014, the changes in circulation at a pressure level of 500 hPa were characterized by a wind direction shift from westerly to easterly in the summer and by a wind direction shift from northerly to southerly in the autumn. Under these circumstances, the southward-moving cold air is favorable for the activities of a low-pressure system such as plateau vortex and shear line, and may lead to more precipitation in the HRB in autumn. With the transformation of general circulation of 500 hPa from divergence to convergence in the autumn, the increase in atmospheric instability and the transmission of water vapor were also strengthened. Second, the vertical upward motion provided good dynamic conditions for precipitation in the autumn. The strong upward movement is also beneficial to the development of low-pressure disturbances in the plateau region. Finally, stronger water vapor transmission and its convergence provide the necessary water vapor conditions for precipitation in autumn. Zhang and Xu reported that water vapor for precipitation in spring and summer mainly came from the ocean air mass; conversely, precipitation in autumn and winter was mostly derived from continental recycled water in the HRB. Previous studies also found that the proportion of precipitation formed by continental recycling and water evaporation increased significantly in the HRB. All these factors may together contribute to the increase in autumn precipitation in the HRB. Conclusions The ground measurements of precipitation from 25 stations across the southern part of HRB from 1984 to 2014 were analyzed with statistical methods. The findings demonstrate that the regional annual precipitation and NDP increased by 13.1 mm and 3.2 days per decade, respectively, from 1984 to 2014. Such increases were mainly due to the increase in autumn precipitation, the slope of which was 13.7 mm per decade. There was an abrupt increase around 1997. This point corresponded to the climate warming hiatus. The findings suggest that the increase in autumn precipitation was induced by atmospheric circulation, which may lead to more water vapor flux, intensified upward motion, and the convergence of dynamic conditions. This study suggests that, along with the climate warming hiatus, the large-scale circulation changed and, hence, the regional/local precipitation changed as a response. |
/*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.core.common.type;
import org.graalvm.compiler.core.common.LIRKind;
import org.graalvm.compiler.core.common.spi.LIRKindTool;
import org.graalvm.compiler.debug.GraalError;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.MemoryAccessProvider;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.PrimitiveConstant;
import jdk.vm.ci.meta.ResolvedJavaType;
/**
* Type describing pointers to raw memory. This stamp is used for example for direct pointers to
* fields or array elements.
*/
public class RawPointerStamp extends AbstractPointerStamp {
protected RawPointerStamp() {
super(false, false);
}
@Override
public LIRKind getLIRKind(LIRKindTool tool) {
return tool.getWordKind();
}
@Override
protected AbstractPointerStamp copyWith(boolean newNonNull, boolean newAlwaysNull) {
// RawPointerStamp is a singleton
assert newNonNull == nonNull() && newAlwaysNull == alwaysNull();
return this;
}
@Override
public Stamp meet(Stamp other) {
assert isCompatible(other);
return this;
}
@Override
public Stamp improveWith(Stamp other) {
return this;
}
@Override
public Stamp join(Stamp other) {
assert isCompatible(other);
return this;
}
@Override
public Stamp unrestricted() {
return this;
}
@Override
public Stamp empty() {
// there is no empty pointer stamp
return this;
}
@Override
public boolean hasValues() {
return true;
}
@Override
public ResolvedJavaType javaType(MetaAccessProvider metaAccess) {
throw GraalError.shouldNotReachHere("pointer has no Java type");
}
@Override
public Stamp constant(Constant c, MetaAccessProvider meta) {
return this;
}
@Override
public boolean isCompatible(Stamp other) {
return other instanceof RawPointerStamp;
}
@Override
public boolean isCompatible(Constant constant) {
if (constant instanceof PrimitiveConstant) {
return ((PrimitiveConstant) constant).getJavaKind().isNumericInteger();
} else {
return constant instanceof DataPointerConstant;
}
}
@Override
public Constant readConstant(MemoryAccessProvider provider, Constant base, long displacement) {
throw GraalError.shouldNotReachHere("can't read raw pointer");
}
@Override
public String toString() {
return "void*";
}
}
|
Adipogenesis as a Potential Anti-Obesity Target: A Review of Pharmacological Treatment and Natural Products Abstract Obesity is recognized as a severe threat to overall human health and is associated with type 2 diabetes mellitus, dyslipidemia, hypertension, and cardiovascular diseases. Abnormal expansion of white adipose tissue involves increasing the existing adipocytes cell size or increasing the number through the differentiation of new adipocytes. Adipogenesis is a process of proliferation and differentiation of adipocyte precursor cells in mature adipocytes. As a key process in determining the number of adipocytes, it is a possible therapeutic approach for obesity. Therefore, it is necessary to identify the molecular mechanisms involved in adipogenesis that could serve as suitable therapeutic targets. Reducing bodyweight is regarded as a major health benefit. Limited efficacy and possible side effects and drug interactions of available anti-obesity treatment highlight a constant need for finding novel efficient and safe anti-obesity ingredients. Numerous studies have recently investigated the inhibitory effects of natural products on adipocyte differentiation and lipid accumulation. Possible anti-obesity effects of natural products include the induction of apoptosis, cell-cycle arrest or delayed progression, and interference with transcription factor cascade or intracellular signaling pathways during the early phase of adipogenesis. Introduction According to the World Health Organization, 39% of adults are overweight, and 13% are obese globally. 1 Obesity has nearly tripled since 1975 and is predicted to triple by 2030. 2 Obesity poses a severe threat to overall human health due to its close association with a cluster of pathological entities globally designated as metabolic syndrome, including type 2 diabetes mellitus (T2DM), dyslipidemia, hypertension, and cardiovascular diseases. 3 Obesity is also associated with increased oxidative stress levels due to excessive production of reactive oxygen species (ROS) and dysfunctional antioxidant systems. Adipose tissue is an important energy store and essential regulator of energy balance, but also an active endocrine organ that secretes numerous bioactive peptides and proteins called adipokines. 4 Adipokines generate ROS, reduce the antioxidant capacity, and stimulate the production of pro-inflammatory cytokines such as interleukin 1 (IL-1) and 6 (IL-6), and tumor necrosis factor-alpha (TNF-), causing an increase in oxidative stress levels. Thus, obesity induces oxidative stress via low-grade chronic inflammation, but also through other mechanisms such as mitochondrial and peroxisomal oxidation of fatty acids and over-consumption or altered O2 metabolism. ROS induces endothelial dysfunction, decreases vasodilator and increases contractile factors, and damages cell structures, causing atherosclerosis, heart failure, hepatic steatosis, and cancer. 5 The link between chronic inflammation and cancer lies in tumor promoters' ability to recruit inflammatory cells and stimulate them to generate ROS. Significant damage may occur to cell structure and functions, inducing somatic mutations, and neoplastic transformation. Oxidative stress causes cancer initiation and progression by interacting with the initiation (gene mutations and structural alterations of the DNA), promotion (abnormal gene expression, blockage of cell-to cell communication, modification of second messenger systems), and progression (further DNA alterations) of cancer. There is a significant contribution to cancer development of the triad of over-weight/obesity, insulin resistance (IR), and adipocytokines. Some of the effects of obesity in cancer etiopathogenesis comprise inducing hyperinsulinemia and subclinical chronic low-grade inflammation and oxidative stress and causing alterations in adipocytokine pathophysiology, and sex hormones biosynthesis. 6 In light of the current COVID-19 pandemic, it is important to emphasize an association between obesity and infectious diseases, especially pulmonary infections. Obesity increases the risk of hospitalization and admission to intensive care units, in addition to greater severity of the disease and higher mortality in COVID-19 patients. In patients under the age of 60, obesity is the main predictor of severe symptoms and doubles the risk of being admitted to critical care. 7 Underlying mechanisms include obesityrelated comorbidities (T2DM, cardiovascular and renal diseases), immune system impairments facilitating a systemic diffusion of infection, increased type 2 inflammation with effects on the lung parenchyma, raised IL-6 levels, and abnormal secretion of adipokines and cytokines inducing low-grade inflammation. 8 Given the obvious physical constraints and associated psychological stress, as well as the risk of obesity-related health complications, reducing body weight is regarded as a major health benefit. The etiologic-mechanistic perspective of obesity is still poorly understood, and there are very few effective pharmacological approaches for obesity prevention. The etiology of obesity involves an interaction between genetic and environmental factors, the latter being the main reason for the increase in the global prevalence of obesity. Changes in lifestyle and dietary habits have resulted in an outbreak of the obesity pandemic over the last decades. Obesity results from an imbalance between energy intake and expenditure. The increased caloric intake from diets high in saturated fats, sugar, and processed foods, together with reduced physical activity, results in an energy imbalance. 9 Adipose Tissue and Adipogenesis Excess energy is stored in the form of lipids in adipocytes, and an excessive accumulation of adipose tissue characterizes obesity. There are two types of adipose tissues, brown (BAT) and white (WAT). BAT is mainly responsible for non-shivering thermogenesis in response to cold stress or -adrenergic stimulus, while WAT plays a crucial role in lipid homeostasis and maintaining energy balance. 10 Abnormal expansion of WAT associated with obesity involves increasing the cell size of the existing adipocytes (hypertrophy) or increasing the number through differentiation of new adipocytes (hyperplasia). 11 Under normal circumstances, excess energy does not damage the organism as long as it is efficiently stored in the adipose tissue. However, when amounts of fat exceed the adipose tissue's storage capacity and overwhelm adipose tissue's functional capacity, fat begins to deposit ectopically in other metabolically relevant organs, such as the liver, skeletal muscle, kidney, and pancreas. 12 With obesity progression, adipose tissue becomes inflamed and fibrotic, worsening the dysfunction and decreasing the WAT's metabolic flexibility, leading to the development of metabolic abnormalities, such as dyslipidemia and IR. 13 Hypertrophic WAT expansion due to increased white adipose cells, macrophage infiltration, and fibrosis disrupt hormonal balance. The release of inflammatory cytokines and adipokines alters the normal energy homeostasis and causes metabolic syndrome. 14 Adipocyte hyperplasia, also known as adipogenesis, is a process of proliferation and differentiation of adipocyte precursor cells in mature adipocytes. 15 It is a key process in determining the number of adipocytes, occurring mainly during childhood and adolescence, further determining the lipid-storing capacity of adipose tissue and fat mass in adults. 10 Therefore, the regulation of size and number of adipocytes might be a possible therapeutic approach for obesity, and it is important to understand the molecular mechanisms of adipose tissue formation and alterations in obesity. Identifying potential adipogenic molecular targets submit your manuscript | www.dovepress.com DovePress Diabetes, Metabolic Syndrome and Obesity: Targets and Therapy 2021:14 susceptible to modulation by external factors can utilize adipogenesis regulation to control or reverse obesity. This review focuses on available conventional medicine and natural products to prevent or treat obesity by targeting adipogenesis and discussing potential adipogenesis mechanisms suitable for the therapeutic approach. Molecular Regulators of Adipogenesis as Potential Therapeutic Targets Adipogenesis is a complex multi-step process through which preadipocytes convert into mature, lipid-containing adipocytes. It is essential to renew adipose tissue and support adipose dynamics since approximately 10% of our body's fat cells are regenerated each year. 16 Two adipogenesis phases have been recognized: pluripotent stem cells' commitment to a unipotent preadipocyte and terminal differentiation of preadipocytes into mature adipocytes. When pluripotent stem cells commit to the adipocyte lineage, they lose the ability to differentiate into other cell types and undergo morphological and functional changes due to numerous signaling pathways, transcription factors, and genes. 17 Differentiation of 3T3-L1 preadipocyte fibroblast clonal cell line into mature fat cells is one of the most commonly used in vitro models to study adipose tissue biology. After induction of differentiation by proadipogenic factors, this line shows the morphology and gene expression of white adipose tissue. 18 Adipogenesis in vitro occurs in four steps: growth arrest, mitotic clonal expansion (MCE), early differentiation, and terminal differentiation. 19 After contact inhibition and growth arrest of post-confluent 3T3-L1 preadipocytes, the differentiation is induced by hormonal stimulation with insulin, dexamethasone, and 1-methyl-3-isobutyl-xanthine (IBMX). 20 Dexamethasone and IBMX directly induce genes responsible for the expression of adipogenic transcription factors, while insulin stimulates cells to take up glucose and store it in the form of triacylglycerol. 21,22 After adipogenic cocktail-induced differentiation, cells re-enter the cell cycle synchronously and undergo one or two mitosis cycles, regarded as MCE, when an irreversible commitment to differentiation occurs. 23 MCE is a crucial prerequisite for the differentiation process -if cells are prevented from entering the S phase during MCE, the expression of transcription factors and regulators of adipogenesis will not occur, and differentiation will be blocked. 24 Cell mitosis is required to unwind DNA allowing transcription factors to access regulatory elements in genes involved in the differentiation process. Therefore, sustaining cells at one point in the cell cycle might be an effective way to block adipogenesis. Cyclindependent kinase (CDK) complexes with cyclin D and E are essential for retinoblastoma (Rb) phosphorylation and the reentry into the cell cycle. CDK inhibitors such as p21CIP and p27KIP1 are associated with cell-cyclearrested preadipocytes, while their degradation results in G1/S phase progression. 25 During early differentiation, a morphological rounding of preadipocytes occurs, and the terminal phase of differentiation is characterized by lipid synthesis and transport, adipocyte-specific proteins secretion, insulin-associated metabolic processes activation, and mature lipid-loaded adipocytes morphology ( Figure 1). 26 Adipogenesis is strictly regulated by the transcriptional cascade and signaling pathways ( Figure 1). During the early stages of differentiation, transient high expression of CCAAT/enhancer-binding proteins (C/EBP), C/EBP, and C/EBP occur. During the intermediate stage of adipogenesis, C/EBP/ stimulate C/EBP and peroxisome proliferator-activated receptor (PPAR), key transcription factors of adipogenesis. PPAR and C/EBP cooperatively promote differentiation and induction of several adipocyte-specific genes, including lipoprotein lipase (LPL), adipocyte protein 2 (aP2), fatty acid synthase (FAS), and perilipin in the terminal stage of differentiation ( Figure 1). 27 Transcription Factors in Adipogenesis CCAAT/Enhancer-Binding Proteins C/EBP and C/EBP are the first transcription factors induced immediately after stimulation by adipogenic hormonal cocktails and play an important role in directing the differentiation process. The localization of C/EBP to the nucleus facilitates DNA-binding activity and leads to phosphorylation and transcriptional activation of PPAR and C/ EBP. 28 Decreased nuclear localization of C/EBP and disrupted DNA-binding activity inhibits C/EBP and PPAR gene expression, thereby suppressing adipogenesis. In C/EBP-null mice, adipogenesis is severely impaired, meaning that C/EBP and PPAR in the absence of C/EBP are not sufficient for complete differentiation. 29 Therefore, C/EBP inhibition could be one potential target for preventing or treating obesity, as decreasing early adipogenic transcription markers inhibits subsequent transcriptional cascade and suppresses terminal adipogenic differentiation. Diabetes, Metabolic Syndrome and Obesity: Targets and Therapy 2021:14 submit your manuscript | www.dovepress.com 69 Some C/EBP family members, such as the C/EBP homologous protein (CHOP), form inactive heterodimers with C/ EBP and C/EBP. Heterodimers cannot bind DNA and function as a dominant-negative inhibitor of gene transcription, suppressing adipocyte differentiation. 30 The direct inhibition of C/EBP activity by increasing the CHOP level can lead to PPAR suppression and adipogenesis prevention. Peroxisome Proliferator-Activated Receptor PPAR controls gene network expression in adipogenic differentiation, glucose and lipid metabolism, inflammation, and other physiological processes. Protein isoform PPAR2 is abundantly expressed in the adipose tissue, and it is essential for adipogenesis and the maintenance of the differentiated state. Activation of PPAR increases the number of small and insulin-sensitive adipocytes and up-regulates adiponectin, improving insulin sensitivity in the liver and muscle. 31 Given its crucial role in adipogenesis, PPAR has been a critical target in developing antiobesity drugs. PPAR binds to specific DNA sequences as a heterodimer with the retinoid X receptor (RXR) and regulates target genes' transcription. 32 The activity of PPAR can be regulated by binding agonist ligands, such as thiazolidinediones, which improve IR, enhance glucose uptake, and lower glucose concentration. They also exert anti-inflammatory effects, which is potentially important in treating obesity and T2DM. 33 In vitro studies showed that insulin and corticosteroids induce the expression of PPAR mRNA, 34 whereas TNF down-regulates the expression of PPAR. 35 On the other hand, unliganded PPAR/RXR heterodimers interact with co-repressor molecules to repress the transcription of target genes, which means that the investigation of PPAR antagonists may be a logical approach for research of anti-obesity medication. PI3K/AKT and MAPK/ERK Signaling Pathways The hormonal induction cocktail activates PI3K/AKT and MAPK/ERK pathways during the early stage of differentiation. Intracellular MAPK signaling is important for regulating cell proliferation and differentiation, while ERK activation is essential for the induction of MCE and adipogenesis. 36 In 3T3-L1 preadipocytes, inactivation of the PI3K/AKT pathway inhibits adipogenesis, while activation of this pathway contributes to adipocyte differentiation. 37 However, different studies showed that MAPK pathways phosphorylate PPAR and reduce its transcriptional activity and that activation of MAPK antagonizes 3T3-L1 adipocytic differentiation. 38 Clear elucidation of MAPK/ERK signaling pathway effects on adipogenesis could provide another potential target of adipose tissue formation in obesity. Wnt/-Catenin Signaling Pathways Wnt signaling maintains preadipocytes in an undifferentiated state by inhibiting PPAR and C/EBP. In 3T3-L1 preadipocytes, Wnt induction inhibits adipogenesis by dysregulation of the cell cycle and blocking PPAR and C/EBP expression, while disruption of Wnt signaling leads to adipogenic differentiation. 39 After adipogenesis induction, phosphorylated glycogen synthase kinase 3 (GSK3) suppresses Wnt signaling by the degradation of -catenin. Wnt signaling promotes -catenin stabilization and nuclear translocation, causing the downstream inhibition of C/EBP and PPAR. 36 The stabilization and nuclear localization of -catenin, as an important step in adipogenesis inhibition, might be a potential therapeutic target for the prevention/treatment of obesity. AMP-Activated Protein Kinase Signaling Pathway AMPK is a serine/threonine-protein kinase activated by phosphorylation of the subunit when cellular ATP levels are decreased. When phosphorylated, AMPK promotes catabolic pathways such as fatty acid oxidation and inhibits energy-consuming pathways such as fatty acid synthesis. 10 Since adipogenesis can be considered an energy-consuming process, AMPK acts as a negative regulator of adipogenesis and can be considered a target for the treatment of obesity. 40 The anti-adipogenic effects of AMPK are mediated by suppressing PPAR via positive regulation of p38 MAPK, which promotes PPAR phosphorylation and inhibits its transcriptional activity. 41 In the 3T3-L1 cell line, AMPK activation inhibits MCE and the expression of C/EBP, PPAR, and late adipogenic markers. 42 Bone Morphogenic Protein Signaling Pathway BMPs are members of the transforming growth factor- (TGF-) superfamily and display varied effects on adipogenesis, depending on BMP's concentration and type. Generally, TGF- inhibits preadipocyte differentiation in vitro by interacting with C/EBP and repressing its transcriptional activity. 43 Hedgehog Signaling Pathway Activation of the Hh signaling pathway impairs adipogenesis and lipid accumulation. This pathway is down-regulated during human adipocyte differentiation. Hh protein inhibits adipogenesis by reducing the expression of C/EBP, PPAR, and aP2, whereas inhibition of Hh signaling using increases adipogenic differentiation in 3T3-L1. 46 Nearly complete inhibition of adipocyte differentiation is shown by Oil Red O staining, a 40% reduction in triglyceride accumulation, a 50% decrease of adipocyte marker expression, and upregulation of preadipocyte factor-1 (Pref-1). 47 Adipocyte differentiation inhibition occurs even after one hour of Hh stimulation concomitant with adipogenic induction, suggesting that Hh signaling is maintained several days after its stimulation or controls critical early steps of differentiation. 48 Other Regulators of Adipogenesis Positive Regulators of Adipogenesis Several factors are identified as positive regulators of adipogenesis, such as the Kruppel-like factor family (KLF), sterol regulatory element-binding protein 1 (SREBP1), cyclic AMP response element-binding protein (CREB), zinc finger protein 423 (ZFP423), and farnesoid X receptor (FXR). Decreasing adipogenic transcription factors might be a good approach to inhibit adipose tissue development during obesity progression. 71 Several KLF zinc-finger transcription factors are induced during adipogenesis in 3T3-L1 preadipocytes. 31 KLF4 is an early marker of adipogenesis, expressed within the first 30 min after exposure of 3T3-L1 cells to an adipogenic cocktail. 49 KLF5 is induced by C/EBP/ during the early stages of adipogenesis, binds directly to the PPAR2 promoter, and cooperates with C/EBPs. 22 Inhibition of KLF9, which is usually up-regulated during the middle stage of differentiation and binds directly to the PPAR2 promoter, inhibits adipogenesis. 50 Inhibition of KLF15 also leads to reduced expression of PPAR, blocking adipogenesis in 3T3-L1 preadipocytes. 51 SREBP1 regulates the expression of FAS and LPL and increases the activity of PPAR, augmenting adipogenesis. 52 The expression of CREB is stimulated by the adipogenic cocktail, which can be sufficient to initiate lipid accumulation and the expression of PPAR and fatty acid-binding protein (FABP). 53 ZFP423 can promote adipogenesis of nonadipogenic NIH 3T3, while its inhibition in 3T3-L1 cells blocks PPAR expression and adipogenic differentiation. 54 Furthermore, in bovine stromal vascular cells, ZFP423 increases lipid accumulation and expression of PPAR and C/EBP. 55 FXR is a nuclear hormone receptor that promotes adipocyte differentiation by partially inducing PPAR2 and C/EBP expression. After RXR heterodimerization, the agonist ligand activates FXR, which then binds to FXR response elements and regulates target gene expression. 56 Therefore, investigating FXR activity inhibition by antagonist ligands for FXR can be considered for fighting obesity. Negative Regulators of Adipogenesis On the other hand, high and sustained levels of KLF2, Pref-1, transcriptional-coactivator with PDZ-binding motif (TAZ), differentiated embryo chondrocyte (DEC), GATA transcription factors, and histone deacetylase Sirtuin 1 (SIRT1) inhibits adipogenesis and keeps cells at the preadipocyte stage. Targeting these factors is a potentially effective therapeutic approach to intervene in obesity. KLF2 represses adipogenesis by inhibition of PPAR, C/ EBP, and SREBP1 expression in 3T3-L1 preadipocytes. 57 Pref-1 is highly expressed in preadipocytes and inhibits adipocyte differentiation by preventing lipid accumulation and expression of PPAR, C/EBP FAS, and aP2. 58 TAZ suppresses adipocyte differentiation via PPAR activity repression, and its diminished expression enhances adipogenic differentiation. 59 DEC 1 and 2 are abundantly expressed in preadipocytes and down-regulated during adipogenesis. They inhibit the transcriptional activity of C/ EBP/. 60 The GATA family of transcription factors play important roles in a variety of biological processes, including adipogenesis. GATA-2 and GATA-3 are predominantly present in white adipose tissue and significantly contribute to adipocyte differentiation regulation. Their constitutive expression inhibits adipogenesis by trapping cells in the preadipocyte stage. This effect could be a result of direct suppression of PPAR expression through PPAR promoter or the formation of protein complexes with C/EBP and C/EBP. 61 GATA2 and GATA3 are down-regulated during the terminal differentiation process, and their defective expression is associated with obesity. 62 These findings indicate the crucial role of GATA transcriptional factors during terminal adipocyte differentiation and their potential as targets for the therapeutic intervention of obesity. Sirtuins (SIRT) and miRNAs are recently discovered modulators of adipogenesis with various effects on adipocyte differentiation progression. SIRT1 is an NAD+-dependent nuclear deacetylase that acts as a negative modulator of adipogenesis in the 3T3-L1 cell line. SIRT1 attenuates adipogenesis by interacting with its cofactors, nuclear receptor co-repressor (NCoR), and the silencing mediator of retinoid and thyroid hormone receptors (SMRT). 63 SIRT1 binds to the same DNA sequences as PPAR, acting as its corepressor. SIRT1 can also induce BAT-specific genes while repressing visceral WAT genes and induce the expression of genes involved in fatty acid oxidation. 64 Additionally, SIRT2 exerts an inhibitory effect on adipogenesis by FOXO1 deacetylation and subsequent PPAR transcriptional activity repression. 65 On the other hand, SIRT7 was shown to be important for PPAR expression and proper adipocyte differentiation. Therefore, activation of SIRT 1 and 2 or inhibition of SIRT7 during adipogenesis could provide a novel therapeutic strategy for obesity. However, it is difficult to find a single compound that would activate some SIRTs while inhibiting others, and it is hard to obtain tissue action specificity. miRNAs are small non-coding RNAs that bind to specific target mRNAs to promote their degradation or prevent their translation. 66 EBP). On the other hand, some miRNAs inhibit adipocyte differentiation (miR-27a and b, miR-31, miR-128-3p, miR-130a and b, miR-146a-5p, miR-155, miR-540) by directly targeting C/EBPs and PPAR. 11 Additionally, some miRNAs, such as miR-30a, play an important role in mature WAT biology. Lower levels of miR-30a in subcutaneous WAT correlate with IR, while its overexpression improves insulin sensitivity and energy expenditure. 67 miR-30a also exerts an anti-inflammatory effect by targeting signal transducer and activator of transcription 1 (STAT1). Moreover, miR-103 and miR-107 can regulate the size of the preadipocyte population in WAT, directly suppressing the expression of Wnt3a, an activator of the Wnt/-catenin pathway, thus promoting stress-mediated apoptosis in preadipocyte. 68 In addition, the miR-128 was found to be one of the most upregulated miRNAs in hypoxic 3T3-L1 adipocytes. It directly targets the 30-UTR sequence of the INSR gene, reducing the expression of plasma membrane tyrosine kinase receptor protein INSR through which insulin exerts its biological effects. It was shown that obesity-induced hypoxia increases the expression of miR-128, which then negatively affects INSR mRNA and protein expression levels in adipose tissue of both obese patients and high-fat diet-fed mice, correlating with the decrease in INSR expression. This result was consistent with the miR-128 expression level in hypoxic 3T3-L1 adipocytes. 69 miRNAs could be used as clinical biomarkers to predict the development of obesity and related complications or to assess therapeutic anti-obesity strategies' effectiveness due to the normalization of miRNAs levels upon acute weight loss. 70 miRNAs can also regulate SIRTs activity, so there is a possibility to modify the action of SIRTs by specific miRNAs for treating obesity. miR-34a, miR-146b, and miR-181a are negative regulators of SIRT1, and SIRT7 is a metabolic target for miR-93, a negative regulator of adipogenesis. 71 However, safely targeting specific tissue and avoiding side effects using miRNA therapeutics is still a challenge. Therapeutic Approach -Conventional Medicine with Effects on Adipogenesis Obesity treatment aims not only for weight reduction but also a reduction of obesity-related complications. The most commonly used therapeutic strategies include lifestyle modification, calorie restriction combined with increased physical activity, while bariatric surgery is limited to morbidly obese patients. 72 Long-term effects of lifestyle modification are frequently disappointing, with 90% of the people returning to their original weight within two to five years. 36 Although anti-obesity drugs might be a promising solution, their limited efficacy, together with possible side effects and drug interactions, highlights a constant need to find novel, efficient, and safe anti-obesity ingredients. For that purpose, it is necessary to identify pathogenic molecular mechanisms that could serve as suitable therapeutic targets. To observe available medications for treating obesity, one has to bear in mind the connection of obesity with metabolic syndrome and the risk for developing other chronic diseases such as T2DM and cardiovascular disease. Although different pathophysiological mechanisms lead to metabolic syndrome, it is associated with obesity through dysfunction of adipose tissue as the main contributor to obesity and subsequent complications. Disturbed metabolic homeostasis leads to visceral obesity, atherogenic dyslipidemia, arterial hypertension, and IR. 73 Since adipose tissue dysfunction mainly presents as obesity and dyslipidemia, currently approved medications for obesityrelated conditions also affect adipose tissue functions and adipogenesis, and knowing the underlying mechanisms of these effects has great clinical value. Statins Statins are 3-hydroxy-3-methyl-glutaryl-coenzyme A (HM G-CoA) reductase inhibitors that inhibit the conversion of HMG-CoA to mevalonic acid in a competitive manner. They lower total cholesterol, LDL cholesterol, and triglyceride levels while increasing HDL cholesterol levels. 74 In adipose tissue, they enhance lipolysis and decrease lipid accumulation in mature adipocytes, increase mRNA LPL expression in preadipocytes, preventing adipocyte hypertrophy by increasing the number of small adipocytes. 75 Their effect on adipogenesis in vitro goes through down-regulation of C/EBP, PPAR, SREBP1, leptin, FABP4, and adiponectin. 76 Fibrates Fibrates increase LPL and fatty acids hepatic uptake while reducing hepatic triglyceride production and increasing HDL cholesterol levels. Fibrates act as synthetic ligands for PPAR increasing fatty acids hepatic B-oxidation, LPL activity, and VLDL clearance. 77 Through PPAR stimulation and upregulation of fatty acid oxidation enzymes in adipose tissue, fibrates can decrease body weight and reduce plasma leptin concentration. 76 They also can Diabetes, Metabolic Syndrome and Obesity: Targets and Therapy 2021:14 submit your manuscript | www.dovepress.com DovePress increase energy expenditure and even induce the browning of WAT adipocytes. 78 Binding directly to PPAR, fibrates induce adipogenesis and forming small and numerous lipid droplets in adipocytes. 79 Niacin Niacin is the most effective for increasing HDL levels and decreases total cholesterol, LDL, triglyceride synthesis, and fatty acid re-esterification. 80 It stimulates adipogenesis throughout increasing PPAR, FABP4, adiponectin, and leptin expression in 3T3-L1 cells. 81 Metformin Metformin is the most commonly used drug to treat T2DM. It suppresses hepatic glucose production and improves adipose tissue metabolism in the liver and muscle, leading to decreased plasma glucose levels. 82 Metformin reduces lipolysis, increases glucose uptake into skeletal muscle cells, increases intestinal glucose utilization, and improves pancreatic -cell survival. 83 Metformin has a pleiotropic effect in reducing appetite, preventing cardiovascular diseases, improving endothelial function, modulation of inflammation, and cancer prevention. 84 In addition to all of the above, metformin also leads to weight loss severity, although this effect's mechanism is still unknown. The effect of metformin on endocrine adipose tissue function is still a matter of debate, given the fact that it has been shown more effective in obese patients with TMD2 than in those with lower body mass index. 85 Metformin is known to act through AMPK, whose activation inhibits adipogenesis in 3T3-L1 cell culture. 42 Metformin interferes with oxidative phosphorylation in mitochondria and stimulates osteogenic differentiation via AMPK, which is known to promote osteogenic and suppress adipogenic differentiation, although the exact mechanism of this action is unknown. 86 Liraglutide Liraglutide was firstly approved as an antidiabetic drug and, but in higher doses, it showed anti-obesity effects. As a glucagon-like peptide 1 receptor agonist, it reduces food ingestion and appetite and can also slow gastric emptying while showing anti-adipogenic, antilipogenic, and prolipolytic effects in human mature adipocytes. 70 Liraglutide reduces total fat mass and can change fat depots' regional distribution. 87 Downregulation of AKT and PI3K pathways and upregulation of AMPK decreases lipogenesis in WAT, reducing lipid storage. 88 Liraglutide also increases energy expenditure by increased thermogenesis. 89 In 3T3-L1 cells, it induces PPAR, C/EBP/, and modulates ERK1/2, PKCB, and AKT pathways. 90 However, in human adipocytes, liraglutide exerts an anti-adipogenic effect through the cAMP pathway. Binding directly to GLP-1R decreases adipogenesis and lipogenesis-related genes while increasing the expression of the lipolytic ones. 91 Bioactive Molecules with Effects on Adipogenesis Natural products have played an important role in alleviating a number of health problems throughout history and remained a large portion of pharmaceutical agents nowadays. For example, over 60% of the current anticancer drugs were derived from natural sources. 92 Biomolecules serve as models for the preparation of efficacious analogs, which results in more effective and less toxic targeted therapies. Furthermore, natural products help identify bioactive compounds as a basis for developing anti-inflammatory drugs. The best example is polyphenolics that modulate the inflammatory pathways and serve as biomarkers that can be used to prepare therapeutic agents for treating inflammatory disorders. 93 Natural products have also become a part of our daily diet. Moreover, some antidiabetic agents, such as widely used drug metformin, have been developed from natural sources. Many plants are used traditionally as a part of diabetes treatment throughout the world, and their efficacy and safety have been validated through clinical use over the years. They are commonly considered to be less toxic and with fewer side effects than synthetic medicines. 94 In addition, a variety of natural plants, functional fatty acids, and other natural dietary compounds are ingredients of current anti-obesity products or in consideration as potential ingredients for future anti-obesity products. Active compounds of natural products are mostly derived from plants, including fruits, vegetables, grains, and herbs containing a high amount of phytochemicals, fibers, and unsaturated fatty acids. 95 Mechanisms of action of natural products include interfering with nutrient absorption, decreasing adipogenesis and increasing thermogenesis, suppressing the appetite, and modifying the intestinal microbiota composition. 96 Recently, numerous studies have investigated the inhibitory effects of natural products on adipocyte differentiation and lipid accumulation. Possible anti-obesity effects of natural products include the induction of apoptosis, cellcycle arrest or delayed progression, and interference with transcription factor cascade or intracellular signaling pathways during the early phase of adipogenesis. The submit your manuscript | www.dovepress.com DovePress Diabetes, Metabolic Syndrome and Obesity: Targets and Therapy 2021:14 following sections briefly discuss some of the natural products, while others are listed in Table 1, grouped by their mechanism of action. Delphinidin Delphinidin is an anthocyanin found in pigmented fruits and vegetables with antioxidant, anti-inflammatory, antiatherosclerosis, and anti-cancer bioactivities. It downregulates the expression of adipogenesis and lipogenesis markers, inhibits lipid accumulation, and upregulates fatty acid metabolism gene expression in 3T3-L1 adipocytes. 97 In addition, the activation of Wnt and nuclear translocation and stabilization of -catenin decreases lipid accumulation in 3T3-L1 cells. Additionally, delphinidin up-regulates p21CIP or p27KIP1 expression, decreases C/EBP expression, and suppresses GSK3 expression. 98 Genistein Genistein, an isoflavone found in legumes, by enhancing CHOP blocks the DNA binding and transcriptional activity of C/EBP in 3T3-L1 preadipocytes, thus inhibiting protein expression of PPAR and C/EBP. 99 Other studies involving 3T3-L1 cells showed that genistein inhibits adipocyte formation through activation of AMPK, induces apoptosis in mature adipocytes, 100 inhibits the phosphorylation of P38 MAPK, and prevents C/EBP expression. 101 Genistein also suppresses hormonal-induced proliferation and blocks cell entry into the S phase and the S to the G2/M phase transition. 102 In primary human adipocytes, genistein inhibited aP2, SREBP 1, and FAS. 103 In human adipose tissuederived mesenchymal stem cells, adipogenesis inhibition was associated with the Wnt/-catenin signaling pathway through the expression of Wnt3, adipogenesis inhibitor, the inhibition of Wnt signaling antagonists, and increase of mRNA and protein levels of -catenin. 104 Guggulsterone Plant sterol guggulsterone by FXR antagonism exhibits cholesterol-lowering activity and prevents preadipocyte differentiation. 52 In 3T3-L1 cells, cis-guggulsterone downregulates PPAR2, C/EBP, and C/EBP. 105 In addition, the combination of guggulsterone with genistein exerts anti-adipogenic effects more potently than individual compounds. 106 Recently it was shown that guggulsterone exerts its anti-obesity effects by inducing beiging of adipocytes through mitochondrial biogenesis and an upregulation of UCP1 and cellular oxygen consumption in 3T3-L1 preadipocytes. 107 Berberine Berberine is an isoquinoline derivative alkaloid that stimulates weight loss, increases insulin sensitivity, lowers blood glucose, and improves lipid metabolism. It increases the mRNA expression of adiponectin and decreases the secretion of leptin and resistin. 108 Although one recent randomized controlled trial reported no change in BMI and body weight, it reported a reduction in hemoglobin A1C (HbA1c) and triglyceride levels. 109 During adipogenesis berberine affects PPAR transcriptional activity, mRNA, and protein levels in 3T3-L1 cells by interfering with the C/EBP signal. 110 Berberine can also increase GATA-2 and GATA-3 mRNA and protein expression in 3T3-L1 cells and reduce expression of PPAR and C/EBP mRNA and weight gain in high-fat diet-induced obese mice. 111 Other anti-adipogenic mechanisms of berberine include phosphorylation of p38/AMPK, deactivation of PPAR, 112 and upregulation of DEC2 mRNA levels. 113 Curcumin Curcumin, a polyphenol from an Asian spice herb Curcuma longa, exerts anti-adipogenic effects through activation of Wnt/ -catenin signaling in 3T3-L1 cells. During differentiation, curcumin restores -catenin's nuclear translocation suppresses the expression of catenin destruction complex members and increases mRNA levels of cyclin D1. 114 Other anti-adipogenic mechanisms of curcumin include activating AMPK, downregulating PPAR transcription, 115 decreasing phosphorylation of MAPKs, altered abundance or phosphorylation of GSK3, 114 upregulation of KLF4 and KLF5, blocking cell entry into the S phase and the S to the G2/M phase transition, decreasing C/EBP expression and suppressing adipogenic cocktail-induced proliferation. 116 In vivo study using mice on high fat diet showed that 500 mg/kg dietary curcumin significantly decreased weight, total body fat and serum cholesterol compared to untreated mice. 96 Epigallocatechin Gallate Green tea polyphenol Epigallocatechin gallate (EGCG) is known to possess antiproliferative, antioxidant, antibacterial, and chemopreventive effects. 117 Other health benefits induced by green tea extracts include anti-hypertensive and insulin-sensitizing effects. In humans, EGCG exerts antiobesity effects through ghrelin secretion inhibition, adiponectin levels increase, appetite control, nutrient absorption decrease, and adipogenesis inhibition. 118 It suppresses adipocyte clonal expansion and inhibits adipogenesis in 3T3-L1 Diabetes, Metabolic Syndrome and Obesity: Targets and Therapy 2021:14 submit your manuscript | www.dovepress.com DovePress adipocytes via the PI3K/AKT and MAPK/ERK signaling pathway. 119 Moreover, EGCG blocks cell entry into the S phase and the S to G2/M phase transition and suppresses adipogenic cocktail-induced proliferation. 120 In other studies, using 3T3-L1 cells, EGCG reduced triglyceride accumulation and inhibited the expression of PPAR and C/ EBP, 121 up-regulated phosphorylation of AMPK and the expression of key Wnt signaling related genes, 120 and increased energy expenditure and thermogenesis. 122 In vivo studies on high fat diet-induced obese mice showed that EGCG reduced body weight and plasma lipids, decreased PPAR, C/EBP, SREBP1, aP2, LPL, and FAS in WAT, increased the expression of key genes for lipolysis, oxidation and thermogenesis, 123 and attenuated fat tissue formation and body weight gain. 124 Oxysterols Oxysterols are oxidized cholesterol metabolites capable of inhibiting the expression of key adipogenic transcripts and adipogenic differentiation. In mouse bone marrow stromal cells, oxysterols inhibited PPAR2 expression and adipogenic differentiation via Hh signaling pathway; 125 reduced expressions of key adipogenic transcripts through Hh and ERK signaling in hen preadipocytes; 126 and reduced expression of PPAR2, LPL, and aP2 in MSCs. 127 Resveratrol Resveratrol (RSV) is a member of the natural polyphenols found in peanuts, groundnuts, grapevines, and red vines. 128 It is beneficial for human health due to the cardioprotective effect, anti-inflammatory, and anti-cancer properties. 129 In studies using 3T3-L1 cells, resveratrol treatment significantly decreased lipid accumulation, down-regulated the expression of C/EBP, LPL, FAS, and SREBP-1c through activation of AMPK, 130 decreased phosphorylation of MAPKs, and reduced Rb phosphorylation, 131 suppressed hormonal-induced AKT activation and cell proliferation, and inhibited cell entry into the S phase and the S to the G2/M phase transition. 132 RSV is the first polyphenolic compound that activates SIRT1, inhibiting proliferation and adipogenic differentiation in human preadipocytes. 133 A reformulated version of RSV was tested on obese patients where it showed a reduction of blood pressure, serum glucose, and triglyceride levels and increased the number of small adipocytes in subcutaneous adipose tissue. 134 In another study on patients with T2DM, RSV increased SIRT1 and AMPK expression in muscles. 135 However, its prophylactic administration to non-obese individuals showed no significant effect on insulin sensitivity, blood pressure, and body composition. 136 The effect of RSV in humans still needs further investigations using larger cohorts and longer follow-up time. Gum Dietary fibers have recently been recognized as an important ally in the management of hypertension and obesity. Fibers contribute to weight loss, increase insulin sensitivity, have glucose-lowering effects, reduce lipid levels and blood pressure. Dietary gum is rich in fibers and can decrease body weight and blood pressure. Some of the mechanisms include decreased energy intake and adipose tissue accumulation, and downregulation of PPAR-. One meta-analysis of 21 studies with 990 participants summarized results on decreased body weight and waist circumference without effect on BMI. That effect was better with shorter administration of ≤15 g/day gum intake. 137 Phytosterols Phytosterols are components of the cell membrane in plants structurally similar to cholesterol. The primary dietary sources of phytosterols are vegetable oils, nuts, fruits, and seeds. They have been shown to lower cholesterol absorption in animals, possibly due to the chemical similarity with cholesterol causing cholesterol absorption inhibition. 138 One study showed that glucose levels decreased and insulin levels increased after oral administration of -sitosterol in hyperglycemic rats. 139 Several meta-analyses have concluded that phytosterols use decreases obesity indices, reduces serum lipoprotein and free fatty acid, and improves the lipid profile in humans. A plausible mechanism regarding favorable effects in diabetes might be related to the expression and translocation of GLUT-4 in the skeletal muscle, liver, and white adipose tissue. In vitro studies showed stimulation and phosphorylation of the AMPK pathway enhancing GLUT-4 translocation and expression. 140 Natural Products and Potential Risks As the global use of herbal medicinal products increase, and approximately 80% of people today depend upon herbal medication as a component of their primary health care, concerns about their safety and efficacy are more recognized. Only medicines have to be proven safe before being released into the market, and herbal products do not fall under that category. They are readily available in the market without prescription without control for purity and potency. The general perception that herbal remedies are natural, safe, and have fewer side effects is misleading. Knowledge of potential adverse effects are limited as herbal medicines are untested, and their use and effect are not monitored. 141 People often do not consider how natural products may interact with any prescription drug they are taking or with each other. Herbs have been shown to produce a wide range of adverse reactions if taken irregularly, in excessive amounts, or in combination with some medicines. In general, extensive biochemical monitoring and follow-up are necessary for patients taking herbal preparations regularly. 142 Conclusion Over the last few years, adipogenesis is considered an important factor in the pathophysiology of obesity and obesityrelated complications. As a complex process involving various transcriptional cascades, signaling pathways, and molecular mechanisms, significant effort has been made to identify the most suitable adipogenesis regulators to serve as potential therapeutic targets. Most studies are carried out in vitro, revealing additional mechanisms through which conventional medications that are already in use for treating dyslipidemia or T2DM can also affect adipogenesis. Despite the increase in the number of available drugs, obesity prevalence is still rising. That is why several natural products are 77 being investigated as anti-obesity agents due to their ability to reduce adipose tissue mass through inhibiting adipogenesis. More evidence indicates that natural products can target more than one known pathway or transcriptional cascade involved in adipogenesis. Our understanding of adipogenesis and its key modulators is still limited. The goal is to increase knowledge on the key adipogenesis determinants' function and relevance to adipose tissue pathophysiology, resulting in new targets for anti-obesity drug development without compromising patients' health. There is still a need to investigate further potential treatment in vivo since their clinical translation is still limited. More studies that will elucidate the best ways for interfering with adipocyte formation, and give precise data on the safety and metabolism of potential antiobesity treatment, will make adipogenesis molecular mechanisms powerful targets in fighting obesity. |
1. Field of the Invention
The present disclosure relates to a vehicle lamp configured to irradiate infrared light in a vehicle forward direction.
2. Related Art
In recent years, an infrared-light night vision camera system is used in order to improve night driving safety. The infrared-light night vision camera system picks up an image in a vehicle forward direction while irradiating infrared light in a vehicle forward direction and recognizes a state in a vehicle forward direction by displaying the pick-up image on a monitor or the like.
In terms of the infrared-light night vision camera system, it is possible to obtain information in a vehicle forward direction, the information being not obtainable during a general visible light irradiation operation. For example, in a state where a head lamp unit irradiates the visible light in a low beam mode, it is not possible to obtain information on a space above a cutoff line of a low beam distribution pattern. However, when the infrared light is irradiated together with the visible light, it is possible to sufficiently recognize a situation in a vehicle forward direction without giving a glare to a driver or the like in the opposite vehicle.
In the infrared-light night vision camera system, the infrared light in a near-infrared range is used. However, since a red light is included in a part of the irradiated light, a front lens is tinged with red when a vehicle lamp is observed from the front side upon irradiating the infrared light, thereby causing a problem in that the driver in the opposite vehicle feels uncomfortable.
For this reason, in the past, as disclosed in JP-A-2003-19919 or JP-A-2004-146162, a study has been carried out which prevents in advance the front lens from being tinged with red in such a manner that the red light and the visible light are simultaneously irradiated from the vehicle lamp.
In the vehicle lamp disclosed in JP-A-2003-19919, the red light and the visible light are simultaneously irradiated in such a manner that an infrared light non-formation region, through which a visible light component of a light source passes, is formed in the outer periphery of an infrared light transmission film through which a red light component of the light source passes.
On the other hand, in the vehicle lamp disclosed in JP-A-2004-146162, the red light and the visible light are simultaneously irradiated in such a manner that an incandescent bulb is disposed in front of an infrared light transmission filter disposed in a lamp room and the incandescent bulb is simultaneously turned on upon irradiating the red light.
The vehicle lamp disclosed in JP-A-2003-19919 or JP-A-2004-146162 has a function of preventing the front lens from being tinged with red upon irradiating the infrared light in a vehicle forward direction, but does not have any other functions.
That is, the vehicle lamp disclosed JP-A-2003-19919 is not configured to irradiate the visible light.
On the other hand, the vehicle lamp disclosed in JP-A-2004-146162 is configured to irradiate the visible light by turning on the incandescent bulb in addition to the infrared light. However, since the light of the incandescent bulb is not controlled upon being emitted from the front lens, it is difficult to form a desired light distribution pattern by means of the light of the incandescent bulb. |
package org.dataone.client.types;
import static org.junit.Assert.*;
import java.util.Date;
import org.dataone.client.v1.types.D1TypeBuilder;
import org.dataone.service.types.v1.Identifier;
import org.junit.Before;
import org.junit.Test;
public class ObsoletesChainTest {
private ObsoletesChain chain;
private ObsoletesChain chainWithNulls;
private Identifier foo1 = D1TypeBuilder.buildIdentifier("foo1");
private Identifier foo2 = D1TypeBuilder.buildIdentifier("foo2");
private Identifier foo3 = D1TypeBuilder.buildIdentifier("foo3");
private Identifier foo4 = D1TypeBuilder.buildIdentifier("foo4");
private Identifier foo5 = D1TypeBuilder.buildIdentifier("foo5");
private Identifier foo6 = D1TypeBuilder.buildIdentifier("foo6");
private Identifier foo7 = D1TypeBuilder.buildIdentifier("foo7");
private Identifier foo8 = D1TypeBuilder.buildIdentifier("foo8");
private Identifier foo9 = D1TypeBuilder.buildIdentifier("foo9");
@Before
public void setUp() throws Exception {
chain = new ObsoletesChain(foo3);
chain.addObject(foo4, new Date(4000000), foo3, foo5, true);
chain.addObject(foo3, new Date(3000000), foo2, foo4, true);
chain.addObject(foo2, new Date(2000000), foo1, foo3, true);
chain.addObject(foo1, new Date(1000000), null, foo2, true);
chain.addObject(foo5, new Date(5000000), foo4, foo6, true);
chain.addObject(foo6, new Date(6000000), foo5, foo7, true);
chain.addObject(foo7, new Date(7000000), foo6, foo8, true);
chain.addObject(foo8, new Date(8000000), foo7, foo9, true);
chain.addObject(foo9, new Date(9000000), foo8, null, false);
chainWithNulls = new ObsoletesChain(foo3);
chainWithNulls.addObject(foo4, new Date(4000000), foo3, foo5, true);
chainWithNulls.addObject(foo3, new Date(3000000), foo2, foo4, true);
chainWithNulls.addObject(foo2, new Date(2000000), foo1, foo3, true);
chainWithNulls.addObject(foo1, new Date(1000000), null, foo2, true);
chainWithNulls.addObject(foo5, new Date(5000000), foo4, foo6, true);
chainWithNulls.addObject(foo6, new Date(6000000), foo5, foo7, true);
chainWithNulls.addObject(foo7, new Date(7000000), foo6, foo8, true);
chainWithNulls.addObject(foo8, new Date(8000000), foo7, foo9, true);
chainWithNulls.addObject(foo9, new Date(9000000), foo8, null, null);
}
@Test
public void testGetStartingPoint() {
assertTrue(chain.getStartingPoint().equals(foo3));
}
// @Test
public void testAddObject() {
fail("Not yet implemented");
}
@Test
public void testGetVersionAsOf() {
assertTrue(chain.getVersionAsOf(new Date(6300000)).equals(foo6));
assertNull(chain.getVersionAsOf(new Date(300000)));
assertTrue(chain.getVersionAsOf(new Date(10300000)).equals(foo9));
}
@Test
public void testNextVersion() {
assertTrue(chain.nextVersion(foo2).equals(foo3));
assertNull(chain.nextVersion(foo9));
}
@Test
public void testPreviousVersion() {
assertTrue(chain.previousVersion(foo8).equals(foo7));
assertNull(chain.previousVersion(foo1));
}
@Test
public void testGetLatestVersion() {
assertTrue(chain.getLatestVersion().equals(foo9));
}
@Test
public void testGetOriginalVersion() {
assertTrue(chain.getOriginalVersion().equals(foo1));
}
@Test
public void testGetByPosition() {
assertTrue(chain.getByPosition(4).equals(foo5));
}
@Test
public void testSize() {
assertTrue(chain.size() == 9);
}
@Test
public void testIsComplete() {
assertTrue(chain.isComplete());
}
@Test
public void testIsArchived() {
assertTrue(chain.isArchived(foo2));
assertFalse(chain.isArchived(foo9));
}
@Test
public void testLatestIsArchived() {
assertFalse(chain.latestIsArchived());
}
@Test
public void testGetPublishDate() {
Date expect = new Date(2000000);
System.out.print(expect.getTime());
System.out.print(chain.getPublishDate(foo2).getTime());
assertTrue(chain.getPublishDate(foo2).equals(expect));
}
@Test
public void testIsLatestVersion() {
assertTrue(chain.isLatestVersion(foo9));
assertFalse(chain.isLatestVersion(foo5));
}
@Test
public void testIsArchived_Null() {
assertTrue(chainWithNulls.isArchived(foo2));
assertFalse(chainWithNulls.isArchived(foo9));
}
}
|
Microbial Growth Models in Gilthead Sea Bream (Sparus aurata) Stored in Ice ABSTRACT This study analyzes microbiological changes in whole, ungutted farmed gilthead sea bream (Sparus aurata) stored for an 18-day period in ice using traditional methods for mesophilic aerobic bacteria, psychrotrophic, Pseudomonas spp., Aeromonas spp., Shewanella putrefaciens, Enterobacteriaceae, sulphide-reducing Clostridium (Clostridia), and Photobacterium phosphoreum in muscle, skin, and gills, evaluating their seasonal differentiation. Two different statistical models were used to analyze microbiological growth. Simultaneously, physicochemical parameters such as the temperature, pH, biological oxygen demand (BOD), total dissolved solids, salinity, ammonia nitrogen, and total phosphorus content of growing waters were analyzed. The results showed that by the end of the storage time, specific spoilage bacteria (SSB) such as Pseudomonas spp., Aeromonas spp., and S. putrefaciens as H2S-producing bacteria were dominant in sea bream harvested in temperate water in the Canary Islands. Muscle tissue had the least contamination, followed by skin and gills. The values of the analyzed seawater parameters were constant during the four seasons, except that the temperature showed a small difference between winter and summer. Seasonal effects were observed among the fish analyzed, suggesting that the lower levels of contamination detected in winter may have been due to the slight difference observed in water temperature in that season. |
Alfred Westou
Alfred, son of Westou (fl. c. 1020 – after 1056) was a medieval English priest and relic collector, active in Northumberland. He is now best known for allegedly stealing the remains of Bede and bringing them in secret to the shrine of St Cuthbert in Durham, although some modern scholars consider this unlikely. He is also documented as having translated the remains of Boisil of Melrose Abbey, as well as numerous northern English minor saints of the 7th and 8th centuries: the anchorites Balther and Bilfrid; Acca, Alchmund and Eata, bishops of Hexham; Oswin, king of Deira; and the abbesses Ebba and Æthelgitha. He served as the sacristan at Cuthbert's shrine under three bishops, and was renowned for his devotion to the saint.
Cuthbert's shrine and the Durham Ecclesia Major
Alfred served as sacristan at the shrine of St Cuthbert in Durham during the time of the bishops Edmund, Æthelric and Æthelwine, in the early–mid 11th century. The miraculously incorrupt remains of the saint, who died in 687, were then housed in a large stone church or cathedral referred to as the Ecclesia Major, dedicated in 998 and demolished to make way for the existing Norman cathedral in around 1093.
The early chronicler of Durham's history Symeon of Durham praises Alfred as a pious man and an ideal custodian to Cuthbert's relics, and the later chronicler Reginald of Durham describes him as being "of decent life". His descendant Ailred of Rievaulx describes him as an "active teacher". The modern theologian and historian Benedicta Ward, in her biography of Bede, describes Alfred as a stern teacher to the cathedral's young novices, and states that he was recorded as being respected by the "honest and God-fearing". The modern historian John Crook writes that Alfred was "highly respected" by all three of the Durham bishops. W. M. Aird, on the other hand, describes him as the leader of a group that expelled Bishop Æthelric in around 1045; the bishop was subsequently reinstated by Earl Siward and succeeded by his brother Æthelwine.
For part or all of his time as sacristan, Alfred is reported to have had the sole responsibility for tending to Cuthbert's remains, and several stories have accumulated about his exceptional devotion to Cuthbert. According to Symeon and Reginald, Alfred removed one of Cuthbert's hairs, and found that it miraculously failed to burn. Reginald adds that he frequently opened the coffin to wrap the saint's body in robes, and to trim his fingernails and cut or comb his hair and beard. An ivory liturgical or ordinary comb was among the treasures found in Cuthbert's shrine in 1827. Reginald claims that the two exchanged "familiar speech" at times, stating that Cuthbert gave Alfred detailed instructions on what to do with the various saints' relics he collected. He also recounts a story about a weasel that reared her litter in the reliquary.
Modern historians consider Reginald's uncorroborated material to be of dubious historical value. Calvin B. Kendall has suggested that the story of Alfred tending to the body's hair and nails might have originated in a similar account relating to the Norwegian king and saint Olaf, whose body was said to be tended by his son after his death in 1030; according to Kendall, this story would have been known to Turgot of Durham – the prior of the Durham monastery who oversaw the translation of Cuthbert's remains into the new cathedral in 1104 – as he had previously stayed at the Norwegian court. Ward notes its similarity to stories associated with English saints, including Osmund of Salisbury.
Hexham and personal life
In addition to his sacristan duties, Alfred also held the church of Hexham, Northumberland, from Bishop Edmund, where his family were hereditary priests. As he lived in Durham, his Hexham duties were delegated first to Gamel the Elder (Gamel Hamel) and then to Gamel iunge. Alfred was married, his wife being the sister of Collan, prior of Hexham. His date of death is unknown, but he is recorded to be still alive at the time of Bishop Æthelwine (1056–71); Crook speculates that he might have died just before the Norman Conquest.
Alfred's son Eilaf Larwa and his grandson, also named Eilaf, each succeeded him as the priest at Hexham. A grandson Aldred or Aluredus is also recorded as a shrine keeper. The saint Ailred, Cistercian abbot of Rievaulx, was Alfred's great-grandson.
Hexham bishops: Acca, Alchmund and Eata
A variant version of the story of Alchmund of Hexham's translation is given by an anonymous author, probably from Hexham, in the Historia Regum. The vision of Bishop Alchmund is here given to a person referred to as "Dregmo", who summons Alfred to rebury the remains in Hexham church. Alfred complies, but secretly takes a fingerbone, which he plans to take to the shrine in Durham. On the following day the saint's bier proves immovable from the portico; Dregmo has a second vision exposing the theft, to which Alfred readily admits. After the restoration of the fingerbone, the ceremony proceeds unhindered. This version is repeated by Ailred of Rievaulx.
According to the Historia Regum as well as the accounts of Richard of Hexham and Ailred of Rievaulx, when Bishop Acca was reburied in Hexham, several relics were removed undamaged from his grave. These included some of his vestments (chasuble, dalmatic and maniple), his shroud and a silk tunic, as well as a wooden portable altar. The chasuble and portions of his "face-cloth" appear in a list of Durham Cathedral's relics compiled in 1383.
The 12th-century Life of St Eata suggests that a third Hexham bishop and saint, Eata (died 686), might also have been translated within the Hexham church by Alfred, although he is not mentioned in either Symeon's list of saints or Ailred's work. Eata also served as Abbot of Melrose Abbey and Bishop of Lindisfarne, and had taught both Cuthbert and Boisil.
Theft of Bede
Alfred is also traditionally reported to have stolen the bones of the scholar and saint Bede (died 735) from its shrine in Jarrow, and translated them to Durham in secret. Symeon's detailed account is uncharacteristically circumspect. No vision is mentioned. After establishing that Alfred was in the habit of commemorating Bede's death by visiting the Jarrow monastery, it states that one year he arrived back early, having left his companions behind, and never returned to Jarrow. He is then said to have acted as if he had "secured the object of his desires", saying when asked about the whereabouts of Bede's bones that they were in Cuthbert's shrine, but enjoining his listeners to keep the matter to themselves. When Cuthbert's coffin was opened a few days before its translation to the Norman cathedral, around half a century after Alfred's death, a little linen bag was discovered, subsequently claimed to contain Bede's bones. The story has some similarities with the 9th-century theft by Ariviscus of the French Sainte Foy's relics from Agen, Aquitaine.
The discovery of the bag is also described by an eye-witness to the opening of the coffin in the later "Miracle 18" account. The anonymous author states that Bede's bones were known to have been removed from his original burial place in Jarrow; he names Alfred only indirectly as the person who also translated Boisil's remains.
Kendall notes that examinations of Cuthbert's coffin in the 1050s are not recorded to have found a linen bag. He considers the tradition of Alfred's secret translation of Bede to be "probably apocryphal", inferring that it was invented to provide provenance for the unidentified bones in the linen bag. Some subsequent 20th- and 21st-century scholars have also cast doubts on the story's authenticity. Ward describes it as a "strange story", and draws attention to its close parallels with the medieval "pious theft" literary tradition, a genre that embraces wholly fictional accounts. She notes that the earliest written account of the removal of the bones dates from at least 100 years later, there is no external evidence for Alfred's action, and the attendant secrecy meant that the translation did not fulfil its purpose. She suggests another possibility: that monks from Jarrow translated the remains in 1083 when the Benedictine priory was founded in Durham. |
<filename>tools/visualization/extract_time_and_pressures_tips.py
import os
import json
import numpy as np
import argparse
def reformat_data(d):
if len(d.shape) == 1:
d = d.reshape((len(d), 1))
return d
def load_data_by_vessel(directory_name, v):
d_list = {}
if 'filepath_p' in v['filepaths']:
d_list['p'] = reformat_data(np.loadtxt(os.path.join(directory_name, v['filepaths']['filepath_p'])))
if 'filepath_c' in v['filepaths']:
d_list['c'] = reformat_data(np.loadtxt(os.path.join(directory_name, v['filepaths']['filepath_c'])))
if 'filepath_V' in v['filepaths']:
d_list['V'] = reformat_data(np.loadtxt(os.path.join(directory_name, v['filepaths']['filepath_V'])))
if 'filepath_p_out' in v:
d_list['p_out'] = reformat_data(np.loadtxt(os.path.join(directory_name, v['filepath_p_out'])))
return d_list, v
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Animator for the vessel data.')
parser.add_argument('--filepath', type=str, help='Filepath to a file containing the pressures and flows.', required=True)
parser.add_argument('--output-filepath', type=str, help='Filepath to a file containing the pressures and flows.', required=True)
parser.add_argument('--t-start', type=float, help='Start point when to plot', default=0.)
parser.add_argument('--t-stop', type=float, help='Start point when to plot', required=False)
parser.add_argument('--dofs', type=int, nargs='+', help='A list of dofs to observer.', default=[-1])
args = parser.parse_args()
directory_name = os.path.dirname(args.filepath)
with open(args.filepath) as f:
metainfo = json.loads(f.read())
t = np.array(metainfo['times'])
start_index = sum(t < args.t_start)
if args.t_stop is not None:
stop_index = sum(t <= args.t_stop)
else:
stop_index = len(t)
data_list = []
for vertex in metainfo['vertices']:
data, vertex = load_data_by_vessel(directory_name, vertex)
p = data['p'][start_index:stop_index, -1] * 1e3 # kg -> g conversion factor
p_mean = p.mean()
R = vertex['resistance'][-1] * 1e3 # kg -> g
level = len(vertex['resistance'])
vertex_id = vertex['vertex_id']
coordinates = vertex['coordinates']
data_list.append({
'p': coordinates,
'vertex_id': vertex_id,
'pressure': p_mean,
'concentration': 1,
'R2': R,
'radius': vertex['radii'][-1],
'level': level
})
serialized_data = json.dumps({'vertices': data_list}, indent=0)
print(serialized_data)
with open(args.output_filepath, 'w') as f:
f.write(serialized_data)
print('wrote to {}'.format(args.output_filepath))
|
Field of the Invention
The subject matter disclosed herein generally relates micro-services and, more specifically, to accessing and executing these micro-services.
Brief Description of the Related Art
Computing systems utilize micro-services to, among other things, process and display information to users. In aspects, a micro-service is a component (e.g., a component written in software) that performs a single unit of work. The unit of work may be defined as the accomplishment of a work function. For example, micro-services can be used within a web page to display price, display suppliers, or display product ratings, to mention a few examples. Other example of micro-services include micro-services for validation of code (e.g., determine if there are viruses in the code), micro-services that provide user authentication, and micro-services that provide for classification of data.
Micro-services can be executed as layers, by calling (or executing) other micro-services. Micro-services, however, are not independently aware of the physical addresses of the dependent micro-services. In-order for one micro-service to call another micro-service, the calling micro-service requires knowledge of the physical address of the called micro-services. In other words, the addresses were static and the code of the calling micro-service was embedded with the physical address of the called micro-service.
This type of architecture created various problems. If the physical addresses of the called micro-service changed, then calling micro-service would need to be reconfigured and re-deployed. In another problem, if a first server that executed a micro-service went down or otherwise failed, there was no possibility a second server could be utilized to execute the micro-service since the address of the server could not be changed. Registrations of micro-services were manual and required resolution of all the micro-services present in the ecosystem.
All of these problems resulted in some user dissatisfaction with previous approaches. |
from .BST_nearest_val import nearest_val as NV
def test_BST_nearest_val_example_one():
data = sorted([1, 3, 6, 4, 7, 8, 10, 14, 13])
assert NV(data, 9) == 10
def test_BST_nearest_val_example_two():
data = sorted([8, 3, 1, 6, 4, 7, 10, 14, 13])
assert NV(data, 13) == 13
def test_BST_nearest_val_example_three():
data = sorted([8, 3, 1, 6, 4, 7, 10, 14, 13])
assert NV(data, 0) == 1
def test_BST_nearest_val_final_one():
data = sorted([15, 20, 7, 9, 3, 32, 17])
assert NV(data, 13) == 15
def test_BST_nearest_val_final_two():
data = sorted([15, 20, 7, 9, 3, 32, 17])
assert NV(data, 30) == 32
def test_BST_nearest_val_duplicates():
data = sorted([15, 20, 7, 9, 20, 32, 32])
assert NV(data, 30) == 32
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# <NAME>
#
# Copyright 2011 <NAME> <<EMAIL>>
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""":synopsis: Functional programming primitives.
:module: mom.functional
Higher-order functions
-----------------------
These functions accept other functions as arguments and apply them over
specific types of data structures. Here's an example of how to find the
youngest person and the oldest person from among people. Place it into a
Python module and run it::
import pprint
from mom import functional
PEOPLE = [
{"name": "Harry", "age": 100},
{"name": "Hermione", "age": 16},
{"name": "Rob", "age": 200},
]
def youngest(person1, person2):
'''Comparator that returns the youngest of two people.'''
return person1 if person1["age"] <= person2["age"] else person2
def oldest(person1, person2):
'''Comparator that returns the oldest of two people.'''
return person1 if person1["age"] >= person2["age"] else person2
who_youngest = functional.reduce(youngest, PEOPLE)
who_oldest = functional.reduce(oldest, PEOPLE)
pprint.print(who_youngest)
# -> {"age" : 16, "name" : "Hermione"}
pprint.print(who_oldest)
# -> {"age" : 200, "name" : "Rob"}
# More examples.
# Now let's list all the names of the people.
names_of_people = functional.pluck(PEOPLE, "name")
pprint.print(names_of_people)
# -> ("Harry", "Hermione", "Rob")
# Let's weed out all people who don't have an "H" in their names.
pprint.print(functional.reject(lambda name: "H" not in name,
names_of_people))
# -> ("Harry", "Hermione")
# Or let's partition them into two groups
pprint.print(functional.partition(lambda name: "H" in name,
names_of_people))
# -> (["Harry", "Hermione"], ["Rob"])
# Let's find all the members of a module that are not exported to wildcard
# imports by its ``__all__`` member.
pprint.print(functional.difference(dir(functional), functional.__all__))
# -> ["__all__",
# "__author__",
# "__builtins__",
# "__doc__",
# "__file__",
# "__name__",
# "__package__",
# "_compose",
# "_contains_fallback",
# "_get_iter_next",
# "_ifilter",
# "_ifilterfalse",
# "_leading",
# "_some1",
# "_some2",
# "absolute_import",
# "builtins",
# "chain",
# "collections",
# "functools",
# "itertools",
# "map",
# "starmap"]
Higher-order functions are extremely useful where you want to express yourself
succinctly instead of writing a ton of for and while loops.
.. WARNING:: About consuming iterators multiple times
Now before you go all guns blazing with this set of functions, please note
that Python generators/iterators are for single use only. Attempting to use
the same iterator multiple times will cause unexpected behavior in your
code.
Be careful.
Terminology
-----------
* A **predicate** is a function that returns the truth value of its argument.
* A **complement** is a predicate function that returns the negated truth value
of its argument.
* A **walker** is a function that consumes one or more items from a sequence
at a time.
* A **transform** is a function that transforms its arguments to produce a
result.
* **Lazy evaluation** is evaluation delayed until the last possible instant.
* **Materialized iterables** are iterables that take up memory equal to their
size.
* **Dematerialized iterables** are iterables (usually iterators/generators)
that are evaluated lazily.
Iteration and aggregation
~~~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: each
.. autofunction:: reduce
Logic and search
~~~~~~~~~~~~~~~~
.. autofunction:: every
.. autofunction:: find
.. autofunction:: none
.. autofunction:: some
Filtering
~~~~~~~~~
.. autofunction:: ireject
.. autofunction:: iselect
.. autofunction:: partition
.. autofunction:: reject
.. autofunction:: select
Counting
~~~~~~~~
.. autofunction:: leading
.. autofunction:: tally
.. autofunction:: trailing
Function-generators
~~~~~~~~~~~~~~~~~~~
.. autofunction:: complement
.. autofunction:: compose
Iterators
---------
These functions take iterators as arguments.
.. autofunction:: eat
Iterable sequences
------------------
These functions allow you to filter, manipulate, slice, index, etc.
iterable sequences.
Indexing and slicing
~~~~~~~~~~~~~~~~~~~~
.. autofunction:: chunks
.. autofunction:: head
.. autofunction:: ichunks
.. autofunction:: ipeel
.. autofunction:: itail
.. autofunction:: last
.. autofunction:: nth
.. autofunction:: peel
.. autofunction:: tail
.. autofunction:: round_robin
.. autofunction:: take
.. autofunction:: ncycles
.. autofunction:: occurrences
Manipulation, filtering
~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: contains
.. autofunction:: omits
.. autofunction:: falsy
.. autofunction:: ifalsy
.. autofunction:: itruthy
.. autofunction:: truthy
.. autofunction:: without
Flattening, grouping, unions, differences, and intersections
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: flatten
.. autofunction:: flatten1
.. autofunction:: group_consecutive
.. autofunction:: flock
.. autofunction:: intersection
.. autofunction:: idifference
.. autofunction:: difference
.. autofunction:: union
.. autofunction:: unique
Dictionaries and dictionary sequences
-------------------------------------
.. autofunction:: invert_dict
.. autofunction:: ipluck
.. autofunction:: map_dict
.. autofunction:: pluck
.. autofunction:: reject_dict
.. autofunction:: select_dict
.. autofunction:: partition_dict
Predicates, transforms, and walkers
-----------------------------------
.. autofunction:: always
.. autofunction:: constant
.. autofunction:: identity
.. autofunction:: loob
.. autofunction:: never
.. autofunction:: nothing
"""
# pylint: disable-msg=C0302
from __future__ import absolute_import
import collections
import functools
import itertools
try:
# Python 2.x
from itertools import ifilter as _ifilter
from itertools import ifilterfalse as _ifilterfalse
from itertools import imap as map
except ImportError: # pragma: no cover
# Python 3 nuisance.
_ifilter = filter
def _ifilterfalse(predicate, iterable):
"""ifilterfalse replacement for python 3."""
predicate = predicate or bool
def _complement(item):
"""Negates a predicate."""
return not predicate(item)
return filter(_complement, iterable)
from mom import builtins
from mom.itertools import chain
from mom.itertools import starmap
__author__ = "<EMAIL> (<NAME>)"
__all__ = [
"always",
"chunks",
"complement",
"compose",
"contains",
"difference",
"each",
"eat",
"every",
"falsy",
"find",
"flatten",
"flatten1",
"flock",
"group_consecutive",
"head",
"ichunks",
"identity",
"idifference",
"ifalsy",
"intersection",
"invert_dict",
"ipeel",
"ipluck",
"ireject",
"iselect",
"itail",
"itruthy",
"last",
"leading",
"loob",
"map_dict",
"ncycles",
"never",
"none",
"nth",
"occurrences",
"omits",
"partition",
"partition_dict",
"peel",
"pluck",
"reduce",
"reject",
"reject_dict",
"round_robin",
"select",
"select_dict",
"some",
"tail",
"take",
"tally",
"trailing",
"truthy",
"union",
"unique",
"without",
]
# Higher-order functions that generate other functions.
def compose(function, *functions):
"""Composes a sequence of functions such that::
compose(g, f, s) -> g(f(s()))
:param functions:
An iterable of functions.
:returns:
A composition function.
"""
def _composition(a_func, b_func):
"""Composition."""
def _wrap(*args, **kwargs):
"""Wrapper."""
return a_func(b_func(*args, **kwargs))
return _wrap
return builtins.reduce(_composition, functions, function)
def _compose(function, *functions):
"""Alternative implementation.
Composes a sequence of functions such that::
compose(g(), f(), s()) -> g(f(s()))
:param functions:
An iterable of functions.
:returns:
A composition function.
"""
functions = (function,) + functions if functions else (function,)
def _composition(*args_tuple):
"""Composition."""
args = list(args_tuple)
for function in reversed(functions):
args = [function(*args)]
return args[0]
return _composition
def complement(predicate):
"""Generates a complementary predicate function for the given predicate
function.
:param predicate:
Predicate function.
:returns:
Complementary predicate function.
"""
def _negate(*args, **kwargs):
"""Negation."""
return not predicate(*args, **kwargs)
return _negate
# Higher-order functions.
def reduce(transform, iterable, *args):
"""Aggregate a sequence of items into a single item. Python equivalent of
Haskell's left fold.
Please see Python documentation for reduce. There is no change in behavior.
This is simply a wrapper function.
If you need reduce_right (right fold)::
reduce_right = foldr = lambda f, i: lambda s: reduce(f, s, i)
:param transform:
Function with signature::
f(x, y)
:param iterable:
Iterable sequence.
:param args:
Initial value.
:returns:
Aggregated item.
"""
return builtins.reduce(transform, iterable, *args)
def each(walker, iterable):
"""Iterates over iterable yielding each item in turn to the walker function.
:param walker:
The method signature is as follows:
f(x, y)
where ``x, y`` is a ``key, value`` pair if iterable is a dictionary,
otherwise ``x, y`` is an ``index, item`` pair.
:param iterable:
Iterable sequence or dictionary.
"""
if isinstance(iterable, dict):
builtins.dict_each(walker, iterable)
else:
for index, item in enumerate(iterable):
walker(index, item)
def some(predicate, iterable):
"""Determines whether the predicate applied to any element of the iterable
is true.
:param predicate:
Predicate function of the form::
f(x) -> bool
:param iterable:
Iterable sequence.
:returns:
``True`` if the predicate applied to any element of the iterable
is true; ``False`` otherwise.
"""
for item in iterable:
if predicate(item):
return True
return False
def _some1(predicate, iterable):
"""Alternative implementation of :func:`some`."""
return any(map(predicate, iterable))
def _some2(predicate, iterable):
"""Alternative implementation of :func:`some`."""
result = False
for _ in itertools.dropwhile(complement(predicate), iterable):
result = True
return result
def every(predicate, iterable):
"""Determines whether the predicate is true for all elements in the iterable.
:param predicate:
Predicate function of the form::
f(x) -> bool
:param iterable:
Iterable sequence.
:returns:
``True`` if the predicate is true for all elements in the iterable.
"""
# Equivalent to
# return all(map(predicate, iterable))
# but the following short-circuits.
for item in iterable:
if not predicate(item):
return False
return True
def none(predicate, iterable):
"""Determines whether the predicate is false for all elements in in iterable.
:param predicate:
Predicate function of the form::
f(x) -> bool
:param iterable:
Iterable sequence.
:returns:
``True`` if the predicate is false for all elements in the iterable.
"""
return every(complement(predicate), iterable)
def find(predicate, iterable, start=0):
"""Determines the first index where the predicate is true for an element in
the iterable.
:param predicate:
Predicate function of the form::
f(x) -> bool
:param iterable:
Iterable sequence.
:param start:
Start index.
:returns:
-1 if not found; index (>= start) if found.
"""
for i in builtins.range(start, len(iterable)):
if predicate(iterable[i]):
return i
return -1
def leading(predicate, iterable, start=0):
"""Returns the number of leading elements in the iterable for which
the predicate is true.
:param predicate:
Predicate function of the form::
f(x) -> bool
:param iterable:
Iterable sequence.
:param start:
Start index. (Number of items to skip before starting counting.)
"""
i = 0
for _ in itertools.takewhile(predicate,
itertools.islice(iterable, start, None, 1)):
i += 1
return i
def _leading(predicate, iterable, start=0):
"""Alternative implementation of :func:`leading`."""
return len(tuple(map(identity,
itertools.takewhile(predicate,
itertools.islice(iterable,
start, None, 1)))))
def trailing(predicate, iterable, start=-1):
"""Returns the number of trailing elements in the iterable for which
the predicate is true.
:param predicate:
Predicate function of the form::
f(x) -> bool
:param iterable:
Iterable sequence.
:param start:
If start is negative, -1 indicates starting from the last item.
Therefore, -2 would mean start counting from the second last item.
If start is 0 or positive, it indicates the number of items to skip
before beginning to count.
"""
start = abs(start + 1) if start < 0 else start
return leading(predicate, reversed(iterable), start)
def tally(predicate, iterable):
"""Count how many times the predicate is true.
Taken from the Python documentation. Under the PSF license.
:param predicate:
Predicate function.
:param iterable:
Iterable sequence.
:returns:
The number of times a predicate is true.
"""
return sum(map(predicate, iterable))
def select(predicate, iterable):
"""Select all items from the sequence for which the predicate is true.
select(function or None, sequence) -> list
:param predicate:
Predicate function. If ``None``, select all truthy items.
:param iterable:
Iterable.
:returns:
A list of all items for which the predicate is true.
"""
return list(filter(predicate, iterable))
def iselect(predicate, iterable):
"""Select all items from the sequence for which the predicate is true.
iselect(function or None, sequence) --> iterator
:param predicate:
Predicate function. If ``None``, select all truthy items.
:param iterable:
Iterable.
:yields:
A iterable of all items for which the predicate is true.
"""
return _ifilter(predicate, iterable)
def reject(predicate, iterable):
"""Reject all items from the sequence for which the predicate is true.
reject(function or None, sequence) -> list
:param predicate:
Predicate function. If ``None``, reject all truthy items.
:param iterable:
The iterable to filter through.
:returns:
A list of all items for which the predicate is false.
"""
return select(complement(predicate or bool), iterable)
def ireject(predicate, iterable):
"""Reject all items from the sequence for which the predicate is true.
ireject(function or None, sequence) --> iterator
:param predicate:
Predicate function. If ``None``, reject all truthy items.
:param iterable:
Iterable to filter through.
:yields:
A sequence of all items for which the predicate is false.
"""
return _ifilterfalse(predicate, iterable)
def partition(predicate, iterable):
"""Partitions an iterable into two iterables where for the elements of
one iterable the predicate is true and for those of the other it is false.
:param predicate:
Function of the format::
f(x) -> bool
:param iterable:
Iterable sequence.
:returns:
Tuple (selected, rejected)
"""
def _partitioner(memo, item):
"""Partitioner."""
part = memo[0] if predicate(item) else memo[1]
part.append(item)
return memo
return tuple(builtins.reduce(_partitioner, iterable, [[], []]))
# Dictionaries
def partition_dict(predicate, dictionary):
"""Partitions a dictionary into two dictionaries where for the elements of
one dictionary the predicate is true and for those of the other it is false.
:param predicate:
Function of the format::
f(key, value) -> bool
:param dictionary:
Dictionary.
:returns:
Tuple (selected_dict, rejected_dict)
"""
def _pred(tup):
"""Apply arguments to predicate."""
return predicate(*tup)
pairs_a, pairs_b = partition(_pred, dictionary.items())
return dict(pairs_a), dict(pairs_b)
def map_dict(transform, dictionary):
"""Maps over a dictionary of key, value pairs.
:param transform:
Function that accepts two arguments ``key, value``
and returns a ``(new key, new value)`` pair.
:returns:
New dictionary of ``new key=new value`` pairs.
"""
return dict(starmap(transform or (lambda k, v: (k, v)),
dictionary.items()))
def select_dict(predicate, dictionary):
"""Select from a dictionary.
:param predicate:
Predicate function that accepts two arguments ``key, value``
and returns ``True`` for selectable elements.
:returns:
New dictionary of selected ``key=value`` pairs.
"""
def _pred(tup):
"""Apply arguments to predicate."""
return predicate(*tup)
_predicate = _pred if predicate else all
return dict(_ifilter(_predicate, dictionary.items()))
def reject_dict(predicate, dictionary):
"""Reject from a dictionary.
:param predicate:
Predicate function that accepts two arguments ``key, value``
and returns ``True`` for rejected elements.
:returns:
New dictionary of selected ``key=value`` pairs.
"""
def _pred(tup):
"""Apply arguments to predicate."""
return predicate(*tup)
_predicate = _pred if predicate else all
return dict(ireject(_predicate, dictionary.items()))
def invert_dict(dictionary):
"""Inverts a dictionary.
:param dictionary:
Dictionary to invert.
:returns:
New dictionary with the keys and values switched.
"""
return map_dict(lambda k, v: (v, k), dictionary)
# Sequences of dictionaries
def pluck(dicts, key, *args, **kwargs):
"""Plucks values for a given key from a series of dictionaries.
:param dicts:
Iterable sequence of dictionaries.
:param key:
The key to fetch.
:param default:
The default value to use when a key is not found. If this value is
not specified, a KeyError will be raised when a key is not found.
:returns:
Tuple of values for the key.
"""
return tuple(ipluck(dicts, key, *args, **kwargs))
def ipluck(dicts, key, *args, **kwargs):
"""Plucks values for a given key from a series of dictionaries as an iterator.
:param dicts:
Iterable sequence of dictionaries.
:param key:
The key to fetch.
:param default:
The default value to use when a key is not found. If this value is
not specified, a KeyError will be raised when a key is not found.
:yields:
Iterator of values for the key.
"""
if args or kwargs:
default = kwargs["default"] if kwargs else args[0]
def _get_value_from_dict(dictionary):
"""Obtains a value from the dictionary for the given key."""
return dictionary.get(key, default)
else:
_get_value_from_dict = lambda w: w[key]
return map(_get_value_from_dict, dicts)
# Sequences
def contains(iterable, item):
"""Determines whether the iterable contains the value specified.
:param iterable:
Iterable sequence.
:param item:
The value to find.
:returns:
``True`` if the iterable sequence contains the value; ``False``
otherwise.
"""
try:
return iterable.__contains__(item)
except AttributeError:
try:
try:
return iterable.index(item) >= 0
except ValueError:
return False
except AttributeError:
return _contains_fallback(iterable, item)
def _contains_fallback(iterable, item):
"""Fallback to determine whether the iterable contains the value specified.
Uses a loop instead of built-in methods.
:param iterable:
Iterable sequence.
:param item:
The value to find.
:returns:
``True`` if the iterable sequence contains the value; ``False``
otherwise.
"""
for element in iter(iterable):
if element == item:
return True
return False
def omits(iterable, item):
"""Determines whether the iterable omits the value specified.
:param iterable:
Iterable sequence.
:param item:
The value to find.
:returns:
``True`` if the iterable sequence omits the value; ``False``
otherwise.
"""
return not contains(iterable, item)
def difference(iterable1, iterable2):
"""Difference between one iterable and another.
Items from the first iterable are included in the difference.
iterable1 - iterable2 = difference
For example, here is how to find out what your Python module exports
to other modules using wildcard imports::
>> difference(dir(mom.functional), mom.functional.__all__)
["__all__",
# Elided...
"range",
"takewhile"]
:param iterable1:
Iterable sequence.
:param iterable2:
Iterable sequence.
:returns:
Iterable sequence containing the difference between the two given
iterables.
"""
return select(functools.partial(omits, iterable2), iterable1)
def idifference(iterable1, iterable2):
"""Difference between one iterable and another.
Items from the first iterable are included in the difference.
iterable1 - iterable2 = difference
:param iterable1:
Iterable sequence.
:param iterable2:
Iterable sequence.
:yields:
Generator for the difference between the two given iterables.
"""
return _ifilter(functools.partial(omits, iterable2), iterable1)
def without(iterable, *values):
"""Returns the iterable without the values specified.
:param iterable:
Iterable sequence.
:param values:
Variable number of input values.
:returns:
Iterable sequence without the values specified.
"""
return difference(iterable, values)
def head(iterable):
"""Returns the first element out of an iterable.
:param iterable:
Iterable sequence.
:returns:
First element of the iterable sequence.
"""
return nth(iterable, 0)
def tail(iterable):
"""Returns all elements excluding the first out of an iterable.
:param iterable:
Iterable sequence.
:returns:
All elements of the iterable sequence excluding the first.
"""
return iterable[1:]
def itail(iterable):
"""Returns an iterator for all elements excluding the first out of
an iterable.
:param iterable:
Iterable sequence.
:yields:
Iterator for all elements of the iterable sequence excluding
the first.
"""
return itertools.islice(iterable, 1, None, 1)
def nth(iterable, index, default=None):
"""Returns the nth element out of an iterable.
:param iterable:
Iterable sequence.
:param index:
Index
:param default:
If not found, this or ``None`` will be returned.
:returns:
nth element of the iterable sequence.
"""
return builtins.next(itertools.islice(iterable, index, None), default)
def last(iterable):
"""Returns the last element out of an iterable.
:param iterable:
Iterable sequence.
:returns:
Last element of the iterable sequence.
"""
return nth(iterable, len(iterable) - 1)
def occurrences(iterable):
"""Returns a dictionary of counts (multiset) of each element in the
iterable.
Taken from the Python documentation under PSF license.
:param iterable:
Iterable sequence with hashable elements.
:returns:
A dictionary of counts of each element in the iterable.
"""
multiset = collections.defaultdict(int)
for k in iterable:
multiset[k] += 1
return multiset
def peel(iterable, count=1):
"""Returns the meat of an iterable by peeling off the specified
number of elements from both ends.
:param iterable:
Iterable sequence.
:param count:
The number of elements to remove from each end.
:returns:
Peeled sequence.
"""
if count < 0:
raise ValueError("peel count cannot be negative: %r" % count)
if not iterable:
return iterable
return iterable[count:-count]
def ipeel(iterable, count=1):
"""Returns an iterator for the meat of an iterable by peeling off
the specified number of elements from both ends.
:param iterable:
Iterable sequence.
:param count:
The number of elements to remove from each end.
:yields:
Peel iterator.
"""
if count < 0:
raise ValueError("peel count cannot be negative: %r" % count)
if not iterable:
return iter([])
try:
return itertools.islice(iterable, count, len(iterable) - count, 1)
except ValueError:
return iter([])
def ichunks(iterable, size, *args, **kwargs):
"""Splits an iterable into iterators for chunks each of specified size.
:param iterable:
The iterable to split. Must be an ordered sequence to guarantee order.
:param size:
Chunk size.
:param padding:
If a pad value is specified appropriate multiples of it will be
appended to the end of the iterator if the size is not an integral
multiple of the length of the iterable:
map(tuple, ichunks("aaabccd", 3, "-"))
-> [("a", "a", "a"), ("b", "c", "c"), ("d", "-", "-")]
map(tuple, ichunks("aaabccd", 3, None))
-> [("a", "a", "a"), ("b", "c", "c"), ("d", None, None)]
If no padding is specified, nothing will be appended if the
chunk size is not an integral multiple of the length of the
iterable. That is, the last chunk will have chunk size less than
the specified chunk size. :yields: Generator of chunk iterators.
"""
length = len(iterable)
if args or kwargs:
padding = kwargs["padding"] if kwargs else args[0]
for i in builtins.range(0, length, size):
yield itertools.islice(
chain(iterable,
itertools.repeat(padding, (size - (length % size)))),
i, i + size)
else:
for i in builtins.range(0, length, size):
yield itertools.islice(iterable, i, i + size)
def chunks(iterable, size, *args, **kwargs):
"""Splits an iterable into materialized chunks each of specified size.
:param iterable:
The iterable to split. Must be an ordered sequence to guarantee order.
:param size:
Chunk size.
:param padding:
This must be an iterable or None. So if you want a ``True`` filler,
use [True] or (True, ) depending on whether the iterable is a list or
a tuple. Essentially, it must be the same type as the iterable.
If a pad value is specified appropriate multiples of it will be
concatenated at the end of the iterable if the size is not an integral
multiple of the length of the iterable:
tuple(chunks("aaabccd", 3, "-"))
-> ("aaa", "bcc", "d--")
tuple(chunks((1, 1, 1, 2, 2), 3, (None,)))
-> ((1, 1, 1, ), (2, 2, None))
If no padding is specified, nothing will be appended if the
chunk size is not an integral multiple of the length of the
iterable. That is, the last chunk will have chunk size less than
the specified chunk size. :yields: Generator of materialized
chunks.
"""
length = len(iterable)
if args or kwargs:
padding = kwargs["padding"] if kwargs else args[0]
if padding is None:
if builtins.is_bytes_or_unicode(iterable):
padding = ""
elif isinstance(iterable, tuple):
padding = (padding,)
else:
iterable = list(iterable)
padding = [padding]
sequence = iterable + (padding * (size - (length % size)))
for i in builtins.range(0, length, size):
yield sequence[i:i + size]
else:
for i in builtins.range(0, length, size):
yield iterable[i:i + size]
def truthy(iterable):
"""Returns a iterable with only the truthy values.
Example::
truthy((0, 1, 2, False, None, True)) -> (1, 2, True)
:param iterable:
Iterable sequence.
:returns:
Iterable with truthy values.
"""
return select(bool, iterable)
def itruthy(iterable):
"""Returns an iterator to for an iterable with only the truthy values.
Example::
tuple(itruthy((0, 1, 2, False, None, True))) -> (1, 2, True)
:param iterable:
Iterable sequence.
:yields:
Iterator for an iterable with truthy values.
"""
return _ifilter(bool, iterable)
def falsy(iterable):
"""Returns a iterable with only the falsy values.
Example::
falsy((0, 1, 2, False, None, True)) -> (0, False, None)
:param iterable:
Iterable sequence.
:returns:
Iterable with falsy values.
"""
return select(loob, iterable)
def ifalsy(iterable):
"""Returns a iterator for an iterable with only the falsy values.
Example::
tuple(ifalsy((0, 1, 2, False, None, True))) -> (0, False, None)
:param iterable:
Iterable sequence.
:yields:
Iterator for an iterable with falsy values.
"""
return ireject(bool, iterable)
def flatten(iterable):
"""Flattens nested iterables into a single iterable.
Example::
flatten((1, (0, 5, ("a", "b")), (3, 4))) -> [1, 0, 5, "a", "b", 3, 4]
:param iterable:
Iterable sequence of iterables.
:returns:
Iterable sequence of items.
"""
def _flatten(memo, item):
"""Flattener."""
if isinstance(item, (list, tuple)):
return memo + builtins.reduce(_flatten, item, [])
else:
memo.append(item)
return memo
return builtins.reduce(_flatten, iterable, [])
def flatten1(iterable):
"""Flattens nested iterables into a single iterable only one level
deep.
Example::
flatten1((1, (0, 5, ("a", "b")), (3, 4))) -> [1, 0, 5, ("a", "b"), 3, 4]
:param iterable:
Iterable sequence of iterables.
:returns:
Iterable sequence of items.
"""
def _flatten(memo, item):
"""Flattener."""
if isinstance(item, (list, tuple)):
return memo + list(item)
else:
memo.append(item)
return memo
return builtins.reduce(_flatten, iterable, [])
def group_consecutive(predicate, iterable):
"""Groups consecutive elements into subsequences::
things = [("phone", "android"),
("phone", "iphone"),
("tablet", "ipad"),
("laptop", "dell studio"),
("phone", "nokia"),
("laptop", "macbook pro")]
list(group_consecutive(lambda w: w[0], things))
-> [(("phone", "android"), ("phone", "iphone")),
(("tablet", "ipad"),),
(("laptop", "dell studio"),),
(("phone", "nokia"),),
(("laptop", "macbook pro"),)]
list(group_consecutive(lambda w: w[0], "mississippi"))
-> [("m",), ("i",),
("s", "s"), ("i",),
("s", "s"), ("i",),
("p", "p"), ("i",)]
:param predicate:
Predicate function that returns ``True`` or ``False`` for each
element of the iterable.
:param iterable:
An iterable sequence of elements.
:returns:
An iterator of lists.
"""
return (tuple(group) for key, group in itertools.groupby(iterable, predicate))
def flock(predicate, iterable):
"""Groups elements into subsequences after sorting::
things = [("phone", "android"),
("phone", "iphone"),
("tablet", "ipad"),
("laptop", "dell studio"),
("phone", "nokia"),
("laptop", "macbook pro")]
list(flock(lambda w: w[0], things))
-> [(("laptop", "dell studio"), ("laptop", "macbook pro")),
(("phone", "android"), ("phone", "iphone"), ("phone", "nokia")),
(("tablet", "ipad"),)]
list(flock(lambda w: w[0], "mississippi"))
-> [("i", "i", "i", "i"), ("m",), ("p", "p"), ("s", "s", "s", "s")]
:param predicate:
Predicate function that returns ``True`` or ``False`` for each
element of the iterable.
:param iterable:
An iterable sequence of elements.
:returns:
An iterator of lists.
"""
return (tuple(group) for key, group in
itertools.groupby(sorted(iterable), predicate))
def unique(iterable, is_sorted=False):
"""Returns an iterable sequence of unique values from the given iterable.
:param iterable:
Iterable sequence.
:param is_sorted:
Whether the iterable has already been sorted. Works faster if it is.
:returns:
Iterable sequence of unique values.
"""
# If we used a "seen" set like the Python documentation implementation does,
# we'd have to ensure that the elements are hashable. This implementation
# does not have that problem. We can improve this implementation.
if iterable:
def _unique(memo, item):
"""Find uniques."""
cond = last(memo) != item if is_sorted else omits(memo, item)
if cond:
memo.append(item)
return memo
return builtins.reduce(_unique, itail(iterable), [head(iterable)])
else:
return iterable
def union(iterable, *iterables):
"""Returns the union of given iterable sequences.
:param iterables:
Variable number of input iterable sequences.
:returns:
Union of the iterable sequences.
"""
if not iterables:
return iterable
return unique(iter(chain(iterable, *iterables)))
def intersection(iterable, *iterables):
"""Returns the intersection of given iterable sequences.
:param iterables:
Variable number of input iterable sequences.
:returns:
Intersection of the iterable sequences in the order of appearance
in the first sequence.
"""
if not iterables:
return iterable
def _does_other_contain(item):
"""Determines whether the other list contains an item."""
return every(functools.partial(contains, item=item), iterables)
return select(_does_other_contain, unique(iterable))
def take(iterable, amount):
"""Return first n items of the iterable as a tuple.
Taken from the Python documentation. Under the PSF license.
:param amount:
The number of items to obtain.
:param iterable:
Iterable sequence.
:returns:
First n items of the iterable as a tuple.
"""
return tuple(itertools.islice(iterable, amount))
def eat(iterator, amount):
"""Advance an iterator n-steps ahead. If n is None, eat entirely.
Taken from the Python documentation. Under the PSF license.
:param iterator:
An iterator.
:param amount:
The number of steps to advance.
:yields:
An iterator.
"""
# Use functions that consume iterators at C speed.
if amount is None:
# Feed the entire iterator into a zero-length deque.
collections.deque(iterator)
else:
# Advance to the empty slice starting at position n.
builtins.next(itertools.islice(iterator, amount, amount), None)
def _get_iter_next(iterator):
"""Gets the next item in the iterator."""
attr = getattr(iterator, "next", None)
if not attr:
attr = getattr(iterator, "__next__")
return attr
def round_robin(*iterables):
"""Returns items from the iterables in a round-robin fashion.
Taken from the Python documentation. Under the PSF license.
Recipe credited to <NAME>
Example::
round_robin("ABC", "D", "EF") --> A D E B F C"
:param iterables:
Variable number of inputs for iterable sequences.
:yields:
Items from the iterable sequences in a round-robin fashion.
"""
pending = len(iterables)
nexts = itertools.cycle(_get_iter_next(iter(it)) for it in iterables)
while pending:
try:
for next_ in nexts:
yield next_()
except StopIteration:
pending -= 1
nexts = itertools.cycle(itertools.islice(nexts, pending))
def ncycles(iterable, times):
"""Yields the sequence elements n times.
Taken from the Python documentation. Under the PSF license.
:param iterable:
Iterable sequence.
:param times:
The number of times to yield the sequence.
:yields:
Iterator.
"""
return chain.from_iterable(itertools.repeat(tuple(iterable), times))
# Predicates, transforms, and walkers
def identity(arg):
"""Identity function. Produces what it consumes.
:param arg:
Argument
:returns:
Argument.
"""
return arg
def loob(arg):
"""Complement of bool.
:param arg:
Python value.
:returns:
Complementary boolean value.
"""
return not bool(arg)
def always(_):
"""Predicate function that returns ``True`` always.
:param _:
Argument
:returns:
``True``.
"""
return True
def never(_):
"""Predicate function that returns ``False`` always.
:param _:
Argument
:returns:
``False``.
"""
return False
def constant(c):
"""Returns a predicate function that returns the given constant.
:param c:
The constant that the generated predicate function will return.
:returns:
A predicate function that returns the specified constant.
"""
def _func(*args, **kwargs):
return c
return _func
def nothing(*args, **kwargs):
"""A function that does nothing.
:param args:
Any number of positional arguments.
:param kwargs:
Any number of keyword arguments.
"""
pass
|
<reponame>MarcoBuster/AOC
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
func navigateTicket(r int, ticket string) int {
var seats []int
for i := 0; i <= r; i++ {
seats = append(seats, i)
}
for _, c := range ticket {
if c == 'F' || c == 'L' { // lower half
seats = seats[:len(seats)/2]
} else if c == 'B' || c == 'R' { // upper half
seats = seats[len(seats)/2:]
}
}
return seats[0]
}
func main() {
f, _ := os.Open("input.txt")
b := bufio.NewScanner(f)
high := 0
var ticketIDs []int
for b.Scan() {
ticket := b.Text()
row := navigateTicket(127, ticket[:7])
column := navigateTicket(7, ticket[7:10])
ticketID := row*8 + column
if ticketID > high {
high = ticketID
}
ticketIDs = append(ticketIDs, ticketID)
}
fmt.Println("Answer (part 1):", high)
sort.Ints(ticketIDs)
for i, t := range ticketIDs {
if i+1 >= len(ticketIDs) {
break
}
if t+1 != ticketIDs[i+1] && t+2 == ticketIDs[i+1] {
fmt.Println("Answer (part 2):", t+1)
break
}
}
}
|
In the days before Hurricane Florence would make landfall on the Carolina coast, before Helene and what would become Joyce would turn north and Isaac would break up in the Caribbean, our journalists were packing bags and preparing to do their jobs.
From Florida’s East Coast, a team of certified drone pilots — journalists who trained and then tested and certified by the Federal Aviation Administration — from the FLORIDA TODAY-TCPalm team, headed to projected flood zones to capture history.
FLORIDA TODAY’s Rick Neale also followed the 920th Rescue Wing from Patrick Air Force Base to Building 519 and hangar C-17 hangar in Charleston, from which they’ll stage operations. Just as he did last year in Texas after Harvey, he’s there to document their heroics.
Neale’s coordinated with the 920th to meet them in South Carolina. He hopes to go where they go because what they do is important and should be recorded.
Our engagement and public affairs editor, Isadora Rangel, also as she did a year ago during Hurricane Irma, headed south to work beside experts with the National Hurricane Center to bring live and specific reports on what would — and did — happen once the storms began. Thousands of people across the eastern United States followed her live reports.
Our journalists joined others from USA TODAY Network sites in Asheville, Greenville, Anderson in the Carolinas and from USA TODAY's home base in Virginia to cover Florence.
Meanwhile, dozens of other journalists monitored reports and updated the news from their cities. At FLORIDA TODAY, for example, with all the attention rightly on Florence, we reported on Isaac’s potential impact on the still-recovering Puerto Rico island and later Florida.
Other journalists scoured social media and news stories around the clock, looking for additional information that would provide insights and help prepare people for what was coming their way.
We knew people in Florida cared what was happening hundreds of miles away in the Carolinas. Many here go there for a summer getaway. Others own property or have friends and family. The connections between here and there is strong.
For me, it was a little personal. I spent five years as the executive editor of the Asheville Citizen-Times in the early 2000s and one of my children graduated from high school and college in North Carolina. We were there in 2004 when remnants of the Florida storms ravished the mountains, destroying 140 homes and killing 11 in mudslides and floods.
I thought about my former colleagues and neighbors as this unprecedented hurricane now slowly crept their way.
The coordination among the dozens of journalists covering for the USA TODAY Network was precise and professional. It had to be; lives were at stake and we wanted our team to be in position to do their jobs to warn the public, but also to be safe themselves.
We’re continuing to follow what remains of these storms and will keep our eyes open for new threats throughout the hurricane season, which ends Nov. 30.
It is the type of care we take in all we do as journalists, whether covering a historic storm or an election: Our job is to always be on your side, no matter what side you are on, and to provide you the information you need to make informed choices.
In this case, our readers responded in a big way. Amazing numbers of people watched our video reports and read our stories. Monthly unique visitors to floridatoday.com ranged between three to six times normal. They consumed millions of pages of information in the last week, mostly around storm coverage.
And it means a lot to us as journalists that you trust FLORIDA TODAY and our local journalists in times like this when the rubber meets the road.
We are sincerely grateful. We’ll continue to work hard to keep your trust. |
from collections import Counter
from math import ceil
t=int(input())
children = [int(x) for x in input().split()]
d=Counter(children)
count = 0
threeOnes = min(d[3], d[1])
d[3]-=threeOnes
d[1]-=threeOnes
count+=threeOnes + d[3]
twos = d[2]//2
d[2]-=twos*2
count+=twos
count+=d[4]
if(d[2]==1):
count+=1
d[1]-=min(2,d[1])
count+=ceil(d[1]/4)
print(count) |
If you really want to understand the great global warming scam you must listen to my podcast this week with Rupert Darwall.
In his new book Green Tyranny, Darwall tells a story so extraordinary and implausible that it’s no wonder most of the mainstream media has been too scared to touch it.
The bottom line: it all started with the Nazis.
Yes, I know. It sounds so click-baity, doesn’t it?
That’ll be why even those journals and writers that have reviewed the book favorably have tended to steer clear of the key chapter in Darwall’s book. The one mischievously titled ‘Europe’s First Greens’.
Europe’s First Greens were, of course, the Nazis.
The documentary evidence provided by Darwall is irrefutable, for this is a considered, well-researched and scholarly work not a potboiler.
What Darwall demonstrates is that the ideology driving the current climate scare originated in Hitler’s Germany.
Angela Merkel’s Energiewende, the brainwashing of your kids in school with green propaganda, the Climate Industrial Complex, the black outs in South Australia, Solyndra, Obama promising that electricity prices would “necessarily skyrocket”, the bat-chomping bird-slicing eco-crucifixes destroying a skyline near you, the real reason Trump just had to pull the U.S. out of the Paris climate accord – it’s all basically the fault of the Nazis.
That’s because Nazis – though similar in so many ways to their fellow totalitarians the Communists – had at least one major point of difference with Marxist ideology: they feared and loathed industrial progress and they worshipped nature.
Hitler wrote in Mein Kampf:
When man attempts to rebel against the iron logic of Nature, he comes into struggle with the principles to which he himself owes his existence as a man.
The Fuhrer, in other words, was as big a Gaia worshipper as even Naomi Klein or Emma Thompson or Leonardo di Caprio.
As Hitler thought, so did the Nazi intelligentsia. Many of them were vegetarians and, like Rudolf Hess and Agriculture Minister Walter Darre were big fans of organic farming. The party was fiercely anti-smoking (even though the Germans continued to smoke fanatically so long as tobacco was available). They were also massively into “renewable” energy, especially wind, tidal power and hydroelectric.
Hitler said in a dinner party conversation in 1941:
“We shall have to use every method of encouraging whatever might ensure us the gain of a single kilowatt…Coal will disappear one day.”
He then speculated on renewable solutions to this ‘peak coal’ problem:
“The future belongs, surely, to water – to the wind and the tides.”
(This isn’t mentioned in the book but Hitler’s favorite SS commando – Otto Skorzeny – who miraculously survived the war and retired to live in Spain spent his later years campaigning on behalf of the wind industry.)
Darwall doesn’t mince his words:
The Nazis’ profound hostility to capitalism and their identification with nature-politics led them to advocate green policies half a century before any other political party. As an approximation, subtract Nazi race-hate, militarism and desire for world conquest, and Nazi ideology ends up looking not dissimilar to today’s environmental movement.
What Darwall goes on to demonstrate is how this mindset, unabated by the defeat of Nazi Germany, continued to dominate European political thought. This was especially so in the two countries most responsible for promulgating the climate change scare: Sweden and Germany.
In Germany, the Nazis’ green ideology became linked inextricably with that of the Peace movement – which, with a certain irony, was largely sponsored by the Soviet Union.
Sweden, meanwhile, did most to get the global warming scare up and running in the early days. Bert Bolin, the first chairman of the Intergovernmental Panel on Climate Change (IPCC) was a Swede.
You’ll have to read Darwall’s book for the full, rather complicated story. By the end you’ll have an answer to perhaps the most puzzling of the many questions about the global warming industry: why, given the scientific evidence is so flimsy, does it carry on pushing its cause so fervently?
The answer is simple: because “global warming” is not about “the science” and never was about “the science.”
Like the “acid rain” scare and the “nuclear winter” scare, the man-made global warming scare is a fake news story designed to push a political and economic agenda.
At the bottom of that agenda is the same superstitious fear the Nazis had: that industrial progress is morally wrong because it is against Nature.
Hence the greenies’ obsession with renewables. Despite all the evidence that renewables do at least as much environmental damage as fossil fuels, only much more expensively, and without making any meaningful difference to “climate change” the green ideology persists in pretending that renewables are the “clean” “natural” alternative to “dirty” fossil fuels.
It’s about emotion not logic; about the narrative, not reality.
For decades we’ve been gulled by a compliant (and invariably ignorant) media into believing that the global warming scare is about scientists doing clever sciencey stuff and reaching important conclusions which the world can only ignore at its peril.
But actually, all along, the tail has been wagging the dog.
The scientists are a virtual irrelevance in this story: merely the useful idiots of a political agenda.
That agenda is part religion – a kind of pagan nature worship expressed through opposition to Western industrial civiliation and the embrace of retrograde technologies like wind power.
And it’s part leftist politics and economics: a way by which Europe can destroy and overtake the United States’ economic hegemony by neutralising one of its greatest competitive advantages – the abundance of fossil fuels which have now made it the world’s number one energy superpower.
Donald Trump probably hasn’t a clue about the intellectual and ideological undercurrents which created the great global warming scare. But he’s a businessman and saw what was happening through gut instinct.
Global warming is a scam – the biggest the world has ever seen.
Trump, for one, didn’t fall for it. |
//! Black volatility (smile) surface
/*! This abstract class defines the interface of concrete
Black volatility (smile) surface which will
be derived from this one.
Volatilities are assumed to be expressed on an annual basis.
*/
class BlackVolSurface : public BlackAtmVolCurve {
public:
BlackVolSurface(BusinessDayConvention bdc = Following,
const DayCounter& dc = DayCounter());
BlackVolSurface(const Date& referenceDate,
const Calendar& cal = Calendar(),
BusinessDayConvention bdc = Following,
const DayCounter& dc = DayCounter());
BlackVolSurface(Natural settlementDays,
const Calendar&,
BusinessDayConvention bdc = Following,
const DayCounter& dc = DayCounter());
boost::shared_ptr<SmileSection> smileSection(const Period&,
bool extrapolate) const;
boost::shared_ptr<SmileSection> smileSection(const Date&,
bool extrapolate) const;
boost::shared_ptr<SmileSection> smileSection(Time,
bool extrapolate) const;
void accept(AcyclicVisitor&);
protected:
Real atmVarianceImpl(Time t) const;
Volatility atmVolImpl(Time t) const;
virtual boost::shared_ptr<SmileSection> smileSectionImpl(Time) const=0;
} |
<reponame>javierholguera/kafka-utils
package com.javierholguera.utils.streams.topology;
import org.apache.kafka.streams.StreamsBuilder;
/**
* Describes a Kafka Streams topology using either DSL or Processor API.
*/
public interface TopologyDescriptor {
/**
* Configures the topology steps.
*
* @param streamsBuilder receives DSL and Processor API instructions to describe the topology.
*/
void configure(StreamsBuilder streamsBuilder);
}
|
import fs from "fs"
import type { ResultedCaseMessageParsedXml } from "src/types/IncomingMessage"
import parseSpiResult from "./parseSpiResult"
const parseFile = (file: string): ResultedCaseMessageParsedXml => {
const inputMessage = fs.readFileSync(file).toString()
return parseSpiResult(inputMessage).DeliverRequest.Message.ResultedCaseMessage
}
describe("parseSpiResult", () => {
it("should handle messages with multiple offences", () => {
const result = parseFile("test-data/input-message-001.xml")
expect(Array.isArray(result.Session.Case.Defendant.Offence)).toBe(true)
expect(result.Session.Case.Defendant.Offence).toHaveLength(3)
})
it("should handle messages with single offences", () => {
const result = parseFile("test-data/input-message-010b.xml")
expect(Array.isArray(result.Session.Case.Defendant.Offence)).toBe(true)
expect(result.Session.Case.Defendant.Offence).toHaveLength(1)
})
it("should handle messages with no offences", () => {
const result = parseFile("test-data/input-message-no-offences.xml")
expect(Array.isArray(result.Session.Case.Defendant.Offence)).toBe(true)
expect(result.Session.Case.Defendant.Offence).toHaveLength(0)
})
it("should handle offences with multiple results", () => {
const result = parseFile("test-data/input-message-003.xml")
const offence = result.Session.Case.Defendant.Offence[0]
expect(Array.isArray(offence.Result)).toBe(true)
expect(offence.Result).toHaveLength(2)
})
it("should handle offences with single results", () => {
const result = parseFile("test-data/input-message-001.xml")
const offence = result.Session.Case.Defendant.Offence[0]
expect(Array.isArray(offence.Result)).toBe(true)
expect(offence.Result).toHaveLength(1)
})
it("should handle offences with no results", () => {
const result = parseFile("test-data/input-message-no-results.xml")
const offence = result.Session.Case.Defendant.Offence[0]
expect(Array.isArray(offence.Result)).toBe(true)
expect(offence.Result).toHaveLength(0)
})
})
|
Clyde S. Kilby
Biography
Kilby's parents, James Lafayette and Sophronia Kilby, lived along the Nolichuckey River in the north portion of East Tennessee's hill country. The youngest of eight children, he was the first of his family to graduate from college. While studying at the University of Arkansas, he worked part-time in the registrar's office at nearby John Brown University. Clyde graduated in 1929, and the next year married Martha Harris, a mathematics teacher at JBU. They moved to Minnesota, where Kilby earned a master's degree in 1931 from the University of Minnesota.
In 1935, Kilby moved to Wheaton, Illinois, where he became an assistant professor of English. In 1938, he earned his Ph.D. by correspondence from NYU. He became chair of the English department at Wheaton in 1951, a post he retained until 1966. Dr. Kilby retired from teaching at Wheaton in 1981, and retired to Columbus, Mississippi, his wife's hometown, where he died on October 18, 1986.
In his honour, the Clyde S. Kilby Award for Inkling Studies was issued (one notable winner is Colin Duriez), and also the Clyde S. Kilby Research Grant (Diana Pavlac Glyer is a recipient). There is a Clyde S. Kilby Chair at Wheaton College (currently Christina Bieber Lake). |
package connector
import "testing"
func TestIsLiteral(t *testing.T) {
cases := []struct {
plaintext string
want bool
}{
{"A", true},
{"~A", true},
{"A^B", false},
{"AvB", false},
}
for _, c := range cases {
got := Parse(c.plaintext).isLiteral()
want := c.want
if got != want {
t.Errorf("Parse(%q).isLiteral(): %t != %t", c.plaintext, got, want)
}
}
}
|
<reponame>leduong/richie<gh_stars>100-1000
# Generated by Django 2.2.7 on 2019-11-19 23:14
from django.db import migrations
from cms.api import add_plugin
from cms.models import StaticPlaceholder
def migrate_footer_to_static_placeholder(apps, schema_editor):
"""
Create a footer with the new static placeholder from the existing footer pages that were
placed under the "annex" page and displayed in the footer via a `show_menu_below_id`
template tag.
"""
Page = apps.get_model("cms", "Page")
Title = apps.get_model("cms", "Title")
# We should import StaticPlaceholder from apps but its `draft` and `public` fields
# are custom foreign key field that checks that they are targeting an instance of
# `cms.models.Placeholder` so the code would not work. We can safely assume that the
# Placeholder and StaticPlaceholder models are still there when this migration is run
static_placeholder, was_created = StaticPlaceholder.objects.get_or_create(
code="footer"
)
if not was_created:
# If the static placeholder was already existing, it means this migration is being
# replayed and we better do nothing.
return
for is_draft in [False, True]:
# Look for an existing footer page
try:
footer_page = Page.objects.get(
reverse_id="annex", publisher_is_draft=is_draft
)
except Page.DoesNotExist:
return
placeholder = (
static_placeholder.draft if is_draft else static_placeholder.public
)
for language in Title.objects.filter(page=footer_page).values_list(
"language", flat=True
):
# Create the <ul> section to carry the list of links
section = add_plugin(
placeholder,
plugin_type="SectionPlugin",
language=language,
template="richie/section/section_list.html",
)
# Create a <li> link for each page in the exiting footer menu
for page in Page.objects.filter(
node__parent=footer_page.node,
in_navigation=True,
title_set__language=language,
publisher_is_draft=is_draft,
):
title = page.title_set.get(language=language)
add_plugin(
placeholder,
plugin_type="LinkPlugin",
language=language,
internal_link_id=page.id,
name=title.title,
target=section,
)
class Migration(migrations.Migration):
dependencies = [
("courses", "0009_auto_20191014_1801"),
("section", "0003_auto_20191119_1650"),
]
operations = [
migrations.RunPython(
migrate_footer_to_static_placeholder, migrations.RunPython.noop
)
]
|
Soraya Marcano
Soraya Marcano (born 1965 in Puerto Rico) is a visual artist based in New York City. She studied at the University of Puerto Rico and completed a master's degree in Fine Arts at Pratt Institute.
Work
Her mixed media artwork has been exhibited internationally and it is represented in public and private collections, including the Museum of Contemporary Art of Chamalieres, Center for the Humanities, The New York Public Library, Rockefeller Library, and Institute of Puerto Rican Culture, among others. Marcano has participated in international artist-in-residence programs, including White Colony, Millay Colony and the Jamaica Center for the Arts; furthermore, she is the recipient of several recognitions and awards. She has also been an educator at Bronx Museum of the Arts, El Museo del Barrio, and The Guggenheim Museum.
Her work, which includes mixed media, writing, objects, and digital work, provides an exploration of mobility, as well as the experience of massive displacement and dislocation of the island. She writes that : "In my work, I explore ideas about life and mobility. As we travel to new places, we become hybrids. I comment on this state of flux by working with radically different media, blurring the borderlines of art categories from painting and collage, to sewing, to writing and digital art." Much of her work concentrates on the changing of Puerto Rico, and the evolution of national and international citizens in the current world purview. She explains that "my work also explores themes related to the nature of hybridism and the shifting identities of the transnational citizen." It also explores images and artistic practices emerging from migratory histories, as well as from the dissolution of community and the reconstruction of culture in the floating societies. Emma Hill explains that "other artists have retold the stories of their own family histories, translating narratives into poignant sculptural objects. Soraya Marcano's tiny paper boats in Exile are examples of the many 'books' that tell of memory and the specificity of place, without words, but in forms that are full of poetic potential." |
package com.fairy.cloud.seckill.service;
import com.fairy.cloud.common.api.CommonResponse;
import com.fairy.cloud.common.exception.ResultException;
import com.fairy.cloud.seckill.domain.ConfirmOrderResult;
import com.fairy.cloud.seckill.domain.MqCancelOrder;
import com.fairy.cloud.seckill.domain.OmsOrderDetail;
import com.fairy.cloud.seckill.domain.OrderParam;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 前台订单管理Service
*/
public interface OmsPortalOrderService {
/**
* 根据用户购物车信息生成确认单信息
*/
ConfirmOrderResult generateConfirmOrder(List<Long> itemIds, Long memberId) throws ResultException;
/**
* 根据提交信息生成订单
*/
@Transactional
// @ShardingTransactionType(TransactionType.XA)
CommonResponse generateOrder(OrderParam orderParam, Long memberId) throws ResultException;
/**
* 订单详情
* @param orderId
* @return
*/
CommonResponse getDetailOrder(Long orderId);
/**
* 支付成功后的回调
*/
@Transactional
Integer paySuccess(Long orderId, Integer payType);
/**
* 自动取消超时订单
*/
@Transactional
CommonResponse cancelTimeOutOrder();
/**
* 取消单个超时订单
*/
@Transactional
void cancelOrder(Long orderId, Long memberId);
/**
* 删除订单[逻辑删除],只能status为:3->已完成;4->已关闭;5->无效订单,才可以删除
* ,否则只能先取消订单然后删除。
* @param orderId
* @return
* 受影响的行
*/
@Transactional
int deleteOrder(Long orderId);
/**
* 发送延迟消息取消订单
*/
void sendDelayMessageCancelOrder(MqCancelOrder mqCancelOrder);
/**
* 查询会员的订单
* @param pageSize
* @param pageNum
* @param memberId
* 会员ID
* @param status
* 订单状态
* @return
*/
CommonResponse<List<OmsOrderDetail>> findMemberOrderList(Integer pageSize, Integer pageNum, Long memberId, Integer status);
}
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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 org.jetbrains.plugins.groovy.console;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.console.ConsoleHistoryController;
import com.intellij.execution.console.LanguageConsoleImpl;
import com.intellij.execution.console.LanguageConsoleViewImpl;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.runners.AbstractConsoleRunnerWithHistory;
import com.intellij.execution.runners.ConsoleExecuteActionHandler;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkType;
import com.intellij.openapi.projectRoots.JdkUtil;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkTypeId;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ui.configuration.ModulesAlphaComparator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Key;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl;
import org.jetbrains.plugins.groovy.util.GroovyUtils;
import java.util.*;
/**
* @author peter
*/
public class GroovyShellAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.console.GroovyShellAction");
private static final String GROOVY_SHELL_LAST_MODULE = "Groovy.Shell.LastModule";
public static final Key<Boolean> GROOVY_SHELL_FILE = Key.create("GROOVY_SHELL_FILE");
private static List<Module> getGroovyCompatibleModules(Project project) {
ArrayList<Module> result = new ArrayList<Module>();
for (Module module : ModuleManager.getInstance(project).getModules()) {
if (GroovyUtils.isSuitableModule(module)) {
Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
result.add(module);
}
}
}
return result;
}
@Override
public void update(AnActionEvent e) {
final Project project = e.getData(PlatformDataKeys.PROJECT);
boolean enabled = project != null && !getGroovyCompatibleModules(project).isEmpty();
e.getPresentation().setEnabled(enabled);
e.getPresentation().setVisible(enabled);
}
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = e.getData(PlatformDataKeys.PROJECT);
assert project != null;
List<Module> modules = new ArrayList<Module>();
final Map<Module, String> versions = new HashMap<Module, String>();
for (Module module : getGroovyCompatibleModules(project)) {
GroovyShellRunner runner = GroovyShellRunner.getAppropriateRunner(module);
if (runner != null) {
modules.add(module);
versions.put(module, runner.getTitle(module));
}
}
if (modules.size() == 1) {
runShell(modules.get(0));
return;
}
Collections.sort(modules, ModulesAlphaComparator.INSTANCE);
BaseListPopupStep<Module> step =
new BaseListPopupStep<Module>("Which module to use classpath of?", modules, PlatformIcons.CONTENT_ROOT_ICON_CLOSED) {
@NotNull
@Override
public String getTextFor(Module value) {
return value.getName() + versions.get(value);
}
@Override
public String getIndexedString(Module value) {
return value.getName();
}
@Override
public boolean isSpeedSearchEnabled() {
return true;
}
@Override
public PopupStep onChosen(Module selectedValue, boolean finalChoice) {
PropertiesComponent.getInstance(selectedValue.getProject()).setValue(GROOVY_SHELL_LAST_MODULE, selectedValue.getName());
runShell(selectedValue);
return null;
}
};
for (int i = 0; i < modules.size(); i++) {
Module module = modules.get(i);
if (module.getName().equals(PropertiesComponent.getInstance(project).getValue(GROOVY_SHELL_LAST_MODULE))) {
step.setDefaultOptionIndex(i);
break;
}
}
JBPopupFactory.getInstance().createListPopup(step).showCenteredInCurrentWindow(project);
}
private static void runShell(final Module module) {
final GroovyShellRunner shellRunner = GroovyShellRunner.getAppropriateRunner(module);
if (shellRunner == null) return;
AbstractConsoleRunnerWithHistory<GroovyConsoleView> runner =
new AbstractConsoleRunnerWithHistory<GroovyConsoleView>(module.getProject(), "Groovy Shell", shellRunner.getWorkingDirectory(module)) {
@Override
protected GroovyConsoleView createConsoleView() {
GroovyConsoleView res = new GroovyConsoleView(getProject());
GroovyFileImpl file = (GroovyFileImpl)res.getConsole().getFile();
assert file.getContext() == null;
file.putUserData(GROOVY_SHELL_FILE, Boolean.TRUE);
file.setContext(shellRunner.getContext(module));
return res;
}
@Override
protected Process createProcess() throws ExecutionException {
JavaParameters javaParameters = shellRunner.createJavaParameters(module);
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
assert sdk != null;
SdkTypeId sdkType = sdk.getSdkType();
assert sdkType instanceof JavaSdkType;
final String exePath = ((JavaSdkType)sdkType).getVMExecutablePath(sdk);
return JdkUtil.setupJVMCommandLine(exePath, javaParameters, true).createProcess();
}
@Override
protected OSProcessHandler createProcessHandler(Process process) {
return new OSProcessHandler(process);
}
@NotNull
@Override
protected ConsoleExecuteActionHandler createConsoleExecuteActionHandler() {
ConsoleExecuteActionHandler handler = new ConsoleExecuteActionHandler(getProcessHandler(), false) {
@Override
public void processLine(String line) {
super.processLine(shellRunner.transformUserInput(line));
}
@Override
public String getEmptyExecuteAction() {
return "Groovy.Shell.Execute";
}
};
new ConsoleHistoryController("Groovy Shell", null, getLanguageConsole(), handler.getConsoleHistoryModel()).install();
return handler;
}
};
try {
runner.initAndRun();
}
catch (ExecutionException e1) {
LOG.info(e1);
Messages.showErrorDialog(module.getProject(), e1.getMessage(), "Cannot run Groovy Shell");
}
}
private static class GroovyConsoleView extends LanguageConsoleViewImpl {
protected GroovyConsoleView(final Project project) {
super(new LanguageConsoleImpl(project, "Groovy Console", GroovyFileType.GROOVY_LANGUAGE));
}
}
}
|
Barcelona’s city council is planning to create officially regulated premises for the use of prostitutes, in an attempt to remove them from the streets of its picturesque old quarters.
Led by Left-wing mayor Ada Colau , the proposals include removing hefty fines for both sex workers and their clients that were introduced in 2012.
At the moment, a prostitute can be fined up to €350 (£245) for soliciting in the street, while for clients the penalty can be as high as €3,000 (£2,100) if the sexual transaction takes place in a public place.
This week the council’s social rights committee decided to create “a legal framework for women who wish to practise prostitution voluntarily and in safe and hygienic conditions”.
Mrs Colau’s Barcelona en Comú coalition voted in favour of the initiative, along with Left-wing Catalan nationalists from the ERC and CUP parties .
Laura Pérez, in charge of the council’s social department, described the move as “historic”, in that prostitutes would no longer be criminalised.
“The regulation we have is not working: only 10 per cent of the fines have been collected and the number of women who work in the street is just as high. Nor does fining clients work; the problem are the mafias.”
Any legal premises set up would need to be approved and inspected periodically by the council and could only be used by prostitutes who work independently without a pimp.
A working group has been set up including the police, members of the judiciary and NGOs to help women who are victims of trafficking.
A spokeswoman for the Barcelona group Indignant Prostitutes, which has been campaigning for greater freedom and rights for the city’s sex workers, said it was “a step in the right direction”.
Prostitution is not illegal in Spain but it occupies a legal grey area which tends to work against the women who practise it. Local authorities pursue prostitutes who solicit in the street while thousands of women, many of whom are the victims of people trafficking, offer sex in roadside clubs and bars. |
<filename>gs/gs-sys/gs-sys-web/src/main/java/com/gs/sys/mapper/SysMenuMapper.java
package com.gs.sys.mapper;
import com.gs.sys.dto.SysMenuDTO;
import com.gs.sys.model.SysMenu;
import com.gs.sys.model.SysMenuExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface SysMenuMapper {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int countByExample(SysMenuExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int deleteByExample(SysMenuExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int deleteByPrimaryKey(Integer menuId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int insert(SysMenu record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int insertSelective(SysMenu record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
List<SysMenu> selectByExample(SysMenuExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
SysMenu selectByPrimaryKey(Integer menuId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int updateByExampleSelective(@Param("record") SysMenu record,
@Param("example") SysMenuExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int updateByExample(@Param("record") SysMenu record,
@Param("example") SysMenuExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int updateByPrimaryKeySelective(SysMenu record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table sys_menu
* @mbggenerated Mon Dec 04 02:57:11 CST 2017
*/
int updateByPrimaryKey(SysMenu record);
List<SysMenuDTO> getAllMenu();
} |
April 8, 2016 A resupply capsule, bearing an inflatable habitat, is en route to the International Space Station, and the first stage of the rocket that launched it has returned for a sea landing without exploding.
March 22, 2016 In some cases, a planet's winds could slowly bleed a world of its chance as a safe haven for life — or the winds could boil the world away, says astrophysicist Adam Frank.
March 18, 2016 Aerospace engineer Claudia Kessler is searching for Germany's first female astronaut. The country's previous 11 astronauts were all men, which she says highlights German sexism in the sciences.
March 11, 2016 Recently returned from a historic 340-day off-planet mission, Kelly announced Friday he will retire from NASA on April 1, but still continue to participate in research related to his experiment.
March 11, 2016 The total solar eclipse on March 9 wasn't visible anywhere in North America, but Indonesia got a perfect view. Now you can see the eclipse from the other side ... that is, the view from space.
March 4, 2016 Kelly says his twin brother, Scott Kelly, who just returned to Earth after 340 days in space, was temporarily 2 inches taller. NASA is studying the pair to explore what spaceflight does to the body.
February 24, 2016 Astronomers have known about the powerful pulses but had never been able to catch one in the act to help figure out what's producing them. Last year, they got one.
February 13, 2016 With all the excitement over the discovery of gravitational waves, NPR's Linda Wertheimer takes a moment to remember the man who first imagined a universe we couldn't yet see: Albert Einstein.
February 12, 2016 The crew of Apollo 11 drew a calendar on the wall of their command module, as well as a tribute to the spacecraft, and jotted down numbers and other information from mission control communications.
February 11, 2016 A U.S.-led team says it has seen waves in space-time from two black holes merging together. It is the first time humanity has directly detected such waves.
February 10, 2016 Though accidents may happen, there is no stopping human exploration of space: We are bound to outer shores as we were once bound to shores on this planet, says astrophysicist Marcelo Gleiser.
February 3, 2016 The tiny European country will be investing in research and building a regulatory framework to help make a futuristic industry — the extraction of minerals from objects in space — a reality.
January 25, 2016 In a NASA facility just outside Washington, D.C., workers are building the James Webb Space Telescope, an $8 billion successor to the Hubble. It'll be the largest ever, and it's set to launch in 2018. |
def search():
full_address = {}
full_address.update(request.args.items())
response_code, price, message, hoa = get_unit_price(full_address)
if response_code == 100:
unit_details = get_zillow_unit_details(full_address)
listing = { 'response': response_code,
'price': price,
'message': message,
'neighborhood': unit_details['neighborhood'],
'street': unit_details['street'],
'city': unit_details['city'],
'state': unit_details['state'],
'zipcode': unit_details['zipcode'],
'bedrooms': unit_details['bedrooms'],
'bathrooms': unit_details['bathrooms'],
'sqft': unit_details['sqft'],
'hoa': hoa,
'latitude': unit_details['latitude'],
'longitude': unit_details['longitude'],
'latlng_point': unit_details['latlng_point'],
'zpid': unit_details['zpid']
}
add_listing_to_db(listing)
else:
listing = { 'response': response_code, 'price': price, 'message': message }
return jsonify(listing) |
// license:BSD-3-Clause
// copyright-holders:AJR
/***********************************************************************************************************************************
Skeleton driver for "third generation" TeleVideo terminals (905, 955, 9220).
************************************************************************************************************************************/
#include "emu.h"
#include "machine/tv955kb.h"
#include "bus/rs232/rs232.h"
#include "cpu/m6502/m65c02.h"
#include "machine/input_merger.h"
#include "machine/mos6551.h"
#include "machine/nvram.h"
#include "video/scn2674.h"
#include "screen.h"
class tv955_state : public driver_device
{
public:
tv955_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
, m_crtc(*this, "crtc")
, m_hostuart(*this, "hostuart")
, m_printuart(*this, "printuart")
, m_keybuart(*this, "keybuart")
, m_mainport(*this, "mainport")
, m_printer(*this, "printer")
, m_chargen(*this, "chargen")
{ }
void tv955(machine_config &config);
protected:
virtual void machine_reset() override;
private:
SCN2674_DRAW_CHARACTER_MEMBER(draw_character);
void control_latch_w(u8 data);
DECLARE_WRITE_LINE_MEMBER(system_reset_w);
void mem_map(address_map &map);
void char_map(address_map &map);
void attr_map(address_map &map);
required_device<cpu_device> m_maincpu;
required_device<scn2674_device> m_crtc;
required_device<mos6551_device> m_hostuart;
required_device<mos6551_device> m_printuart;
required_device<mos6551_device> m_keybuart;
required_device<rs232_port_device> m_mainport;
required_device<rs232_port_device> m_printer;
required_region_ptr<u8> m_chargen;
};
void tv955_state::machine_reset()
{
m_printer->write_rts(0);
m_printer->write_dtr(0);
m_printuart->write_cts(0);
m_keybuart->write_cts(0);
}
SCN2674_DRAW_CHARACTER_MEMBER(tv955_state::draw_character)
{
u16 dots = m_chargen[charcode << 4 | linecount] << 1;
if (BIT(dots, 1) && BIT(charcode, 7))
dots |= 1;
// TODO: attribute logic
if (cursor)
dots = ~dots;
for (int i = 0; i < 9; i++)
{
bitmap.pix(y, x++) = BIT(dots, 8) ? rgb_t::white() : rgb_t::black();
dots <<= 1;
}
}
void tv955_state::control_latch_w(u8 data)
{
m_mainport->write_dtr(BIT(data, 0));
m_hostuart->set_xtal(3.6864_MHz_XTAL / (BIT(data, 1) ? 1 : 2));
// CPU clock is inverted relative to character clock (and divided by two for 132-column mode)
if (BIT(data, 7))
{
// 132-column mode
m_maincpu->set_unscaled_clock(31.684_MHz_XTAL / 18);
m_crtc->set_unscaled_clock(31.684_MHz_XTAL / 9);
}
else
{
// 80-column mode
m_maincpu->set_unscaled_clock(19.3396_MHz_XTAL / 9);
m_crtc->set_unscaled_clock(19.3396_MHz_XTAL / 9);
}
}
WRITE_LINE_MEMBER(tv955_state::system_reset_w)
{
m_maincpu->set_input_line(INPUT_LINE_RESET, state ? CLEAR_LINE : ASSERT_LINE);
if (!state)
{
m_keybuart->reset();
m_printuart->reset();
m_hostuart->reset();
}
}
void tv955_state::mem_map(address_map &map)
{
// verified from maintenance manual (131968-00-C)
map(0x0000, 0x07ff).mirror(0x0800).ram().share("nvram");
map(0x1100, 0x1100).mirror(0x00ff).w(FUNC(tv955_state::control_latch_w));
map(0x1200, 0x1203).mirror(0x00fc).rw(m_keybuart, FUNC(mos6551_device::read), FUNC(mos6551_device::write));
map(0x1400, 0x1403).mirror(0x00fc).rw(m_printuart, FUNC(mos6551_device::read), FUNC(mos6551_device::write));
map(0x1800, 0x1803).mirror(0x00fc).rw(m_hostuart, FUNC(mos6551_device::read), FUNC(mos6551_device::write));
map(0x2000, 0x2007).mirror(0x0ff8).rw("crtc", FUNC(scn2674_device::read), FUNC(scn2674_device::write));
map(0x3000, 0x3fff).rom().region("option", 0);
map(0x4000, 0x7fff).ram().share("attrram");
map(0x8000, 0xbfff).ram().share("charram");
map(0xc000, 0xffff).rom().region("system", 0);
}
void tv955_state::char_map(address_map &map)
{
map(0x0000, 0x3fff).ram().share("charram");
}
void tv955_state::attr_map(address_map &map)
{
map(0x0000, 0x3fff).ram().share("attrram");
}
static INPUT_PORTS_START( tv955 )
INPUT_PORTS_END
void tv955_state::tv955(machine_config &config)
{
M65C02(config, m_maincpu, 19.3396_MHz_XTAL / 9);
m_maincpu->set_addrmap(AS_PROGRAM, &tv955_state::mem_map);
INPUT_MERGER_ANY_HIGH(config, "mainirq").output_handler().set_inputline(m_maincpu, m6502_device::IRQ_LINE);
tv955kb_device &keyboard(TV955_KEYBOARD(config, "keyboard"));
keyboard.txd_cb().set("keybuart", FUNC(mos6551_device::write_rxd));
keyboard.reset_cb().set(FUNC(tv955_state::system_reset_w));
NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_0); // HM6116LP-4 + 3.2V battery
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_color(rgb_t::green());
screen.set_raw(19.3396_MHz_XTAL, 846, 0, 720, 381, 0, 364);
//screen.set_raw(31.684_MHz_XTAL, 1386, 0, 1188, 381, 0, 364);
screen.set_screen_update("crtc", FUNC(scn2674_device::screen_update));
SCN2674(config, m_crtc, 19.3396_MHz_XTAL / 9);
// Character clock is 31.684_MHz_XTAL / 9 in 132-column mode
// Character cells are 9 pixels wide by 14 pixels high
m_crtc->set_character_width(9);
m_crtc->set_addrmap(0, &tv955_state::char_map);
m_crtc->set_addrmap(1, &tv955_state::attr_map);
m_crtc->set_display_callback(FUNC(tv955_state::draw_character));
m_crtc->intr_callback().set_inputline(m_maincpu, m6502_device::NMI_LINE);
m_crtc->set_screen("screen");
MOS6551(config, m_hostuart, 0);
m_hostuart->set_xtal(3.6864_MHz_XTAL);
m_hostuart->irq_handler().set("mainirq", FUNC(input_merger_device::in_w<0>));
m_hostuart->txd_handler().set(m_mainport, FUNC(rs232_port_device::write_txd));
m_hostuart->rts_handler().set(m_mainport, FUNC(rs232_port_device::write_rts));
m_hostuart->dtr_handler().set(m_mainport, FUNC(rs232_port_device::write_dtr));
MOS6551(config, m_printuart, 0);
m_printuart->set_xtal(3.6864_MHz_XTAL / 2);
m_printuart->irq_handler().set("mainirq", FUNC(input_merger_device::in_w<1>));
m_printuart->txd_handler().set(m_printer, FUNC(rs232_port_device::write_txd));
MOS6551(config, m_keybuart, 0);
m_keybuart->set_xtal(3.6864_MHz_XTAL / 2);
m_keybuart->irq_handler().set("mainirq", FUNC(input_merger_device::in_w<2>));
m_keybuart->txd_handler().set("keyboard", FUNC(tv955kb_device::write_rxd));
RS232_PORT(config, m_mainport, default_rs232_devices, "loopback"); // DTE
m_mainport->rxd_handler().set(m_hostuart, FUNC(mos6551_device::write_rxd));
m_mainport->cts_handler().set(m_hostuart, FUNC(mos6551_device::write_cts));
m_mainport->dsr_handler().set(m_hostuart, FUNC(mos6551_device::write_dsr));
m_mainport->dcd_handler().set(m_hostuart, FUNC(mos6551_device::write_dcd));
RS232_PORT(config, m_printer, default_rs232_devices, nullptr); // DCE
m_printer->rxd_handler().set("printuart", FUNC(mos6551_device::write_rxd)); // pin 2
m_printer->dsr_handler().set("printuart", FUNC(mos6551_device::write_dsr)); // pin 20 or pin 11
}
/**************************************************************************************************************
Televideo TVI-955 (132160-00 Rev. M)
Chips: G65SC02P-3, 3x S6551AP, SCN2674B, AMI 131406-00 (unknown 40-pin DIL), 2x TMM2064P-10 (near two similar empty sockets), HM6116LP-4, round silver battery
Crystals: 19.3396, 31.684, 3.6864
Keyboard: M5L8049-230P-6, 5.7143, Beeper
***************************************************************************************************************/
ROM_START( tv955 )
ROM_REGION(0x4000, "system", 0)
ROM_LOAD( "t180002-88d_955.u4", 0x0000, 0x4000, CRC(5767fbe7) SHA1(49a2241612af5c3af09778ffa541ac0bc186e05a) )
ROM_REGION(0x1000, "option", 0)
ROM_LOAD( "t180002-91a_calc.u5", 0x0000, 0x1000, CRC(f86c103a) SHA1(fa3ada3a5d8913e519e2ea4817e96166c1fedd32) )
ROM_CONTINUE( 0x0000, 0x1000 ) // first half is all FF (and not addressable)
ROM_REGION(0x1000, "chargen", 0)
ROM_LOAD( "t180002-26b.u45", 0x0000, 0x1000, CRC(69c9ebc7) SHA1(32282c816ec597a7c45e939acb7a4155d35ea584) )
ROM_END
COMP( 1985, tv955, 0, 0, tv955, tv955, tv955_state, empty_init, "TeleVideo Systems", "TeleVideo 955", MACHINE_NOT_WORKING | MACHINE_IMPERFECT_GRAPHICS )
|
1. Field
Embodiments of the present invention relate to agricultural vehicles. More particularly, embodiments of the invention relate to methods and systems for controlling the activation of agricultural vehicle lighting.
2. Related Art
Tractors and other agricultural vehicles are often equipped with auxiliary electrical circuits for powering optional or after-market electrical components such as rear-mounted lighting systems. Many agricultural vehicle lighting systems use high-intensity discharge (HID) lamps such as xenon, mercury vapor, high-pressure sodium, and metal halide lamps because they produce a much larger quantity of light with a relatively smaller bulb when compared to fluorescent and incandescent lamps. HID lamps also last much longer than many other types of lamps and produce a white light that more closely approximates the color of natural daylight.
Unfortunately, however, HID lamps draw a spike or peak of current at start-up before settling to a steady state current level after a few seconds of operation. For example, one type and size of HID lamp draws approximately 10 amps at start-up, 5 amps after 10 seconds, and only 3 amps after 30 seconds. This is a problem when such lamps are powered by auxiliary electrical circuits, because these circuits are typically designed to carry a relatively low maximum current. For example, many agricultural vehicles are equipped with auxiliary electrical circuits with wires and fuses or circuit breakers rated for only 20 amps. To avoid blowing these fuses or overheating the wires, only two HID lamps may be attached to each circuit. One obvious solution to this problem is to provide higher capacity wires and fuses, but this is not practical for existing agricultural vehicles.
Accordingly there is a need for an improved system and method for powering HID lamps and similar lamps installed on agricultural vehicles. |
Estimated glomerular filtration rate in Korean patients exposed to long-term lithium maintenance therapy Background Lithium-induced nephrotoxicity has long been debated. However, it has been rarely explored in Asian populations. The aim of the present study was to assess the effect of lithium maintenance therapy on estimated glomerular filtration rate (eGFR) in Korean patients diagnosed with a psychiatric illness. Methods This was a single-centered, retrospective study that included patients treated with lithium or comparator drug (valproate) in Samsung Seoul Medical Center between November 1994 and July 2020. Patients diagnosed with ICD codes F20-33 who had ≥6 months of exposure to lithium or valproate were included. Patients had to have ≥1 baseline and ≥2 post-baseline eGFR data with post-baseline data having an interval of at least 30 days. Chronic kidney disease (CKD) was defined as CKD stage 3 (eGFR <60 mL/min/1.732). To be considered as CKD, the threshold had to be met at two consecutive post-baseline measurements. Those treated with both lithium and valproate, diagnosed with CKD stages 35, diagnosed with a renal disease, or received kidney transplantation were excluded. Results A total of 766 patients were included (242 treated with lithium and 524 with valproate). Two (0.8%) in the lithium group and 8 (1.5%) in the valproate group developed CKD stage 3. None developed CKD stages 45. Median yearly eGFR change was − 1.3 mL/min/1.732 (IQR: − 6.8, 1.7) for the lithium group and − 1.1 mL/min/1.732 (IQR: − 4.5, 1.5) for the valproate group, showing no significant difference between the two groups (p =0.389). The rate of decline was more rapid for those with CKD in both groups. eGFR values of lithium and valproate groups did not show significant differences during a follow-up duration of 15 years or more. A significant negative correlation between baseline eGFR and yearly eGFR change was identified in a linear regression analysis. Conclusions In Korean patients, treatment with lithium did not increase the risk of developing CKD compared to treatment with valproate. Prevalence of CKD was lower than those previously reported in western populations. Low baseline eGFR showed significant correlation with changes in renal function. Supplementary Information The online version contains supplementary material available at 10.1186/s40345-022-00249-5. Background Lithium is one of the most established drugs in longterm treatment of bipolar disorder. It is effective in preventing relapses of mood episodes and in reducing risk of suicide (Geddes and Miklowitz 2013). Because of its narrow therapeutic index, clinicians are required to regularly monitor serum lithium levels and to titrate the dosage accordingly. Concerns have been raised regarding Page 2 of 9 Cho et al. International Journal of Bipolar Disorders 10:4 nephrotoxic effects of long-term lithium maintenance, with prior studies in the 1970's reporting structural tubular damage and interstitial fibrosis in biopsy findings of lithium users (). Following studies have confirmed such morphologic findings after examining tubulointerstitial nephropathy and relative preservation of the glomeruli (;). Since then, the effect of long-term lithium treatment on renal function has been the topic of debate. Several studies have reported decline of renal function after lithium use, while others have reported negative associations between the two (;;). Lithium-induced nephropathy has been recognized to be slow in progression ("creeping creatinine"). Its rate of progression is associated with age, treatment duration, cumulative dose, and episodes of toxicity (;;;). Compared to other mood stabilizers and atypical antipsychotics, lithium is associated with decline in renal function (eGFR < 60 mL/ min/1.73 2 ), but to a lesser degree with greater eGFR declines (eGFR < 30 mL/min/1.73 2 ) (). Incidence of CKD has been reported to be 21-55% in long-term lithium users (). Progression to end-stage renal disease (ESRD) has been found to be uncommon (0.5-1%) and to require longer time to develop (;;;). Other reports have stated that the rate of eGFR decline does not significantly differ between long-term lithium users and patients treated with other psychotropic agents, advocating the safety of lithium maintenance therapy (). These discrepancies might have derived from differences in study design and comparator groups. As patients who are exposed to lithium have a high probability of co-prescription of other psychotropic medication (;), additional effects of polypharmacy on renal function should be minimized by selecting comparison groups who are likely to be on similar sets of medications. Previous findings based on long-term observational data should also be reviewed with consideration of several biases, including ascertainment bias, channeling bias and survival bias. Increased risk of renal impairment associated with lithium treatment reported in numerous studies may be a result of overestimation due to surveillance bias (). Lithium-induced nephrotoxicity is still a topic of controversy even after a long history of debate. Very limited research exists regarding lithium's effect on renal function in an Asian population. Thus, the aim of the present study was to assess the effect of lithium maintenance therapy on renal function represented by eGFR in a sample of Korean patients diagnosed with a psychiatric illness. We included all patients who were chronically exposed to lithium in a tertiary care setting hospital in Korea and set the comparison group as those who were exposed to valproate. Study participants This study was designed as a single-centered, retrospective study that included patients who had records of being treated with lithium in the Department of Psychiatry, Samsung Seoul Medical Center, Korea between November 9, 1994 and July 20, 2020. Patients who had been treated with valproate, one of first-line drugs in the treatment of bipolar disorder, were assigned to the comparator group. Patients eligible for inclusion were those aged 18 years or older at baseline (the first day of lithium or valproate prescription), those who had at least 6 months of exposure to either lithium or valproate, and those who had ≥ 1 baseline and ≥ 2 post-baseline eGFR data (two consecutive post-baseline data requiring at least 30 days of interval). This study included patients who had ICD codes of F20-29 (schizophrenia or psychotic disorders), F30-31 (bipolar disorders), and F32-33 (depressive disorders) as main diagnosis. Those with other psychiatric and medical conditions as main diagnosis, including brain tumor related conditions (ICD codes C70-71) and epilepsy (ICD codes G40-41), were not included. It is to be noted that the Korean health insurance system is based on a claims data generated by healthcare providers for reimbursement purposes (). As such, certain ICD codes are necessary for coverage of specific drug prescriptions or eligibility for healthcare provision. Therefore, discrepancies can occur between diagnoses entered in the data system and diseases that a patient actually has. Those who had been treated with both lithium and valproate, either at different time or at the same time, were excluded from the analysis. They were identified through prescription records and serum therapeutic drug monitoring (TDM). Those with baseline eGFR < 60 mL/ min/1.73 2 (CKD stages 3-5), those with a baseline kidney disease (ICD codes N00-08 and N10-19), and those who had received kidney transplantation (ICD codes T86.1 and Z94.0) were also excluded. This study was approved by the Institutional Review Board of Samsung Seoul Medical Center (IRB no. 2020-12-029-001). The requirement for written informed consent was exempt by the IRB because this study was based on an anonymized dataset of electronic health records and lab results. Definitions CKD was defined as eGFR < 60 mL/min/1.73 2 (CKD stage 3). The threshold had to be met at the two most recent post-baseline eGFR data measured at least 30 days apart. eGFR was calculated with the Chronic Kidney Disease Epidemiology Collaboration (CKD-EPI) equation, which took age, sex, and race into account (). Baseline eGFR was defined as the eGFR value measured before initiation of lithium or valproate use. Baseline diagnosis of hypertension was confirmed using ICD-9 codes 401-405 and ICD-10 codes I10-16 before prescription of lithium or valproate. Baseline diabetes mellitus was defined as ICD-9 codes 250.0-250.9 and ICD-10 codes E08-13 recorded before the use of lithium or valproate. We used three different cutoff points in defining episodes of lithium toxicity: lithium TDM > 0.8 mmol/L, TDM > 1.0 mmol/L, and TDM > 1.2 mmol/L. Lithium has a narrow therapeutic index of 0.5-0.8 mmol/L in maintenance phase and 0.8-1.2 mmol/L in acute manic phase. It has been reported that even one serum level of > 1.0 mmol/L can cause significant effect on eGFR (Raja 2011;). Thus, cutoff points were set at short intervals to closely monitor effects of toxic lithium levels. Statistical analyses Clinical characteristics were compared between those treated with lithium or valproate presented as mean ± standard deviation (SD) or as number (%). Median years to reach eGFR < 60 mL/min/1.73 2 and yearly eGFR change were calculated for each group (lithium group and valproate group). We prepared a scatter plot of eGFR over the follow-up period and compared the overall trend in eGFR change between the lithium group and the valproate group. Linear regression was carried out with yearly eGFR change as dependent variable to explore associations between demographic factors, baseline comorbidities, and clinical variables such as medication of use (lithium vs. valproate), primary diagnosis, baseline eGFR, treatment duration, average daily dose of medication and lithium toxicity. Kaplan-Meier method was used to predict the number of years required to reach eGFR < 60 mL/ min/1.73 2. All statistical analyses were performed using R 4.0.3. Statistical significance was considered when p value was less than 0.05. Results Among 9493 patients with at least one prescription record of lithium or valproate during the observation period, 766 patients (242 on lithium and 524 on valproate) met the inclusion and exclusion criteria (Fig. 1). Mean age of the study population was 39.3 years (SD: 16.0 years; median: 35.0 years; range: 18.0-86.0 years). A total of 410 (53.5%) women and 356 (46.5%) men were included. Of them, 425 (55.5%) patients had primary ICD-10 diagnosis of bipolar disorder (codes F30-31). Table 1 shows baseline characteristics of the study population. Patients treated with lithium tended to be younger than those treated with valproate (mean age: 37.0 years vs. 40.4 years, p = 0.005). No significant differences existed between the two groups regarding sex and baseline comorbidities of hypertension and diabetes mellitus. As for primary psychiatric diagnoses, the lithium group included a larger proportion of those diagnosed with bipolar disorder (ICD-10 codes F30-31) than the valproate group (71.5 vs. 48.1%). The valproate group had a higher percentage of patients whose eGFR fell below 60 mL/min/1.73 m 2 (CKD stage 3) during the follow-up period, although the difference between the two was insignificant . No patient in either group reached CKD stages 4-5. The lithium group had a median yearly eGFR change of − 1.3 mL/min/1.73 m 2 (IQR: − 6.8, 1.7) and the valproate group had a median yearly eGFR change of − 1.1 mL/ min/1.73 m 2 (IQR: − 4.5, 1.5). There was no significant difference in yearly eGFR change between lithium and valproate groups (p = 0.389). Baseline and yearly eGFR values showed no significant differences between the two groups up to year 15, at which the mean eGFR was 73.7 ± 21.1 mL/min/1.73 m 2 for the lithium group and 99.6 ± 15.6 mL/min/1.73 m 2 for the valproate group, showing no significant (p = 0.085) difference between the two. Among patients who reached CKD stage 3, median years to reach eGFR < 60 mL/min/1.73 m 2 were 8.7 years (range, 4.9-21.4 years) for the overall study population, 12.8 years (range, 9.8-15.9 years) for the lithium group, and 7.4 years (range, 4.9-21.4 years) for the valproate group. Two lithium users who developed CKD stage 3 both had baseline diagnosis of hypertension with a history of lithium toxicity reaching serum level > 1.0 mmol/L Page 4 of 9 Cho et al. International Journal of Bipolar Disorders 10:4 during follow-up. Each of them required 15.88 years and 9.82 years since the start of lithium until development of CKD (Additional file 1: Table S1). Linear regression revealed significant negative correlation between baseline eGFR and yearly eGFR change (Table 2, adjusted coefficient: − 2.2; p = 0.030). The choice of drug (lithium vs. valproate) did not display significant correlation with eGFR change in linear regression analyses. Subgroup analyses by diagnoses did not show significant correlations with annual eGFR decline, with the exception of age in patients diagnosed with F32-33 (Additional file 1: Tables S2-1, S2-2, S2-3). Figure 2 shows a scatter plot of all eGFR values measured during the follow-up duration for the lithium group (red) and the valproate group (green). While eGFR values of the lithium group generally showed a decreasing pattern with longer duration of treatment, few seemed to fall below significant levels (CKD stages 3-5; eGFR < 60 mL/min/1.73 m 2 ). Figure 3 shows a Kaplan-Meier plot for years of treatment taken to enter CKD stage 3 (eGFR < 60 mL/min/1.73 m 2 ). Although analysis was limited due to a small sample size, the time to enter CKD stage 3 did not show significant differences between lithium and valproate groups (p = 0.855). We additionally compared the basic characteristics between patients finally included in the study and patients excluded due to insufficient eGFR data. Age group and sex were similar between two groups, but the excluded patients from the analyses were more likely to be diagnosed with bipolar disorder (F30-31), were more likely to be on lithium, and had shorter follow-up duration compared to those included in the study. However, among patients excluded in the study, those who had CKD stage 3 were more common in valproate group (lithium group 4.3% vs. valproate group 12.6%, p = 0.004). Discussion This is the first study that explores the effect of lithium nephrotoxicity in an Asian population. In our study, lithium use did not show greater eGFR decline as compared to valproate use. Kidney function was preserved in both groups up to 15 years of follow-up. As stated earlier, use of diverse psychotropic medication can affect renal function. Polypharmacy is highly prevalent in treatment of bipolar disorder. In particular, valproate and atypical antipsychotics as drugs commonly used as alternatives for lithium are known to have nephrotoxic effects (Gitlin 1999; ). In addition, genetic () and environmental (a(Barbour et al., 2010b factors both can affect renal function. Thus, having a comparator group that is ethnically identical and likely to be exposed to similar sets of psychotropic medication is crucial in evaluating the nephrotoxicity of lithium. In line with our study findings, Clos et al. have demonstrated no significant differences in the rate of eGFR decline between those exposed to lithium and Year 20 eGFR -81.5 ± 21.9 -Page 6 of 9 Cho et al. International Journal of Bipolar Disorders 10:4 those exposed to other first-line drugs after adjusting for various demographic and clinical factors. Our study obtained similar results after adjusting for demographic factors, comorbidities, primary psychiatric diagnoses, and clinical variables such as baseline renal function, treatment duration, and average daily dose of medication. The relatively lower rate of CKD observed in our study could be associated with ethnic and environmental factors that can affect renal function. Previous studies have suggested that ethnic differences exist in CKD development and that changes in eGFR are associated with genetic variants (). Individuals of Asian descent living in western environments have shown increased burden of ESRD and rapid progression of CKD as compared to Caucasians (a(Barbour et al., 2010b, suggesting the effect of gene-environment interaction on renal function. Genetic determinants, alongside exposure to different diet and social environments, may contribute to ethnic differences in CKD progression (a). Despite such findings, no prior study has reported lithium nephrotoxicity in Asian patients. Further study is needed to confirm our study findings. Aside from ethnic and environmental differences, specific characteristics of the study population and care settings of our study have to be considered when reviewing our findings. All patients had severe psychiatric illnesses requiring treatment in a tertiary care setting hospital. However, they were well-monitored and were in relatively good physical health. Prior studies with comparator groups have included patients with more frequent medical comorbidities, including hypertension, diabetes, and dyslipidemia, compared to patients in our study (;;). It is difficult to compare annual eGFR changes with previous studies directly due to environmental and ethnic differences. The median yearly eGFR change for the lithium maintenance group was − 1.3 mL/min/1.73 m 2 (IQR: − 6.8, 1.7) in our study. This rate of annual decline was within the normal range of GFR changes (up to 10 mL/min/1.73 m 2 for 5 years) established by NICE chronic kidney disease guidelines (). It was not significantly higher than the rate of the comparator group. Previous studies have reported annual rate of eGFR decline to be 1.0-5.0 mL/min/1.73 m 2 in longterm lithium treatment groups (;;). Our estimates for annual decline are comparable to previous findings of Clos et al. (mean annual eGFR decline of 1.3 mL/ min/1.73 m 2, SE: 0.02, t test, p > 0.05). In our analysis, only 10 (1.3%) participants developed CKD stage 3. The incidence of CKD was not significantly different between the two groups (2 on lithium vs. 8 on valproate, Fisher's exact test, p = 0.733). No participant reached CKD stages 4-5, which might be due to close monitoring and timely intervention. The prevalence of CKD development was relatively low in our study population, considering that the prevalence of CKD stage 3 in the general population of Korea was 7.9% in the national survey of 2011-12 and the prevalence of CKD stage 3-4 (6.9%) in the US population (Ji and Kim 2016;), Previous studies in western environments have also reported higher CKD prevalence of 21-55% in long-term lithium users (; ;). The relatively lower age and shorter treatment duration in our study might have affected study findings (vs. mean age of 39.3 ± 16.0 years and mean duration on lithium of 3.5 ± 3.5 years in our study) (). In previous literature, age, female sex, duration of lithium therapy, lower initial eGFR, comorbidities such as hypertension and diabetes, cumulative lithium dose, prior episodes of lithium toxicity, nephrogenic diabetes insipidus and concomitant use of nephrotoxic medication have been identified as factors that can increase the risk of lithium-induced nephropathy (). In our study, baseline eGFR was the only factor that showed a significant correlation with eGFR change in linear regression analyses. Correlation between age and eGFR change was marginally significant (p = 0.056). Insignificant correlation between episode of lithium toxicity and decreased renal function may have reflected regular monitoring and immediate intervention. These findings need to be further investigated in a larger sample of Korean patients with longer lithium exposure to determine predictors for eGFR decline. Although we could not conduct statistical analysis due to a small sample size, both lithium users who reached CKD stage 3 had comorbid hypertension with toxic serum lithium level > 1.0 mmol/L at least once. The strength of this study was that it was based on a well-monitored group of patients with regular follow-up on serum creatinine, eGFR, and serum lithium levels. The hospital-based setting provided abundant clinical data and allowed comprehensive evaluation of each patient. We also selected a comparator group that was likely to be treated under similar circumstances. However, the present study also has limitations. The tertiary hospital setting might have contributed to selection bias of participants recruited in this study. Excluding those who have been exposed to both drugs also might have led to selection bias. Lithium users are frequently monitored for renal function and serum concentration, leading to the possibility of surveillance bias. As such, patients who receive long-term lithium maintenance therapy are likely to be those with sustained renal function and tolerability to the medication (). Frequent monitoring of renal function may have resulted in timely discontinuation in others with less tolerability. In our study, patients who were excluded from the analysis due to insufficient eGFR data had shorter follow-up duration compared to those included in the study. We also did not explore the effect of co-prescribed medications. Discrepancies in the diagnoses have also limited our analysis, as failure to control for diagnosis of bipolar disorder have previously been associated with potential risk of confounding (). Diagnostic discrepancies may explain the considerable number of patients diagnosed with schizophrenia or depressive disorder being treated with lithium or valproate in our study. It is notable that lithium use in schizophrenia and depression are quite common (;), and that diagnostic changes between schizophrenia, bipolar disorder and depression are also common (). This study was based on a limited number of patients, and thus needs to be replicated with a larger sample of Asian population. Conclusions There was little evidence that Korean patients treated with lithium developed significant decline in renal function more rapidly than patients treated with valproate. In light of these findings, lithium is likely to be safe for long-term use with careful monitoring and intervention in majority of patients. |
<gh_stars>10-100
// $Id: client.cpp 91648 2010-09-08 13:25:56Z johnnyw $
#include "tao/ORB.h"
#include "tao/Object.h"
#include "tao/SystemException.h"
#include "ace/Get_Opt.h"
const ACE_TCHAR *ior_output_file = ACE_TEXT("test.ior");
int
parse_args (int argc, ACE_TCHAR *argv[])
{
ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:"));
int c;
while ((c = get_opts ()) != -1)
switch (c)
{
case 'k':
ior_output_file = get_opts.opt_arg ();
break;
case '?':
default:
ACE_ERROR_RETURN ((LM_ERROR,
"usage: %s "
"-k <ior> "
"\n",
argv [0]),
-1);
}
// Indicates successful parsing of the command line
return 0;
}
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
try
{
CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);
if (parse_args (argc, argv) != 0)
return 1;
CORBA::Object_var tmp =
orb->string_to_object("iiop://1\"/2$/$3211:2500/EndPoint");
}
catch (const CORBA::INV_OBJREF&)
{
ACE_DEBUG ((LM_DEBUG, "Test succeeded\n"));
}
catch (...)
{
ACE_ERROR ((LM_ERROR, "Caught invalid exception\n"));
return 1;
}
// Write dummy file to trigger the test framework we are ready.
FILE *output_file= ACE_OS::fopen (ior_output_file, "w");
if (output_file == 0)
ACE_ERROR_RETURN ((LM_ERROR,
"Cannot open output file for writing IOR: %s\n",
ior_output_file),
1);
ACE_OS::fprintf (output_file, "dummy");
ACE_OS::fclose (output_file);
return 0;
}
|
#include<stdio.h>
int main()
{
int i,j;
int lasa[28];
int value[31];
for(i=1;i<=30;i++)
{
value[i]=i;
}
for(i=0;i<=28;i++)
{
scanf("%d\n",&lasa[i]);
}
for(i=0;i<29;i++)
{
for(j=1;j<31;j++)
{
if(lasa[i]==value[j])
{
value[j]=-1;
}
}
}
for(i=1;i<=30;i++)
{
if(value[i]>-1)
{
printf("%d\n",value[i]);
}
}
return 0;
} |
What Did 'The Defiant Ones' Show Us?
July 18, 2017 The HBO mini-series portrays the story of Apple Music's Dr. Dre and Jimmy Iovine, who came together to work on some of the 20th century's most important music.
July 11, 2017 The new song comes in conjunction with the revealing HBO documentary The Defiant Ones, which intertwines the lives and legacies of Dr. Dre and Jimmy Iovine.
July 7, 2017 The new HBO mini-series charts the shared and individual histories of Dr. Dre and Jimmy Iovine, whose partnership helped redefine hip-hop and rock music.
August 7, 2015 The producer behind the West Coast gangsta rap sound looks back over his career on a long-awaited album that sounds less like one man's vanity project than a grand group effort.
Dr. Dre's 'Compton': Who Are The Album's New Artists?
August 4, 2015 He gave us Snoop Dogg, Eminem and Kendrick Lamar. Now, the producer has a new crop of protégés.
February 21, 2014 Alt.Latino sits down with rapper Bocafloja and blogger Juan Data to discuss the many ways hip-hop has trickled into Latin America and its music scene.
August 20, 2008 The songs on this list were made before iTunes was a glimmer in Steve Jobs' eye, so it stands to reason that they sound better bumping out of car speakers. Give these a spin and then track down the CDs, because they deserve to be heard the old-fashioned way. Turn your woofers up and roll down your windows — all of them.
June 1, 2007 Producer Dr. Dre is one of the most important and influential figures in rap music, known for popularizing the distinct West Coast rap sound, as author Ronin Ro explains in his new biography.
November 22, 2010 What happened last night at the American Music Awards, plus other music stories from around the web. |
THU0564COULD A PROBABILISTIC REASONING AI ACCELERATE RARE DISEASE DIAGNOSIS? EVALUATING THE POTENTIAL IMPACT OF A DIAGNOSTIC DECISION SUPPORT SYSTEM IN A RETROSPECTIVE STUDY Background: The diagnosis of rare diseases is often delayed by years. The main factor for this delay is believed to be the lack of knowledge and awareness regarding rare diseases. Probabilistic diagnostic decision support systems (DDSS) have the potential to accelerate rare disease diagnosis by highlighting differential diagnoses for physicians. DDSSs are based on case input and incorporated medical knowledge. Objectives: We examine a probabilistic DDSS prototype and assess its potential to provide accurate rare disease suggestions early in the course of rare disease cases. Methods: Retrospectively, information from the medical records of 93 patients was transferred to the DDSS. Each of these patients had a confirmed rare inflammatory systemic disease. The accuracy of the DDSS disease suggestions was assessed for all documented visits over time. Time to correct top fit (TF) and top five fit (T5F) disease suggestion was assessed, as was the original time to clinical diagnosis (TD). TF/TD as well as T5F/TD were calculated to allow for comparison of TF respective T5F normalized to TD. Wilcoxon signed-rank test was conducted for TD-TF and TD-T5F. Results: The DDSS suggested the correct disease at a time earlier than the time of clinical diagnosis among the top five fit disease suggestions in 53.8% of cases (50 of 93), and as the top fit disease suggestion in 37.6% of cases (35 of 93). Median advantage of correct disease suggestions compared to the time point of clinical diagnosis was 3 months or 50% for top five fit respective 1 month or 21% for top fit. The correct diagnosis was suggested at the first documented patient visit among the top five fit disease suggestions in 33.3% (top five fit), respective 16.1% of cases (top fit). Wilcoxon signed-rank test shows a significant difference between the time to clinical diagnosis and the time to correct disease suggestion for both top five fit and top fit (z-score -6.68, respective -5.71, =0.05, p-value <0.001). The DDSS suggested the correct rare disease at the time of diagnosis in 89% of cases (83 of 93) Conclusion: The DDSS was capable of providing accurate rare disease suggestions in most of the rare disease cases. In many cases it provided correct rare disease suggestions early in the course of the disease, sometimes in the very beginning of a patients journey. The interpretation of these results suggests that DDSSs have the potential to highlight the possibility of a rare disease to physicians early in the course of a case. Limitations of this study derive from its retrospective and unblinded design, data input by a single user, and the optimization of the knowledge base during the course of the study. Whether the use of this DDSS leads to a reduced time to rare disease diagnosis in a clinical setting should be validated in prospective studies. References: Bl S, et al. Diagnostic needs for rare diseases and shared prediagnostic phenomena: Results of a German-wide expert Delphi survey. PLOS ONE. 2017feb;12:e0172532. Available from: http://dx.plos.org/10.1371/journal.pone.0172532. Nationales Aktionsbndnis fr Menschen mit Seltenen Erkrankungen (NAMSE). Nationaler Aktionsplan fr Menschen mit Seltenen Erkrankungen. 2013. Available from: http://www.namse.de/images/stories/Dokumente/nationaler_aktionsplan.pdf. Kostopoulou O, et al. Early diagnostic suggestions improve accuracy of family physicians: a randomized controlled trial in Greece. Family Practice. 2015jun;32:323328. Riches N, et al. The effectiveness of electronic differential diagnoses (DDX) generators: A systematic review and meta-analysis. PLoS ONE. 2016mar;11:e0148991. Available from: http://dx.plos.org/10.1371/journal.pone.0148991. Disclosure of Interests: Simon Ronicke Employee of: Ada Health GmbH, Berlin, Martin C. Hirsch Shareholder of: Ada health GmbH, Ewelina Trk Employee of: Ada Health GmbH, Berlin, Katharina Larionov: None declared, Daphne Tientcheu: None declared, Annette D. Wagner: None declared |
import { Portal } from '@/components/Portal';
import style from '@/styles/create.module.scss';
import { useEffect, useRef, useState } from 'react';
import { useStore } from '@/store';
import axios from 'axios';
import { DragEvent } from 'react';
import { useSlate } from 'slate-react';
import { insertImage } from '../utils/block/InsertImage';
import { useRouter } from 'next/router';
import Image from 'next/image';
const ImagePortal = () => {
const isOpenImagePortal = useStore((state) => state.isOpenImagePortal);
const toggleImagePortal = useStore((state) => state.toggleImagePortal);
const router = useRouter();
const { id } = router.query;
const editor = useSlate();
const inputRef = useRef<HTMLInputElement>(null);
const [objectURL, setObjectURL] = useState<string | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [altText, setAltText] = useState<string>('');
const altTextChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setAltText(e.target.value);
};
const uploadImage = async () => {
try {
const params = new FormData();
imageFile && params.append('file', imageFile);
const { data } = await axios.post(`http://127.0.0.1:4000/uploadImage/${id}`, params, {
headers: {
'content-type': 'multipart/form-data',
},
});
console.log(data);
const { filename } = data;
insertImage(editor, {
format: 'image',
src: `https://delivery.far-float.jp/${id}/${filename}`,
alt: altText,
});
toggleImagePortal();
} catch (error) {
console.log(error);
}
};
const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
const file = e.target.files;
setImageFile(file[0]);
const objectURL = URL.createObjectURL(file[0]);
setObjectURL(objectURL);
}
};
const clickHiddenInput = () => {
if (inputRef !== null) {
inputRef?.current?.click();
}
};
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
let files = [...e.dataTransfer.files];
console.log(files);
};
const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
return (
<Portal>
<div
style={{
visibility: isOpenImagePortal ? 'visible' : 'hidden',
opacity: isOpenImagePortal ? 1 : 0,
}}
className={style.portal_overlay}
onMouseDown={(e) => {
e.preventDefault();
toggleImagePortal();
}}
>
<div className={style.portal_container}>
<div
className={style.portal_uploadImage_content}
onMouseDown={(e) => {
e.stopPropagation();
}}
>
<div className={style.portal_title_container}>
<h2 className={style.portal_title}>画像をアップロードする</h2>
</div>
{objectURL ? (
<figure className={style.objectURL_container}>
<Image
src={objectURL}
height={`300px`}
width={`400px`}
objectFit={`contain`}
alt={`preview_img`}
/>
</figure>
) : (
<div
className={style.portal_drop_field_wrapper}
onDrop={(e: DragEvent<HTMLDivElement>) => handleDrop(e)}
onDragOver={(e: DragEvent<HTMLDivElement>) => handleDragOver(e)}
>
<div className={style.portal_drop_field}>
<div className={style.select_file} onClick={() => clickHiddenInput()}>
ファイルを選択する
</div>
</div>
</div>
)}
<input
hidden
ref={inputRef}
type='file'
accept='image/*'
onChange={onFileInputChange}
/>
<div className={style.alt_input_wrapper}>
<label htmlFor='image_alt' className={style.alt_input_label}>
Alt
</label>
<input
className={style.alt_input}
id='image_alt'
type='text'
onChange={altTextChange}
value={altText}
/>
</div>
<div className={style.insert_button_wrapper}>
<button
className={style.insert_image_button}
onClick={() => imageFile && uploadImage()}
>
アップロード
</button>
</div>
</div>
</div>
</div>
</Portal>
);
};
export default ImagePortal;
|
Movement Along the Spine Induced by Transcranial Electrical Stimulation Related Electrode Positioning Study Design. A prospective, nonrandomized cohort study. Objective. To describe a technique quantifying movement induced by transcranial electrical stimulation (TES) induced movement in relation to the positioning of electrodes during spinal deformity surgery. Summary of Background Data. TES induced movement may cause injuries and delay surgical procedures. When TES movements are evoked, muscles other than those being monitored any adjustments in stimulation protocols and electrode positioning may be expected to minimize movement whereas preserving quality of monitoring. In this study, seismic evoked responses (SER) induced through TES were studied at different electrode positions. Methods. Intraoperative TES-motor evoked potentials were carried out in 12 patients undergoing corrective spine surgery. Accelerometer transducers recorded SER in two directions at four different locations of the spine for TES-electrode montage groups Cz-Fz and C3-C4. A paired t test was used to compare the means of SER and the relationship between movement and TES electrode positioning. Results. SERs were strongest in the upper body. All mean SERs values for the Cz-Fz group were up to five times larger when compared with the C3-C4 group. However, there were no differences between the C3-C4 and Cz-Fz groups in the lower body locations. Both electrode montage groups showed a gradual stepwise reduction in all mean SER values along the spine from the cranial to caudal region. For the upper body locations, there were no significant associations between SER and both montages; in contrast, a significant association SER was demonstrated in the lumbar region. Conclusion. At supramaximum levels, movements resulting from multipulse TES are likely caused by relatively strong contractions from muscles in the neck resulting from direct extracranial stimulation. When interchanging electrode montages in individual cases, the movement in the neck may become reduced. At lumbar levels transcranial evoked muscle contractions dominate movement in the surgically exposed areas. Level of Evidence: 4 |
A CASE SERIES OF THREE PATIENTS WITH BILATERAL CORNEAL ABRASION AND ROLE OF EYE PAD IN HEALING OF CORNEAL ABRASION Corneal abrasion is common presenting problem at an eye casualty department. Although short lasting, a corneal abrasion gives rise to marked discomfort and visual disability and requires prompt management. Eye pad is commonly used in the treatment of corneal abrasions. Need for use of eye pad in the healing of corneal abrasions was evaluated. |
Influence of Gas Humidity and Flow Rate on the Water Movement Direction through an Anion Exchange Membrane Fuel Cell Environmental concerns lead to a continually growing demand for clean energy generation. Thus, alternative energy sources or green fuels attract attention. The anion exchange membrane fuel cell (AEMFC) emerged as an excellent alternative due to its air CO2-free emissions, low-cost electrocatalyst used at the cathode, and industrial-scale membrane production development. Many efforts have been made to have AEMFC performances like those already shown by the proton exchange membrane fuel cell (PEMFC). Excellent results have been obtained for the lasted technology regarding power densities and operational cell life. It should be recognized that due to the nature of the electrode reactions in AEMFC, Eqs. 1-2, the performance enhancement of the overall cell reaction, Eq. 3, depends not only on the selected catalysts and ionomers/membranes but also on the cell's water management. The complexity of water management relies on the simultaneous production and consumption of water in anode and cathode, respectively, where the production is two-fold higher than the consumption. This effect might lead to anode flooding during the hydrogen oxidation reaction (HRR), Eq. 1. In contrast, during oxygen reduction reaction (OER), Eq. 2, the risk of membrane drying is latent as long as a water imbalance arises between both anodic and cathodic sides. It has been confirmed quantitatively that water direction movement could go from anode to cathode in a hydrophilic membrane (diffusion transport mode); however, using a membrane with hydrophobic properties promotes the water to travel from cathode to anode (electro-osmotic drag, EOD mode). In this context, it is convenient to identify the water direction trend under variable selected operating conditions. In particular, achieving the anode-to-cathode water direction would improve the AEMFC performance by avoiding flooding on the anode by cathode hydration through water diffusion through the membrane. Therefore, this work tested the influence of symmetric and asymmetric flow rates and relative humidities within an AEMFC using a hydrophilic membrane. According to both modes of transport, the AEMFC performance was studied using polarization curves. The experimental procedure involved trapping water out of each half-cell during a chronoamperometry in steady-state conditions. Also, the water incoming was quantified independently for each selected operating condition in order to make a mass balance (Figure 1a). The variable operating conditions were the reactant flow rate, low (125 cm3 min-1) and high (250 cm3 min-1), and the reactant humidity level. In Figure 1b, the results demonstrated that the EOD predominance was promoted when low symmetric flow rates (125 cm3 min-1 for anode and cathode) were used in the AEMFC, suggesting membrane dehydration. On the contrary, the water diffusion dominance appears under high (250 cm3 min-1) symmetric and asymmetric flow rates between anode and cathode; under these conditions, the membrane dehydration might be suppressed by anode flooding alleviation. Once the flow conditions are given, no changes in water transport mode were detected for changes in the humidity level (Figure 1c-d). The AEMFC performance was affected by the water transport mechanism, giving lower peak power densities for EOD-dominated systems (35.2 mW cm-2 at 60°C, Figure 1e) than those obtained by diffusion (62.8 mW cm-2 at 60°C, Figure 1f). The most suitable operating condition is under water-diffusion at non-saturated streams (below 65%), where a decrease in performance is experienced as the humidifier temperature increases from 60°C to 80°C (supersaturated flow), with peak power densities of 62.8 and 3.7 mW cm-2, respectively. References: Zhang, J. Liu, Y. Wang, L. An, M. D. Guiver, N. Li, Highly Stable Anion Exchange Membranes Based on Quaternized Polypropylene, J. Mater. Chem. A 3 12284-12296. https://doi.org/10.1039/C5TA01420D G. Wright, F. Jiantao, B. Britton, T. Weissbach, H. F. Lee, E. A. Kitching, T. J. Peckham, S. Holdcroft, Hexamethyl-p-terphenyl poly(benzimidazolium): A Universal Hydroxide-Conducting Polymer for Energy Conversion Devices, Energy Environ. Sci. 9 2130-2142. https://doi.org/10.1039/c6ee00656f Zhang, Y. Hua, Z. Gao, Strategies to Optimize Water Management in Anion Exchange Membrane Fuel Cells, J. Power Sources 525 231141. https://doi.org/10.1016/j.jpowsour.2022.231141 Gottesfeld, D. R. Dekel, M. Page, C. Bae, Y. Yan, P. Zelenay, Y. S. Kim, Anion Exchange Membrane Fuel Cells: Current Status and Remaining Challenges, J. Power Sources 375 170-184. https://doi.org/10.1016/j.jpowsour.2017.08.010 Figure 1 |
Cerebral Microbleeds in Murine Amyloid Angiopathy: Natural Course and Anticoagulant Effects Background and Purpose Cerebral microbleeds (CMBs) predispose patients to intracerebral hemorrhage. Preclinical models to examine the effects of antithrombotic treatments on the development of clinically overt intracerebral hemorrhage are needed. We examined the natural course of CMB development and the effects of long-term anticoagulation with warfarin or dabigatran on cerebral micro- and macrohemorrhage in mice overexpressing the APP23 (amyloid precursor protein). Methods Repeated susceptibility-weighted magnetic resonance imaging was performed in APP23 mice at the age of 18 and 21 months, respectively. After establishing stable long-term anticoagulation effects of warfarin and dabigatran on number and total volume of CMBs, the outcome parameters were compared with nonanticoagulated control. Results CMBs were equally located in lobar and deep brain regions, and number and total volume of CMBs increased over time. Anticoagulation with either warfarin or dabigatran did not increase CMBs in APP23 significantly. Mice treated with warfarin numerically had a higher mortality (nonanticoagulated: 31%; dabigatran: 35% versus warfarin: 55%; P=0.21). In postmortem brains of prematurely dying animals warfarin caused significantly more frequently large intracerebral hemorrhage than control and dabigatran. Conclusions Anticoagulation with warfarin or dabigatran for 3 to 4 months does not promote the formation of CMBs in aged APP23 mice. Nevertheless, warfarin but not dabigatran is associated with a higher risk of extensive intracerebral hemorrhage, suggesting that this model may allow preclinical safety evaluation of antithrombotic therapies. |
Michael Carter-Williams and Allen Iverson now have another thing in common. Both have earned the Rookie of the Month designation multiple times.
During 17 games in January, the first-rounder from Syracuse hasaveraged 16.5 points, 5.6 rebounds and 5.6 assists. He even posted his career high this month in a 33 points performance in Cleveland on Jan 7, making him the first Sixers rookie to score 30 or more points since Iverson in 1997.
Carter-Williams leads all rookies in scoring (17.3 ppg), rebounding (5.4 rpg), assists (6.6 apg) and steals (2.30 spg).
In NBA history, only three rookies have averaged at least 17.0 points, 5.0 rebounds and 6.0 assists for an entire season. They are Oscar Robertson, Magic Johnson and Steve Francis. |
In recent years, optical coherence tomography (OCT) for forming images that represent surface and/or internal morphologies of objects by using light beams from laser light sources etc. has attracted attention. Unlike X-ray CT, optical coherence tomography is noninvasive to human bodies and is therefore expected to be utilized in medical and biological fields in particular. For example, in ophthalmology, apparatuses for forming images of fundus, cornea, etc. are in practical stages.
An apparatus disclosed in Patent Document 1 uses so-called “Fourier Domain OCT” technique. More specifically, this apparatus irradiates low-coherence light beam to an object, superposes its reflected light and reference light to generate interference light, and acquires spectral intensity distribution of the interference light and executes Fourier transform to image morphology in a depth direction (z-direction) of the object. Further, this apparatus is provided with a galvano mirror for scanning light beams (signal light) along one direction (x-direction) perpendicular to the z-direction, and forms an image of a desired measurement target region of the object. An image formed by this apparatus is a two-dimensional cross-sectional image along the depth direction (z-direction) and scanning direction (x-direction) of the light beam. Such a technique is specifically called Spectral Domain.
Patent Document 2 discloses a technique that scans signal light in horizontal and vertical directions (x-direction and y-direction) to form two-dimensional cross-sectional images along the horizontal direction, and acquires three-dimensional cross-sectional information of a measured area based on these cross-sectional images to perform imaging. Such three-dimensional imaging techniques include, for example, a method that arranges and displays cross-sectional images along the vertical direction (referred to as stack data etc.), method that executing rendering processing on volume data (voxel data) created from stack data to form a three-dimensional image.
Patent Documents 3 and 4 disclose other types of OCT. An OCT apparatus disclosed in Patent Document 3 scans wavelengths of light irradiated to an object (wavelength sweeping), detects interference light obtained by superposing reflected lights of the respective wavelengths on reference light to acquire spectral intensity distribution, and executes Fourier transform on it to image morphology of an object. Such an OCT technique is called Swept Source etc. Swept Source OCT is a kind of Fourier Domain OCT.
An OCT apparatus disclosed in Patent Document 4 irradiates light having predetermined beam diameter to an object and analyzes components of interference light obtained by superposing reflected light thereof and reference light, thereby forming an image of a cross section of the object orthogonal to irradiating direction of the light. Such an OCT technique is called Full-Field, En-face, etc.
Patent Document 5 discloses an example of OCT application to ophthalmology. Before OCT was applied, retinal cameras, slit lamp microscopes, scanning laser ophthalmoscopes (SLO) etc. were used for observing eyes (see Patent Documents 6 to 8 for example). Retinal cameras photograph fundus by irradiating illumination light onto an eye and receiving reflected light from the fundus. Slit lamp microscopes obtain a cross-sectional image of cornea by cutting off a light section of the cornea using slit light. SLO images morphology of retinal surface by scanning fundus with laser light and detecting reflected light by high-sensitive elements such as a photomultiplier. These modalities photograph fundus, cornea, etc. from the front to acquire images (front images).
OCT apparatuses have advantages over retinal cameras etc. in that high-definition images may be obtained, cross-sectional and three-dimensional images may be obtained, etc.
Because OCT apparatuses may be used for observing various sites of eyes and is capable of obtaining high-definition images in this way, they have been applied to diagnoses of various ophthalmologic disorders. |
#include "starbytes/Syntax/SyntaxA.h"
#include <fstream>
#include <llvm/ADT/DenseMap.h>
#include <llvm/Support/Error.h>
#include <llvm/Support/ErrorHandling.h>
#include <llvm/ADT/Optional.h>
#include <llvm/ADT/ArrayRef.h>
#include "SymTable.h"
#ifndef STARBYTES_PARSER_SEMANTICA_H
#define STARBYTES_PARSER_SEMANTICA_H
namespace starbytes {
struct ASTScope;
struct SemanticADiagnostic final : public Diagnostic {
typedef enum : int {
Error,
Warning,
Suggestion
} Ty;
Ty type;
ASTStmt *stmt;
std::string message;
bool isError() override{
return type == Error;
};
void format(llvm::raw_ostream &os) override{
os << llvm::raw_ostream::RED << "ERROR: " << llvm::raw_ostream::RESET << message << "\n";
};
SemanticADiagnostic(Ty type,const llvm::formatv_object_base & message,ASTStmt *stmt):type(type),stmt(stmt),message(message){
};
SemanticADiagnostic(Ty type,ASTStmt *stmt):type(type),stmt(stmt){
/// Please Set Message!
};
~SemanticADiagnostic() override = default;
};
struct ASTScopeSemanticsContext {
ASTScope *scope = nullptr;
llvm::DenseMap<ASTIdentifier *,ASTType *> *args = nullptr;
};
/**
* @brief The Semantics Analyzer
* */
class SemanticA {
Syntax::SyntaxA & syntaxARef;
DiagnosticBufferedLogger & errStream;
bool typeExists(ASTType *type,
Semantics::STableContext & symbolTableContext,
ASTScope *scope);
ASTType *evalExprForTypeId(ASTExpr *expr_to_eval,
Semantics::STableContext & symbolTableContext,
ASTScopeSemanticsContext & scopeContext);
bool typeMatches(ASTType *type,
ASTExpr *expr_to_eval,
Semantics::STableContext & symbolTableContext,
ASTScopeSemanticsContext & scopeContext);
ASTType * evalGenericDecl(ASTDecl *stmt,
Semantics::STableContext & symbolTableContext,
ASTScopeSemanticsContext & scopeContext,
bool* hasErrored);
/**
@param args Used with BlockStmts embedded in Function Decls.
*/
ASTType * evalBlockStmtForASTType(ASTBlockStmt *block,
Semantics::STableContext & symbolTableContext,
bool * hasErrored,
ASTScopeSemanticsContext & scopeContext,
bool inFuncContext = false);
bool checkSymbolsForStmtInScope(ASTStmt *stmt,
Semantics::STableContext & symbolTableContext,
ASTScope *scope,
llvm::Optional<Semantics::SymbolTable> tempSTable = {});
public:
static void start();
void finish();
void addSTableEntryForDecl(ASTDecl *decl,
Semantics::SymbolTable *tablePtr);
bool checkSymbolsForStmt(ASTStmt *stmt,
Semantics::STableContext & symbolTableContext);
SemanticA(Syntax::SyntaxA & syntaxARef,
DiagnosticBufferedLogger & errStream);
};
}
#endif
|
/*
** my_str_to_wordtab.c for my_str_to_wordtab in /home/nomad/C/J7/barrea_m/my_str_to_wordtab
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Oct 21 19:23:08 2017 <NAME>
** Last update Tue Oct 24 14:44:22 2017 <NAME>
*/
#include <stdlib.h>
char *my_strncpy(char *dest, char *src, int n);
int detect_wd(char c)
{
if (((c > 64) && (c < 91)) || ((c > 96) && (c < 123)))
return (1);
else
return (0);
}
int detect_nb(char c)
{
if ((c > 47) && (c < 58))
return (1);
else
return (0);
}
int nb_word(char c)
{
if ((detect_wd(c) == 1) || (detect_nb(c) == 1))
return (1);
return (0);
}
int count_word(char *str)
{
int cpt;
int nb;
int wd;
int nb_word;
cpt = 0;
nb_word = 0;
while (str[cpt] != '\0')
{
nb = 0;
wd = 0;
while (detect_wd(str[cpt]) || detect_nb(str[cpt]))
{
if (detect_wd(str[cpt]) == 1)
wd = 2;
else
nb = 1;
cpt = cpt + 1;
}
if (wd > 0 || nb > 0)
nb_word = nb_word + 1;
if (str[cpt] != '\0')
cpt = cpt + 1;
}
return (nb_word);
}
char **my_str_to_wordtab(char *str)
{
int cpt;
int cptr;
int len;
char **tab;
cpt = cptr = len = 0;
tab = malloc((count_word(str) + 1) * sizeof(char *));
if (tab == 0)
return (0);
while (str[cpt] != '\0')
{
if (nb_word(str[cpt]) == 1)
len = len + 1;
if ((nb_word(str[cpt + 1]) == 0) && (nb_word(str[cpt]) == 1))
{
tab[cptr] = malloc((len + 1) * sizeof(char));
tab[cptr] = my_strncpy(tab[cptr], str + cpt - len + 1, len);
tab[cptr][len] = '\0';
len = 0;
cptr = cptr + 1;
}
cpt = cpt + 1;
}
tab[count_word(str)] = 0;
return (tab);
}
|
Renewable Energy: Enhancement in the Operation and Design of Hybrid Power Systems In this paper strategic developments of renewable energy systems are reviewed. This is prepared in order to develop and enhance better standalone applications using solely renewable energy. The paper attempts to present a comprehensive recommendation on hybrid renewable energy systems for the development of standalone applications. This utilizes interleaving a multiple input DC-DC converter to increase the reliability in maximizing the energy harvested from renewable energy. |
Combinatorial Therapy of Letrozole- and Quercetin-Loaded Spanlastics for Enhanced Cytotoxicity against MCF-7 Breast Cancer Cells Breast cancer is the most widespread cancer in women with rising incidence, prevalence, and mortality in developed regions. Most breast cancers (80%) are estrogen receptorpositive, indicating that disease progression could be controlled by estrogen inhibition in the breast tissue. However, drug resistance limits the benefits of this approach. Combinatorial treatment could overcome the resistance and improve the outcome of breast cancer treatment. In the current study, we prepared letrozole-(LTZSPs) and quercetin-loaded spanlastics (QuSPs) using different edge activatorsTween 80, Brij 35, and Cremophor RH40with different concentrations. The spanlastics were evaluated for their average particles size, surface charge, and percent encapsulation efficiency. The optimized formulations were further examined using transmission electron microscopy, Fourier transform infrared spectroscopy, in vitro drug release and ex vivo skin permeation studies. The prepared spherical LTZSPs and QuSPs had average particle sizes ranged between 129310 nm and 240560 nm, respectively, with negative surface charge and high LTZ and Qu encapsulation (94.397.2% and 97.999.6%, respectively). The in vitro release study of LTZ and Qu from the selected formulations showed a sustained drug release for 24 h with reasonable flux and permeation through the rat skin. Further, we evaluated the in vitro cytotoxicity, cell cycle analysis, and intracellular reactive oxygen species (ROS) of the combination therapy of letrozole and quercetin either in soluble form or loaded in spanlastics against MCF-7 breast cancer cells. The LTZSPs and QuSPs combination was superior to the individual treatments and the soluble free drugs in terms of in vitro cytotoxicity, cell cycle analysis, and ROS studies. These results confirm the potential of LTZSPs and QuSPs combination for transdermal delivery of drugs for enhanced breast cancer management. Introduction Breast cancer, the most invasive cancer among women globally, is the primary cause of cancer-related deaths among women worldwide. In case of local stage tumor, the 5-year survival rate is 99%, compared to 86% and 27% at regional stage and metastatic breast cancer, respectively. Early detection through breast screening (mammogram) and advanced therapeutic strategies result in better prognosis and improved survival rates. Since most breast cancers (80%) are estrogen receptor-positive (ER+), the growth and survival of cancerous breast epithelial cells are promoted by estrogen through binding to ER. Accordingly, the estrogen-dependent progression of most breast cancers could be combined delivery of LTZ/Qu. The aim of this study is thus bi-fold; first to study the effect of encapsulating LTZ and Qu on their anti-cancer potential, and second to examine the efficacy of their combination, in comparison with individual drugs against MCF-7 cells. We hypothesize that using LTZ and Qu loaded in the same nanoparticulate system could facilitate the coordinated delivery of drug combinations with different therapeutic properties. Therefore, we developed and characterized different spanlastic formulations loaded with each drug (either LTZ or Qu) using different types and ratios of EA. After that, we evaluated the in vitro release and ex vivo permeation of LTZ/Qu from each selected LTZ-loaded spanlastics (LTZSPs)/Qu-loaded spanlastics (QuSPs) through rat skin. Then, to prove our concept, we tested the cytotoxic activity of LTZ, Qu, and their combination, compared to LTZSPs, QuSPs, and their combination against MCF-7 cell line using MTT assay. Finally, we studied their effect on MCF-7 cell cycle using flow cytometry and the intracellular reactive oxygen species (ROS) levels using enzyme-linked immunosorbent assay (ELISA). Materials Quercetin was kindly gifted by Searle, Augusta, GA, USA. Letrozole was a kind donation from PHARCO Pharmaceuticals Inc. (Alexandria, Egypt). Span 60 and Brij 35 were purchased from Sigma-Aldrich Co. (St. Louis, MO, USA). Tween 80 and ethanol were obtained from El-Nasr Pharmaceutical Chemicals Co. (Cairo, Egypt). Cremophor RH40 was purchased from CISME (EMAROL H40 TM, Milano, Italy). All other chemicals and reagents used were of analytical grade. Preparation of LTZSPs and QuSPs Drug-loaded spanlastic dispersions were prepared using ethanol injection method, as previously reported using different compositions, as shown in Table 1. Briefly, specified amounts of Span 60 and drug (either LTZ or Qu) were dissolved in 2 mL of absolute ethanol and kept at 50 C, while EA was dissolved in 10 mL preheated double distilled water (DDW, 60 C). The ethanolic solution was then slowly injected into the preheated aqueous solution. After 3 h of stirring to remove alcohol, the dispersion was sonicated for 2 min and stored overnight at refrigerator (~4 C). The effects of different types of EA (Tween 80, Brij 35 and Cremophor RH40) and different Span 60: EA ratios (80:20 and 60:40) were studied. The effect of using different drug amounts was also investigated. Particle Size, Polydispersity Index and Zeta-Potential Measurements Malvern Zetasizer Nano series ZS instrument (Malvern Instruments, Malvern, UK) was used to determine the average hydrodynamic diameters, size distribution (polydispersity indices, PDIs), and zeta-potential values of the formulated LTZSPs and QuSPs dispersions in DDW at~1 mg/mL at room temperature. Estimation of the Encapsulation Efficiencies of LTZSPs and QuSPs Drug encapsulation efficiency of the prepared spanlastics was calculated by the indirect method. Briefly, the freshly prepared drug-loaded spanlastics were centrifuged using Amicon ® Ultra-15 centrifugal filters (100 kDa NMWL, Merk Millipore, Darmstadt, Germany) at 6000 rpm for 30 min. Next, the supernatant was collected and analyzed using Shimadzu UV-Vis spectrophotometer (model UV-1601 PC, Kyoto, Japan) at = 240 nm or = 372 nm for LTZ and Qu, respectively. Finally, the drug concentration was calculated from calibration curves. Encapsulation efficiency was calculated from the following equation: Encapsulation efficiency (%) = ((Total drug concentration − drug concentration in supernatant)/Total drug concentration) 100 The total amount of LTZ in the prepared LTZSPs is 10 mg (1 mg/mL) and 15 mg (1.5 mg/mL) while the total amount of Qu in the prepared QuSPs is 5 mg (0.5 mg/mL) and 10 mg (1 mg/mL). Abbreviations: LTZSPs; letrozole-loaded spanlastics, QuSPs; quercetin-loaded spanlastics, EA; edge activator. Evaluation of LTZSPs and QuSPs Morphology The selected formulations of LTZSPs (L8) and QuSPs (Q5) were imaged using a JEOL 100 CX II TEM (transmission electron microscope, Tokyo, Japan). A drop of particle dispersion (~1 mg/mL) was placed on a carbon-coated copper grid, negatively stained with 1% phosphotungstic acid and allowed to air dry prior to imaging. In Vitro Release Study of the Selected LTZSPs (L8) and QuSPs (Q5) The in vitro release of LTZ and Qu from the selected spanlastic formulations was studied, as previously reported. One-half mL of L8 preparation (equivalent to 0.75 mg LTZ) or one mL of Q5 formulation (equivalent to one mg Qu) was placed over a previously soaked cellulose membrane (Spectra/Por ® dialysis membrane with molecular weight cutoff 12,000-14,000) held at the lower end of a glass cylinder. After that, the glass cylinder was immersed in a beaker, including either hydroalcoholic phosphate buffer saline (PBS) solution (60 mL, PBS pH 7.4: methanol; 1:1) or PBS pH 7.4 plus 1% Tween 80 (50 mL) for LTZSPs and QuSPs, respectively. The temperature was maintained at 37 ± 0.5 C and the stirring rate was set to 50 rpm using a thermostatically controlled water bath (Gesellschaft fr Labortechnik GmbH, Burgwedel, Germany). At predetermined time points, aliquots of 3 mL sample were withdrawn and replaced with a freshly prepared release medium. Controls containing same concentration of free drug dispersions were tested, along with the spanlastic dispersions. The drug content of the release samples was assessed via utilizing a UV-Vis spectrophotometer (Shimadzu Seisakusho, Ltd., Kyoto, Japan) at = 240 nm or = 372 nm for LTZ and Qu, respectively. The cumulative percent drug released was plotted against time. The experiment was performed in triplicate. Ex Vivo Skin Permeation and Deposition Studies of LTZSPs and QuSPs The animal experiments were authorized by the Ethical Review Board of the Faculty of Pharmacy, Assiut University, Assiut, Egypt (Ref: S25-21, December 2021). Male Sprague Dawley rats (6-8 weeks) were acquired from the University Central Animal House Facility. All animals were fed with access to drinking water that was purified. The rats were retained at a room temperature of 25 ± 5 C. Rats were anesthetized with chloral hydrate and shaved gently with electric clippers and skin samples were excised from their dorsal side. Skin samples were then mounted at the lower end of a glass cylinder, with the stratum corneum side facing the donor compartment. The glass cylinder was then submerged in a beaker containing either hydroalcoholic PBS solution (60 mL, PBS pH 7.4: methanol; 1:1) or PBS pH 7.4 plus 1% Tween 80 (50 mL) for LTZSPs and QuSPs, respectively. The donor cell was loaded with either the optimized LTZSPs (L8, one-half mL equivalent to 0.75 mg LTZ) or QuSPs (Q5, one mL equivalent to one mg Qu), and the diffusion was compared with the controls (same drug concentration dispersed in DDW). The diffusion cells were agitated at 50 rpm for 24 h at 37 ± 0.5 C. Three mL aliquots were withdrawn at specified time, replaced with equal volume of the fresh medium, and analyzed as previously mentioned in the in vitro release study section. The permeation profiles were constructed by plotting the cumulative amount of drug permeated per unit of skin membrane area (Q n, mg/cm 2 ) versus time (h). Apparent permeability coefficients (P app values) were estimated according to the following equation: where ∆Q/∆t = linear mass appearance rate of the solute of interest in the receiver compartment, C 0 = initial solute concentration in the donor compartment, and A = surface area of the skin membrane (i.e., 4.9 cm 2 ). The steady-state flux (Jss, mg/cm 2 h) was calculated from the slope of the plot using linear regression analysis. After 24 h, the skin was withdrawn from the cells and washed with PBS and DDW to remove the excess drug. The skin was sliced into small pieces and homogenized. The drug remaining in the homogenized skin (deposited inside the skin) was extracted with methanol (48 h), sonicated for 30 min, centrifuged at 10,000 rpm for 60 min, and the concentration of either LTZ or Qu in the supernatant was determined spectrophotometrically as described above. Serial dilutions (10-150 M) of soluble LTZ, Qu (in DMSO), and combination of the two (1:1), and LTZSPs, QuSPs, and their combination (1:1) were tested for effects on the viability of MCF-7 cells. One day before treatment, cells were seeded in 96-well plates at a density of 1.2 10 4 cells/well. Treatments were then added as specified and after two days, media was aspirated and replaced with 100 L fresh media and 10 L MTT reagent (thiazolyl blue tetrazolium bromide, catalog no. M5655, Sigma-Aldrich, St. Louis, MO, USA), and plates were incubated at 37 C for 2 h. Absorbance was measured spectrophotometrically at = 570 nm. Cell viability was stated as the absorbance percentage from treated cells, compared to that from the untreated cells. IC 50 values for LTZ, Qu and their combination and LTZSPs, QuSPs and their combination were calculated using GraphPad Prism software. Additionally, the LTZSPs and QuSPs combination was evaluated using CompuSyn software (ComboSyn Inc., Paramus, NJ, USA) and combination index (CI) values were computed, where CI < 1 indicates synergy. Cell Cycle Analysis by Flow Cytometry Flow cytometry was used for quantitative assessment of apoptosis by dual staining the cells with annexin-V/propidium iodide (PI). It is based on using annexin-V coupled with fluorescein isothiocyanate (FITC) to label phosphatidyl serine sites on the membrane surface of apoptotic cells, as well as PI to flag cellular DNA in necrotic cells when the cell membrane has been completely degraded. MCF-7 cells were plated at a density of 1 10 5 cells/well in 6-well plates and incubated overnight. Then, cells were treated with soluble LTZ, Qu (in DMSO), and combinations of the two (1:1) and also by LTZSPs, QuSPs, and their combination (1:1) and incubated for 24 h. Treatments were added at 50% of the specified IC 50 in the aforementioned cytotoxicity study. After that, the cells were rinsed, trypsinized, and washed with DMEM medium, collected in falcon tubes in which respective supernatant was collected and cell pellets were washed twice using PBS. Then, the cell suspension (100 L) was transferred to a FACS tube and mixed with 5 L annexin V-FITC and 5 L PI. Tubes were gently vortexed and incubated for 30 min at room temperature in the dark. Finally, 400 L of the binding buffer were added to the FACS tube, and the tubes were run through a FACS machine within 1 h. Analysis of the different population of cells was done to determine apoptosis by assessing the annexin V-FITC/PI. Viable cells that were unlabeled, early apoptotic cells bound to annexin-V FITC only, late apoptotic cells bound to both annexin-V FITC/PI, and necrotic cells bound to PI only. Moreover, cell percentages were identified in each cell cycle (G 0 /G 1, S, and G2/M). Analysis was done using the FACSCalibur system (BD, San Jose, CA, USA). The data were analyzed with Cell Quest software (BD, San Jose, CA, USA). Assessment of Intracellular Reactive Oxygen Species (ROS) by ELISA The human breast cancer cell lines MCF-7 were seeded in DMEM supplemented with 10% v/v FBS and 1% penicillin/streptomycin in 96-well plates at a density of 1.2 10 4 (37 C, 5% CO 2 ). The medium was then removed, and standard solutions and the treatments were added in 0.1 mL/well each (n = 3). The treatments (soluble LTZ, Qu in DMSO and their combination and LTZSPs, QuSPs and their combination) dispersed in DMEM were added at specified concentration (50% of the specified IC 50 in the aforementioned cytotoxicity study) and left for 24 h, while control wells were left untreated. An amount of 100 L of the detection antibody working solution were added to each well, covered, and incubated at room temperature for 2 h with shaking at 400 rpm. Then, plates were incubated at 37 C for 90 min. The plate content was then discarded and 0.1 mL of biotin-detection antibody working solution was added into the standard, the test sample, and the control wells, and plates were incubated at 37 C for 60 min and then washed 3 times with wash buffer. Streptavidin-HRP (SABC) working solution was added into each well, and plates were incubated again at 37 C for 30 min and washed 5 times with wash buffer. An amount of 90 L of TMB define substrate was added into each well and incubated at 37 C in dark within 15-30 min. Finally, 50 L of stop solution was added into each well and mixed thoroughly. The optical density absorbance was measured at 450 nm using a microplate reader immediately after adding the stop solution. The ROS content was determined based on the absorbance difference between the tested samples and control, and a calibration curve was drawn with standard solutions. Statistical Analyses GraphPad Prism software for Windows version 8.3.0 (GraphPad Software Inc., San Diego, CA, USA) was used for the statistical analyses. Data were analyzed using two-tailed unpaired t-test or one-way analysis of variance (ANOVA) followed by Tukey post-hoc test to compare the effect of different drug concentrations and different types and ratios of EA on the average particle size, the zeta potential, the drug encapsulation efficiencies of the prepared spanlastics, and the permeation study data. Moreover, the results of IC 50 and ROS concentrations between the free drugs and their combination, and the drug-loaded spanlastics and their combination using MCF-7 cell lines were compared. Particle Size of the Prepared LTZSPs and QuSPs As shown in Table 2, the particle size of the prepared LTZSPs (L1-L9) ranged between 129 ± 2.6 nm and 310 ± 8.4 nm. As clearly noticed, using different types of the EA in the formulations significantly (p < 0.001) affected the size of the produced particles due to the difference in alkyl chain length and HLB values of EAs. Formulations L2, L5, and L8 containing Brij 35 exhibited the smallest particle size compared to those containing Tween 80 (formulations L1, L4, and L7) and Cremophor RH40 (formulations L3, L6, and L9). Brij 35 has the shortest alkyl chain length (C = 12) and the least bulky structure compared to Cremophor RH40 (bulky branched structure) and Tween 80 (C = 18). In addition, the average particle size of LTZSPs was significantly decreased (p < 0.001) when increasing the amount of EA (Tween 80, Brij 35 and Cremophor RH40) from 20% (L1-L3) to 40% (L4-L6). Increasing the amount of EAs in the formulation caused a reduction in the interfacial tension that facilitated particle partition and formation of smaller nanovesicles. Our results are in concordance with previously reported data. It is noteworthy that the increase in EA concentration was on the expenses of Span 60 concentration, which is another factor that was shown previously to decrease the vesicles particle size. Increasing the amount of LTZ used in the spanlastics preparation from 10 mg (L4-L6) to 15 mg (L7-L9) increased the size of the particles significantly (p < 0.001) due to the increased concentration of the drug loaded in the formulation that will expand the size of the vesicles, except in the case of Tween 80, where increasing amount of drug did not show significant differences. The particle size of the prepared QuSPs (Q1-Q8) ranged between 240 ± 80 nm and 560.3 ± 76 nm. Spanlastic formulations that were prepared using Tween 80 (Q1, Q3, Q5, and Q7) exhibited smaller particle size (statistically insignificance p > 0.05), compared to those prepared using Cremophor RH40 (Q2, Q4, Q6, and Q8). This could be due to the bulky branched structure of Cremophor RH40 molecules that could lead to the production of larger particle size of the spanlastic formulations. In addition, the increase in the amount of Tween 80 from 20 mg (Q1 and Q5) to 40 mg (Q3 and Q7) produced spanlastics with smaller sizes (statistically insignificance p > 0.05), which could be attributed to the interfacial tension reduction observed with higher amounts of Tween 80, as mentioned earlier. On the contrary, increasing the amount of Cremophor RH40 from 20 mg (Q2 and Q6) to 40 mg (Q4 and Q8) increased (statistically insignificance p > 0.05) the size of the prepared spanlastics, which could be attributed to its bulky structure. The particle size of the prepared QuSPs was increased insignificantly (p > 0.05) when increasing the loaded amount of Qu from 5 mg (Q1-Q4) to 10 mg (Q5-Q8). The prepared spanlastic formulations showed PDI values ranging from 0.2 ± 0.06 to 0.7 ± 0.01, indicating that they were relatively heterogeneous. Encapsulation Efficiencies Percent (EE%) of the Prepared LTZSPs and QuSPs As shown in Table 2, spanlastic formulations exhibited high EE% in the range of 94.3 ± 0.5% to 97.2 ± 0.8% for LTZSPs and 97.9 ± 0.2% to 99.6 ± 0.1% for QuSPs formulations, respectively. The type and amount of EA affected the EE% of the formulations. Formulations containing Tween 80 (L1, L4 and L7) provided an insignificantly higher (p > 0.05) drug encapsulation efficiency, compared to those containing Brij 35 (L2, L5, and L8) or Cremophor RH40 (L3, L6, and L9). This could be attributed to the relatively lower HLB value of Tween 80, compared to the other studied EAs, in addition to its longer carbon chain length (C18). Changing the amount of EA showed no significant differences (p > 0.05) in the drug EE% of the spanlastics. Likewise, increasing the LTZ amount from 10 mg (L4 and L5) to 15 mg (L7 and L8) led to an insignificant increase (p > 0.05) in their EE%. In contrast, the drug EE% of formulations containing Cremophor RH40 (L9) increased significantly (p < 0.05) with increasing the LTZ amount. For QuSPs formulations containing different amounts of Tween 80 and Cremophor RH40, increasing the EA concentration showed an insignificant increase in drug EE% (p > 0.05). Regarding the amount of Qu, the EE% increased significantly (p < 0.05) with increasing the amount of drug from 5 mg to 10 mg in case of the formulation containing Tween 80 (Q5 and Q7), while there was no significant difference (p > 0.05) between formulations containing Cremophor RH40 (Q6 and Q8). Zeta Potential of the Prepared LTZSPs and QuSPs All the prepared spanlastic formulations showed negative zeta potential values ( Table 2). The high charge on the vesicle surface causes repulsion between them, allowing them to be stable without agglomeration and provides a uniformly distributed suspension. The type of EA in LTZSPs had a great influence on the zeta potential Pharmaceutics 2022, 14, 1727 9 of 21 of the vesicles. Thus, zeta potential ranged from −19.9 ± 0.6 mV to −43.8 ± 0.7 mV in case of Tween 80, from −25.4 ± 1.6 mV to −39.6 ± 1.8 mV in case of Brij 35, and from −7.8 ± 1.3 mV to −21.6 ± 0.4 mV in case of Cremophor RH40. The differences in zeta potential between these three EAs were statistically significant (p < 0.05), due to their different HLB values. In addition, the increase in EA concentration resulted in a significant increase in zeta potential for the three studied EAs (p < 0.001, p < 0.001 and p < 0.005 for Tween 80, Brij 35 and Cremophor RH40, respectively). This could be attributed to the decreased size of the spanlastics when increasing the amount of EA, resulting in slower migration velocity of the charged particles and higher zeta potential value. In contrast, increasing the amount of LTZ in the formulated spanlastics decreased their zeta potential values (p < 0.001, p = 0.064 and p = 0.001 for Tween 80, Brij 35, and Cremophor RH40, respectively). This could be attributed to the basic drug nature that might reduce the value of the negative zeta potential when increasing its amount in the formulation. Zeta potential values of QuSPs ranged from −17.6 ± 1.6 mV to −33.2 ± 2.0 mV. The formulations containing Tween 80 had significantly higher (p < 0.05) zeta potential values, compared to those containing Cremophor RH40. This could be attributed to the different HLB value of the used EA; the zeta potential of spanlastics increases with lower HLB value (in case of Tween 80), as more -OH ion adsorption occurs at the interface of the hydration medium. The zeta potential values were significantly decreased (p < 0.05) with increasing the amount of EA (from 20 mg to 40 mg), which could be due to the formation of more hydrogen bonding with water molecules, due to the presence of (CH 2 -CH 2 -O) n group in their structure. The opposite effect was observed with increasing the amount of Qu from 5 mg to 10 mg that increased the zeta potential values, which might be due to the acidic nature of the drug. Based on the aforementioned data, LTZSPs (L8) and QuSPs (Q5) were selected for further investigations. These formulations showed high zeta potential values that impart good stability (−35.5 for L8 and −33.23 for Q5) with homogenous size distribution (PDI = 0.4 for L8 and PDI = 0.2 for Q5), high EE% (96.3% for L8 and 99.1% for Q5), and reasonable average particle size (164.9 nm for L8 and 450.1 nm for Q5). These parameters could increase the potential of these spanlastics as transdermal drug delivery systems. TEM Measurements Representative TEM photomicrographs of the selected LTZSPs (L8) and QuSPs (Q5) show homogenous, non-aggregating, and spherically shaped nanoparticles with sharp boundaries (Figures 1A and 1B, respectively). The spherical shape of the drug-loaded spanlastics could be attributed to the amphiphilic nature of the non-ionic surfactants used in spanlastic preparation, which form a closed bilayer vesicles in water and reduce their surface-free energy. The size of LTZSPs (~100 nm) and QuSPs (~250 nm) obtained from TEM measurements is smaller than that obtained from DLS measurements (164.9 nm and 450.1 nm, respectively), which could be attributed to the different measurement conditions. DLS gives the average particle size of hydrated particles, while TEM measures the size of dried ones, resulting in a smaller particle size for the latter. Fourier-Transform Infrared (FTIR) Spectroscopy Studies The selected LTZSPs and QuSPs formulations and their individual components were analyzed using FTIR spectroscopy and the spectra are shown in Figures 2A and 2B, respectively. The FTIR spectrum of LTZ displays its characteristic absorption bands at 2229 cm −1 for C≡N stretching, 1263 cm −1 for C-N stretching, and 690-900 cm −1 for out of plane C-H bending. The FTIR spectrum of Qu shows stretching of the -OH groups at 3406 and 3283 cm −1, bending of phenolic -OH at 1379 cm −1, C=O aryl ketonic stretching absorption at 1666 cm −1, and C=C aromatic ring stretching bands at 1666, 1610, 1560, and 1510 cm −1. Moreover, the spectrum displays absorption bands due to in-plane bending at 1317 cm −1 and out-of-plane bending at 933, 820, 679, and 600 cm −1 of the C-H in the aromatic hydrocarbon. The C-O stretching in the aryl ether ring, the C-O stretching in phenol, and the C-CO-C stretch and bending in ketone display bands at 1263, 1200, and 1165 cm −1, respectively. boundaries ( Figure 1A and Figure 1B, respectively). The spherical shape of the drugloaded spanlastics could be attributed to the amphiphilic nature of the non-ionic surfactants used in spanlastic preparation, which form a closed bilayer vesicles in water and reduce their surface-free energy. The size of LTZSPs (~100 nm) and QuSPs (~250 nm) obtained from TEM measurements is smaller than that obtained from DLS measurements (164.9 nm and 450.1 nm, respectively), which could be attributed to the different measurement conditions. DLS gives the average particle size of hydrated particles, while TEM measures the size of dried ones, resulting in a smaller particle size for the latter. Fourier-Transform Infrared (FTIR) Spectroscopy Studies The selected LTZSPs and QuSPs formulations and their individual components were analyzed using FTIR spectroscopy and the spectra are shown in Figure 2A and Figure 2B, respectively. The FTIR spectrum of LTZ displays its characteristic absorption bands at 2229 cm −1 for C≡N stretching, 1263 cm −1 for C-N stretching, and 690-900 cm −1 for out of plane C-H bending. The FTIR spectrum of Qu shows stretching of the -OH groups at 3406 and 3283 cm −1, bending of phenolic -OH at 1379 cm −1, C=O aryl ketonic stretching absorption at 1666 cm −1, and C=C aromatic ring stretching bands at 1666, 1610, 1560, and 1510 cm −1. Moreover, the spectrum displays absorption bands due to in-plane bending at 1317 cm −1 and out-of-plane bending at 933, 820, 679, and 600 cm −1 of the C-H in the aromatic hydrocarbon. The C-O stretching in the aryl ether ring, the C-O stretching in phenol, and the C-CO-C stretch and bending in ketone display bands at 1263, 1200, and 1165 cm −1, respectively. The spectrum of Span 60 shows characteristic bands, such as aliphatic O-H stretching at 3410 cm −1, asymmetric and symmetric aliphatic C-H stretching at 2916 and 2849 cm −1, respectively, and C=O stretching of the ester at 1745 cm −1. Tween 80 spectrum shows bands at 2907 and 2855 cm −1 related to the asymmetric and symmetric vibration of methylene (-CH 2 ), respectively. The band at 1735 cm −1 is caused by the ester group's C=O stretching. The O-H stretching vibration is responsible for the strong band around 3436 cm −1. The FTIR spectrum of Brij 35 shows its characteristic bands at 2882 cm −1, 1965 cm −1, and 1101 cm −1 for -C=CH 3 stretching, carbonyl band, and C-O stretching, respectively. The FTIR spectrum of blank spanlastic formulations shows the characteristic bands of both Span 60 and Brij 35 in the case of LTZSPs and the characteristic bands of Span 60 and Tween 80 in case of QuSPs. However, the bands show lower intensity compared with the same bands of the individual components. The lipid bilayer formulation is responsible for the lower intensity of the bands in the blank spanlastic formulations. Furthermore, the characteristic bands of either LTZ or Qu and different formulation excipients that were used in the optimized spanlastic formulations are shown in the FTIR spectrum, indicating that there were no interactions between the drug and the different excipients. The observed slight shifting and decreased intensity of the bands may be attributed to hydrogen bond formation, Van der Wall forces, or dipole interactions between either LTZ or Qu and other excipients, improving both drug encapsulation and nano-vesicle stability. The spectrum of Span 60 shows characteristic bands, such as aliphatic O-H stretching at 3410 cm −1, asymmetric and symmetric aliphatic C-H stretching at 2916 and 2849 cm −1, respectively, and C=O stretching of the ester at 1745 cm −1. Tween 80 spectrum shows bands at 2907 and 2855 cm −1 related to the asymmetric and symmetric vibration of methylene (-CH2), respectively. The band at 1735 cm −1 is caused by the ester group's C=O stretching. The O-H stretching vibration is responsible for the strong band around 3436 cm −1. The FTIR spectrum of Brij 35 shows its characteristic bands at 2882 cm −1, 1965 cm −1, and 1101 cm −1 for -C=CH3 stretching, carbonyl band, and C-O stretching, respectively. The FTIR spectrum of blank spanlastic formulations shows the characteristic bands of both Span 60 and Brij 35 in the case of LTZSPs and the characteristic bands of Span 60 and Tween 80 in case of QuSPs. However, the bands show lower intensity compared with the same bands of the individual components. The lipid bilayer formulation is responsible for the lower intensity of the bands in the blank spanlastic formulations. Furthermore, In Vitro Drug Release Study The in vitro release profiles of LTZSPs and QuSPs are depicted in Figures 3A and 3B, respectively. The individual dispersions of free LTZ or free Qu were used as controls to confirm the release of the drug through the dialysis membrane and to investigate the effect of drug encapsulation into spanlastics on its release profiles. LTZ aqueous suspension exhibited cumulative percent drug release of 98.8 ± 3.7% (0.74 ± 0.03 mg) after 4 h. LTZ release was fast from the aqueous suspension as it was only governed by the dissolution rate of the drug. In contrast, LTZ loaded into spanlastic preparations showed a more controlled drug release (cumulative drug release of 75.0 ± 1.4% (0.56 ± 0.01 mg) after 4 h). At the end of 24 h, the corresponding percent drug released was 99.9 ± 1.2% (0.75 ± 0.01 mg). The release of drug from spanlastic formulations was influenced by the attractive forces within the phospholipids bilayer that resulted in a more delayed drug release. Qu dispersion showed a maximum drug release of 61.5 ± 6.3% (0.62 ± 0.06 mg) after 72 h. Regarding Qu release from spanlastics, a slow drug release pattern was observed with an initial percent drug release of 10.9 ± 1.1% (0.11 ± 0.02 mg) after 8 h, followed by a more controlled sustained release of 27.7 ± 1.2% (0.28 ± 0.01 mg) after 72 h. The entire amount of loaded drug was not released from the vesicles. This might be due to entrapment of the drug in the lipophilic region of the vesicles. The slower release of both LTZ and Qu from spanlastics compared with the free drugs could be attributed to the high transition temperature and the long-chain length of the non-ionic surfactant Span 60, which leads to formation of a more rigid, less permeable bilayer. These results were consistent with previous studies, which indicated that spanlastics had sustained release profiles compared to free drug dispersion. Qu dispersion showed a maximum drug release of 61.5 ± 6.3% (0.62 ± 0.06 mg) after 72 h. Regarding Qu release from spanlastics, a slow drug release pattern was observed with an initial percent drug release of 10.9 ± 1.1% (0.11 ± 0.02 mg) after 8 h, followed by a more controlled sustained release of 27.7 ± 1.2% (0.28 ± 0.01 mg) after 72 h. The entire amount of loaded drug was not released from the vesicles. This might be due to entrapment of the drug in the lipophilic region of the vesicles. The slower release of both LTZ and Qu from spanlastics compared with the free drugs could be attributed to the high transition temperature and the long-chain length of the non-ionic surfactant Span 60, which leads to formation of a more rigid, less permeable bilayer. These results were consistent with previous studies, which indicated that spanlastics had sustained release profiles compared to free drug dispersion. Ex Vivo Permeation Study Freshly excised rat skin was used as an in vitro model for comparing transdermal permeation properties of LTZSPs and QuSPs versus free LTZ and Qu dispersions to give an insight into the skin permeability properties of the optimized spanlastic formulations. In comparison to the free drug dispersion, the quantitative mass transfer of LTZ across skin was lower when administered in form of LTZSPs ( Figure 4A and Table 3). The LTZ cumulative percent permeated as free drug dispersion was 99.8 ± 1.5% (0.153 ± 0.017 mg/cm 2 ) after 6 h, compared to 41.8 ± 7.9% (0.064 ± 0.013 mg/cm 2 ) for the LTZSPs formulation at the same time. The maximum percent of drug permeated after 24 h from optimized LTZSPs was 88.4 ± 10.9% (0.135 ± 0.012 mg/cm 2 ). LTZSPs exhibited a sustained permeation of the drug over the LTZ dispersion. This could be explained by the entrapment of LTZ within the vesicular structure of spanlastics leading to slow flux and permeability for 24 h. On the contrary, free LTZ from the LTZ dispersion could permeate freely through the skin. Ex Vivo Permeation Study Freshly excised rat skin was used as an in vitro model for comparing transdermal permeation properties of LTZSPs and QuSPs versus free LTZ and Qu dispersions to give an insight into the skin permeability properties of the optimized spanlastic formulations. In comparison to the free drug dispersion, the quantitative mass transfer of LTZ across skin was lower when administered in form of LTZSPs ( Figure 4A and Table 3). The LTZ cumulative percent permeated as free drug dispersion was 99.8 ± 1.5% (0.153 ± 0.017 mg/cm 2 ) after 6 h, compared to 41.8 ± 7.9% (0.064 ± 0.013 mg/cm 2 ) for the LTZSPs formulation at the same time. The maximum percent of drug permeated after 24 h from optimized LTZSPs was 88.4 ± 10.9% (0.135 ± 0.012 mg/cm 2 ). LTZSPs exhibited a sustained permeation of the drug over the LTZ dispersion. This could be explained by the entrapment of LTZ within the vesicular structure of spanlastics leading to slow flux and permeability for 24 h. On the contrary, free LTZ from the LTZ dispersion could permeate freely through the skin. Qu permeability (mg/cm 2 ) from spanlastics formulation Q5 in comparison with drug dispersion is shown in Figure 4B. The optimized QuSPs had a significant increase (p < 0.01) in cumulative percent drug permeated when compared to free drug dispersion with 27.9 ± 0.6% (0.057 ± 0.001 mg/cm 2 ) drug permeation after 8 h, compared to only 7.5 ± 0.9% (0.015 ± 0.007 mg/cm 2 ) from the free drug dispersion after the same time. The maximum percent of drug permeated after 24 h from the optimized QuSPs was approximately 2.7-fold higher than that from free Qu dispersion. The apparent permeability coefficient (P app ) value for QuSPs was about 3.8-fold higher than that from the free drug suspension. The in vitro permeation parameters also revealed that QuSPs showed significantly higher (p < 0.05) transdermal flux (J ss ) compared to Qu dispersion ( Table 3). The enhanced Qu permeability from the vesicles could be attributed to multiple factors, including the nanosized vesicle diameter and the presence of surfactants. Nonionic surfactants within SPs formulation could impart elasticity and deformability to the vesicles, which enhances their ability to squeeze themselves through the intercellular space and augment drug permeability. As shown in Supplementary Materials Figure S1, high proportions of LTZ/Qu were permeated from LTZSPs/QuSPs through rat skin after 24 h incubation (88.4 ± 11% and 46.2 ± 0.11%, respectively), which could be sufficient for their therapeutic effect. It is noteworthy that the skin permeability profiles were different for LTZSPs and QuSPs where the former had much slower drug permeation. The reason behind this is not clear but might be related to the different physicochemical properties of the two drugs. Based on the aforementioned experimental findings, the combined application of LTZSPs and QuSPs as transdermal delivery systems could have significant potential in alleviating breast cancer development and progression. Cell Viability Assay of LTZSPs, QuSPs, and Their Combinatorial Treatment The cytotoxic activity of the selected LTZSPs and QuSPs against MCF-7 breast cancer cells was investigated in vitro to evaluate the impact of the nanospanlastic delivery systems on enhancing the cytotoxicity of soluble LTZ and Qu using MTT assay. The results showed enhanced cytotoxic activity and marked a statistically significant drop in the IC 50 after incorporation into spanlastics, compared to the free soluble LTZ and Qu ( Figure 5A,B). The IC 50 values of the soluble LTZ, Qu, and their combination were decreased significantly (p < 0.001) after being formulated; from 38.8 ± 2.0, 25.9 ± 1.4, and 20.3 ± 1.0 M to 3.9 ± 0.2, 8.8 ± 0.5, and 3.2 ± 0.2 M, respectively. The enhanced cytotoxic effect of the drugs encapsulated into spanlastics could be due to either the added cytotoxic effect of blank (drug-free) spanlastics or the drug-loaded spanlastics. To exclude the effect of blank spanlastics, we measured their IC 50 and found it to be 192 ± 10 M, 108 ± 6 M, and 215 ± 11 M for letrozole-free spanlastics, quercetin-free spanlastics and their combination, respectively. This is compared to 3.9 ± 0.2 M for LTZSPs, 8.8 ± 0.5 M for QuSPs, and 3.2 ± 0.2 M for their combination. Looking into this difference in IC 50, it could be concluded that the enhanced IC 50 of the drug-loaded spanlastics is due to nanoparticle cellular uptake. This assumption is supported by other reported findings where the better cytotoxic performance of the drug-loaded spanlastics was attributed to the protective role of the nanocarrier with their higher permeability through the cell membrane due to its elasticity and the presence of edge activators. Previous studies have reported that Span-60 containing nano-formulations showed enhanced cellular uptake with improved cytotoxic activity against MCF-7 breast cancer cell line. Mehanna, et al. also reported that the enhanced anticancer effect of thymoquinone-loaded nanoparticles is due to the high capacity of nanoparticle to be internalized and localized inside the cellular target of MCF-7 breast cancer cells. Pharmaceutics 2022, 14, 16 of 22 that the enhanced IC50 of the drug-loaded spanlastics is due to nanoparticle cellular uptake. This assumption is supported by other reported findings where the better cytotoxic performance of the drug-loaded spanlastics was attributed to the protective role of the nanocarrier with their higher permeability through the cell membrane due to its elasticity and the presence of edge activators. Previous studies have reported that Span-60 containing nano-formulations showed enhanced cellular uptake with improved cytotoxic activity against MCF-7 breast cancer cell line. Mehanna,et al. also reported that the enhanced anticancer effect of thymoquinone-loaded nanoparticles is due to the high capacity of nanoparticle to be internalized and localized inside the cellular target of MCF-7 breast cancer cells. Combination strategy is important to overcome the predisposed resistance to the aromatase inhibitor, LTZ. The cytotoxic activity of the combination treatment of the soluble LTZ and Qu or LTZSPs and QuSPs against MCF-7 breast cancer cells was investigated and compared to the single treatment of each. A more pronounced cytotoxic activity was achieved by the combinatorial treatment of soluble Qu and LTZ or QuSPs and LTZSPs at the studied concentration range ( Figure 5A). Additionally, a significant 2-fold (p < 0.001) and 1.3-fold (p < 0.05) decrease in the IC50 of soluble LTZ and Qu combination was obtained compared to the IC50 of their corresponding individual drugs; LTZ and Qu, respectively ( Figure 5B). Furthermore, the LTZSPs and QuSPs combination was assessed using CompuSyn software for their synergism, the resulting combination index (CI) showed a synergistic pattern (CI < 1) at high drug doses (with high effect level) ( Figure S2), which is more relevant to the anticancer therapy than the small drug doses. Cell Cycle Analysis by Flow Cytometry Flow cytometry and annexin V/PI staining were applied to determine whether the cytotoxic effect of LTZ, Qu or their combination and LTZSPs, QuSPs or their combination on MCF-7 cell growth is due to the induction of apoptosis or not. The concentrations of the treatment in this study were selected according to our previous cytotoxicity results and below their obtained individual IC50. The treatment of MCF-7 cells with LTZ, Qu, or their combination resulted in an enhanced apoptosis and necrosis compared to untreated Combination strategy is important to overcome the predisposed resistance to the aromatase inhibitor, LTZ. The cytotoxic activity of the combination treatment of the soluble LTZ and Qu or LTZSPs and QuSPs against MCF-7 breast cancer cells was investigated and compared to the single treatment of each. A more pronounced cytotoxic activity was achieved by the combinatorial treatment of soluble Qu and LTZ or QuSPs and LTZSPs at the studied concentration range ( Figure 5A). Additionally, a significant 2-fold (p < 0.001) and 1.3-fold (p < 0.05) decrease in the IC 50 of soluble LTZ and Qu combination was obtained compared to the IC 50 of their corresponding individual drugs; LTZ and Qu, respectively ( Figure 5B). Furthermore, the LTZSPs and QuSPs combination was assessed using CompuSyn software for their synergism, the resulting combination index (CI) showed a synergistic pattern (CI < 1) at high drug doses (with high effect level) ( Figure S2), which is more relevant to the anticancer therapy than the small drug doses. Cell Cycle Analysis by Flow Cytometry Flow cytometry and annexin V/PI staining were applied to determine whether the cytotoxic effect of LTZ, Qu or their combination and LTZSPs, QuSPs or their combination on MCF-7 cell growth is due to the induction of apoptosis or not. The concentrations of the treatment in this study were selected according to our previous cytotoxicity results and below their obtained individual IC 50. The treatment of MCF-7 cells with LTZ, Qu, or their combination resulted in an enhanced apoptosis and necrosis compared to untreated cells ( Figure 6A). The percentage of necrotic and apoptotic cell population was increased from 1.96% for the control MCF-7 cells to 32.81% for soluble LTZ and Qu combination. Moreover, the use of this combination in the form of spanlastics increased the percentage of apoptotic and necrotic cells to 43.18%. As shown in Figures 6B and S3, Qu and QuSPs arrested MCF-7 cells at G 0 /G 1 phase (64.28% and 66.41%, respectively) compared to control cells, while LTZ and LTZSPs arrested the cell growth at G 0 /G 1 phase (62.47% and 63.57%, respectively) and S phase (29.26% and 31.72%, respectively). However, the combination of LTZSPs and QuSPs had a more pronounced increase in the S phase apoptosis (43.55%), compared with that of the soluble Qu and LTZ combination (34.81%), indicating higher growth arrest at this stage. cells ( Figure 6A). The percentage of necrotic and apoptotic cell population was increased from 1.96% for the control MCF-7 cells to 32.81% for soluble LTZ and Qu combination. Moreover, the use of this combination in the form of spanlastics increased the percentage of apoptotic and necrotic cells to 43.18%. As shown in Figures 6B and S3, Qu and QuSPs arrested MCF-7 cells at G0/G1 phase (64.28% and 66.41%, respectively) compared to control cells, while LTZ and LTZSPs arrested the cell growth at G0/G1 phase (62.47% and 63.57%, respectively) and S phase (29.26% and 31.72%, respectively). However, the combination of LTZSPs and QuSPs had a more pronounced increase in the S phase apoptosis (43.55%), compared with that of the soluble Qu and LTZ combination (34.81%), indicating higher growth arrest at this stage. Qu is a flavonoid antioxidant that promotes apoptosis, which is the ultimate objective in cancer treatment, and previous research reported its effect on the reduction in MCF-7 cells viability. Our results showed enhanced percentage of necrosis in MCF-7 Qu is a flavonoid antioxidant that promotes apoptosis, which is the ultimate objective in cancer treatment, and previous research reported its effect on the reduction in MCF-7 cells viability. Our results showed enhanced percentage of necrosis in MCF-7 cells after treatment using Qu either alone or combined with LTZ, which is similar to the previously reported results. Flow cytometry results showed that Qu arrested the MCF-7 cell growth at G 1 check point while LTZ arrested cell growth at G 1 and S phase, which is consistent with previous reports. Previously, the combination of Qu and LTZ with lower doses was highly effective on cell apoptosis through the induction of mitochondrial apoptosis. Our results showed that the effect of Qu and LTZ combinatorial treatment with lower concentrations induced higher necrosis and apoptosis than each single drug. Moreover, an increase in the MCF-7 cell necrosis and apoptosis was obtained after cell treatment using the drug-loaded spanlastics, compared to their free counterpart. The observed enhanced cell cytotoxicity, cell necrosis, and apoptosis are probably attributed to the improved drug permeability and cell membrane diffusion that enhanced the drug accumulation inside the cells. This is due to the presence of edge activators in spanlastic formulations, which enhances the elasticity and deformability of vesicles. Assessment of Reactive Oxygen Species (ROS) ROS act as vital intracellular secondary messengers for numerous cytokines and growth factors in cancer cells, thereby they have a strong pro-survival effect when present in controlled levels. However, elevated ROS levels can trigger cellular damage and even cell death. ROS levels using ELISA assay against MCF-7 cell line are shown in Figure 7. Both LTZ and Qu either free or loaded in spanlastics significantly (p < 0.001) increased ROS levels in the MCF-7 cells compared to control. The combination of LTZSPs and QuSPs showed 1.4-fold enhanced ROS levels compared with the soluble LTZ-Qu combination. cells after treatment using Qu either alone or combined with LTZ, which is similar to the previously reported results. Flow cytometry results showed that Qu arrested the MCF-7 cell growth at G1 check point while LTZ arrested cell growth at G1 and S phase, which is consistent with previous reports. Previously, the combination of Qu and LTZ with lower doses was highly effective on cell apoptosis through the induction of mitochondrial apoptosis. Our results showed that the effect of Qu and LTZ combinatorial treatment with lower concentrations induced higher necrosis and apoptosis than each single drug. Moreover, an increase in the MCF-7 cell necrosis and apoptosis was obtained after cell treatment using the drug-loaded spanlastics, compared to their free counterpart. The observed enhanced cell cytotoxicity, cell necrosis, and apoptosis are probably attributed to the improved drug permeability and cell membrane diffusion that enhanced the drug accumulation inside the cells. This is due to the presence of edge activators in spanlastic formulations, which enhances the elasticity and deformability of vesicles. Assessment of Reactive Oxygen Species (ROS) ROS act as vital intracellular secondary messengers for numerous cytokines and growth factors in cancer cells, thereby they have a strong pro-survival effect when present in controlled levels. However, elevated ROS levels can trigger cellular damage and even cell death. ROS levels using ELISA assay against MCF-7 cell line are shown in Figure 7. Both LTZ and Qu either free or loaded in spanlastics significantly (p < 0.001) increased ROS levels in the MCF-7 cells compared to control. The combination of LTZSPs and QuSPs showed 1.4-fold enhanced ROS levels compared with the soluble LTZ-Qu combination. The enhanced ROS levels in MCF-7 cancer cells produced by either LTZ or LTZSPs could be attributed to the decrease in estrogen levels in the cells, which is believed to have an antioxidant effect. Additionally, the treatment of cancer cells with Qu produces quercetin-semiquinones and quercetin-quinones, that have pro-oxidant properties inside The enhanced ROS levels in MCF-7 cancer cells produced by either LTZ or LTZSPs could be attributed to the decrease in estrogen levels in the cells, which is believed to have an antioxidant effect. Additionally, the treatment of cancer cells with Qu produces quercetin-semiquinones and quercetin-quinones, that have pro-oxidant properties inside the cells that are responsible for their anticancer activity. These compounds are extremely reactive to thiols and react with reduced glutathione (GSH), causing its depletion. Cell death by apoptosis results from the disturbance of GSH antioxidant defense in cells with persistent ROS overload, such as malignant cells. The combination of LTZ and Qu offers two distinct mechanisms to generate high ROS levels inside cancer cells, which might reduce the needed dose, reduce the adverse effects, and improve the patient compliance. Conclusions LTZ and Qu were successfully loaded into spanlastics having high drug encapsulation efficiency, relatively small size, and negative zeta potential. The results of the in vitro cell cytotoxicity study highlight the potential of combinatorial treatment of LTZ and Qu in the improvement of breast cancer treatment outcomes. Moreover, loading these drugs into spanlastics substantially enhanced the drugs' cytotoxic effects at much lower doses, compared to their soluble free drug counterparts. Therefore, the transdermal delivery of LTZSPs and QuSPs could be a promising site-specific delivery approach to enhance their cytotoxic effects and reduce the harmful adverse effects. |
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package counter
import (
"fmt"
"io"
"net/http"
"strconv"
"appengine"
"appengine/memcache"
)
func serveError(c appengine.Context, w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
io.WriteString(w, "Internal Server Error")
c.Errorf("%v", err)
}
func handle(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
item, err := memcache.Get(c, r.URL.Path)
if err != nil && err != memcache.ErrCacheMiss {
serveError(c, w, err)
return
}
n := 0
if err == nil {
n, err = strconv.Atoi(string(item.Value))
if err != nil {
serveError(c, w, err)
return
}
}
n++
item = &memcache.Item{
Key: r.URL.Path,
Value: []byte(strconv.Itoa(n)),
}
err = memcache.Set(c, item)
if err != nil {
serveError(c, w, err)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "%q has been visited %d times", r.URL.Path, n)
}
func init() {
http.HandleFunc("/", handle)
}
|
Pharmacodynamics of florfenicol for calf pneumonia pathogens The antimicrobial properties of florfenicol were investigated for the bovine respiratory tract pathogens, Mannheimia haemolytica and Pasteurella multocida. Three in vitro indices of efficacy and potency were determined; minimum inhibitory concentration (MIC), minimum bactericidal concentration (MBC) and in vitro time-kill curves for six pathogenic strains of each organism. Each was monitored in two matrices, Mueller Hinton broth (MHB) and calf serum. MBC:MIC ratios were low, 1.8:1 for M haemolytica in both MHB and serum and 2.4:1 and 2.1:1 for P multocida in MHB and serum, respectively. The killing action of florfenicol had the characteristics of concentration dependency against M haemolytica and codependency (on time and concentration) against P multocida. Modelling of the time-kill data after 24hours exposure was undertaken to quantify three levels of activity for the ratio, area under concentration-time curve over 24hours (AUC24h)/MIC; bacteriostatic action (no change in bacterial count), 3log10 reduction and 4log10 reduction in bacterial count. Mean AUC24h/MIC values for P multocida in MHB (and serum) were 22.0 (23.3) hour, 34.5 (39.9) hour and 45.8 (50.4) hour, respectively. Similar numerical values were obtained for M haemolytica. For both bacterial species, interstrain variability was low; coefficients of variation ( per cent) in serum for 3log10 and 4log10 reductions in count were, respectively, 14.3 and 24.1 for P multocida and 7.8 and 11.4 for M haemolytica. These data form a rational basis for dosage selection for treatment of calf pneumonia caused by M haemolytica or P multocida. |
#include "config.h"
#include "csr.hpp"
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/ossl_typ.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <cstdio>
#include <filesystem>
#include <memory>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/elog.hpp>
#include <phosphor-logging/log.hpp>
#include <utility>
#include <xyz/openbmc_project/Certs/error.hpp>
#include <xyz/openbmc_project/Common/error.hpp>
namespace phosphor::certs
{
using ::phosphor::logging::elog;
using ::phosphor::logging::entry;
using ::phosphor::logging::level;
using ::phosphor::logging::log;
using ::sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
namespace fs = std::filesystem;
using X509ReqPtr = std::unique_ptr<X509_REQ, decltype(&::X509_REQ_free)>;
using BIOPtr = std::unique_ptr<BIO, decltype(&::BIO_free_all)>;
CSR::CSR(sdbusplus::bus::bus& bus, const char* path, std::string&& installPath,
const Status& status) :
internal::CSRInterface(bus, path, true),
objectPath(path), certInstallPath(std::move(installPath)), csrStatus(status)
{
// Emit deferred signal.
this->emit_object_added();
}
std::string CSR::csr()
{
if (csrStatus == Status::FAILURE)
{
log<level::ERR>("Failure in Generating CSR");
elog<InternalFailure>();
}
fs::path csrFilePath = certInstallPath;
csrFilePath = csrFilePath.parent_path() / defaultCSRFileName;
if (!fs::exists(csrFilePath))
{
log<level::ERR>("CSR file doesn't exists",
entry("FILENAME=%s", csrFilePath.c_str()));
elog<InternalFailure>();
}
FILE* fp = std::fopen(csrFilePath.c_str(), "r");
X509ReqPtr x509Req(PEM_read_X509_REQ(fp, nullptr, nullptr, nullptr),
::X509_REQ_free);
if (x509Req == nullptr || fp == nullptr)
{
if (fp != nullptr)
{
std::fclose(fp);
}
log<level::ERR>("ERROR occurred while reading CSR file",
entry("FILENAME=%s", csrFilePath.c_str()));
elog<InternalFailure>();
}
std::fclose(fp);
BIOPtr bio(BIO_new(BIO_s_mem()), ::BIO_free_all);
int ret = PEM_write_bio_X509_REQ(bio.get(), x509Req.get());
if (ret <= 0)
{
log<level::ERR>("Error occurred while calling PEM_write_bio_X509_REQ");
elog<InternalFailure>();
}
BUF_MEM* mem = nullptr;
BIO_get_mem_ptr(bio.get(), &mem);
std::string pem(mem->data, mem->length);
return pem;
}
} // namespace phosphor::certs
|
<filename>h2o-test-support/src/main/java/water/TestFrameCatalog.java
package water;
import org.junit.Ignore;
import water.fvec.Frame;
import water.fvec.TestFrameBuilder;
import water.fvec.Vec;
import static water.TestUtil.*;
@Ignore // prepackaged small H2O Frames
public class TestFrameCatalog {
public static Frame oneChunkFewRows() {
return new TestFrameBuilder()
.withVecTypes(Vec.T_NUM, Vec.T_NUM, Vec.T_CAT, Vec.T_CAT)
.withDataForCol(0, new double[]{1.2, 3.4, 5.6})
.withDataForCol(1, new double[]{-1, 0, 1})
.withDataForCol(2, new String[]{"a", "b", "a"})
.withDataForCol(3, new String[]{"y", "y", "n"})
.build();
}
public static Frame specialColumns() {
return new TestFrameBuilder()
.withColNames("Fold", "ColA", "Response", "ColB", "Weight", "Offset", "ColC")
.withVecTypes(Vec.T_NUM, Vec.T_NUM, Vec.T_NUM, Vec.T_STR, Vec.T_NUM, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ard(0, 1, 0, 1, 0, 1, 0))
.withDataForCol(1, ard(Double.NaN, 1, 2, 3, 4, 5.6, 7))
.withDataForCol(2, ard(1, 2, 3, 4, 1, 2, 3))
.withDataForCol(3, ar("A", "B", "C", "E", "F", "I", "J"))
.withDataForCol(4, ard(0.25, 0.25, 0.5, 0.5, 0.5, 0.75, 0.75))
.withDataForCol(5, ard(0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2))
.withDataForCol(6, ar("A", "B,", "A", "C", "A", "B", "A"))
.build();
}
}
|
Cross time-bin photonic entanglement for quantum key distribution We report a fully fibered source emitting cross time-bin entangled photons at 1540 nm from type-II spontaneous parametric down conversion. Compared to standard time-bin entanglement realizations, the preparation interferometer requires no phase stabilization, simplifying its implementation in quantum key distribution experiments. Franson/Bell-type tests of such a cross time-bin state are performed and lead to two-photon interference raw visibilities greater than 95%, which are only limited by the dark-counts in the detectors and imperfections in the analysis system. Just by trusting the randomness of the beam-splitters, the correlations generated by the source can be proved of non-classical origin even in a passive implementation. The obtained results confirm the suitability of this source for time-bin based quantum key distribution. stage (the transcriber), and allows 75% of the detected pairs to be exploited, as opposed to 50% for standard pulsed regime time-bin schemes. By simply trusting the randomness of beam-splitters, it provides correlations that cannot be achieved with classical means even in a passive implementation. The setup. -The setup of the source is shown in FIG. 1. Experimental setup for generating and analysing time-bin entangled states starting with cross-polarized pairedphotons. Two different Bell states can be prepared: on one hand the | + state, using the bypass, and on the other hand the | − state, using the transcriber. The analysis is done using two equally unbalanced Mach-Zehnder interferometers in the Franson configuration. APD: avalanche photodiode; FM: Faraday mirror. FIG. 1. Pairs of cross-polarized, i.e. horizontally (|H ) and vertically (|V ), photons are generated at the wavelength of 1540 nm from spontaneous parametric downconversion (SPDC) of a 770 nm CW, |H polarized, 2.5 mW, pump laser in a type-II PPLN waveguide. This degenerate phase-matching condition is reached in our case for a 3.6 cm long, 9.0 m periodically poled, sample, heated at the temperature of 110 C. Note that various phase-matching conditions obtained in periodically poled materials can be found summarized in. The brightness of the PPLN/W was measured to be ∼ 2 10 4 generated pairs per second, mW of pump power, and GHz of emission bandwidth, coupled into a single mode fiber, while multiple-pair emission probability is kept below 1% per time detection window. We then select only pairs of wavelength degenerate photons so as to prevent any polarization discernibility as a function of the wavelength. To this end, a fiber Bragg grating (FBG) filter is used to reduce the natural SPDC emission bandwidth from ∼850 pm down to 200 pm, therefore avoiding undesirable spectral responses associated with alternative phase-matchings. This results in a single-photon coherence time of ∼17 ps (↔ coherence length of ∼5 mm). After the filtering stage, the two photons are sent to a transcriber, arranged as a Michelson interferometer, so as to introduce a time delay between the |H and |V polarization modes. A fiber polarization controller (PC 1 ) allows optimizing the separation of the two polarization components at a fiber-pigtailed polarizing beam-splitter (PBS 1 ). In each arm, we use a fiber Faraday mirror (FM), rotating the associated polarization state by 90 after a round trip. This ensures that both photons leave the transcriber through the output port of PBS 1. For this experiment, the transcriber's optical path length difference is set to ∼60 cm (↔ ∼2 ns), which is much greater than both the coherence time of the single-photons and timing jitter of the employed detectors (∼0.4 ns). This prevents the photons to overlap temporally and the state at the output of the transcriber therefore reads |H, 0 |V, 1, where 0 and 1 denote short and long time-bins, respectively. Next, the photons are sent to an additional polarizing beam-splitter (PBS 2 ) which is oriented at 45 with respect to the {H; V } basis in which the photons are created. This way, the polarization modes are no longer associated with the timebins, therefore reducing the two-photon state to | A,B = Subsequently, the maximally entangled Bell state | − can be post-selected among all other events using a coincidence detection electronics between the two parties. This state is insensitive to the phase accumulated by the two photons in the transcriber, unlike in standard time-bin schemes where entanglement is prepared using a stabilized unbalanced interferometer placed on the path of a pulsed pump laser. The entanglement analysis is performed using a Franson setup with two equally unbalanced interferometers, one at each side. Each interferometer is made of a 50/50 fiber coupler and two fiber-pigtailed FMs to compensate for the birefringence within the analyzer. As the interferometers' path length difference are adjusted to suitably match the transcriber time-bin separation, such analyzers transform their respective incoming single-photon state in the following way, | j → 1 √ 2 | j + e ij | + 1 j, where = {0, 1} represents the considered time-bin, j Alice or Bob, and j the phase in Alice's or Bob's interferometer, respectively. After the complete analysis apparatus including the post-selection procedure, the two-photon state reads: As can be understood from Eq. 1, one needs to consider five relative arrival times between Alice and Bob detectors. The time-dependent second order intensity correlation function is measured using a free running InGaAs avalanche photodiode (APD, IDQ-210) on Alice's side which is used as a trigger for Bob's gated InGaAs APD (IDQ-201). FIG. 2 shows the coincidence histogram as a function of the time delay between the photon detection on Alice's and Bob's sides. The central peak, labelled as T 0, contains the two contributions associated with photon-pairs in the state |1 A |1 B. The indistinguishablitiy of these two contributions results in usual timebin entanglement for which the coincidence rate follows R T0 c ∝ cos 2 A−B 2. In our CW experimental setup, the pump coherence time ( p c ≃ 400 ns) is significantly larger than the time-bin separation (2 ns), such that the emission times of the paired photons remain unknown within p c. As a result, the paths |0 A |1 B and |1 A |2 B, as well as |1 A |0 B and |2 A |1 B, are also indistinguishable. These contributions are respectively labelled as T −1 and T +1 in FIG. 2. In these cases, the coincidence rate is given by R T±1 c ∝ cos 2 A+B 2. Remarkably, the peaks T ±1 on one hand, and T 0 on the other hand, naturally define two complementary basis useful for entanglementbased QKD protocols. To quantify the quality of our analysis interferometers, we first perform a two-photon interference experiment using a genuine energy-time Franson setup. In this case, the transcriber is bypassed (see FIG. 1), such that the cross-polarized pairs of photons are directly sent to PBS 2. The polarization state of the two photons is adjusted using PC 3 for the pairs to be deterministically separated at this PBS. The relative phase between the analysers is varied by tuning the temperature of Alice's interferometer, while that of Bob's is kept constant. We achieve net and raw visibilities of 98±2% and 96±2%, respectively (curve not represented). The net visibility is obtained after subtraction of accidental coincidences due to the detectors dark-counts. We ascribe ∼1% net contrast reduction to the length mismatch between the two analysers which was measured to be 0.3±0.1 mm. Note that multiple-pair generation probabilities in this experiment are very small (<0.1%). Eventually, we test the cross time-bin state | − A,B prepared with the transcriber. For the three coincidence peaks T −1, T +1, and T 0, two-photon interference is also recorded by tuning the phase A, while keeping B ≈ 0. As shown in FIG. 3 (a), the three coincidence rates are modulated as a function of the global phase ( A + B ) and lead to net (raw) visibilities exceeding 97±2% (95±2%). For this test, we ascribe an additional 1% visibility reduction to the path length mismatch between the transcriber and the analysers. In addition, the visibility associated with events detected in the T 0 time-bin is strongly dependent on the polarization state adjustments in front of the second PBS where the | − state is prepared. Also, the raw visibilities could be improved by employing detectors showing better dark-count figures, such as those offered by super-conducting devices. Furthermore, to show that the three contributions follow the expected phase dependency, we change the phase of Bob's interferometer to B = /2. As expected, FIG. 3 (b) confirms that the phase relation of the interference patterns between T ±1 and T 0 is shifted by. Note that the analysers are only temperature stabilized which explains the drifts between the patterns shown in FIG. 3 (a) and (b). This could be avoided by employing active interferometer stabilization schemes enabling accurate phase control and setting, as was demonstrated using a frequency stabilized laser combined to a phase measurement. Theory. -For the characterization of the setup, we have plotted interference patterns, out of which one may check the violation of some Bell inequality under some assumptions proper to time-bin implementations. However, we want to operate this setup for QKD in a passive implementation, that is A and B are going to be fixed. The detections of any passive setup can always be reproduced by a local variable model if one does not make additional assumptions: indeed here, if Eve can choose the time of the detection, she can obviously fulfill all the requirements. So we make the following assumption on Alice's and Bob's measurements separately: if some signal comes in the analyzer at time, the detection can happen either at or at + 1 (up to the propagation time in the interferometer) and this time is not for Eve to control. In other words, we trust the randomness introduced by the beam-splitter. Under this assumption, we are going to provide a semi-deviceindependent criterion for quantumness, analog to a Bell inequality. Consider Eve sending some signal in Alice's lab at time A and some signal in Bob's lab at times B. As per our assumption, detection at Alice's side can happen at A or at A + 1. Apart from this uncertainty in the time of firing, we assume the most favorable situation for Eve, namely that for both times she knows with certainty which detector will fire; we also assume that only one detector will fire (notice that there may be no state of light such that this can actually happen: we give more power to Eve by assuming only her impossibility of choosing the time of the firing). We do similar assumptions for Bob. Thus, Eve knows the four possible outcomes a( A ), For definiteness, we assume A = B = 0: for these values, ideally, the quantum source produces identical outcomes at T 0 and T ±1, and completely uncorrelated outcomes at T ±2. The QKD protocol we want to propose uses the detections at T 0 and T ±1 as the raw key, while the lateral peaks could be used to detect the presence of an eavesdropper. We need to see how close Eve can come to simulating the ideal quantum source (we assume that the beam-splitters in the Michelson interferometer have 50/50 coupling ratio, although this additional assumption can easily be relaxed): (a) A = B = : in this case, T 0 happens with probability 1 2, and T ±1 with probability 1 4 each. Eve can ensure that Alice and Bob get the same outcomes by fixing a( ) = a( + 1) = b( ) = b( + 1). But, if Eve does only this, there will never be any event T ±2. As we see, one has to check for high correlations in T 0,±1, for the presence of uncorrelated coincidences in T ±2, and for the absence of coincidences in T ±3. There are several ways to do that; among the simplest, one can form a single linear function like where P (T x ) is the probability of a coincidence T x and E is the correlation coefficient. All the classical strategies above reach at most S = 1, while perfect experimental results would lead to S = 1.25. Our experimental raw data from FIG. 3 (a) lead to S exp raw = 1.20 ± 0.02, corresponding to 10 standard deviations above the classical boundary. To infer this value, we take into account the above mentioned visibilities for the coincidence peaks T ±1 and T 0, as well as an average visibility of 0±2% for the coincidence peaks T ±2 (curves not shown). This result can be improved by employing lower dark-count detectors and by adjusting actively the path length difference of the analysis interferometers to match that of the transcriber. Note that a similar theoretical/experimental analysis with A = − 2 and B = 2 (case of FIG. 3 (b)) leads to the same results and conclusion. In this case, Alice and Bob expect the observation of coincidences in T 0 and simultaneously anti-coincidences in T ±1. As Eve cannot know in which coincidence peak the photons are detected, she cannot mimic the correct coincidence/anticoincidence behavior. Conclusion. -We have demonstrated, for the first time, a scheme that allows analysing the cross timebin entangled state | −. From the experimental side, the simplicity of the scheme associated with the phase-insensitivity of the prepared state to the transcriber fluctuations, make this source a promising candidate for time-bin entanglement based long-distance QKD. In this perspective, such a novel strategy offers naturally the two necessary complementary basis. This makes it possible to operate entanglement based QKD protocols in a full passive fashion, requiring only one stabilized analyser plus two detectors at each user's location, and allowing the exploitation of 75% of the detected pairs of photons. Moreover, the source can be operated in both CW and pulsed regimes, without any further experimental modification but the laser. The latter regime is particularly interesting when synchronization between different locations is required, as is the case in quantum relay schemes. Using exclusively standard fiber telecom components allowed us reaching an overall loss figure of ∼5 dB from the output of the PPLN/W to the detectors. A simple theoretical model trusting only the randomness of the beam-splitters also confirms the quantum nature of the source, and therefore its potential for passive implementations of entanglement-based QKD. |
<reponame>ONSdigital/ras-frontstage<gh_stars>1-10
import unittest
from frontstage import app
class TestMaintenancePage(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
app.config["UNDER_MAINTENANCE"] = True
def tearDown(self):
app.config["UNDER_MAINTENANCE"] = False
def test_maintenance_page_redirect(self):
response = self.app.get("/", follow_redirects=True)
self.assertEqual(response.status_code, 200)
self.assertTrue("This site is currently offline for maintenance.".encode() in response.data)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.