content
stringlengths
10
4.9M
Efficient octave-spanning frequency comb generation in normal dispersion regime In this paper, we present a stable dark soliton with its spectrum spanning about one octave generated in the silicon nitride microring resonator with normal dispersion. The dark soliton can be generated straightforwardly from noise. Then, we investigate the dependence of bandwidth and power level on pump power, the second-order dispersion, the ratio of coupling and intracavity loss coefficient and free spectral range.
// Counting Sort implementation, which removes duplicate elements // and replaces them with zeroes // RETURNS: how many duplicates it has found // For example: 5 2 3 5 becomes 0 2 3 5 int countingSort(int* arr, int size) { int maxNumber = 0; for (int i = 0; i < size; i++) { if (arr[i] > maxNumber) { maxNumber = arr[i]; } } int* countingArray = new int[maxNumber + 1]; for (int i = 0; i < maxNumber + 1; i++) { countingArray[i] = 0; } for (int i = 0; i < size; i++) { countingArray[arr[i]]++; } int duplicates = 0; for (int i = 1; i <= maxNumber; i++) { while (countingArray[i] > 1) { countingArray[i]--; countingArray[0]++; duplicates++; } } int sortedIndex = 0; for (int i = 0; i < size; i++) { while (countingArray[sortedIndex] == 0) { sortedIndex++; } arr[i] = sortedIndex; countingArray[sortedIndex]--; } delete[] countingArray; return duplicates; }
Old evidence and new technology led to an arrest in a 25-year-old cold case, and to welcome closure for the victim’s family, Toronto police said Tuesday. Surinder Singh Parmar was 38 when he was stabbed to death inside a gas station bathroom on Danforth Road on Nov. 19, 1990. He had just arrived in Canada in July on a visitor’s permit and had left his wife and two children in India. Parmar was a schoolmaster with a PhD in history and was exploring Canada as a place for his family to live, Det. Sgt. Stacy Gallant said at a news conference. His wife and children came to Ontario for the funeral and stayed. Parmar’s children, now adults, “were shocked to get a phone call from police a few weeks ago,” Gallant said. “To go 25 years without knowing who did this to their father was very difficult for them to cope with,” he added, saying the family would not be speaking to reporters. Gallant said police opened up the case in August and re-examined old evidence. Rupert Richards, 61, was arrested and charged with first-degree murder on Monday. Richards, who lives alone in the west end, was unemployed at the time of the arrest. He is known to police. Richards, who would have been 36, was not a suspect at the time. While he was known to police, he had never been investigated for murder. “He was surprised to see us there, from homicide. He was quite surprised,” Gallant said. Police said the motive was likely robbery. Parmar was killed for a “small” amount of cash, Gallant said, but didn’t say how much. The investigation into Parmar’s death is part of Project Never Give Up. Under that initiative, police are taking advantage of advancements in technology, especially DNA and fingerprint technology, to solve cold cases. That’s what happened in Parmar’s case, but, detectives warn, not every case has evidence that can be re-examined. Staff Insp. Greg McLane said that in other cases, “samples may be degraded thorugh the passage of time, or the collection method [used at the time] was not appropriate.” McLane said that if a murder isn’t solved in three years, the homicide investigation is moved to the cold case team. While many cold cases have been reopened, tips from the public are still crucial, police said. “We have a number of cases where we have the DNA of the person responsible, we just don’t have the name,” Gallant said.
#include <bits/stdc++.h> using namespace std; const int N = 100005; int n, mod; vector<int> g[N]; int f[N]; int ans[N]; int mul(int x,int y) { return (long long) x * y % mod; } void dfs(int u,int p) { auto it = find(g[u].begin(), g[u].end(), p); if (it != g[u].end()) { g[u].erase(it); } f[u] = 1; for (int v : g[u]) { dfs(v, u); f[u] = mul(f[u], f[v] + 1); } } void dfs2(int u,int up) { ans[u] = mul(f[u], up + 1); int sz = g[u].size(); vector<int> pre(sz); vector<int> suf(sz); int now = 1; for (int i = 0; i < sz; ++i) { int v = g[u][i]; now = mul(now, f[v] + 1); pre[i] = now; } now = 1; for (int i = sz - 1; ~i; --i) { int v = g[u][i]; now = mul(now, f[v] + 1); suf[i] = now; } for (int i = 0; i < sz; ++i) { int v = g[u][i]; int coef = 1; if (i) { coef = mul(coef, pre[i - 1]); } if (i + 1 < sz) { coef = mul(coef, suf[i + 1]); } dfs2(v, mul(coef, up + 1)); } } int main() { scanf("%d %d", &n, &mod); for (int i = 2; i <= n; ++i) { int u, v; scanf("%d %d", &u, &v); g[u].push_back(v), g[v].push_back(u); } dfs(1, -1), dfs2(1, 0); for (int i = 1; i <= n; ++i) { printf("%d\n", ans[i]); } }
A handful of protesters got rowdy in front of New York City’s Crosby Street Hotel Saturday, heeding the hacktivist group Anonymous’ call for a protest against a former member. But they never saw him. Hector “Sabu” Monsegur, scheduled to speak at the second day of the Suits and Spooks security conference in the hotel, arrived early and used a different entrance. Monsegur, a former ringleader of Anonymous splinter groups AntiSec and LulzSec, was caught in 2011 and cooperated with the FBI in hopes of a reduced sentence. The sentencing judge cited Monsegur’s cooperation in the FBI investigation into his former colleague, Jeremy Hammond, as reason for leniency. Hammond is currently serving a 10-year sentence for his role in AntiSec’s now legendary hack into Stratfor, a for-profit intelligence service often contracted by government agencies. The protesters had already achieved one major disruption, convincing Suits and Spooks’ original venue, the SoHo House, to deny the event, forcing director Jeffrey Carr to move it to Crosby Street. While Monsegur spoke inside, though, things were quiet. Two protesters wore shirts saying “Fuck Sabu, Free Jeremy Hammond.” Roughly a dozen people, though at one point their ranks swelled to nearly 20, stood outside the hotel—talking to each other, checking their phones and smoking cigarettes. There was no chanting, no signs, and no voices louder than a calm conversation, and nobody wore the trademark Guy Fawkes mask. Security looked on at the protest from inside the hotel, checking their wristwatches. More cops now at hotel to protect #Sabu. Hotel is kicking people out pic.twitter.com/6I8nTq8C7Z — JamesFromTheInternet (@JamesFTInternet) June 20, 2015 But as the time for Monsegur’s talk came and went without sight of him, some protesters walked into the hotel lobby and ordered drinks from the bar. Eventually, they were asked to leave the hotel and were escorted out by security. As things started to wind down, four NYPD officers and hotel security escorted Monsegur into a van through a back exit, and asked the protesters to leave. Some claimed there’d been a bomb threat called in to the hotel. But security denied that. “There was absolutely no bomb threat, and we would have evacuated if that was the case,” a member of Crosby Street’s security staff, who requested his name not be used in this story, told the Daily Dot. Illustration by Max Fleishman
// Extend world - ECS enabled impl World<Input> for MyWorld { fn new() -> Self { Self { entity_manager: EntityManager::new(), positions: PositionRegistry::new(), counters: CounterRegistry::new(), players: PlayerRegistry::new(), player_id_map: PlayerIdMap::new(), } } fn run_systems(&mut self, input: Input) { // Systems to run conditionally match input.0 { Message::AddPlayer => add_player_system(self, input.1), Message::W => { update_player_pos_system(self, input.1, Position::displacement(0, 1)); } Message::A => { update_player_pos_system(self, input.1, Position::displacement(-1, 0)); } Message::S => { update_player_pos_system(self, input.1, Position::displacement(0, -1)); } Message::D => { update_player_pos_system(self, input.1, Position::displacement(1, 0)); } Message::RemovePlayer => { remove_player_system(self, input.1); } _ => {} } // Systems to always run counter_system(&mut self.counters.components); } }
<filename>src/Chapter_14_Databases/MultipleApartments.cpp #include <iostream> /** * Write a SQL query to get a list of tenants who are renting * more than one apartment. */ int main() { std::cout << "Whenever you write a GROUP BY clause in an interview\n" "(or in real life), make sure that anything in the SELECT\n" "clause is either an aggregate function or contained within\n" "the GROUP BY clause. count(*) in this example counts number of\n" "rows for each TenantID. SQL query to get a list of tenants who\n" "are renting more than one apartment:\n" "SELECT TenantName\n" "FROM Tenants\n" "INNER JOIN\n" " (SELECT TenantID FROM AptTenants GROUP BY TenantID HAVING count(*) > 1) C\n" "ON Tenants.TenantID = C.TenantID\n"; }
/** * Parses a binary multiset operator. */ final public SqlBinaryOperator BinaryMultisetOperator() throws ParseException { SqlBinaryOperator op; jj_consume_token(MULTISET); if (jj_2_472(2)) { jj_consume_token(UNION); op = SqlStdOperatorTable.MULTISET_UNION; if (jj_2_465(2)) { if (jj_2_463(2)) { jj_consume_token(ALL); op = SqlStdOperatorTable.MULTISET_UNION_ALL; } else if (jj_2_464(2)) { jj_consume_token(DISTINCT); op = SqlStdOperatorTable.MULTISET_UNION; } else { jj_consume_token(-1); throw new ParseException(); } } else { ; } } else if (jj_2_473(2)) { jj_consume_token(INTERSECT); op = SqlStdOperatorTable.MULTISET_INTERSECT; if (jj_2_468(2)) { if (jj_2_466(2)) { jj_consume_token(ALL); op = SqlStdOperatorTable.MULTISET_INTERSECT_ALL; } else if (jj_2_467(2)) { jj_consume_token(DISTINCT); op = SqlStdOperatorTable.MULTISET_INTERSECT; } else { jj_consume_token(-1); throw new ParseException(); } } else { ; } } else if (jj_2_474(2)) { jj_consume_token(EXCEPT); op = SqlStdOperatorTable.MULTISET_EXCEPT; if (jj_2_471(2)) { if (jj_2_469(2)) { jj_consume_token(ALL); op = SqlStdOperatorTable.MULTISET_EXCEPT_ALL; } else if (jj_2_470(2)) { jj_consume_token(DISTINCT); op = SqlStdOperatorTable.MULTISET_EXCEPT; } else { jj_consume_token(-1); throw new ParseException(); } } else { ; } } else { jj_consume_token(-1); throw new ParseException(); } {if (true) return op;} throw new Error("Missing return statement in function"); }
/// do a quick check it the entry is in the lower triangle part of the matrix fn check_lower_triangle(r: usize, c: usize) -> Result<(), MatrixMarketError> { if c > r { return Err(MatrixMarketError::from_kind_and_message( MatrixMarketErrorKind::NotLowerTriangle, format!( "Entry: row {} col {} should be put into lower triangle", r, c ), )); } Ok(()) }
class WebhookServer: """Instantiate a WebhookServer class to handle incoming webhook payloads They should use the serve_forever() startup method, because Relay will manage the lifecycle of the trigger container. They should not expect any state to be preserved between requests, nor rely on any persistence on the local container filesystem. """ _app: ASGIFramework _config: Config _sockets: Sockets _termination_policy: TerminationPolicy _task: Optional[asyncio.Task[None]] def __init__(self, app: Union[ASGIFramework, 'WSGIApplication'], *, termination_policy: Optional[TerminationPolicy] = None, port: Optional[int] = None): if not is_async_callable(app): app = WsgiToAsgi(app) if termination_policy is None: termination_policy = DEFAULT_TERMINATION_POLICY if port is None: try: port = int(os.environ['PORT']) except KeyError: port = DEFAULT_PORT except ValueError: raise PortParseError() self._app = cast(ASGIFramework, app) self._config = Config() self._config.bind = [f'0.0.0.0:{port}'] self._sockets = self._config.create_sockets() self._termination_policy = termination_policy self._task = None @property def port(self) -> int: return self._sockets.insecure_sockets[0].getsockname()[1] def listening(self) -> bool: return self._task is not None and not self._task.done() async def serve(self) -> None: if self._task is None: loop = asyncio.get_running_loop() shutdown_trigger = await self._termination_policy.attach() self._task = loop.create_task(worker_serve( self._app, self._config, sockets=self._sockets, shutdown_trigger=shutdown_trigger, )) await self._task async def _serve_wait(self) -> None: current_task = asyncio.current_task() assert current_task is not None await self.serve() await asyncio.gather( *filter(lambda t: t != current_task, asyncio.all_tasks()), return_exceptions=True, ) def serve_forever(self) -> None: asyncio.run(self._serve_wait())
/// NewWallets creates Wallets and fills it from a file if it exists pub fn new() -> Result<Wallets> { let mut wlt = Wallets { wallets: HashMap::<String, Wallet>::new(), }; let db = sled::open("data/wallets")?; for item in db.into_iter() { let i = item?; let address = String::from_utf8(i.0.to_vec())?; let wallet = deserialize(&i.1.to_vec())?; wlt.wallets.insert(address, wallet); } drop(db); Ok(wlt) }
<gh_stars>1-10 /** * */ package bean; /** * @author parsh * */ public class VideoStore { private Video[] store; public int getStoreSize() { if (store != null) return store.length; else return 0; } public Video getLastAdded() { if (store != null) return store[store.length - 1]; else return null; } public void addVideo(String name) { Video video = new Video(name); int storeSize; try { storeSize = store.length; } catch (Exception e) { storeSize = 0; } Video[] newStore = new Video[storeSize + 1]; newStore[storeSize] = video; store = newStore; } public void doCheckout(String name) { if (store == null || store.length == 0) { System.out.println("Store is empty"); return; } for (Video video : store) { if (video.getName().equals(name)) { video.doCheckout(); } } } public void doReturn(String name) { if (store == null || store.length == 0) { System.out.println("Store is empty"); return; } for (Video video : store) { if (video.getName().equals(name)) { video.doReturn(); } } } public void receiveRating(String name, int rating) { if (store == null || store.length == 0) { System.out.println("Store is empty"); return; } for (Video video : store) { if (video.getName().equals(name)) { video.receiveRating(rating); } } } public void listInventory() { if (store == null || store.length == 0) { System.out.println("Store is empty"); return; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.printf("\n\t%-20s\t|\t%-10s\t|\t%-15s\n", "Name", "Rating", "Checkout"); for (int i = 0; i < 80; i++) System.out.print("-"); for (Video video : store) { System.out.printf("\n\t%-20s\t|\t%-10s\t|\t%-15s\n", video.getName(), video.getRating(), video.getCheckout()); } for (int i = 0; i < 80; i++) System.out.print("-"); } }
/** * Obtain the 64-bit table identifier associated with this tombstone. */ uint64_t ObjectTombstone::getTableId() { return header.tableId; }
// LeetCode: 36. Valid Sudoku (Medium) class Solution { public: bool isValidSudoku(vector <vector<char>> &board) { int n = board.size(); for (int i = 0; i < n; ++i) { set<char> s; for (int j = 0; j < n; ++j) { if (board[i][j] != '.') { if (s.find(board[i][j]) != s.end()) { return false; } s.insert(board[i][j]); } } } for (int j = 0; j < n; ++j) { set<char> s; for (int i = 0; i < n; ++i) { if (board[i][j] != '.') { if (s.find(board[i][j]) != s.end()) { return false; } s.insert(board[i][j]); } } } for (int i = 0; i < n; i += 3) { for (int j = 0; j < n; j += 3) { set<char> s; for (int k = 0; k < 3; ++k) { for (int m = 0; m < 3; ++m) { if (board[i + k][j + m] != '.') { if (s.find(board[i + k][j + m]) != s.end()) { return false; } s.insert(board[i + k][j + m]); } } } } } return true; } }
To encourage film producers to make original Kannada movies, rather than go for remakes, Kannada Chalanachitra Academy (KCA) is coming out with a repository of stories. The academy, a government- appointed panel, has completed the process of compiling 150 original stories penned by both amateurs and professionals writers in Kannada. The story bank covers a wide gamut of topics, including drama, adventure, romance, action, horror, suspense among others. “We will submit the story bank to Chief Minister Siddaramaiah in Bengaluru on March 15 with a recommendation that the State government provide some subsidy to producers who choose their script from the repository,” KCA chairman S V Rajendra Singh Babu said. The concept of having a Kannada story bank was mooted by the academy last year after it was found that producers and directors complained of lack of good original storylines which they could produce into movies. Also, the dearth of interesting stories prompted producers to borrow stories from other languages or go in for remakes. Officials at the academy pointed out that the story bank would be a continuous exercise with stories being added to the repository on a regular basis. Platform for new talent It would also be a platform to tap and encourage new talent. Under the project, producers who approach the academy will be provided with a brief narrative of the various stories in repository. “Once a story is picked, the academy will act as a facilitator between the producer, director and the writer,” Babu said. Janata theatre At the same time, a 14-member advisory committee of film experts constituted by the State government has suggested that provision be made to provide low-interest loans to those who come forward to construct ‘Janata theatres’. Akin to ‘Amma theatre’ Janata theatre, created along the lines of ‘Amma theatre’ in Tamil Nadu to provide cinema-viewing at an affordable cost, was announced by Chief Minister Siddaramaiah in his budget two years back. However, the proposal has not moved much forward since. The advisory committee, comprising actors, representatives of the Karnataka Film Chamber of Commerce has recommended that the government take steps to make Janata theatre a reality. Babu said many in the Kannada film industry were ready to take up the initiative if the government was willing to provided them with low-interest loans.
/******************************************************************************* * Copyright [2015] [Onboard team of SERC, Peking University] * * 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 com.onboard.service.index.model; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; public class SearchQueryBuilder { private final SearchQuery searchQuery = new SearchQuery(); public static SearchQueryBuilder getBuilder(){ return new SearchQueryBuilder(); } public SearchQuery build(){ return searchQuery; } public SearchQueryBuilder modelTypes(List<String> modelTypes){ searchQuery.setModelTypes(modelTypes); return this; } public SearchQueryBuilder projectIds(List<Integer> projectIds){ searchQuery.setProjectIds(projectIds); return this; } public SearchQueryBuilder creatorIds(List<Integer> creatorIds){ searchQuery.setCreatorIds(creatorIds); return this; } public SearchQueryBuilder companyIds(List<Integer> companyIds){ searchQuery.setCompanyIds(companyIds); return this; } public SearchQueryBuilder relatorIds(List<Integer> relatorIds){ searchQuery.setRelatorIds(relatorIds); return this; } public SearchQueryBuilder otherQueryStrings(Map<String, List<Object>> queryStrings) { Map<String, List<Object>> originQueryStrings = searchQuery.getQueryStrings(); if(originQueryStrings == null){ searchQuery.setQueryStrings(queryStrings); }else { originQueryStrings.putAll(queryStrings); } return this; } public SearchQueryBuilder otherQueryString(String fieldName, List<Object> queryStrings) { Map<String, List<Object>> originQueryStrings = searchQuery.getQueryStrings(); if(originQueryStrings == null){ originQueryStrings = Maps.newHashMap(); searchQuery.setQueryStrings(originQueryStrings); } originQueryStrings.put(fieldName, queryStrings); return this; } }
// Convert from Apache Headers Spring Headers private HttpHeaders mapHeaders(List<Header> requestHeaders) { HttpHeaders headers = new HttpHeaders(); for (Header h : requestHeaders) { String value = getScript().expand(h.getValue()); logger.info(String.format("Request header: %s: %s", h.getName(), possiblyMaskedHeaderValue(h))); headers.add(h.getName(), value); } return headers; }
/** * The outgoing class. */ class Outgoing { final Out message; final ChannelPromise promise; /** * @param message The output message * @param promise The channel promise */ Outgoing(Out message, ChannelPromise promise) { this.message = message; this.promise = promise; } }
Fishing for Answers in Canada's Inside Passage: Exploring the Use of the Transit Fee as a Countermeasure In 1994, following the breakdown of negotiations to revise the Canada-United States Pacific Salmon Treaty, Canada imposed a fee of $1500 Canadian on all U.S. commercial fishing boats transiting Canada's Inside Passage between Washington and southeast Alaska. The attempted revisions to the Treaty concerned an effort by the parties to create a meaningful conservation regime that would allot to all parties an equitable catch of Pacific salmon, while allowing many endangered salmon stocks the chance to recover from overfishing. The Inside Passage transit fee lasted eighteen days during which roughly three hundred U.S. boats were made to pay the fee. The transit fee violated many provisions of the United Nations Convention on the Law of the Sea (UNCLOS). In particular, the fee violated the right of innocent passage afforded to vessels travelling through waterways like the Canadian Inside Passage. In addition, the fee violated transit guarantees under the General Agreement on Tariffs and Trade (GATT). However, international law is not composed only of treaty law but also includes uncodified international norms and customs--customary international law. This customary international law is often forged in the crucible of international disputes. How states behave and what behavior is considered acceptable by other members of the international community create much of the corpus of customary international law. This Article's examination of the international dispute over the Inside Passage fee will cast light on the emerging customary international law doctrine of lawful, nonforcible countermeasures. Countermeasures may serve to legitimate a state's otherwise illegal breach of international law. However, unlike common law justification, international law justification has not been codified in any international treaty or convention. Rather, it is an emerging and debated norm of customary international law. Hence, examinations of international disputes in which countermeasures are used can illuminate the doctrine of countermeasures. Every resort to a countermeasure within a dispute helps to define the boundaries of that doctrine. This Article will argue that the Canadian Inside Passage transit fee can be characterized as a countermeasure. When so characterized, the transit fee should not be considered illegal under international law, even though the imposition of such a fee violated many of Canada's treaty obligations. In addition, because the Inside Passage fee is a concrete example of a countermeasure, an examination of the fee can help illuminate this emerging doctrine of customary international law. The Pacific salmon dispute involves competing claims and conservation plans for the salmon in the region. This Article will primarily explore the actions of the parties involved in one of the more serious manifestations of this ongoing dispute, the Canadian Inside Passage transit fee. The Article will not examine the complex questions surrounding the merits of the parties' underlying claims, namely, who is entitled to the disputed salmon; rather, the Article will focus on the recent countermeasures employed by the two parties. In addition, this Article will focus on the parties' individual actions and not on the many complex negotiations involved in this dispute. Part II of this Article will describe the history of the dispute, recent developments, and the parties' individual perspectives. Part III will examine the legality of the fee under international treaty law and under the emerging doctrine of countermeasures.
/** * Helper method to get the api key from a file location */ public static String LoadAPIKey(String filename) throws IOException { String apiKey; if (null == filename || 0 == filename.length()) throw new IllegalArgumentException("Empty API key file specified."); File file = new File(filename); FileInputStream fis = new FileInputStream(file); BufferedReader breader = new BufferedReader(new InputStreamReader(fis)); apiKey = breader.readLine().replaceAll("\\n", "").replaceAll("\\r", ""); fis.close(); breader.close(); if (null == apiKey || apiKey.length() < 10) throw new IllegalArgumentException("Too short API key."); return apiKey; }
Eating habits among primary and secondary school students in the Gaza Strip, Palestine: A cross-sectional study during the COVID-19 pandemic Background The COVID-19 pandemic has a great impact on the eating habits, dietary intake, and purchasing behaviours of students. At this critical moment, there is an urgent need to identify the eating habits of school students, in particular, who live in low-income countries, during the lockdown period. Therefore, the present study aims to identify the influence of COVID-19 on the eating habits, quality and quantity of food intake among school students in the Gaza Strip, Palestine. Methods A cross-sectional study was carried out among 2398 primary and secondary school students aged 6–18 year old through an online questionnaire which included questions on socio-demographic, eating habits as well as quality and quantity of food intake. Students over the age of 11 years completed the questionnaire on their own, whereas for students under the age of 12 years, the students' guardians were instructed to answer the questionnaire on their behalf. A Wilcoxon Signed-Rank and McNemar tests were applied to perform a comparison between general dietary habits before and during COVID-19. Also, a Wilcoxon Signed Rank test was used to compare the median scores of food quality and quantity before and during the COVID-19 pandemic based on student's sociodemographic. Results During the COVID-19 pandemic, there was a significant increase in eating home-cooked foods (91.6%), avoiding ordering food from outside per week (93.3%) and buying groceries online (7.7%) (p < 0.001). There was a marked increase in the students reporting fear about food hygiene outside the home from 20.8% before COVID-19 to 72.9% during the COVID-19 period (p < 0.001). The results showed that the median score for food quality during the COVID-19 pandemic (11.0/6.0) was significantly higher than the before COVID-19 period (10.0, IQR = 8.0) (p < 0.001). The results revealed that the median score for food quantity before the COVID-19 pandemic (15.0, IQR = 5.0) was significantly higher than the during COVID-19 pandemic (14.0, IQR = 7.0) (p < 0.001). The results showed significant differences between the before and during COVID-19 period for food quality and quantity across socio-demographic variables (gender, age group, parent's highest level of education, monthly household income, and household size). During the COVID-19 pandemic, students from a high-income and a small size family had the highest score in terms of food quality and quantity among other counterparts when compared to other counterparts. Conclusion Eating habits have significantly altered among school students during the COVID-19 pandemic. In spite of some good healthy habits enhanced among students, the quantity and the quality of the food was compromised. Therefore, the responsible officials at the Ministry of Education must focus on enhancing school students' awareness towards increased intake of healthy food and adopting good eating habits during the spread of pandemics and health diseases to avoid its negative effects on students. Background: The COVID-19 pandemic has a great impact on the eating habits, dietary intake, and purchasing behaviours of students. At this critical moment, there is an urgent need to identify the eating habits of school students, in particular, who live in low-income countries, during the lockdown period. Therefore, the present study aims to identify the influence of COVID-19 on the eating habits, quality and quantity of food intake among school students in the Gaza Strip, Palestine. Methods: A cross-sectional study was carried out among 2398 primary and secondary school students aged 6-18 year old through an online questionnaire which included questions on socio-demographic, eating habits as well as quality and quantity of food intake. Students over the age of 11 years completed the questionnaire on their own, whereas for students under the age of 12 years, the students' guardians were instructed to answer the questionnaire on their behalf. A Wilcoxon Signed-Rank and McNemar tests were applied to perform a comparison between general dietary habits before and during COVID-19. Also, a Wilcoxon Signed Rank test was used to compare the median scores of food quality and quantity before and during the COVID-19 pandemic based on student's sociodemographic. Results: During the COVID-19 pandemic, there was a significant increase in eating home-cooked foods (91.6%), avoiding ordering food from outside per week (93.3%) and buying groceries online (7.7%) (p < 0.001). There was a marked increase in the students reporting fear about food hygiene outside the home from 20.8% before COVID-19 to 72.9% during the COVID-19 period (p < 0.001). The results showed that the median score for food quality during the COVID-19 pandemic (11.0/6.0) was significantly higher than the before COVID-19 period (10.0, IQR = 8.0) (p < 0.001). The results revealed that the median score for food quantity before the COVID-19 pandemic (15.0, IQR = 5.0) was significantly higher than the during COVID-19 pandemic (14.0, IQR = 7.0) (p < 0.001). The results showed significant differences between the before and during COVID-19 period for food quality and quantity across socio-demographic variables (gender, age group, parent's highest level of education, monthly household income, and household size). During the COVID-19 pandemic, students from a high-income and a small size family had the highest score in terms of food quality and quantity among other counterparts when compared to other counterparts. Conclusion: Eating habits have significantly altered among school students during the COVID-19 pandemic. In spite of some good healthy habits enhanced among students, the quantity and the quality of the food was compromised. Therefore, the responsible officials at the Ministry of Education must focus on enhancing school students' awareness towards increased intake of healthy food and adopting good eating habits during the spread of pandemics and health diseases to avoid its negative effects on students. Introduction In March 2020, the World Health Organization (WHO) declared the COVID-19 as a pandemic due to the rapid spread of COVID-19 around the world. Many countries have imposed preventive procedures and followed the policy of lockdown to prevent the rapid spread of COVID-19. In spite of the importance of preventive procedures in control the widespread of COVID-19, they undoubtedly have consequences on eating habits, dietary intake and food consumption (FAO, 2020a(FAO, , p. 2020Xu et al., 2020a;Benton, 2020;Cecchetto et al., 2020;Jansen et al., 2021;Martínez-de-Quel et al., 2021). During this crisis, the people were enforced to stay at their home, resulting in increased fear, panic, anxiety and stress levels (Radwan and Radwan, 2020b;Radwan et al., 2020a and c). Unfortunately, anxiety and stress levels are positively linked with increased food consumption, especially unhealthy comfort foods (Machado et al., 2013). Overconsumption of unhealthy food can increase the risk of chronic diseases which can increase complications of COVID-19 (Renzo et al., 2020 a and b). It was reported that the COVID-19 pandemic has caused disruptions in food chains around the globe, influencing supply and demand (FAO, 2020a andb, p. 2020). During the lockdown, it might difficult to buy fresh fruits and vegetables and provide the necessary food products. On the other hand, several studies reported that more home cooking due to lockdown could teach individuals skills that enhance their nutrition behaviours and knowledge (Simmons and Chapman, 2012;Fulkerson et al., 2017). Recently, many studies were conducted to investigate eating habits and food consumption during the COVID-19 pandemic. For example, Ammar et al. (2020) conducted an international online survey that included 1047 participants to investigate the influence of COVID-19 confinement on the eating behaviours of participants. They showed that food consumption was more unhealthy during home confinement. Another international study conducted by Ruiz-Roso et al. (2020) found that COVID-19 had influenced the dietary habits of the study participants. Also, Sánchez-Sánchez et al. (2020) conducted a cross-sectional study to evaluate the dietary consumption before and during the COVID-19 pandemic among the Spanish population. They found that Mediterranean diet adherence was slightly increased during COVID-19, however, the consumption of unhealthy food also increased. In the study of Di Renzo et al. (2020a and b) they found that the COVID-19 crisis has a significant impact on the Italian population with consequences on eating habits. Almost half of the participants felt anxious due to the fact of their eating habits, consumed comfort food and were inclined to increase food intake to feel better. Furthermore, Ismail et al. (2020) showed that the dietary habits were closer to unhealthy patterns and distanced from the Mediterranean diet principles among participants in the United Arab Emirate. During the COVID-19 pandemic, shifted toward unhealthy dietary pattern such as increased frequencies of eating unhealthy food, eating out of control, snacking between meals, and having an increased number of meals per day was also found among participants in the USA (Chenarides et al., 2020, pp. 1-38), Spain (López-Moreno et al., 2020), Chile (Reyes-Olavarría et al., 2020), Poland (Sidor & Rzymski, 2020), France (Flaudias et al., 2020;Marty et al., 2021), UK (Robinson et al., 2021;Brown et al., 2020), Italy (Amatori et al., 2020), Netherlands (Poelman et al., 2020). On the other hand, some studies found a shift toward the consumption of healthy food and avoiding unhealthy food. For example, Hassen et al. (2020) studied the influence of COVID-19 on food consumption among Qatari consumer. They found an increase in the consumption of healthier diets and a shift toward domestic products to ensure the safety of food. In addition, in the study of Błaszczyk-Bębenek et al. (2020), they found a significant changes in the diet of Polish adults during lockdown due to COVID-19. They found that half of the participants avoid feat food outside the house during the lockdown. The percentage of participants snacking between meals was increased. Eggs, potatoes, sweets, canned meat and alcohol were consumed considerably more frequently during the COVID-19 pandemic, while fast-food products, instant soups and energy drinks were consumed significantly less commonly. The impact of COVID-19 differs from one country to another depending on several factors such as the epidemiological situation and socioeconomic status. In this regard, the case of the Gaza Strip, one of the poorest countries in the world, is particularly very interesting. In Palestine, the first case of COVID-19 was reported on March 5, 2020, where the Palestinian Ministry of Health put a lot of effort into controlling the widespread of COVID-19 among people. The Palestinian government in the Gaza Strip enforced lockdown and instructed the individuals to follow the preventive procedures to control the spread of COVID-19. The entire Palestinian community was negatively affected because all vital places have been closed during the lockdown period. Only pharmacies, clinics, and bakeries remained partially open, allowing providing the necessaries for individuals. The government also closed all educational institutions such as kindergartens, universities, schools, and collages. As educators, the safety of our students during the lookdown period must be taken into consideration. In this regard, the students 'habits with respect to the daily activities, eating, dietary intake, and purchasing behaviours changed or will be changed, especially some students reported that the COVID-19 lockdown negatively affected the economic status of their families . At this critical moment, there is an urgent need to identify the eating habits of school students during the lockdown period due to the spread of COVID-19 in the Gaza Strip, Palestine. Before the COVID-19 pandemic, the school health department at the Ministry of Education and Higher Education established various health initiatives that aimed at educating students to consume healthy food, follow healthy practices and avoid eating unhealthy food. These initiatives have been implemented in some schools under the supervision of school health coordinators due to the prevalence of unhealthy food consumption among students in schools. During the COVID-19 pandemic, the whole situation was completely different were all school principals, school health coordinators and teachers were instructed to implement more health programs and initiatives through social media platforms and other digital tools. Also, they were instructed to disseminate posts, photos, and essays about the necessity of adherence to consuming healthy food. In addition, various brochures were distributed to students and handled on the walls of all schools. To date, however, very little information derived from integrated studies is available on the eating habits of school students regarding nutrition and dietary intake during the COVID-19 pandemic. In August 2020, we conducted a survey during the COVID-19 crisis to obtain more detailed information about the eating habits of students in relation to nutrition and dietary intake. The rationale for this study was to improve our knowledge of school student regarding their food consumption and eating habits, to collect data that would facilitate the design and implementation of interventions aimed at promoting good nutrition in students via the school and, consequently, to contribute to the improvement of student' health during the health crises including the COVID-19 pandemic and any upcoming diseases in the future. Despite the spread of nutrition education initiatives in schools in the Gaza Strip, it is somewhat surprising that no study has highlighted eating habits among the students or other specific group samples, in particular during the current crisis. Therefore, the present study aims to investigate the eating habits of primary and secondary school students during the closing of schools as a result of the rapid outbreak of COVID-19 in the Gaza Strip, Palestine. Study design and sampling methods This was a cross-sectional study conducted on a sample of primary and secondary school students in the Gaza Strip during the COVID-19 lockdown. A total of 2398 students from primary and secondary schools responded to the online questionnaire, which distributed via social media platforms during the school closure period. The current study was carried out between August 26 and September 30, 2020, during the lockdown period due to the COVID-19 pandemic. To date of 30 September, the total number of confirmed cases in the Gaza Strip was 2948, where 1595 cases have recovered and 21 have deaths (MOH, 2020). According to the statistics of the Ministry of Education and Higher Education, the total number of confirmed cases among school students between August 26 and September 30, 2020, was 463 cases. During this period, the number of confirmed cases was rapidly increased day by day and it reached the highest number from the first detection of infected cases in March 2020. The questionnaire comprised four main sections. Each section consisted of the same questions for the periods before and during the COVID-19 pandemic. The first section involved demographic questions; the second section included general dietary habits; the third section covered questions about dietary food in terms of quality of food, and the last section contained questions related to dietary food in terms of quantity of food. The questionnaire applied in this study was derived from five previously published studies (Paxton et al., 2011;Corallo et al., 2019;Di Renzo et al., 2020 ;Alhusseini & Alqahtani, 2020;Yilmaz et al., 2020) and changed to fit the objective of the study. The questionnaire was written originally in English language and then translated to Arabic by a healthcare specialist with good experience in health survey design and proficiency in both languages. Next, it was back-translated into English by other bilingual clinical researchers with similar experiences. Initially, a reliability test was applied to measure the internal consistency of the questionnaire. A Cronbach's value equal to 0.953 was obtained, which shows an acceptable level of reliability. Before starting data collection, a pilot study was conducted with 45 participants to test the clarity of the questions of the Arabic version of the questionnaire. Some sentences were modified to suit the educational level of the participating students. The demographics questions involved age, gender, parent's highest level of education, family size, and economic status of the family. The five questions regarding food quality were on a Likert scale of 1-5 (Strongly disagree to Strongly agree); the sum of the five questions was taken to give the total quality of food score. The eight questions regarding the quantity of food were on a scale of 0-3 based on the frequency of food item use per week or day. The sum of these eight questions was taken to represent the total quantity of food score. Students have answered the same questions for before and during the COVID-19 pandemic. Ethical approval Ethics approvals were obtained from the Ministry of Education and Higher Education before conducting the data collection. An electronic informed consents were obtained from the students (aged 12 or more) or their guardians (students aged less than 12 years). Before answering the questionnaire, students answered the question: Do you agree to participate in this study? if they choose "No" they do not complete the questionnaire. If they choose "Yes", they forward to answering the questions of the scale. In this study, confidentiality and privacy were ensured and personal information was not disclosed. Statistical analysis Statistical analyses were performed using the Statistical Package for the Social Sciences (SPSS) software, version 22 (IBM, Chicago, Illinois, USA). Data analysis was based on descriptive statistics including frequencies and percentages for categorical variables. Due to the skewed of the obtained data, both food quantity and quality were presented as the median and interquartile range (IQR). A Wilcoxon Signed-Rank test for paired samples was applied to perform a comparison between general dietary habits before and during COVID-19 for ordinal variables, whereas a McNemar test was made for nominal variables. Also, a Wilcoxon Signed Rank test was used to compare the median scores of food quality and quantity before and during the COVID-19 pandemic based on student's sociodemographic. A p-value <0.05 was considered a statistically significant difference for all the statistical tests. Results A total of 2398 primary and secondary school students on aged ranges between 6 and 18 years participated in this study. Of those, 1911 (79.7%) were girls, 2107 (87.8%) were from the age group of 10-14 years, and 1396 (58.2%) were from families with high parental education levels. A high number of the participants 1742 (72.6%) were from low-income families. More than half of the students (59.3%) have a medium-size family (Table 1). Table 2 reveals the comparison of eating habits before and during the COVID-19 pandemic. Significant differences were found for all six questions for eating habits. There was an increase in the students rating of their eating healthy food as very good/excellent from 17.6% before the COVID-19 period to 40.7% during the COVID-19 period (p < 0.001). The majority of students (91.6%) reported eating home cooked-meals daily during COVID-19 compared to 47.2% before COVID-19 (p < 0.001). The proportion of ordering food from outside per week was 0 in 93.3% of students during the COVID-19 period as compared to 3.0% in the before period (p < 0.001). There was a decrease in the proportion of students whose families bought groceries every day from 13.2% before the COVID-19 period to 11.0% during the COVID-19 period (p < 0.001). The proportion of buying groceries online or delivery increased to 7.7% during the COVID-19 period as compared to 4.4% before; the majority of students (85.7%) used to buy groceries from the market before, but this decreased to 74.7% during the COVID-19 period (p < 0.001). There was a marked increase in the students reporting fear about food hygiene from outside from 20.8% before COVID-19 to 72.9% during the COVID-19 period (p < 0.001) ( Table 2). With regards to food quality, the results indicated that the COVID-19 pandemic has affected the quality of consumed food for school students to a slight degree (Table 3). Some items regarding food quality were positively affected during the current crisis, however, some of them Large: more than 7 members. b Based on PCBS indicator for households in the Gaza Strip. c The highest level of both father and mother. For example: If your father had got a bachelor's degree and your mother had graduated from secondary school, you will select the "Graduate" choice. were negatively changed. The results showed that the median score for food quality during the COVID-19 pandemic (11.0/6.0) was significantly higher than the before COVID-19 period (10.0, IQR = 8.0) (p < 0.001). Before the COVID-19 pandemic, more than half of students (52.9%) disagreed or strongly disagreed with the idea of preferring long shelf-life food items that take a long time to expire when buying food products. This percentage was significantly decreased to 49.5% during the COVID-19 period (p < 0.001). Students were more likely to prefer a lower cost when buying a food product during the COVID-19 period than before the COVID-19 period, where the percentage of the students who disagreed or strongly disagreed with the idea of preferring food products with lower cost was significantly decreased to 55.8% during the COVID-19 period as compared to before the COVID-19 period (59.4%) (p < 0.001). Before the COVID-19 pandemic, 64.6% disagreed or strongly disagreed that they care about the health effects of the food product when they buy, but this percentage was significantly decreased to 54.8% during the COVID-19 pandemic. Before COVID-19, 28.9% of students stated neither agree nor disagree about their attention to the health of food products when they buy. This percentage increased to 39.4% during the COVID-19. Before the COVID-19 period, only 5.7% of the students agreed or strongly agreed on being careful about the freshness of the food product when they buy. This percentage was significantly increased to 6.2% during the COVID-19 pandemic (p < 0.001). In addition, before the COVID-19 period, only 5.6% of students agreed or strongly agreed with the idea of the choice of food according to calorie and healthy properties when they buy. This percentage was slightly increased to 10.3% during the COVID-19 pandemic (p < 0.001). With respect to food quantity, the results revealed that the median score for food quantity before the COVID-19 pandemic (15.0, IQR = 5.0) was significantly higher than the during COVID-19 pandemic (14.0, IQR = 7.0) (p < 0.001). Most students (86.8%) consumed fast food four times/week or more before the COVID-19 pandemic. This percentage was significantly decreased to 63.5% during the COVID-19 pandemic. Before the COVID-19 pandemic, more than half of the students (53.5%) reported eating fruits two times or less per day. This percentage was slightly increased to 55.3% during the COVID-19 pandemic (p < 0.001). During the COVID-19 period, most students had a lower likelihood than before the COVID-19 period to consume vegetables two times or more each day (p < 0.001), where the percentage of students (58.2%) who daily consume vegetables two times or less was decreased to 55.3% during the COVID-19 pandemic. During the COVID-19 period, more than half of the students have a lower likelihood than before the COVID-19 period to drink sodas or glasses of sweet tea three times or more each day (p < 0.001), where the percentage of students decreased from 60.7% before COVID-19 to 41.3% during the COVID-19 pandemic ( Table 4). The percentage of students who consume beans, chicken or fish one time or more per week were significantly increased to 40.4% during the COVID-19 period when compared to before the COVID-19 period (17.0%) (p < 0.001). According to the current study, most of the students (83.0%) were found to consume beans, chicken or fish less than one time/week before the COVID-19 pandemic and this percentage was decreased to 59.6% during the COVID-19 pandemic. Before COVID-19, most of the students (80.5%) was regularly consumed snack chips or crackers four times or more per week. This percentage was significantly decreased to 70.3% during the COVID-19 pandemic. The percentage of eating desserts and other sweets/week four times or more was significantly decreased to 54.4% during the COVID-19 period as compared to 87.9% in the before period (p < 0.001). Most students (82.6%) showed the highest use of margarine, butter, or meat fat to season food before the COVID-19 period and this percentage was markedly decreased to 35.5% during the COVID-19 period (p < 0.001). The median values of the total score of food quality and quantity were compared by the categories of the different socio-demographic variables (gender, age group, parent's highest level of education, monthly household income, and household size), as presented in Table 5. There were significant differences between the before and during COVID-19 period for food quality and quantity across all five demographic variables. With regards to parent's highest level of education, all categories of age groups had a significantly higher score during COVID-19 than the before of COVID-19 period, except students whose parents graduated from the university or college. Students whose parents graduated from primary or secondary school, or got post-graduate level had a significantly higher score during the COVID-19 period than the before of COVID-19 period (p < 0.001). The results showed that students in the higher monthly income group were found to have the highest quality of food score when compared to low and moderate-income. For students in high-income families, the median score of food quality before the COVID-19 pandemic was (14.0, IQR = 8.3) and after the COVID-19 pandemic was (14.5, IQR = 8.5). The difference between before and after COVID-19 was statistically Table 5 Comparison median (IQR) total scores for quality and quantity of food by socio-demographic variables in a sample of 2398 school students before and during the COVID-19 pandemic. a Wilcoxon signed-rank test for significant difference between before and during median score. significant (p < 0.001). Also, students from the moderate-income family had a slightly higher score during COVID-19 (10.0, IQR = 5.0) than the before period (10.0, IQR = 3.0). In addition, students from the lowincome family had a higher score during COVID-19 (13.0, IQR = 8.0) than the before COVID-19 pandemic (10.0, IQR = 8.0). According to the current study, students from small families had the highest score when compared to medium and large families before and during the COVID-19 pandemic. For students in small families, the median score of food quality before the COVID-19 pandemic was (15.0, IQR = 15.0) and after the COVID-19 pandemic was (17.0, IQR = 15.3). The difference between before and after COVID-19 was statistically significant (p < 0.001). Also, students who have a medium family had a significantly higher score during COVID-19 (15.0, IQR = 5.0) than the before period (11.0, IQR = 5.0). A similar trend was also observed in students from large families. With regards to food quantity, analysis of data before and after COVID-19 found that students' food quantity score decreased overall during the COVID-19 period (14.0, IQR = 7.0) as compared to before the COVID-19 period (15.0, IQR = 5.0) (p < 0.001). The results revealed that all categories in socio-demographic variables showed a significant difference between before and during the COVID-19 period. Before the COVID-19 period, food quantity scores for both girls and boys significantly decreased during the COVID-19 period compared to before the COVID-19 period (p < 0.001). When comparing age groups, students aged 6-9 and 15-18 years got a higher score during the COVID-19 period than before the COVID-19 period (p < 0.001). In contrast, students aged 10-14 years got a lower score during the COVID-19 period (14.0, IQR = 7.0) than before the COVID-19 period (15.0, IQR = 5.0) (p < 0.001). With regards to the parent's highest level of education, food quantity scores for all categories of age groups significantly decreased during the COVID-19 period when compared to the before COVID-19 period (p < 0.001). A similar trend was observed with respect to the monthly income of the family, where the quantity of food they consume was significantly decreased during the COVID-19 pandemic (p < 0.001). The small size of students' families had the highest score when compared to medium and large families before and during the COVID-19 pandemic (p < 0.001). The students in the higher monthly income group were found to have the highest score for the quantity of food score when compared to low and moderate-income (p < 0.001). According to the present study, students from small families had the highest score when compared to medium and large families before and during the COVID-19 pandemic. The results showed that food quality scores significantly decreased in students from low, moderate, and highincome families during the COVID-19 pandemic when compared to the before COVID-19 pandemic (p < 0.001). For students in small families, the median score of food quality before the COVID-19 pandemic was (16.0, IQR = 5.0) and after the COVID-19 pandemic was (15.0, IQR = 8.0). The difference between before and after COVID-19 was statistically significant (p < 0.001). Also, students who have a medium family had a significantly lower score during COVID-19 (14.0, IQR = 6.0) than the before period (16.0, IQR = 5.0). A similar trend was also observed in students from large families. Eating habits Since the COVID19 pandemic is still spreading in our country, this study is considered the first study, to our knowledge, that highlights dietary change and eating habits among school students during the school closure as a result of the COVID-19 pandemic in the Gaza Strip, Palestine. This study aims to identify the change in eating habits as well as the quantity and quality of food intake during the COVID-19 pandemic. During the closure of school due to the COVID-19 pandemic, the eating habits of school students are influenced due to restriction of the movement, imposed quarantine, change in routine activities, and staying home for a long time. The change in eating habits is due to consuming fast food, limited available necessities, inability to access food, loss of household income, and reduced working hours in grocery (Mattioli et al., 2020a and b;Di Renzo et al., 2020). With regard to eating habits, the results showed a marked significant increase in healthy food rating from 17.6% before the COVID-19 pandemic to 46.1% during the COVID-19 pandemic (p < 0.001). The shift from unhealthy food to healthy food by some of the students was due to the health initiatives carried out by the Ministry of Education and Higher Education in the schools before and during the COVID-19 pandemic. During the COVID-19 crisis, teachers participated in several campaigns to educate students and provide them with correct information about COVID-19, including encouraging consuming healthy foods and home-cooked meals as well as avoiding unhealthy foods and outside-cooked meals. This helps students to incorporate healthy food components into their diets, but does not necessarily mean minimizing the consumption of high-carbohydrates and sugars food, where some students may increase such food intake because of the different definition of the concept of healthy food, which differs according to their educational level, age and other sociodemographic variables (Ganasegeran et al., 2012;Sun et al., 2013;Kim et al., 2016;Martinez-Lacoba et al., 2018;Kabir et al., 2018;Omage and Omuemu, 2019). The results revealed that more than half of students (53.9%) were found to still consuming unhealthy food during the current crisis due to deterioration in the economic status of their families during COVID-19, which was the worst before the COVID-19 pandemic. In the Gaza Strip, it was found that the economic harms of school closures during the COVID-19 pandemic were high, where the majority of families (77.9%) reported their wage loss during this closure , resulting inability of households to provide the necessary needs for their children, particularly healthy food, food supplements, medicines, sterilizers, facemasks, disinfectants (Nicola et al., 2020). Because of the deteriorating social and economic conditions in the Gaza Strip represented by high prices and a shortage of basic food commodities, a significant number of students follow an unhealthy diet (Al Sabbah et al., 2007;Jalambo et al., 2018;Nasser et al., 2010;Selmi and Al-Hindi, 2011, p. 7). At the same time, there has been an increasing concern about the quality of the food available and the general issue of food safety. In the last decades, the Gaza Strip has experienced dietary transitions, as this region has greatly influenced by the political circumstances, in particular the blockade imposed on the Gaza Strip by the Israeli occupation since 2008. The economic status of the Palestinian families has led to changes in daily practising, affecting food consumption and purchasing. As a result, eating habits have changed greatly due to the deteriorating living conditions of Palestinians at government, population and individual levels. These marked lifestyle changes have affected different age groups, especially school students (children and youth), pregnant women, and older adults (Abudayya et al., 2009;Al Sabbah et al., 2007;Nasser et al., 2010). According to the statistics of the Palestinian Central Bureau of Statistics (PCBS), a high percentage of Palestinian lives below poverty and suffer from the inability to buy healthy foods. Therefore they have replaced healthy traditional foods with fast foods, which compromised food quality and quantity and led to increased health disease among the individuals including the school students. These results were in accordance with the results stated previously in the study conducted in Italy during the COVID-19 pandemic. Di Renzo et al. (2020a) found an increase in the consumption of home-cooked meals and 37.4% of participants reported to consume healthy food during the COVID-19 pandemic. In addition, another study conducted in Canada showed that the eating habits of the participants have changed during the COVID-19 pandemic as they consume more home-cooked meals (Carroll et al., 2020). The lockdown imposed schools, markets, malls, shops and restaurants to open for very limited hours, which have impacted the eating habits as preventive measures contrary to regular eating habits in these places. This factor has influenced many students to shift to homemade meals since there are no other choices. The results also revealed that the majority of students (93.3%) did not order meals from outside per week compared to before COVID-19, as only 3.0% reported ordering meals from outside (p < 0.001). Similar results have previously been reported in the study of Alhusseini and Alqahtani (2020), which was conducted in Saudi Arabia during the COVID-19 crisis. They found that 74.7% of respondents never ordered food from outside compared to before COVID-19 (15%). In addition, another study conducted in Kuwait showed that the proportion of individuals who order food from outside was decreased from 14.7% before COVID-19 to 2.2% during the COVID-19 pandemic (Husain and Ashkanani, 2020). Our results were also in agreement with the results reported in the study of Ghosh et al. (2020), which was conducted in India during the current pandemic. They showed that the majority of respondents (97%) confirmed that they never order meals from restaurants or shops. The results of the present study revealed a marked decrease in the percentage of students who did not go to groceries from 5.4% before the COVID-19 pandemic to 28.6% during the COVID-19 pandemic (p < 0.001). The percentage of buying online or ordering the required things through mobile phones or telephones (delivery) slightly increased to 7.7% during the COVID-19 pandemic compared to only 4.4% before the COVID-19 pandemic. This result was in agreement with the result reported in the studies conducted in Saudi Arabia (Alhusseini & Alqahtani, 2020), Kuwait (Husain and Ashkanani, 2020) and Italy (Di Renzo et al., 2020). In these studies, they observed a slight increase in online purchase and shopping during the COVID-19 pandemic when compared to before the COVID-19 period. On the contrary, the results of this study showed that most of the participant (85.7%) used to shopping and purchase groceries and other required things directly from the market before the COVID-19 pandemic, but this percentage slightly decreased to 74.7% during the COVID-19 period (p < 0.001). The reason behind this decrease is due to anxiety and fear about food hygiene during the COVID-19 pandemic as 72.9% of the students felt panic and anxiety about food from outside the home, while only 20.7% had anxiety (p < 0.001) before the COVID-19 pandemic. During the COVID-19 crisis, it was reported that the physical activity among students decreased since the schools and most public places were imposed to close. The reduction in physical activity, alongside the consumption of unhealthy food, can lead to positive energy balance and increased body weight (Shahidi et al., 2020). Also, during the COVID-19 pandemic, the individuals are still feeling panic and anxiety about food supplies, where they exceed their needs as they fear food insecurity (Galanakis, 2020). Quality of food The results indicated that the COVID-19 pandemic has fairly affected the quality of consumed food for school students to a slightly limited degree. The results showed that more than half of students did not prefer low cost and long shelf-life food products before the COVID-19 pandemic. This percentage was significantly decreased during the COVID-19 period, where the students were more likely to prefer a lower cost and long shelf-life food products when buying a food product during the COVID-19 period than before the COVID-19 period (p < 0.001). Also, the results revealed that students were more careful about the health effects of the food product when they buy before the COVID-19 period than during the COVID-19 period (p < 0.001). On the other hand, students were more careful about the freshness, calorie and healthy properties of the food product when they buy during the COVID-19 period than before the COVID-19 period (p < 0.001). There are two possible explanations for these results in the current study. Firstly, imposed restriction movement and lockdown of grocers lead individuals to buy a huge amount of food products that take a long time to expire during the quarantine period such as canned, tinned and packet food (whether canned vegetables, fruits, meat, .etc.). Secondly, most Palestinian families suffer from poverty and loss of their income source due to the current lockdown, as a result, they have no another option to provide their households with the necessary needs, so they select the lowest cost of food products. It was reported that during the COVID-19 pandemic, school students may be feeling stress, fear and anxiety due to limited food sources, this fear leading students household to purchase and store a significant amount of packaged and long-life food rather than fresh food, which influenced consumed food quality and led to increased weight and intake of unhealthy food (Mattioli et al., 2020a or b). This finding is in line with a previous study conducted by Ruíz-Roso et al. (2020 a or b), they noticed a marked decrease in the levels of physical activity and increase in consumption of processed and packaged food during the COVID-19 pandemic. Also, in the study of Allabadi et al. (2020), they reported that food quality was negatively influenced during the COVID-19 pandemic because of increased intake of consuming sugary beverages (31.5%) and fried food (36.7%). However, they noticed an increase in fruit (33.2%) and vegetable (39.5%) consumption among participants. In addition, in the study of Matsungo and Chopera (2020), they observed that the quality of food sold has decreased and the costs have increased in Zimbabwe. The changes in food quality and costs led to negatively influenced purchasing and consuming habits during the COVID-19 pandemic. Pellegrini et al. (2020) carried out a study to evaluate the changes in weight and dietary habits in patients with obesity during the COVID-19 pandemic in Italy. The results showed an increase in the consumption of cereals, sweets, and snacks, resulting in gaining weight during the COVID-19 pandemic, particularly among individuals who do not exercise regularly. However, the overall results of this study showed that the median score of food quality was slightly higher during COVID-19 than the period before COVID-19 (p < 0.001). Some items of food quality have changed positively during the COVID-19 pandemic, as students purchasing fresh food products and choosing food according to calorie and healthy properties. This result can be attributed to the implementation of health initiatives by educators through social media during the school closure. The COVID-19 pandemic and unexpected closing of schools promote teachers to shifted from face-to-face learning to distance learning and incorporate health programs with the curriculum. This procedure educates students and increases their awareness toward adopting preventive measures to avoid infection with COVID-19 such as consuming healthy food. Quantity of food On the contrary of food quality, the median score of food quantity was higher before the COVID-19 pandemic than during the COVID-19 pandemic (p < 0.001). Some items of food quantity have changed positively during the COVID-19 pandemic, as decreased consumption of fast food, desserts, snack chips, crackers, sodas or sweet tea and increased consumption of beans, chicken, fish, fruits. This result may be due to the fact that the economic crisis generated by the COVID-19 pandemic threatens the students and their families in particular those who came from poor families and those who lost their source income due to the lockdown. Those students have limited access to different sources of healthy food during the COVID-19 period, therefore the quantity of food may be decreased. During COVID-19, some food quantity items have decreased when compared to the before period such as the consuming fast food, where the percentage of students who eat fast food four times or more per week was significantly lower during COVID-19 than the before period. This may be due to lockdown of restaurant, shops and other places which provide students with fast food meals or feeling fear related to become infected with COVID-19 after eating outside the home. However, some food quantity items increased during COVID-19 such as the quantity of consuming fresh vegetables and fruits, where some students from high-income family were found to consume more servings of vegetables and fruits during the COVID-19 pandemic to enhancing their health and building up the immunity system. This result seems to be in harmony with the results stated in the studies of Lippi et al. (2020), Scarmozzino and Visioli (2020), and Sidor and Rzymski (2020). They confirmed the prevalence of unhealthy food habits during the COVID-19 pandemic as there was a decrease in vegetables and fruits consumption and an increase in consuming chocolate, coffee, ice-cream, desserts and snacks. This could be justified as the individuals spent more time at home during the lockdown period and a decrease in movement and routine activities leading to an increase in food intake and weight gain among individuals in the families. Such procedures led students to do the same thing as their parents or relatives during the closure of schools. Also, in the study of Matsungo and Chopera (2020), they found that some participants confirmed a decrease in vegetables, fruits, seeds and nuts intake, whereas others reported an increase in leafy vegetable intake. In the study of Ruiz-Roso et al. (2020 b) carried out a study on nutritional changes in adolescents aged 10-19 years during the COVID-19 lockdown. The results revealed that the COVID-19 pandemic influenced the dietary habits of the participants, as they observed an increase in the consumption of fried and sweet, legumes, fruits, and vegetables during the COVID-19 pandemic. On the other hand, different results have been reported in the study of Xu et al. (2020b). They carried out a comprehensive survey in China to identify the impact of the COVID-19 pandemic on dietary habits among Chinese. The results showed that there was a positive enhancement to a healthy diet during the COVID-19 pandemic among the Chinese participants. Since the outbreak of the COVID-19 pandemic at the beginning of 2020, the food quantity of students has influenced as some of them followed healthy diet intake, whereas others are still following unhealthy diet intake during the current crisis. Socio-demographic The results showed that boys' food quantity score decreased during the COVID-19 period, whereas food quality score increased as compared to before the COVID-19 period (p < 0.001). For girls, food quantity and quality scores decreased during the COVID-19 period as compared to before the COVID-19 period (p < 0.001). The reasons behind a decrease or increase in quantity and quality of food among girls and boys are due to several factors. The COVID-19 pandemic and the preventive measures have caused disruptions of the students daily activities. Despite the importance of these preventive procedures to contain the rapid spread of COVID-19, they undoubtedly have a strong impact on the students mental health and psychology. The restrictions of movement, the closing of schools, staying home for a long time, food insecurity, and inability to adapt to the lifestyle of the quarantine during the COVID-19 pandemic resulted in an increase in the rate of domestic violence, fear, loneliness, anxiety, depression, and panic among school students. In this regard, the eating habits of students may have negatively changed, as some students may avoid eating or intake a little or high amount of food. Recently, it was noticed a relationship between food intake and mental and emotional mood during the COVID-19 pandemic (Leeds et al., 2020;Firth et al., 2020;Di Renzo et al., 2020 b;Van Rheenen et al., 2020). It was reported that stressed students consumed more unhealthy food compared with unstressed counterparts (Papier et al., 2015), as they following unhealthy diet during the COVID-19 pandemic (Xu et al., 2020b). In addition, many students were suffering from stress due to suddenly shifted to online learning, where some students inability to access educational materials through digital platforms, therefore their eating habit changed under these unexpected circumstances (Marbán et al., 2021). When comparing the age categories for food quality, the age group of 6-9 years showed the highest score before and during the COVID-19 pandemic. However, this age group showed the lowest score before and during the COVID-19 pandemic with regards to food quantity. Children students are at great risk when they are infected with the Coronavirus, so families with children are keen to pay attention to the quality of the food they eat to strengthen their immune system against diseases (de Araújo Morais et al., 2020;François et al., 2020;Li et al., 2020;Naja and Hamadeh, 2020). Based on the health initiatives implemented by the MOH and MOEHE in the Gaza Strip through social media platforms, guardians know that children strongly need a healthy balanced diet and regular meals containing foods from each food group to ensure getting the required nutrients to help them stay healthy during this crisis. The change amount of food consumed by the children can be attributed to the economical level of the family, psychological distress, family size, or emotional factors. Also, closure of schools due to COVID-19 may lead to decreasing appetite of school students and feel fear and anxiety about their educational performance. Moreover, imposed quarantined in homes and lack of outdoor activity is likely to change children's lifestyle and can potentially promote neuropsychiatric issues such as annoyance, violence, abuse, monotony, impatience, and feeling lonely, this likely lead to change in the quality and quantity of consumed food (Ghosh et al., 2020). In addition, the sudden shifted to distance learning during this pandemic increased spent time on social media platforms, television, or digital tools and neglecting to eat meals regularly, where students are likely to subject to useful or adulterated online contents attract their attention to movies, plays, . etc. and staying away from the attention of quality and quantity of food. Recently, it was found that spending more time in front of screens (social media platforms, TV, .etc.) were associated with low adherence to the required quality and quantity of consumed food in children and adolescents, where some students may overconsumption food (Arikan & Bekar, 2017;Borghese et al., 2015;Wärnberg et al., 2021) whereas the others may decrease in consuming food (Francis and Birch, 2006). With regard to parent's highest level of education, our findings showed that students whose parents graduated from primary or secondary school have markedly lower scores for food quantity during the COVID-19 period as compared to the before COVID-19 period (p < 0.001). This result can be explained by the fact that the parents of students who finished primary or secondary school are not working or have lost their work as a result of the lockdown and thus suffer from very difficult economic conditions and are unable to meet the needs of their children and provide them with healthy food. On the other hand, students with highly educated parents got a higher score for food quality and quantity during the COVID-19 period as compared to the before period (p < 0.001). This can be justified that many factors are influencing dietary intake and eating behaviour of school students (Kabir et al., 2018) including parental education level (Ajao et al., 2010;Fernández-Alvira et al., 2013;Hu et al., 2016;Kaukonen et al., 2019;Lehto et al., 2018). Parental education level influences on eating habits and food intake of the students as parents with higher education level have good food and nutrition-related knowledge, therefore they encourage healthy eating by providing advice on food selection and consumption of home-cooked diets (Banna et al., 2015;Kim et al., 2016;Lehto et al., 2018). As it is known, parents with higher education level have a great opportunity to get a good job and a stable income, therefore they provide healthy food with high quality for their children, especially in period of health crises and disasters. In the Gaza Strip, this status applies to a small proportion of parents who have a good level of education, as the largest percentage of parents with high education level are unemployed and suffering from very difficult economic status, therefore the inability to secure healthy food for their children in normal times or during the COVID-19 crisis. On the contrary of food quantity, food quantity scores for students whose parents graduated from primary or secondary school significantly increased during the COVID-19 period when compared to the before COVID-19 period (p < 0.001). This slight increase can be attributed to distribute of food aid by local and international agencies. During the COVID-19 pandemic, governmental entities and UNRWA (United Nations Relief and Works Agency for Palestine Refugees in the Near East) carried out the distribution of food aid and medication for some refugees, poor families and those whose guardians did not have a source of income to maintain a high level of safety and prevent the widespread of the COVID-19 pandemic in the Gaza Strip. These aids maybe enhance the quality of consumed food as they contain essential nutrients such as milk, beans, canned fish, .etc. The present study revealed that students from low, moderate and high-income families had a significantly higher score for the quality of food during the COVID-19 pandemic than the before of the COVID-19 pandemic. However, all categories of monthly income a significantly lower score for the quantity of food during the COVID-19 pandemic than the before of the COVID-19 pandemic. The results also showed that students from low-income families were the lowest median score of food quality and quantity among other counterparts. Students with lower family income are more likely to purchase foods of lower nutritional quality and eat poor food quality compared to those with moderate and higher family income. The results also revealed that students in the higher income family had the highest quality and quantity of food score compared to other counterparts. This result can be attributed to the ability of the moderate and high-income family to provide their members with the required nutritional needs and select the best quality and quantity products. It was reported that family income is considered an important factor that influences the student's dietary habits and eating patterns (Kim et al., 2016). This result agrees with the results stated in the study of French et al. (2019), they found a positive association between lower-income families with poorer food quality. During the lockdown period, many families lost their income and stayed without money. When they lose their incomes, food choices shift toward poor quality and cheaper foods. Healthier and high-quality food such as vegetables, fruits, whole grains, and high-quality proteins are sharply dropped, therefore they choose low-cost food to meet the needs of the family members. It was reported that families with higher income can affect the purchasing and consumption of good food quality as they can access fresh, healthier, and nutritious food (French et al., 2019;Hollis-Hansen et al., 2019;Lee and Allen, 2020;Litvak et al., 2020;Shirisha, 2019). Overall, the results showed that students from small, medium and large families had a higher median score for food quality during the COVID-19 pandemic than the before of the COVID-19 pandemic. However, the food quantity score was significantly decreased in students from low, moderate, and high-income families during the COVID-19 pandemic when compared to the before COVID-19 pandemic (p < 0.001). Also, the results revealed that students from large families had the lowest median score for the quantity and quality of food when compared to students with small and medium families. This result can be explained by the fact that increased family size may negatively influence the nutritional status of each member of the family because it may be linked with decreased per capita human inputs, where, the allocation of food per member is more likely to decrease with increasing the number of members in the family. This status became worst in the case of lower economic status, where increased size in poor families means acceptance of lower food quality and quantity. On contract, in some cases, family size may itself reflect a higher economic status of the family. In this situation, large family size may not cause to worsening of quality and quantity of consumed food for each member. This result is consistent with the result reported in the studies of Basit et al. (2012), Owoaje et al. (2014), and Galgamuwa et al. (2017), they found that large family size is considered as a risk factor for malnutrition of their children due to intake of low-quality food. The quality of food in the presence of many family members is impaired and also there is a limited amount available for each member to meet their needs from high-quality food. This further reiterates the important role of limiting family size in enhancing the health of family members, where students from homes with large family had a higher risk of developing health diseases due to poor quality of food compared to those from homes with small and medium families. During the normal condition, the main features of school students' eating patterns include skipping breakfast, eating snacking, dieting, and adoption of specific diets. This situation will be more dangerous during the spread of the COVID-19 pandemic. In recent months, there has been a growing worldwide concern about the dietary and nutritional needs of students during the spread of diseases. Studies indicate that good nutrition is especially important during critical periods, which is a period of spreads of infection with COVID-19 (Ribeiro et al., 2020). Healthy eating habits in students not only help to prevent under-nutrition, growth retardation and acute nutritional problems but also lower the risk of developing chronic non-communicable diseases (Wang et al., 2014). Moreover, good nutrition and healthy food can enhance students' educational performance and support their learning during the closure of schools, in particular during distance learning. Nutrition-related health problems among the students are apparent in developing countries where, paradoxically, both over-and under-nutrition can coexist. Currently, Palestine, particularly the Gaza Strip, is experiencing a severe challenge in the area of health and nutrition, where nutritional deficiencies and over-nutrition are significant in Palestine and that the problem is growing, therefore the development of a health protocol for influenced students is much needed to maintain them remain resilient even during the COVID-19 pandemic. Conclusion The eating habits of school students have significantly altered during the outbreak of the COVID-19 pandemic in the Gaza Strip, Palestine. Despite some good healthy habits being found to increase, such as eating home-cooked food and avoiding eating from outside, food quantity and quality was compromised. The quality and quantity of the consumed food become more unpleasant during the COVID-19 pandemic. Students from low income and large family were most affected during this crisis. Therefore, the responsible officials at the Ministry of Education and Higher Education must focus on enhancing school students' awareness towards increased intake of healthy food and adopting good eating habits during the spread of pandemics and health diseases to avoid its negative effects on students. The role of the Ministry of Health and the experts (nutritionists, pedagogues, and paediatricians) should take into consideration and employ their experience in planning programs related to the nutrition of students. Strengths and limitations The present study is considered unique as it will add new data to the current research about eating habits during the COVID-19 pandemic. The strengths of the current study include the temporal proximity to the developments respecting the COVID-19 pandemic in the Gaza Strip, Palestine. This study was conducted during schools closure as a result of the COVID-19 pandemic. Some of the limitations of this study are that the questionnaire lacks information about other factors related to eating habits such as psychological factors and physical activity, which may add value to the study. As this study is a cross-sectional study, therefore no causal inferences can be derived. Since the COVID-19 pandemic is still widespread in our country, the current is the first study to our knowledge that highlights changing in eating habits during the COVID-19 pandemic. There are no peer-review results about eating habits among people, including school students, during the outbreak of the COVID-19 pandemic in the Gaza Strip. Limitations of this study also include the quarantine period and restriction of the movement were obstacles to communicating with students and gathering data in a systematic method. Future study is highly recommended to be done to better understand the change in eating habits during pandemics using a detailed questionnaire containing questions linked to other related factors affecting eating habits. Ethical consideration All students voluntarily confirm their informed consent to A. Radwan et al. participate in the study after being informed about the objective of the study. The Ethics Committee of MOE approved our study protocol and procedures before the formal survey. The procedures of this study complied with the provisions of the Declaration of Helsinki respecting research on Human participants.
Another one of the “rumors have been flying” stories… that I was getting ready to post about this weekend anyway, but I finally found a nugget of corroborating evidence! Royal Farms is planning on putting one of its Super convenience/gas stations along Blackwood-Clementon Road in Gloucester Township. The address (1409) puts the location right in the Commerce Square shopping center which was the location for the Superfresh Supermarket… which was recently torn down. So the targeted address is known, but can only assume the supermarket was demolished to make room for the Royal Farms store in that area of the shopping center’s lot. Royal Farms is 100% a Super Wawa competitor, and if you walked into one of their stores you’d think they were copying each other. They are making a huge push into South Jersey with locations already in development for Bellmawr, Gloucester City, Magnolia and other locations (I know of one other not-reported location that I am working on) The confirming evidence I found? Well just yesterday the Gloucester Township MUA meeting notes were posted for the 4/20/2017 meeting, and listed in the doc was a reference to the Royal Farms at 1409 Blackwood-Clementon Road. So this doesn’t mean its 100% happening. There has been nothing official stated by the town or Royal Farms, so there is some chance this doesn’t happen. I have more thoughts and comments on the Super Convenience store wars… hopefully will post soon. What do you think about a video? 42Freeway was the first to break this story (as far is I know). If you choose to post about it in your blog or media outlet please mention this site or link to this story (or FB). Thank you!
<filename>doc/doxygen/snippets/line_feed_formatter.cc /** * @file * @brief Shows usage of lf::base::LineFeedFormatter * @author <NAME> * @date 2020-10-08 10:38:42 * @copyright MIT License */ #include <lf/base/base.h> #include <spdlog/pattern_formatter.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> void NormalFormatter() { //! [NormalFormatter] std::shared_ptr<spdlog::logger> logger = spdlog::stdout_color_mt("logger_name"); logger->set_level(spdlog::level::trace); SPDLOG_LOGGER_TRACE(logger, "hello\nworld"); //! [NormalFormatter] } void LineFeedFormatter() { //! [LineFeedFormatter] std::shared_ptr<spdlog::logger> logger = spdlog::stdout_color_mt("logger_name"); logger->set_formatter(std::make_unique<lf::base::LineFeedFormatter>( std::make_unique<spdlog::pattern_formatter>())); logger->set_level(spdlog::level::trace); SPDLOG_LOGGER_TRACE(logger, "hello\nworld"); //! [LineFeedFormatter] }
Former US intelligence chief Michael Hayden, who has previously held top positions at the NSA and CIA, has admitted that US spy agencies – like their Russian counterparts – have previously hacked foreign political parties in past operations. Speaking at an interview hosted by The Heritage Foundation this week (18 October), Hayden argued the main difference between the US and Russian intelligence groups is that the Kremlin has intentionally worked to "weaponise" stolen data to influence the political process. "I have to admit my definition of what the Russians did [at the DNC] is, unfortunately, honourable state espionage," Hayden explained, adding: "A foreign intelligence service getting the internal emails of a major political party in a major foreign adversary? Game on. That's what we do." He continued: "By the way, I would not want to be in an American court of law and be forced to deny that I never did anything like that as director of the NSA, because I could not." He was keen to stress, however, that the Russian hacking campaign "went beyond espionage." The former intelligence chief, who was the director of the NSA between 1999 and 2005 and director of the CIA between 2006 and 2009, said the Russian government likely contracted its hacking to criminal gangs "as a way to create a little distance between the Russian state and the actual actors." The US intelligence community recently released an official statement declaring that Russia's "senior-most officials" likely authorised recent hacks at groups including the Democratic National Committee (DNC) and the Democratic Congressional Campaign Committee (DCCC). "These thefts and disclosures are intended to interfere with the US election process. Such activity is not new to Moscow — the Russians have used similar tactics and techniques across Europe and Eurasia, for example, to influence public opinion there," the statement read. Yet the NSA has been implicated in the past in similar state espionage. In 2013, based on documents released by former agency analyst Edward Snowden, Der Spiegel revealed how the US had tapped phone conversations of German chancellor Angela Merkel and her closest advisers for over 10 years. "They are doing it to mess with our heads" Hayden, however, maintains the Russian attacks are vastly different to the NSA's type of tradecraft. "To take the internal emails and then begin to use them to influence the American election, that's quite a different matter," he said. "That has now moved from an espionage activity to a covert – or not very covert – influence operation. I think they are doing it to mess with our heads, to erode confidence in our political processes. "I think they are doing it because [Russian president Vladimir Putin] is convinced we do this to him all the time. We do not. We don't." Hayden said the recent hacks should be analysed as a broader geo-political issue. "Do not drop this in the cyber problem box," he said. "Drop this in the Russia problem box. Do not treat this by its means, treat it by its actor. By the way, that Russia problem box – we're going to need a bigger box." For its part, and as is to be expected of nation-state activity, the Kremlin has denied being involved in the cyberattacks against the US. In a recent interview, Vladimir Putin said: "Everyone is talking about who did it. But is it that important? The most important thing is what is inside this information. There's nothing there benefitting Russia."
def toggle_loading(self): self.loading = not self.loading self.disabled = self.loading return self
<gh_stars>0 import { ApiPropertyOptional } from '@nestjs/swagger'; import * as mongoose from 'mongoose'; export class CreateGoodsImageDto { @ApiPropertyOptional({ description: '商品ID' }) goodsId: mongoose.Schema.Types.ObjectId @ApiPropertyOptional({ description: '图片地址' }) imgUrl: string // @ApiPropertyOptional({ description: '图片颜色' }) // color_id: number // @ApiPropertyOptional({ description: '图片排序' }) // sort: number // @ApiPropertyOptional({ description: '商品状态' }) // state: number // @ApiPropertyOptional({ description: '增加时间' }) // createAt?: number }
def course_heading_loose_match_with_location( curr_location, prev_location, heading, course, errors, error_type ): number_of_errors = len(errors) bearing = bearing_between_two_points(prev_location, curr_location) delta = 90 if heading: heading_in_degrees = heading.to(unit_registry.degree) if not acceptable_bearing_error(heading_in_degrees, bearing, delta): errors.append( { error_type: f"Difference between Bearing ({bearing:.3f}) and " f"Heading ({heading_in_degrees:.3f}) is more than {delta} degrees!" } ) if course: course_in_degrees = course.to(unit_registry.degree) if not acceptable_bearing_error(course_in_degrees, bearing, delta): errors.append( { error_type: f"Difference between Bearing ({bearing:.3f}) and " f"Course ({course_in_degrees:.3f}) is more than {delta} degrees!" } ) if number_of_errors == len(errors): return True return False
/** * Deletes content on database. Won't delete saved files. * * @param jsonId id of content to delete. * @return true if successfully deleted. */ public boolean deleteContent(String jsonId) { long row = mContentDatabaseAdapter.getPrimaryKey(jsonId); ArrayList<ContentBlock> contentBlocks = mContentBlockDatabaseAdapter .getRelatedContentBlocks(row); for (ContentBlock block : contentBlocks) { mContentBlockDatabaseAdapter.deleteContentBlock(block.getId()); } boolean deleted = mContentDatabaseAdapter.deleteContent(jsonId); return deleted; }
The Lineup Has Arrived. We are so thrilled to host some of our favorite bands in the world, including Victor Wooten, Thao & the Get Down Stay Down, Chali 2na, and of course the wall of power that is RATATAT for their only 2016 festival appearance! We're prepping for a landmark Fall weekend out on the Ranch Sep. 29-Oct. 2. Our site is currently crashed from high volume, but tickets can be purchased at http://www.eventbrite.com/e/eighth-annual-utopiafest-tickets-18546719738?aff=es2 Tickets are limited, and Buy-5-Get-1 FREE is still on. Just purchase five Weekend or Pre-Party passes and we'll email you a FREE one! Get your closest friends and family together for the most audience focussed, easy, fence-free, BYOB, family friendly, educational, adventure of a weekend experience under the FULL MOON! We've got goose-bumps :) Please help us spread the word to the right people - we need your help to keep this festival as the exception - wholly focussed on the experience of our audience and artists. Thanks for making our dream festival a reality - we'll never forget how lucky we are to be able to do this. Much Love, Travis, Aaron, and the UTOPiA team
Still-face Effect in Dogs (Canis familiaris). A Pilot Study. The Still-face Paradigm has been widely used for the assessment of emotion regulation in infants, as well as for the study of the mother-child relationship. Given the close bond that dogs have with humans, the purpose of this research was to evaluate, through an exploratory descriptive study, the presence of the Still-face effect in dogs. To this end, a group of Beagle dogs were exposed to three one-minute phases in which first, an unknown experimenter interacted actively and positively with each dog (Interaction). Then, suddenly, she interrupted the interaction and remained passive, with a non-expressive face and without speaking or petting the dog (Still-face). Finally, the experimenter reestablished the interaction (Reunion). Our results showed a decrease in affiliative behaviors in dogs during the Still-face phase according to changes in the human's behavior, a pattern similar to the one previously found in infants. Contrary to expectations, no stress-related behaviors were shown during that phase. A carry-over effect was also observed in the Reunion phase. This study provides information about the human-dog interaction and the effects of its disruption on dogs' behaviors.
/** * A task is reporting in as 'done'. * * We need to notify the tasktracker to send an out-of-band heartbeat. * If isn't <code>commitPending</code>, we need to finalize the task * and release the slot it's occupied. * * @param commitPending is the task-commit pending? */ void reportTaskFinished(boolean commitPending) { if (!commitPending) { try { taskFinished(); } finally { releaseSlot(); } } notifyTTAboutTaskCompletion(); }
<reponame>rendinam/crds """uses.py defines functions which will list the files which use a given reference or mapping file. >> from pprint import pprint as pp >> pp(_findall_mappings_using_reference("v2e20129l_flat.fits")) ['hst.pmap', 'hst_0001.pmap', 'hst_0002.pmap', 'hst_0003.pmap', 'hst_0004.pmap', 'hst_0005.pmap', 'hst_0006.pmap', 'hst_cos.imap', 'hst_cos_0001.imap', 'hst_cos_flatfile.rmap', 'hst_cos_flatfile_0002.rmap'] """ import sys import os.path from crds.core import config, cmdline, utils, log, rmap @utils.cached def load_all_mappings(observatory, pattern="*map"): """Return a dictionary mapping the names of all CRDS Mappings matching `pattern` onto the loaded Mapping object. """ all_mappings = rmap.list_mappings(pattern, observatory) loaded = {} for name in all_mappings: with log.error_on_exception("Failed loading", repr(name)): loaded[name] = rmap.get_cached_mapping(name) return loaded @utils.cached def mapping_type_names(observatory, ending): """Return a mapping dictionary containing only mappings with names with `ending`.""" return { name : mapping.mapping_names() + mapping.reference_names() for (name, mapping) in load_all_mappings(observatory).items() if name.endswith(ending) } def uses_files(files, observatory, ending): """Alternate approach to uses that works by loading all mappings instead of grepping them on the file system. """ referrers = set() for filename in files: config.check_filename(filename) loaded = mapping_type_names(observatory, ending) for_filename = set(name for name in loaded if filename in loaded[name]) referrers |= for_filename return sorted(list(referrers)) def _findall_rmaps_using_reference(filename, observatory="hst"): """Return the basename of all reference mappings which mention `filename`.""" return uses_files([filename], observatory, "rmap") def _findall_imaps_using_rmap(filename, observatory="hst"): """Return the basenames of all instrument contexts which mention `filename`.""" return uses_files([filename], observatory, "imap") def _findall_pmaps_using_imap(filename, observatory="hst"): """Return the basenames of all pipeline contexts which mention `filename`.""" return uses_files([filename], observatory, "pmap") def _findall_mappings_using_reference(reference, observatory="hst"): """Return the basenames of all mapping files in the hierarchy which mentions reference `reference`. """ mappings = [] for rmap in _findall_rmaps_using_reference(reference, observatory): mappings.append(rmap) for imap in _findall_imaps_using_rmap(rmap, observatory): mappings.append(imap) for pmap in _findall_pmaps_using_imap(imap, observatory): mappings.append(pmap) return sorted(list(set(mappings))) def _findall_mappings_using_rmap(rmap, observatory="hst"): """Return the basenames of all mapping files in the hierarchy which mentions reference mapping `rmap`. """ mappings = [] for imap in _findall_imaps_using_rmap(rmap, observatory): mappings.append(imap) for pmap in _findall_pmaps_using_imap(imap, observatory): mappings.append(pmap) return sorted(list(set(mappings))) def uses(files, observatory="hst"): """Return the list of mappings which use any of `files`.""" mappings = [] for file_ in files: if file_.endswith(".rmap"): mappings.extend(_findall_mappings_using_rmap(file_, observatory)) elif file_.endswith(".imap"): mappings.extend(_findall_pmaps_using_imap(file_, observatory)) elif file_.endswith(".pmap"): pass # nothing refers to a .pmap else: mappings.extend(_findall_mappings_using_reference(file_, observatory)) return sorted(list(set(mappings))) class UsesScript(cmdline.Script): """Command line script for printing rmaps using references, or datasets using references.""" description = """ Prints out the mappings which refer to the specified mappings or references. Prints out the datasets which historically used a particular reference as defined by DADSOPS. IMPORTANT: 1. You must specify references or rules on which to operate with --files. 2. You must set CRDS_PATH and CRDS_SERVER_URL to give crds.uses access to CRDS mappings and databases. """ epilog = """ crds.uses can be invoked like this: % crds uses --files n3o1022ij_drk.fits --hst hst.pmap hst_0001.pmap hst_0002.pmap hst_0003.pmap ... hst_0041.pmap hst_acs.imap hst_acs_0001.imap hst_acs_0002.imap hst_acs_0003.imap ... hst_acs_0008.imap hst_acs_darkfile.rmap hst_acs_darkfile_0001.rmap hst_acs_darkfile_0002.rmap hst_acs_darkfile_0003.rmap ... hst_acs_darkfile_0005.rmap """ def add_args(self): """Add command line parameters unique to this script.""" super(UsesScript, self).add_args() self.add_argument("--files", nargs="+", help="References for which to dump using mappings or datasets.") self.add_argument("-i", "--include-used", action="store_true", dest="include_used", help="Include the used file in the output as the first column.") def main(self): """Process command line parameters in to a context and list of reference files. Print out the match tuples within the context which contain the reference files. """ if not self.args.files: self.print_help() sys.exit(-1) self.print_mappings_using_files() return log.errors() def locate_file(self, file_): """Just use basenames for identifying file references.""" return os.path.basename(file_) def print_mappings_using_files(self): """Print out the mappings which refer to the specified mappings or references.""" for file_ in self.files: for use in uses([file_], self.observatory): if self.args.include_used: print(file_, use) else: print(use) def test(): """Run the module doctest.""" import doctest from . import uses return doctest.testmod(uses) if __name__ == "__main__": sys.exit(UsesScript()())
<reponame>nichtl/datav import React, { useState } from 'react'; import { Icon} from 'src/packages/datav-core'; import {Row} from 'antd' import { useUpdateEffect } from 'react-use'; import {renderOrCallToRender} from 'src/core/library/utils/renderOrCallToRender' import './QueryOperationRow.less' interface QueryOperationRowProps { title?: ((props: { isOpen: boolean }) => React.ReactNode) | React.ReactNode; headerElement?: React.ReactNode; actions?: | ((props: { isOpen: boolean; openRow: () => void; closeRow: () => void }) => React.ReactNode) | React.ReactNode; onOpen?: () => void; onClose?: () => void; children: React.ReactNode; isOpen?: boolean; } export const QueryOperationRow: React.FC<QueryOperationRowProps> = ({ children, actions, title, headerElement, onClose, onOpen, isOpen, }: QueryOperationRowProps) => { const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true); useUpdateEffect(() => { if (isContentVisible) { if (onOpen) { onOpen(); } } else { if (onClose) { onClose(); } } }, [isContentVisible]); const titleElement = title && renderOrCallToRender(title, { isOpen: isContentVisible }); const actionsElement = actions && renderOrCallToRender(actions, { isOpen: isContentVisible, openRow: () => { setIsContentVisible(true); }, closeRow: () => { setIsContentVisible(false); }, }); return ( <div className={'query-operation-row-wrapper'}> <div className={'header'}> <Row justify="space-between" style={{width: '100%'}}> <div className={'titleWrapper'} onClick={() => { setIsContentVisible(!isContentVisible); }} aria-label="Query operation row title" > <Icon name={isContentVisible ? 'angle-down' : 'angle-right'} className={'collapseIcon'} /> {title && <span className={'title'}>{titleElement}</span>} {headerElement} </div> {actions && actionsElement} </Row> </div> {isContentVisible && <div className={'content'}>{children}</div>} </div> ); }; QueryOperationRow.displayName = 'QueryOperationRow';
/** * * Copyright 2016 Xiaofei * * 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 xiaofei.library.concurrentutils; import org.junit.Test; import xiaofei.library.concurrentutils.ObjectCanary; import xiaofei.library.concurrentutils.util.Action; import xiaofei.library.concurrentutils.util.Condition; import static org.junit.Assert.assertEquals; /** * Created by Xiaofei on 16/7/5. */ public class ActionNonBlockingTest { class A { volatile int i; } @Test public void test() throws Exception { { Condition<A> condition = new Condition<A>() { @Override public boolean satisfy(A o) { return o != null && o.i == 9; } }; ObjectCanary<A> a = new ObjectCanary<>(); for (int i = 0; i < 100; ++i) { final int tmp = i; a.actionNonBlocking(new Action<A>() { @Override public void call(A o) { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } System.out.println(tmp); } }, condition); } System.out.println("start"); A tmp = new A(); tmp.i = 9; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("set"); a.set(tmp); System.out.println("end"); } } }
<gh_stars>0 const Icon = () => { return ( <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fillRule="evenodd" imageRendering="optimizeQuality" shapeRendering="geometricPrecision" textRendering="geometricPrecision" viewBox="0 0 8268 11692" xmlSpace="preserve" className="astroSVG" > <g transform="matrix(5.15212 0 0 5.15747 -9408.358 -14342.93)"> <path d="M1524 5048v-167c186-49 359-84 518-103V3048c-172-16-345-49-518-99v-168c300 83 668 125 1104 125 437 0 805-42 1105-125v168c-174 50-347 83-519 99v1730c159 19 332 54 519 103v167c-342-90-710-134-1105-134s-763 44-1104 134zm719-282c115-13 243-19 385-19s270 6 385 19V3062c-104 7-232 11-385 11-154 0-282-4-385-11v1704z" className="fil0" ></path> </g> </svg> ); }; export default Icon;
/* * Copyright (c) 2008-2023, Hazelcast, 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. */ package com.hazelcast.internal.diagnostics; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.test.HazelcastTestSupport; import org.junit.Before; import java.io.CharArrayWriter; import java.io.File; import java.io.PrintWriter; import java.lang.reflect.Field; import static com.hazelcast.internal.nio.IOUtil.deleteQuietly; import static com.hazelcast.test.Accessors.getNodeEngineImpl; public class AbstractDiagnosticsPluginTest extends HazelcastTestSupport { protected DiagnosticsLogWriterImpl logWriter; private CharArrayWriter out; @Before public final void setupLogWriter() { logWriter = new DiagnosticsLogWriterImpl(); out = new CharArrayWriter(); logWriter.init(new PrintWriter(out)); } protected void reset() { out.reset(); } protected String getContent() { return out.toString(); } protected void assertContains(String expected) { assertContains(getContent(), expected); } protected void assertNotContains(String expected) { assertNotContains(getContent(), expected); } static Diagnostics getDiagnostics(HazelcastInstance hazelcastInstance) { NodeEngineImpl nodeEngine = getNodeEngineImpl(hazelcastInstance); try { Field field = NodeEngineImpl.class.getDeclaredField("diagnostics"); field.setAccessible(true); return (Diagnostics) field.get(nodeEngine); } catch (Exception e) { throw new RuntimeException(e); } } static void cleanupDiagnosticFiles(Diagnostics diagnostics) { if (diagnostics == null) { return; } File[] files = diagnostics.directory.listFiles(); if (files == null) { return; } for (File file : files) { String name = file.getName(); if (name.startsWith(diagnostics.baseFileName) && name.endsWith(".log")) { deleteQuietly(file); } } } }
. As supplementary material to Health Education programs about synthetic drugs, the authors present a historical summary on LSD, stramonium and khat. "Tripis", Special K and other synthetic pills contain these substances and are being widely used by youths. The history of these main hallucinogenic active ingredients has a strong tie to the mythology of witchcraft and witches: a historically interesting time period bearing a large amount of religious intolerance. The objective of this review is to end the belief today's youth have that they are taking new substances which have no risks.
<filename>frontend/csi/rest.go<gh_stars>1-10 // Copyright 2019 NetApp, Inc. All Rights Reserved. package csi import ( "bytes" "crypto/tls" "crypto/x509" "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/netapp/trident/config" "github.com/netapp/trident/utils" ) type RestClient struct { url string httpClient http.Client } func CreateTLSRestClient(url, caFile, certFile, keyFile string) (*RestClient, error) { tlsConfig := &tls.Config{} if "" != caFile { caCert, err := ioutil.ReadFile(caFile) if err != nil { return nil, err } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) tlsConfig.RootCAs = caCertPool tlsConfig.ServerName = "trident-csi" } else { tlsConfig.InsecureSkipVerify = true } if "" != certFile && "" != keyFile { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return nil, err } tlsConfig.Certificates = []tls.Certificate{cert} } return &RestClient{ url: url, httpClient: http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, }, }, nil } // InvokeAPI makes a REST call to the CSI Controller REST endpoint. The body must be a marshaled JSON byte array ( // or nil). The method is the HTTP verb (i.e. GET, POST, ...). The resource path is appended to the base URL to // identify the desired server resource; it should start with '/'. func (c *RestClient) InvokeAPI(requestBody []byte, method string, resourcePath string) (*http.Response, []byte, error) { // Build URL url := c.url + resourcePath var request *http.Request var err error var prettyRequestBuffer bytes.Buffer var prettyResponseBuffer bytes.Buffer // Create the request if requestBody == nil { request, err = http.NewRequest(method, url, nil) } else { request, err = http.NewRequest(method, url, bytes.NewBuffer(requestBody)) } if err != nil { return nil, nil, err } request.Header.Set("Content-Type", "application/json") // Log the request if requestBody != nil { if err = json.Indent(&prettyRequestBuffer, requestBody, "", " "); err != nil { return nil, nil, fmt.Errorf("error formating request body; %v", err) } } utils.LogHTTPRequest(request, prettyRequestBuffer.Bytes()) response, err := c.httpClient.Do(request) if err != nil { err = fmt.Errorf("error communicating with Trident CSI Controller; %v", err) return nil, nil, err } defer response.Body.Close() responseBody, err := ioutil.ReadAll(response.Body) if err != nil { return nil, nil, fmt.Errorf("error reading response body; %v", err) } if responseBody != nil { if err = json.Indent(&prettyResponseBuffer, responseBody, "", " "); err != nil { return nil, nil, fmt.Errorf("error formating response body; %v", err) } } utils.LogHTTPResponse(response, prettyResponseBuffer.Bytes()) return response, responseBody, err } // CreateNode registers the node with the CSI controller server func (c *RestClient) CreateNode(node *utils.Node) error { nodeData, err := json.Marshal(node) if err != nil { return fmt.Errorf("error parsing create node request; %v", err) } resp, _, err := c.InvokeAPI(nodeData, "PUT", config.NodeURL+"/"+node.Name) if err != nil { return fmt.Errorf("could not log into the Trident CSI Controller: %v", err) } if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK { return fmt.Errorf("could not add CSI node") } return nil } type ListNodesResponse struct { Nodes []string `json:"nodes"` Error string `json:"error,omitempty"` } // GetNodes returns a list of nodes registered with the controller func (c *RestClient) GetNodes() ([]string, error) { resp, respBody, err := c.InvokeAPI(nil, "GET", config.NodeURL) if err != nil { return nil, fmt.Errorf("could not log into the Trident CSI Controller: %v", err) } if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("could not list the CSI nodes") } // Parse JSON data respData := ListNodesResponse{} if err := json.Unmarshal(respBody, &respData); err != nil { return nil, fmt.Errorf("could not parse node list: %s; %v", string(respBody), err) } return respData.Nodes, nil } // DeleteNode deregisters the node with the CSI controller server func (c *RestClient) DeleteNode(name string) error { resp, _, err := c.InvokeAPI(nil, "DELETE", config.NodeURL+"/"+name) if err != nil { return fmt.Errorf("could not log into the Trident CSI Controller: %v", err) } switch resp.StatusCode { case http.StatusOK: case http.StatusNoContent: case http.StatusUnprocessableEntity: case http.StatusNotFound: case http.StatusGone: break default: return fmt.Errorf("could not delete the node") } return nil }
// // Copyright 2017 <NAME> <<EMAIL>> // // This software is supplied under the terms of the MIT License, a // copy of which should be located in the distribution where this // file was obtained (LICENSE.txt). A copy of the license may also be // found online at https://opensource.org/licenses/MIT. // // POSIX pipes. #include "core/nng_impl.h" #ifdef NNG_PLATFORM_POSIX #include <errno.h> // This implementation of notification pipes works ~everywhere on POSIX, // as it only relies on pipe() and non-blocking I/O. // So as much as we would like to use eventfd, it turns out to be completely // busted on some systems (latest Ubuntu release for example). So we go // back to the old but repliable pipe() system call. #undef NNG_USE_EVENTFD #ifdef NNG_USE_EVENTFD // Linux eventfd. This is lighter weight than pipes, and has better semantics // to boot. This is far better than say epoll(). #include <fcntl.h> #include <sys/eventfd.h> #include <unistd.h> #ifdef EFD_CLOEXEC #define NNI_EVENTFD_FLAGS EFD_CLOEXEC #else #define NNI_EVENTFD_FLAGS 0 #endif int nni_plat_pipe_open(int *wfd, int *rfd) { int fd; if ((fd = eventfd(0, NNI_EVENTFD_FLAGS)) < 0) { return (nni_plat_errno(errno)); } (void) fcntl(fd, F_SETFD, FD_CLOEXEC); (void) fcntl(fd, F_SETFL, O_NONBLOCK); *wfd = *rfd = fd; return (0); } void nni_plat_pipe_raise(int wfd) { uint64_t one = 1; (void) write(wfd, &one, sizeof(one)); } void nni_plat_pipe_clear(int rfd) { uint64_t val; (void) read(rfd, &val, sizeof(val)); } void nni_plat_pipe_close(int wfd, int rfd) { NNI_ASSERT(wfd == rfd); (void) close(wfd); } #else // NNG_USE_EVENTFD #include <fcntl.h> #include <unistd.h> int nni_plat_pipe_open(int *wfd, int *rfd) { int fds[2]; if (pipe(fds) < 0) { return (nni_plat_errno(errno)); } *wfd = fds[1]; *rfd = fds[0]; (void) fcntl(fds[0], F_SETFD, FD_CLOEXEC); (void) fcntl(fds[1], F_SETFD, FD_CLOEXEC); (void) fcntl(fds[0], F_SETFL, O_NONBLOCK); (void) fcntl(fds[1], F_SETFL, O_NONBLOCK); return (0); } void nni_plat_pipe_raise(int wfd) { char c = 1; (void) write(wfd, &c, 1); } void nni_plat_pipe_clear(int rfd) { char buf[32]; for (;;) { // Completely drain the pipe, but don't wait. This coalesces // events somewhat. if (read(rfd, buf, sizeof(buf)) <= 0) { return; } } } void nni_plat_pipe_close(int wfd, int rfd) { close(wfd); close(rfd); } #endif // NNG_USE_EVENTFD #endif // NNG_PLATFORM_POSIX
<reponame>CodeLingoBot/libbeat package elasticsearch import ( "crypto/tls" "errors" "net/url" "strings" "time" "github.com/elastic/libbeat/common" "github.com/elastic/libbeat/logp" "github.com/elastic/libbeat/outputs" "github.com/elastic/libbeat/outputs/mode" ) var debug = logp.MakeDebug("elasticsearch") var ( // ErrNotConnected indicates failure due to client having no valid connection ErrNotConnected = errors.New("not connected") // ErrJSONEncodeFailed indicates encoding failures ErrJSONEncodeFailed = errors.New("json encode failed") // ErrResponseRead indicates error parsing Elasticsearch response ErrResponseRead = errors.New("bulk item status parse failed.") ) const ( defaultMaxRetries = 3 defaultBulkSize = 50 elasticsearchDefaultTimeout = 90 * time.Second ) func init() { outputs.RegisterOutputPlugin("elasticsearch", elasticsearchOutputPlugin{}) } type elasticsearchOutputPlugin struct{} type elasticsearchOutput struct { index string mode mode.ConnectionMode topology } // NewOutput instantiates a new output plugin instance publishing to elasticsearch. func (f elasticsearchOutputPlugin) NewOutput( beat string, config *outputs.MothershipConfig, topologyExpire int, ) (outputs.Outputer, error) { // configure bulk size in config in case it is not set if config.BulkMaxSize == nil { bulkSize := defaultBulkSize config.BulkMaxSize = &bulkSize } output := &elasticsearchOutput{} err := output.init(beat, *config, topologyExpire) if err != nil { return nil, err } return output, nil } func (out *elasticsearchOutput) init( beat string, config outputs.MothershipConfig, topologyExpire int, ) error { tlsConfig, err := outputs.LoadTLSConfig(config.TLS) if err != nil { return err } clients, err := mode.MakeClients(config, makeClientFactory(beat, tlsConfig, config)) if err != nil { return err } timeout := elasticsearchDefaultTimeout if config.Timeout != 0 { timeout = time.Duration(config.Timeout) * time.Second } maxRetries := defaultMaxRetries if config.MaxRetries != nil { maxRetries = *config.MaxRetries } maxAttempts := maxRetries + 1 // maximum number of send attempts (-1 = infinite) if maxRetries < 0 { maxAttempts = 0 } var waitRetry = time.Duration(1) * time.Second var maxWaitRetry = time.Duration(60) * time.Second var m mode.ConnectionMode out.clients = clients if len(clients) == 1 { client := clients[0] m, err = mode.NewSingleConnectionMode(client, maxAttempts, waitRetry, timeout, maxWaitRetry) } else { loadBalance := config.LoadBalance == nil || *config.LoadBalance if loadBalance { m, err = mode.NewLoadBalancerMode(clients, maxAttempts, waitRetry, timeout, maxWaitRetry) } else { m, err = mode.NewFailOverConnectionMode(clients, maxAttempts, waitRetry, timeout) } } if err != nil { return err } if config.Save_topology { err := out.EnableTTL() if err != nil { logp.Err("Fail to set _ttl mapping: %s", err) // keep trying in the background go func() { for { err := out.EnableTTL() if err == nil { break } logp.Err("Fail to set _ttl mapping: %s", err) time.Sleep(5 * time.Second) } }() } } out.TopologyExpire = 15000 if topologyExpire != 0 { out.TopologyExpire = topologyExpire * 1000 // millisec } out.mode = m if config.Index != "" { out.index = config.Index } else { out.index = beat } return nil } func makeClientFactory( beat string, tls *tls.Config, config outputs.MothershipConfig, ) func(string) (mode.ProtocolClient, error) { return func(host string) (mode.ProtocolClient, error) { esURL, err := getURL(config.Protocol, config.Path, host) if err != nil { logp.Err("Invalid host param set: %s, Error: %v", host, err) return nil, err } var proxyURL *url.URL if config.ProxyURL != "" { proxyURL, err = url.Parse(config.ProxyURL) if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") { // Proxy was bogus. Try prepending "http://" to it and // see if that parses correctly. If not, we fall // through and complain about the original one. proxyURL, err = url.Parse("http://" + config.ProxyURL) if err != nil { return nil, err } } logp.Info("Using proxy URL: %s", proxyURL) } index := beat if config.Index != "" { index = config.Index } client := NewClient(esURL, index, proxyURL, tls, config.Username, config.Password) return client, nil } } func (out *elasticsearchOutput) PublishEvent( signaler outputs.Signaler, ts time.Time, event common.MapStr, ) error { return out.mode.PublishEvent(signaler, event) } func (out *elasticsearchOutput) BulkPublish( trans outputs.Signaler, ts time.Time, events []common.MapStr, ) error { return out.mode.PublishEvents(trans, events) }
/* * Compile or: as a built in. */ static int doOr() { Codenode block; int flag; genDupTOS(cstate); block = genJumpTForw(cstate); genPopTOS(cstate); flag = optimBlock(); setJumpTarget(cstate, block, 0); if (get_cur_token(tstate) == KeyKeyword) { if (strcmp(get_token_string(tstate), "ifFalse:") == 0) doIfFalse(); else if (strcmp(get_token_string(tstate), "ifTrue:") == 0) doIfTrue(); else if (strcmp(get_token_string(tstate), "or:") == 0) doOr(); else if (strcmp(get_token_string(tstate), "and:") == 0) doAnd(); } return flag; }
<reponame>foxsi/foxsi-smex """ Telescope is a module to handle the FOXSI telescopes """ from __future__ import absolute_import import pyfoxsi import pandas as pd from astropy.units import Unit import os.path import numpy as np class Optic(object): """A FOXSI Optic class definition.""" def __init__(self): path = os.path.dirname(pyfoxsi.__file__) for i in np.arange(3): path = os.path.dirname(path) path = os.path.join(path, 'data/') filename = 'shell_parameters.csv' params_file = os.path.join(path, filename) self.shell_params = pd.read_csv(params_file, index_col=0) the_units = [Unit(this_unit) for this_unit in self.shell_params.loc[np.nan].values] self.units = {} for i, col in enumerate(self.shell_params): self.units.update({col: the_units[i]}) self.shell_params.drop(self.shell_params.index[0], inplace=True) missing_shells = np.setdiff1d(self.shell_params.index, pyfoxsi.shell_ids) self.shell_params.drop(missing_shells) for col in self.shell_params.columns: self.shell_params[col] = self.shell_params[col].astype(float) def shell(self, shell_number): """Return the parameters of one shell""" try: this_shell = self.shell_params.loc[shell_number] except: ValueError('Shell %i is missing.' % shell_number) return this_shell @property def mass(self): return self.shell_params['Mass'].sum() * self.units.get("Mass")
<reponame>sinvsmae/car_crash """ cannot stop the loop wherever break is. after bang print bang twice v1 returned to the last second num. """ import math time_delta = 0.1 time_reaction = 20 def vehicle(time_now, name1, m1, v1, brakeJ1, name2, m2, v2, brakeJ2, pos2_now, gap): for i in range(time_reaction): if gap < 0.0: break else: time_now += time_delta E1 = m1 * pow(v1, 2) / 2 E1_delta = brakeJ1 / 10 print(name1, 'speed1 = '+str(v1), 'E1 = '+str(E1), 'E1_delta ='+str(E1_delta)) E1 -= E1_delta if E1 >= 0: print(name1, 'E1 = '+str(E1)) v1 = math.sqrt(2 * E1 / m1) print(name1, 'speed1 = '+str(v1), 'E1 = '+str(E1)) pos1_now = pos2_now + gap pos1_delta = time_delta * v1 pos1_now += pos1_delta print(name1, 'speed1 = '+str(v1), 'distance1 = '+str(pos1_now)) pos2_delta = time_delta * v2 pos2_now += pos2_delta print(name2, 'speed2 = '+str(v2), 'distance2 = '+str(pos2_now)) print('distance1 = '+str(pos1_now), 'distance2 = '+str(pos2_now)) gap = pos1_now - pos2_now print('gap = '+str(gap)) print('time = '+str(time_now)+'sec', name1, 'speed = ' +str(v1)+' m/s', 'distance = '+str(pos1_now)+' m', name2, 'speed = ' +str(v2)+' m/s', 'distance = '+str(pos2_now)+' m', 'gap = '+str(gap), sep = ' | ') vehicle(time_now, name1, m1, v1, brakeJ1, name2, m2, v2, brakeJ2, pos2_now, gap) print('Bang!') vehicle(time_now =0.0, name1 = 'Honda', m1 = 2500, v1 = 27, brakeJ1 = 250000, name2 = 'Toyota', m2 = 3000, v2 = 27, brakeJ2 = 450000, pos2_now = 0.0, gap = 2)
/* * MIT License * * Copyright (c) 2021 EPAM Systems * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.epam.catgenome.util.motif; import com.epam.catgenome.entity.reference.motif.Motif; import com.epam.catgenome.manager.gene.parser.StrandSerializable; import lombok.Value; import org.springframework.util.Assert; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MotifSearchIterator implements Iterator<Motif> { private static final byte CAPITAL_A = 'A'; private static final byte CAPITAL_C = 'C'; private static final byte CAPITAL_G = 'G'; private static final byte CAPITAL_T = 'T'; private static final byte CAPITAL_N = 'N'; private static final byte LOWERCASE_A = 'a'; private static final byte LOWERCASE_C = 'c'; private static final byte LOWERCASE_G = 'g'; private static final byte LOWERCASE_T = 't'; private static final byte LOWERCASE_N = 'n'; private final Deque<Match> positiveMatches; private final Deque<Match> negativeMatches; private final String contig; private final byte[] sequence; private final int offset; private final boolean includeSequence; private final int maxSizeResultLimit; public MotifSearchIterator(final byte[] seq, final String iupacRegex, final StrandSerializable strand, final String contig, final int start, final boolean includeSequence, final int searchResultSizeLimit) { if (strand != null && strand != StrandSerializable.POSITIVE && strand != StrandSerializable.NEGATIVE) { throw new IllegalStateException("Not supported strand: " + strand); } this.contig = contig; this.sequence = seq; this.offset = start; this.includeSequence = includeSequence; maxSizeResultLimit = searchResultSizeLimit; final Pattern pattern = Pattern.compile(IupacRegexConverter.convertIupacToRegex(iupacRegex), Pattern.CASE_INSENSITIVE); if (strand == null) { this.positiveMatches = populateMatches(pattern.matcher(new String(seq)), true); this.negativeMatches = populateMatches(pattern.matcher(reverseAndComplement(seq)), false); } else if (strand == StrandSerializable.POSITIVE) { this.positiveMatches = populateMatches(pattern.matcher(new String(seq)), true); this.negativeMatches = new LinkedList<>(); } else { this.positiveMatches = new LinkedList<>(); this.negativeMatches = populateMatches(pattern.matcher(reverseAndComplement(seq)), false); } } private Deque<Match> populateMatches(final Matcher matcher, final boolean positive) { int position = 0; LinkedList<Match> matches = new LinkedList<>(); while (matcher.find(position)) { matches.add(createMatch(matcher.start(), matcher.end(), positive)); position = matcher.start() + 1; Assert.isTrue(matches.size() <= maxSizeResultLimit, "Too many result, specify more concrete query. Configured max result size: " + maxSizeResultLimit); } return matches; } private Match createMatch(final int start, final int end, final boolean positive) { return positive ? new Match(start, end - 1) : new Match(sequence.length - end, sequence.length - start - 1); } @Override public boolean hasNext() { return !positiveMatches.isEmpty() || !negativeMatches.isEmpty(); } @Override public Motif next() { Match match; StrandSerializable currentStrand; if (negativeMatches.isEmpty()) { match = positiveMatches.removeFirst(); currentStrand = StrandSerializable.POSITIVE; } else if (positiveMatches.isEmpty() || negativeMatches.peekLast().start < positiveMatches.peekFirst().start) { match = negativeMatches.removeLast(); currentStrand = StrandSerializable.NEGATIVE; } else { match = positiveMatches.removeFirst(); currentStrand = StrandSerializable.POSITIVE; } if (includeSequence) { return getMotif(contig, match.start, match.end, currentStrand); } return new Motif(contig, match.start + offset, match.end + offset, currentStrand, null); } private Motif getMotif(final String contig, final int start, final int end, StrandSerializable strand) { final StringBuilder result = new StringBuilder(); for (int i = start; i <= end; i++) { result.append((char) sequence[i]); } return new Motif(contig, start + offset, end + offset, strand, result.toString()); } /** * Provides reverse complement operation on sequence string * * @param sequence nucleotide sequence * @return reversed complement nucleotide sequence string */ private static String reverseAndComplement(final byte[] sequence) { final byte[] reversedSequence = new byte[sequence.length]; for (int i = 0, j = sequence.length - 1; i < sequence.length; i++, j--) { reversedSequence[i] = complement(sequence[j]); } return new String(reversedSequence); } /** * Converts specified nucleotide to complement one. * * @param nucleotide nucleotide * @return complement nucleotide */ public static byte complement(final byte nucleotide) { switch (nucleotide) { case CAPITAL_A: case LOWERCASE_A: return CAPITAL_T; case CAPITAL_C: case LOWERCASE_C: return CAPITAL_G; case CAPITAL_G: case LOWERCASE_G: return CAPITAL_C; case CAPITAL_T: case LOWERCASE_T: return CAPITAL_A; case CAPITAL_N: case LOWERCASE_N: return CAPITAL_N; default: throw new IllegalStateException("Not supported nucleotide: " + (char)nucleotide); } } @Value public static class Match { Integer start; Integer end; } }
import java.util.*; /* Course : CPCS 202 Name : Dalia Saeed Mohammed Al-Ghamdi ID : 2006543 Section : BAR Name of lab instructor : Abeer Alhuthali , Sara Alnefaie Problem number : 5 Assignment number : 2 Codeforces ID : Dalia-131 URI ID :DALIA MOHAMMED ALGHAMDI CodeChef ID: dalia131 */ public class Problem_5 { public static void main(String[] args) { Scanner input = new Scanner(System.in); long n = input.nextLong(); long k = input.nextLong(); long mid=n/2; if(n%2 !=0){ mid++; } if(k<=mid){ System.out.printf("%d\n",2*k-1); } else{ System.out.printf("%d\n",(k-mid)*2); } } }
/** Spain national citizen card number validation. This validation algorithm is based on the official documentation. Link: http://www.interior.gob.es/web/servicios-al-ciudadano/dni/calculo-del-digito-de-control-del-nif-nie **/ impl validator::CountryValidator for SpainValidator { fn validate_id(&self, id: &str) -> bool { let standard_id = id.replace("-", "").to_uppercase(); if standard_id.len() != 9 { return false; } let control = &standard_id[standard_id.len() - 1..standard_id.len()]; let citizen = &standard_id[0..standard_id.len() - 1] .replace("X", "0") .replace("Y", "1") .replace("Z", "2") .parse::<usize>() .unwrap(); let result = citizen % 23; let validation = &CONTROL_DIGIT[result..result + 1]; return validation == control; } fn country_code(&self) -> Code { return crate::country::Code::ES; } fn extract_citizen(&self, _id: &str) -> Option<Citizen> { return None; } }
/** * A FieldPartitioner that formats a timestamp (long) in milliseconds since * epoch, such as those returned by {@link System#currentTimeMillis()}, using * {@link SimpleDateFormat}. * * @since 0.9.0 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value={ "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", "SE_COMPARATOR_SHOULD_BE_SERIALIZABLE"}, justification="False positive due to generics.") @Immutable public class DateFormatPartitioner extends FieldPartitioner<Long, String> { private static final String DEFAULT_TIME_ZONE = "UTC"; private final SimpleDateFormat format; /** * Construct a new {@link DateFormatPartitioner} for Universal Coordinated * Time, UTC (+00:00), and cardinality 1095 (3 years, 1 day = 1 partition). * @param sourceName Source field name (the field should be a long) * @param name Partition name * @param format A String format for the {@link SimpleDateFormat} constructor */ public DateFormatPartitioner(String sourceName, String name, String format) { this(sourceName, name, format, 1095, TimeZone.getTimeZone(DEFAULT_TIME_ZONE)); } /** * Construct a new {@link DateFormatPartitioner} for Universal Coordinated * Time, UTC (+00:00). * @param sourceName Source field name (the field should be a long) * @param name Partition name * @param format A String format for the {@link SimpleDateFormat} constructor * @param cardinality * A cardinality hint for the number of partitions that will be * created by this partitioner. For example, "MM-dd" produces about * 365 partitions per year. */ public DateFormatPartitioner(String sourceName, String name, String format, int cardinality, TimeZone zone) { super(sourceName, name, Long.class, String.class, cardinality); Preconditions.checkArgument(CharMatcher.is('/').matchesNoneOf(format), "Illegal format: \"/\" is not allowed (use multiple partition fields)"); this.format = new SimpleDateFormat(format); this.format.setTimeZone(zone); } public String getPattern() { return format.toPattern(); } @Override public String apply(Long value) { return format.format(new Date(value)); } @Override public Predicate<String> project(Predicate<Long> predicate) { if (predicate instanceof Exists) { return Predicates.exists(); } else if (predicate instanceof In) { return ((In<Long>) predicate).transform(this); } else if (predicate instanceof Range) { // FIXME: This project is only true in some cases // true for yyyy-MM-dd, but not dd-MM-yyyy // this is lossy, so the final range must be closed: // (2013-10-4 20:17:55, ...] => [2013-10-4, ...] return Ranges.transformClosed((Range<Long>) predicate, this); } else { return null; } } @Override public Predicate<String> projectStrict(Predicate<Long> predicate) { if (predicate instanceof Exists) { return Predicates.exists(); } else { return null; } } @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !getClass().equals(o.getClass())) { return false; } DateFormatPartitioner that = (DateFormatPartitioner) o; return Objects.equal(this.getSourceName(), that.getSourceName()) && Objects.equal(this.getName(), that.getName()) && Objects.equal(this.format, that.format) && Objects.equal(this.getCardinality(), that.getCardinality()); } @Override public int hashCode() { return Objects.hashCode(getSourceName(), getName(), format, getCardinality()); } }
<gh_stars>0 import LandingPageTwoSideContent from "./landingPageTwoSideContent"; export default LandingPageTwoSideContent;
PSYCHIATRY AND THE POLITY: THE SOVIET CASE AND SOME GENERAL IMPLICATIONS * The purpose of this communication is to discuss some problems inherent in the comparative examination of psychiatric practice in two or more cultural settings, I have chosen to focus on psychiatry in the Soviet Union because I am familiar with it, and because it represents certain interesting issues having to do with the general setting of psychiatric practice and with the importance of the polity to that setting. The implied comparative focus is with the United States. The basic point of departure is that psychiatry, unlike most other medical specialties, is primarily concerned with a symptomatology that consists of behavior. As such, this specialty is heavily involved in the evaluation of the ways in which people act, think, express affect, and interact with others. It is concerned with socially expected role performance and with the critical question of conformity/nonconformity. What we label “mental illness” is qualitatively different from, let us say, cardiovascular disease, a broken leg, or a ruptured appendix. The psychiatrist is called in primarily because someone behaves in a bizarre, unexpected, inappropriate, or abnormal manner.
/************************************************************************/ /* ImportFromESRIWisconsinWKT() */ /* */ /* Search a ESRI State Plane WKT and import it. */ /************************************************************************/ OGRErr OGRSpatialReference::ImportFromESRIWisconsinWKT( const char* prjName, double centralMeridian, double latOfOrigin, const char* unitsName, const char* csName ) { if( !prjName && !unitsName && csName ) { char codeS[10] = {}; if( FindCodeFromDict( "esri_Wisconsin_extra.wkt", csName, codeS ) != OGRERR_NONE ) return OGRERR_FAILURE; return importFromDict("esri_Wisconsin_extra.wkt", codeS); } const double* tableWISCRS = nullptr; if( prjName != nullptr && STARTS_WITH_CI(prjName, "Lambert_Conformal_Conic") ) tableWISCRS = apszWISCRS_LCC_meter; else if( prjName != nullptr && EQUAL(prjName, SRS_PT_TRANSVERSE_MERCATOR) ) tableWISCRS = apszWISCRS_TM_meter; else return OGRERR_FAILURE; int k = -1; for( int i = 0; tableWISCRS[i] != 0; i += 3 ) { if( fabs(centralMeridian - tableWISCRS[i]) <= 0.0000000001 && fabs(latOfOrigin - tableWISCRS[i+1]) <= 0.0000000001 ) { k = static_cast<int>(tableWISCRS[i+2]); break; } } if( k > 0 ) { if( unitsName != nullptr && !EQUAL(unitsName, "meters") ) k += 100; char codeS[15] = { '\0' }; snprintf(codeS, sizeof(codeS), "%d", k); return importFromDict( "esri_Wisconsin_extra.wkt", codeS); } return OGRERR_FAILURE; }
"UnKoch my campus," demanded students at nearly 30 colleges on Monday. Protests broke out across the nation as part of a campaign calling for more transparency in what industrialists Charles and David Koch give to college campuses, and how much influence the billionaires wield in academic decisions. Brothers Charles and David, who are each worth $42.7 billion and are tied at No. 4 on the Forbes 400 list of America's Richest, have poured nearly $50 million into 254 universities nationwide since 2005, according to an interactive database recently published by Greenpeace. A decade ago, the same database reports, the Kochs gave to only seven schools. Most of those gifts go towards hiring professors, building economic research centers that promote capitalism or supporting research about libertarian politics. Critics, a number of whom were protesting this week, have said that the billionaires, known for wielding influence in politics through dark money, have too much say in the school's decision-making, and infringed on professors' right to academic freedom. Students at George Mason University, who also staged protests, are demanding to know what departments and programs received portions of the $24 million donated by Koch organizations since 2005. That sum makes George Mason the largest recipient of Koch donations of any university by far, accounting for nearly half of the total funding. Though the George Mason president has said the university doesn't allow donors to sway critical decisions, Inside HigherEd reports that the students there say they deserve proof. Donations from Koch-backed foundations have been increasingly scrutinized since 2011, when officials at Florida State University revealed that a 2008 donation supporting the economics department also created a donor-approved advisory board that could veto a hiring decision. Other colleges reporting "UnKoch My Campus" student protests include Florida State and Michigan State universities. College officials can always reject a donation if they feel the gift wouldn't fit with academic programs on campus, or if they come with uncomfortable strings attached. But so far no school has publicly turned down a Koch gift.
(Photo from Flickr user thisisbossi used under Creative Commons license) The Department of Education is not doing enough to crack down on debt collection agencies that are too aggressive about seeking payments from student loan borrowers, a consumer group said Wednesday. A report from the National Consumer Law Center found that how much debt collectors are paid correlates strongly with how much they collect from people whose student loans have gone into default. It also argued that debt collectors may not always do a good job of informing people about all of the options available to them. “The incentives matter. Money matters,” says Persis Yu, a staff attorney at the center and co-author of the report. “So we need to be able to look at the contracts and make sure borrowers really are served in the best way possible.” Yu says the lower payments debt collectors receive for informing people about alternatives to payment may be steering the 22 collection agencies contracted by the government to seek payments aggressively instead of thoroughly informing consumers. For instance, agencies receive a commission projected to be up to 13 percent of the loan amount when a borrower is rehabilitated out of default to begin payments, according to the center. In contrast, the commission for getting a borrower to consolidate a loan is 2.75 percent of the loan amount. Debt collectors receive a flat fee of $150 for helping borrowers achieve another resolution, such as having the loans discharged because of a death or disability. And because debt collectors are not currently penalized for having a high number of consumer complaints, the center said the department is not doing enough to make sure that debt collectors don’t overreach in their efforts to collect payments. Yu and co-author Deanne Loonin wrote: Although the government must balance the need to collect student loans with the need to assist borrowers, the current system heavily favors high pressure debt collection and debt collector profits to the detriment of financially distressed borrowers seeking the help they so desperately need. According to the complaints cited in the study, some borrowers say they were given misinformation from debt collectors about whether they qualified for income-based repayment, loan consolidation and discharge. Other people complained about receiving multiple calls a day or being called even after they asked for the calls to stop. A look at the ratings used to evaluate and pay debt collectors shows that the more money companies collected in loan payments, the higher they scored, according to the report. (National Consumer Law Center) Meanwhile, those ratings don’t currently take into account how debt collectors treat the borrowers they’re working with. But that part of the payment system will be changing soon. After a report released in July by the department’s Office of the Inspector General found that officials were not doing enough to track and enforce complaints filed against collection agencies, the Department of Education said it would factor in such complaints when deciding how to rank and pay the companies. The changes should be in place by next March, a department official said, but it’s still not clear how much consumer complaints will lower payments because the department is in the process of adjusting its contracts with debt collectors. The department also said collection agencies are required to record their calls, which enables to department to review them to make sure companies complied with the department’s rules. Robert Foehl, vice president of ACA International, a trade association representing third-party debt collectors, said the high volume of calls and requests they make can lead to a high number of complaints, but that agencies work to resolve them quickly. Yu, of the law center, says she would like to see more information about how the department plans to incorporate consumer satisfaction information into ratings. “What we hope is that they’ll be transparent about that change,” she says, “so that we can ensure that those changes are in fact being made.”
This article is about the philosophical ability of the mind to form representations. For the related logical or semantic concept, see Intension . For the idea of doing something with a goal, see Intention Intentionality is a philosophical concept and is defined by the Stanford Encyclopedia of Philosophy as "the power of minds to be about, to represent, or to stand for, things, properties and states of affairs".[1] The once obsolete term dates from medieval scholastic philosophy, but in more recent times it has been resurrected by Franz Brentano and adopted by Edmund Husserl. The earliest theory of intentionality is associated with St. Anselm's ontological argument for the existence of God, and with his tenets distinguishing between objects that exist in the understanding and objects that exist in reality.[2] Overview [ edit ] The concept of intentionality was reintroduced in 19th-century contemporary philosophy by Franz Brentano (a German philosopher and psychologist who is generally regarded as the founder of act psychology, also called intentionalism)[3] in his work Psychology from an Empirical Standpoint (1874). Brentano described intentionality as a characteristic of all acts of consciousness that are thus "psychical" or "mental" phenomena, by which they may be set apart from "physical" or "natural" phenomena. Every mental phenomenon is characterized by what the Scholastics of the Middle Ages called the intentional (or mental) inexistence of an object, and what we might call, though not wholly unambiguously, reference to a content, direction towards an object (which is not to be understood here as meaning a thing), or immanent objectivity. Every mental phenomenon includes something as object within itself, although they do not all do so in the same way. In presentation something is presented, in judgement something is affirmed or denied, in love loved, in hate hated, in desire desired and so on. This intentional in-existence is characteristic exclusively of mental phenomena. No physical phenomenon exhibits anything like it. We could, therefore, define mental phenomena by saying that they are those phenomena which contain an object intentionally within themselves. — Franz Brentano, Psychology from an Empirical Standpoint, edited by Linda L. McAlister (London: Routledge, 1995), pp. 88–89. Brentano coined the expression "intentional inexistence" to indicate the peculiar ontological status of the contents of mental phenomena. According to some interpreters the "in-" of "in-existence" is to be read as locative, i.e. as indicating that "an intended object ... exists in or has in-existence, existing not externally but in the psychological state" (Jacquette 2004, p. 102), while others are more cautious, stating: "It is not clear whether in 1874 this ... was intended to carry any ontological commitment" (Chrudzimski and Smith 2004, p. 205). A major problem within discourse on intentionality is that participants often fail to make explicit whether or not they use the term to imply concepts such as agency or desire, i.e. whether it involves teleology. Dennett (see below) explicitly invokes teleological concepts in the "intentional stance". However, most philosophers use "intentionality" to mean something with no teleological import. Thus, a thought of a chair can be about a chair without any implication of an intention or even a belief relating to the chair. For philosophers of language, what is meant by intentionality is largely an issue of how symbols can have meaning. This lack of clarity may underpin some of the differences of view indicated below. To bear out further the diversity of sentiment evoked from the notion of intentionality, Husserl followed on Brentano, and gave the concept of intentionality more widespread attention, both in continental and analytic philosophy.[4] In contrast to Brentano's view, French philosopher Jean-Paul Sartre (Being and Nothingness) identified intentionality with consciousness, stating that the two were indistinguishable.[5] German philosopher Martin Heidegger (Being and Time), defined intentionality as "care" (Sorge), a sentient condition where an individual's existence, facticity, and being in the world identifies their ontological significance, in contrast to that which is merely ontic ("thinghood").[6] Other 20th-century philosophers such as Gilbert Ryle and A.J. Ayer were critical of Husserl's concept of intentionality and his many layers of consciousness.[7] Ryle insisted that perceiving is not a process,[8] and Ayer that describing one's knowledge is not to describe mental processes.[9] The effect of these positions is that consciousness is so fully intentional that the mental act has been emptied of all content, and that the idea of pure consciousness is that it is nothing.[10] (Sartre also referred to "consciousness" as "nothing").[11] Platonist Roderick Chisholm has revived the Brentano thesis through linguistic analysis, distinguishing two parts to Brentano's concept, the ontological aspect and the psychological aspect.[12] Chisholm's writings have attempted to summarize the suitable and unsuitable criteria of the concept since the Scholastics, arriving at a criterion of intentionality identified by the two aspects of Brentano's thesis and defined by the logical properties that distinguish language describing psychological phenomena from language describing non-psychological phenomena.[13] Chisholm's criteria for the intentional use of sentences are: existence independence, truth-value indifference, and referential opacity.[14] In current artificial intelligence and philosophy of mind, intentionality is sometimes linked with questions of semantic inference, with both skeptical and supportive adherents.[15] John Searle argued for this position with the Chinese room thought experiment, according to which no syntactic operations that occurred in a computer would provide it with semantic content.[16] Others are more skeptical of the human ability to make such an assertion, arguing that the kind of intentionality that emerges from self-organizing networks of automata will always be undecidable because it will never be possible to make our subjective introspective experience of intentionality and decision making coincide with our objective observation of the behavior of a self-organizing machine.[17] Dennett's taxonomy of current theories about intentionality [ edit ] Daniel Dennett offers a taxonomy of the current theories about intentionality in Chapter 10 of his book The Intentional Stance. Most, if not all, current theories on intentionality accept Brentano's thesis of the irreducibility of intentional idiom. From this thesis the following positions emerge: intentional idiom is problematic for science; intentional idiom is not problematic for science, which is divided into: Eliminative Materialism; Realism; Quinean double standard (see below) which is divided into: adherence to Normative Principle (epistemology), which is divided into: who makes an Assumption of Rationality; who follows the Principle of Charity; adherence to Projective Principle. Roderick Chisholm (1956), G.E.M. Anscombe (1957), Peter Geach (1957), and Charles Taylor (1964) all adhere to the former position, namely that intentional idiom is problematic and cannot be integrated with the natural sciences. Members of this category also maintain realism in regard to intentional objects, which may imply some kind of dualism (though this is debatable). The latter position, which maintains the unity of intentionality with the natural sciences, is further divided into three standpoints: Eliminative materialism , supported by W.V. Quine (1960) and Churchland (1981) , supported by W.V. Quine (1960) and Churchland (1981) Realism , advocated by Jerry Fodor (1975), as well as Burge, Dretske, Kripke, and the early Hilary Putnam , advocated by Jerry Fodor (1975), as well as Burge, Dretske, Kripke, and the early Hilary Putnam those who adhere to the Quinean double standard. Proponents of the eliminative materialism, understand intentional idiom, such as "belief", "desire", and the like, to be replaceable either with behavioristic language (e.g. Quine) or with the language of neuroscience (e.g. Churchland). Holders of realism argue that there is a deeper fact of the matter to both translation and belief attribution. In other words, manuals for translating one language into another cannot be set up in different yet behaviorally identical ways and ontologically there are intentional objects. Famously, Fodor has attempted to ground such realist claims about intentionality in a language of thought. Dennett comments on this issue, Fodor "attempt[s] to make these irreducible realities acceptable to the physical sciences by grounding them (somehow) in the 'syntax' of a system of physically realized mental representations" (Dennett 1987, 345). Those who adhere to the so-called Quinean double standard (namely that ontologically there is nothing intentional, but that the language of intentionality is indispensable), accept Quine's thesis of the indeterminacy of radical translation and its implications, while the other positions so far mentioned do not. As Quine puts it, indeterminacy of radical translation is the thesis that "manuals for translating one language into another can be set up in divergent ways, all compatible with the totality of speech dispositions, yet incompatible with one another" (Quine 1960, 27). Quine (1960) and Wilfrid Sellars (1958) both comment on this intermediary position. One such implication would be that there is, in principle, no deeper fact of the matter that could settle two interpretative strategies on what belief to attribute to a physical system. In other words, the behavior (including speech dispositions) of any physical system, in theory, could be interpreted by two different predictive strategies and both would be equally warranted in their belief attribution. This category can be seen to be a medial position between the realists and the eliminativists since it attempts to blend attributes of both into a theory of intentionality. Dennett, for example, argues in True Believers (1981) that intentional idiom (or "folk psychology") is a predictive strategy and if such a strategy successfully and voluminously predicts the actions of a physical system, then that physical system can be said to have those beliefs attributed to it. Dennett calls this predictive strategy the intentional stance. They are further divided into two theses: adherence to the Normative Principle adherence to the Projective Principle Advocates of the former, the Normative Principle, argue that attributions of intentional idioms to physical systems should be the propositional attitudes that the physical system ought to have in those circumstances (Dennett 1987, 342). However, exponents of this view are still further divided into those who make an Assumption of Rationality and those who adhere to the Principle of Charity. Dennett (1969, 1971, 1975), Cherniak (1981, 1986), and the more recent work of Putnam (1983) recommend the Assumption of Rationality, which unsurprisingly assumes that the physical system in question is rational. Donald Davidson (1967, 1973, 1974, 1985) and Lewis (1974) defend the Principle of Charity. The latter is advocated by Grandy (1973) and Stich (1980, 1981, 1983, 1984), who maintain that attributions of intentional idioms to any physical system (e.g. humans, artifacts, non-human animals, etc.) should be the propositional attitude (e.g. "belief", "desire", etc.) that one would suppose one would have in the same circumstances (Dennett 1987, 343). Basic intentionality types according to Le Morvan [ edit ] Working on the intentionality of vision, belief, and knowledge, Pierre Le Morvan (2005)[18] has distinguished between three basic kinds of intentionality that he dubs "transparent", "translucent", and "opaque" respectively. The threefold distinction may be explained as follows. Let's call the "intendum" what an intentional state is about, and the "intender" the subject who is in the intentional state. An intentional state is transparent if it satisfies the following two conditions: (i) it is genuinely relational in that it entails the existence of not just the intender but the intendum as well, and (ii) substitutivity of identicals applies to the intendum (i.e. if the intentional state is about a, and a = b, then the intentional state is about b as well). An intentional state is translucent if it satisfies (i) but not (ii). An intentional state is opaque if it satisfies neither (i) nor (ii). Mental states without intentionality [ edit ] The claim that all mental states are intentional is called intentionalism, the contrary being anti-intentionalism. Some anti-intentionalism, such as that of Ned Block, is based on the argument that phenomenal conscious experience or qualia is also a vital component of consciousness, and that it is not intentional. (The latter claim is itself disputed by Michael Tye.)[19] Another form of anti-intentionalism associated with John Searle regards phenomenality itself as the "mark of the mental" and sidelines intentionality.[20] A further form argues that some unusual states of consciousness are non-intentional, although an individual might live a lifetime without experiencing them. Robert K.C. Forman argues that some of the unusual states of consciousness typical of mystical experience are pure consciousness events in which awareness exists, but has no object, is not awareness "of" anything. Intentionality and self-consciousness [ edit ] Several authors have attempted to construct philosophical models describing how intentionality relates to the human capacity to be self-conscious. Cedric Evans contributed greatly to the discussion with his "The Subject of Self-Consciousness" in 1970. He centered his model on the idea that executive attention need not be propositional in form.[21] See also [ edit ] References [ edit ]
<filename>server_middleware.go<gh_stars>10-100 package amqprpc /* ServerMiddlewareFunc represent a function that can be used as a middleware. For example: func myMiddle(next HandlerFunc) HandlerFunc { // Preinitialization of middleware here. return func(ctx context.Context, rw *ResponseWriter d amqp.Delivery) { // Before handler execution here. // Execute the handler. next(ctx, rw, d) // After execution here. } } s := New("url") // Add middleware to specific handler. s.Bind(DirectBinding("foobar", myMiddle(HandlerFunc))) // Add middleware to all handlers on the server. s.AddMiddleware(myMiddle) */ type ServerMiddlewareFunc func(next HandlerFunc) HandlerFunc /* ServerMiddlewareChain will attatch all given middlewares to your HandlerFunc. The middlewares will be executed in the same order as your input. For example: s := New("url") s.Bind(DirectBinding( "foobar", ServerMiddlewareChain( myHandler, middlewareOne, middlewareTwo, middlewareThree, ), )) */ func ServerMiddlewareChain(next HandlerFunc, m ...ServerMiddlewareFunc) HandlerFunc { if len(m) == 0 { // The middleware chain is done. All middlewares have been applied. return next } // Nest the middlewares so that we attatch them in order. // The first middleware will have the second middleware applied, and so on. return m[0](ServerMiddlewareChain(next, m[1:]...)) }
def execute_run_grpc(api_client, instance_ref, pipeline_origin, pipeline_run): from dagster.grpc.client import DagsterGrpcClient check.inst_param(api_client, 'api_client', DagsterGrpcClient) check.inst_param(instance_ref, 'instance_ref', InstanceRef) check.inst_param(pipeline_origin, 'pipeline_origin', PipelineOrigin) check.inst_param(pipeline_run, 'pipeline_run', PipelineRun) instance = DagsterInstance.from_ref(instance_ref) yield instance.report_engine_event( 'About to start process for pipeline "{pipeline_name}" (run_id: {run_id}).'.format( pipeline_name=pipeline_run.pipeline_name, run_id=pipeline_run.run_id ), pipeline_run, engine_event_data=EngineEventData(marker_start='cli_api_subprocess_init'), ) run_did_fail = False execute_run_args = ExecuteRunArgs( pipeline_origin=pipeline_origin, pipeline_run_id=pipeline_run.run_id, instance_ref=instance_ref, ) for event in api_client.execute_run(execute_run_args=execute_run_args): if isinstance(event, IPCErrorMessage): yield instance.report_engine_event( event.message, pipeline_run=pipeline_run, engine_event_data=EngineEventData( marker_end='cli_api_subprocess_init', error=event.serializable_error_info ), ) if not run_did_fail: run_did_fail = True yield instance.report_run_failed(pipeline_run) else: yield event
/** * delayed schedule of runnable successfully executes after delay */ public void testSchedule3() throws InterruptedException { TrackedShortRunnable runnable = new TrackedShortRunnable(); ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1); p1.schedule(runnable, SMALL_DELAY_MS, MILLISECONDS); Thread.sleep(SHORT_DELAY_MS); assertFalse(runnable.done); Thread.sleep(MEDIUM_DELAY_MS); assertTrue(runnable.done); try { p1.shutdown(); } catch (SecurityException ok) { return; } joinPool(p1); }
Role of Nasal Carriage of Staphylococcus aureus in Chronic Urticaria Aim: To evaluate the role of nasal carriage of Staphylococcus aureus in patients suffering from chronic urticaria. Method: All total 82 patients were included for this study. Study group comprised 57 patients with chronic urticaria and the control group comprised 25 healthy volunteers. Nasal swab specimens were taken from all the 82 patients for bacterial culture and antimicrobial sensitivity. Patients with chronic urticaria who had positive growth for S. aureus were treated with sensitive antimicrobial agent. Nasal swab specimens were taken again from all the patients who received antimicrobial therapy to ensure complete eradication of S. aureus. All patients were followed up for a period of 6 weeks after the treatment. Urticarial activity was measured with the help of urticarial activity score. Results: S. aureus was detected in swab specimens from the nasal cavity in 32 patients in the study group and 7 patients in the control group. In the study group, after the antimicrobial treatment, 9 patients (28.12%) had complete recovery from urticaria during the follow-up period; 4 patients (12.5%) showed partial recovery from urticaria while the remaining patients (59.37%) continued to suffer from urticaria. Conclusion: This study showed that nasal carriage of S. aureus can act as an etiological factor in chronic urticaria.
#pragma once #include "../../Strategy.h" #include "../../Steps/2021/PathFinderStep.h" class PFBounceAutoStrategy : public StepStrategy { public: PFBounceAutoStrategy(std::shared_ptr<World> world) {} virtual ~PFBounceAutoStrategy() {} void Init(std::shared_ptr<World> world) override { const degree_t yaw = 0_deg; auto path = new PathFinderStep({ Target(0_ft, 2_in, 0.1, yaw, 2_in), Target(0_ft, 6_in, 0.4, yaw, 2_in), Target(0_ft, 2.5_ft, 0.6, yaw, 2_in), // First point Target(-3.0_ft, 5_ft, 0.6, yaw, 3_in), Target(-3.25_ft, 5_ft, 0.4, yaw, 3_in), Target(-3_ft, 5_ft, 0.5, yaw, 4_in), Target(-1_ft, 5_ft, 0.4, yaw, 3_in), Target(1.1_ft, 7.0_ft, 0.5, yaw, 3_in), Target(4.0_ft, 8_ft, 0.5, yaw, 3_in), Target(4.7_ft, 12.5_ft, 0.7, yaw, 4_in), // Second point Target(4.7_ft, 13.75_ft, 0.3, yaw, 3_in), Target(1_ft, 13.75_ft, 0.6, yaw, 3_in), Target(-3.25_ft, 14.25_ft, 0.7, yaw, 3_in), Target(4.0_ft, 14.75_ft, 0.7, yaw, 6_in), Target(4.75_ft, 20.00_ft, 0.7, yaw, 3_in), Target(4.75_ft, 22.25_ft, 0.5, yaw, 2_in), // Third point Target(-2.5_ft, 23.25_ft, 0.6, yaw, 4_in), Target(-3.0_ft, 23.25_ft, 0.6, yaw, 4_in), Target(-4_ft, 23.25_ft, 0.4, yaw, 3_in), // Exit // Starting to lose encoders here, so give it an extra boost Target(-0.5_ft, 24_ft, 0.6, yaw, 6_in), Target(0.0_ft, 30.0_ft, 0.5, yaw, 2_in), }); steps.push_back(path); } private: };
Relational energy and co-creation: effects on hospitality stakeholders’ wellbeing ABSTRACT Drawing from service-dominant logic and conservation of resources theory, the aim of this study was to examine the integration of relational energy as a complementary operant resource. US respondents (n = 720) participated in a scenario-based online survey depicting value co-creation at a destination resort as customers (N = 360) and front-line employees (N = 360). PROCESS Model and MANOVA results showed that in value co-creation, relational energy had direct and mediated effects on actors’ subjective wellbeing and perceptions of company competitive service advantage (PSCA). Positive appraisal of co-created value served a mediating role for actors’ wellbeing and PSCA. Generations served as a full moderator from relational energy to wellbeing, and partial moderator from co-created value (CCV) to wellbeing. No moderation effect of generations was found between CCV and PCSA, but partial moderation from relational energy to PSCA. This study is the first to identify relational energy as a resource necessary for successful co-creation that improves actors’ wellbeing.
<gh_stars>1-10 import { FixedArray, FixedArraySize, FixedReadonlyArray, isNotNull, isUndefined, isUnset, TriState, typeOrUndefined, unset, Unset } from "../utils" import { ComponentBase, defineComponent } from "./Component" import * as t from "io-ts" import { COLOR_BACKGROUND, COLOR_COMPONENT_BORDER, COLOR_MOUSE_OVER, GRID_STEP, drawWireLineToComponent, COLOR_COMPONENT_INNER_LABELS } from "../drawutils" import { ContextMenuData, ContextMenuItem, ContextMenuItemPlacement, DrawContext } from "./Drawable" import { tooltipContent, mods, div } from "../htmlgen" const GRID_WIDTH = 6 const GRID_HEIGHT = 19 const INPUT = { A: [0, 1, 2, 3] as const, B: [4, 5, 6, 7] as const, Op: 8, Mode: 9, } const OUTPUT = { S: [0, 1, 2, 3] as const, V: 4, Z: 5, } export const ALUDef = defineComponent(10, 6, t.type({ type: t.literal("alu"), showOp: typeOrUndefined(t.boolean), }, "ALU")) export type ALURepr = typeof ALUDef.reprType export type ALUOp = "add" | "sub" | "and" | "or" export const ALUOp = { shortName(op: ALUOp): string { switch (op) { case "add": return "+" case "sub": return "–" case "and": return "ET" case "or": return "OU" } }, fullName(op: ALUOp): string { switch (op) { case "add": return "Addition" case "sub": return "Soustraction" case "and": return "ET" case "or": return "OU" } }, } const ALUDefaults = { showOp: true, } export class ALU extends ComponentBase<10, 6, ALURepr, [FixedArray<TriState, 4>, TriState, TriState]> { private _showOp = ALUDefaults.showOp public constructor(savedData: ALURepr | null) { super([[false, false, false, false], false, true], savedData, { inOffsets: [ [-4, -8, "w"], [-4, -6, "w"], [-4, -4, "w"], [-4, -2, "w"], // A [-4, 2, "w"], [-4, 4, "w"], [-4, 6, "w"], [-4, 8, "w"], // B [1, -10, "n"], [-1, -10, "n"], // left: mode; right: op ], outOffsets: [ [4, -3, "e"], [4, -1, "e"], [4, 1, "e"], [4, 3, "e"], // Y [-1, 10, "s"], // V [1, 10, "s"], // Z ], }) if (isNotNull(savedData)) { this._showOp = savedData.showOp ?? ALUDefaults.showOp } } toJSON() { return { type: "alu" as const, ...this.toJSONBase(), showOp: (this._showOp !== ALUDefaults.showOp) ? this._showOp : undefined, } } public get componentType() { return "ic" as const } override getInputName(i: number): string | undefined { if (i <= INPUT.A[INPUT.A.length - 1]) { return "A" + i } if (i <= INPUT.B[INPUT.B.length - 1]) { return "B" + (i - INPUT.B[0]) } if (i === INPUT.Op) { return "Op" } if (i === INPUT.Mode) { return "Mode" } return undefined } override getOutputName(i: number): string | undefined { if (i <= OUTPUT.S[OUTPUT.S.length - 1]) { return "S" + i } if (i === OUTPUT.V) { return "V (oVerflow)" } if (i === OUTPUT.Z) { return "Z (Zero)" } return undefined } get unrotatedWidth() { return GRID_WIDTH * GRID_STEP } get unrotatedHeight() { return GRID_HEIGHT * GRID_STEP } public override makeTooltip() { const op = this.op const opDesc = isUnset(op) ? "une opération inconnue" : "l’opération " + ALUOp.fullName(op) return tooltipContent("Unité arithmétique et logique (ALU)", mods( div(`Effectue actuellement ${opDesc}.`) )) } private inputValues = <N extends FixedArraySize>(inds: FixedReadonlyArray<number, N>): FixedArray<TriState, N> => { return inds.map(i => this.inputs[i].value) as any as FixedArray<TriState, N> } public get op(): ALUOp | unset { const mode = this.inputs[INPUT.Mode].value const op = this.inputs[INPUT.Op].value switch (mode) { case false: // arithmetic switch (op) { case false: // 00 return "add" case true: // 01 return "sub" case "?": return Unset } break case true: // logic switch (op) { case false: // 10 return "or" // opcode logic: "only one 1 needed" case true: // 11 return "and"// opcode logic: "two 1s needed" case "?": return Unset } break case "?": return Unset } } protected doRecalcValue(): [FixedArray<TriState, 4>, TriState, TriState] { const op = this.op if (isUnset(op)) { return [[Unset, Unset, Unset, Unset], Unset, Unset] } const a = this.inputValues<4>(INPUT.A) const b = this.inputValues<4>(INPUT.B) function allZeros(vals: TriState[]): TriState { for (const v of vals) { if (isUnset(v)) { return Unset } if (v) { return false } } return true } const y: TriState[] = [Unset, Unset, Unset, Unset] let v: TriState = Unset switch (op) { case "add": { const sum3bits = (a: TriState, b: TriState, c: TriState): [TriState, TriState] => { const asNumber = (v: TriState) => v === true ? 1 : 0 const numUnset = (isUnset(a) ? 1 : 0) + (isUnset(b) ? 1 : 0) + (isUnset(c) ? 1 : 0) const sum = asNumber(a) + asNumber(b) + asNumber(c) if (numUnset === 0) { // we know exactly return [sum % 2 === 1, sum >= 2] } if (numUnset === 1 && sum >= 2) { // carry will always be set return [Unset, true] } // At this point, could be anything return [Unset, Unset] } let cin: TriState = false for (let i = 0; i < a.length; i++) { const [s, cout] = sum3bits(cin, a[i], b[i]) y[i] = s cin = cout } v = cin break } case "sub": { const toInt = (vs: readonly TriState[]): number | undefined => { let s = 0 let col = 1 for (const v of vs) { if (isUnset(v)) { return undefined } s += Number(v) * col col *= 2 } return s } const aInt = toInt(a) const bInt = toInt(b) if (!isUndefined(aInt) && !isUndefined(bInt)) { // otherwise, stick with default Unset values everywhere let yInt = aInt - bInt // console.log(`${aInt} - ${bInt} = ${yInt}`) // we can get anything from (max - (-min)) = 7 - (-8) = 15 // to (min - max) = -8 - 7 = -15 if (yInt < 0) { yInt += 16 } // now we have everything between 0 and 15 const yBinStr = (yInt >>> 0).toString(2).padStart(4, '0') for (let i = 0; i < 4; i++) { y[i] = yBinStr[3 - i] === '1' } v = bInt > aInt } break } // below, we need the '=== true' and '=== false' parts // to distinguish also the Unset case case "and": { for (let i = 0; i < a.length; i++) { if (a[i] === false || b[i] === false) { y[i] = false } else if (a[i] === true && b[i] === true) { y[i] = true } else { y[i] = Unset } } v = false break } case "or": { for (let i = 0; i < a.length; i++) { if (a[i] === true || b[i] === true) { y[i] = true } else if (a[i] === false && b[i] === false) { y[i] = false } else { y[i] = Unset } } v = false break } } const z = allZeros(y) return [y as any as FixedArray<TriState, 4>, v, z] } protected override propagateNewValue(newValue: [FixedArray<TriState, 4>, TriState, TriState]) { for (let i = 0; i < OUTPUT.S.length; i++) { this.outputs[OUTPUT.S[i]].value = newValue[0][i] } this.outputs[OUTPUT.V].value = newValue[1] this.outputs[OUTPUT.Z].value = newValue[2] } doDraw(g: CanvasRenderingContext2D, ctx: DrawContext) { const width = GRID_WIDTH * GRID_STEP const height = GRID_HEIGHT * GRID_STEP const left = this.posX - width / 2 const right = this.posX + width / 2 const top = this.posY - height / 2 const bottom = this.posY + height / 2 // inputs for (let i = 0; i < INPUT.A.length; i++) { const inputi = this.inputs[INPUT.A[i]] drawWireLineToComponent(g, inputi, left, inputi.posYInParentTransform) } for (let i = 0; i < INPUT.B.length; i++) { const inputi = this.inputs[INPUT.B[i]] drawWireLineToComponent(g, inputi, left, inputi.posYInParentTransform) } drawWireLineToComponent(g, this.inputs[INPUT.Mode], this.inputs[INPUT.Mode].posXInParentTransform, top + 6) drawWireLineToComponent(g, this.inputs[INPUT.Op], this.inputs[INPUT.Op].posXInParentTransform, top + 13) // outputs for (let i = 0; i < OUTPUT.S.length; i++) { const outputi = this.outputs[OUTPUT.S[i]] drawWireLineToComponent(g, outputi, right, outputi.posYInParentTransform) } drawWireLineToComponent(g, this.outputs[OUTPUT.V], this.outputs[OUTPUT.V].posXInParentTransform, bottom - 6) drawWireLineToComponent(g, this.outputs[OUTPUT.Z], this.outputs[OUTPUT.Z].posXInParentTransform, bottom - 13) // outline g.fillStyle = COLOR_BACKGROUND g.lineWidth = 3 if (ctx.isMouseOver) { g.strokeStyle = COLOR_MOUSE_OVER } else { g.strokeStyle = COLOR_COMPONENT_BORDER } g.beginPath() g.moveTo(left, top) g.lineTo(right, top + 2 * GRID_STEP) g.lineTo(right, bottom - 2 * GRID_STEP) g.lineTo(left, bottom) g.lineTo(left, this.posY + 1 * GRID_STEP) g.lineTo(left + 2 * GRID_STEP, this.posY) g.lineTo(left, this.posY - 1 * GRID_STEP) g.closePath() g.fill() g.stroke() ctx.inNonTransformedFrame(ctx => { g.fillStyle = COLOR_COMPONENT_INNER_LABELS g.font = "bold 12px sans-serif" let opNameOffset: number let vOffset: number let zOffset: number let mOffset: number let opOffset: number [g.textAlign, opNameOffset, vOffset, zOffset, mOffset, opOffset] = (() => { switch (this.orient) { case "e": case "w": return ["center", 22, 15, 22, 17, 24] as const case "s": return ["right", 14, 19, 25, 13, 19] as const case "n": return ["left", 14, 19, 25, 13, 19] as const } })() g.font = "12px sans-serif" g.fillText("M", ...ctx.rotatePoint(this.posX - GRID_STEP, top + mOffset)) g.fillText("Op", ...ctx.rotatePoint(this.posX + GRID_STEP, top + opOffset)) g.fillText("V", ...ctx.rotatePoint(this.posX - GRID_STEP, bottom - vOffset)) g.fillText("Z", ...ctx.rotatePoint(this.posX + GRID_STEP, bottom - zOffset)) g.font = "bold 14px sans-serif" g.fillText("A", ...ctx.rotatePoint(this.posX - 20, top + 4 * GRID_STEP + 6)) g.fillText("B", ...ctx.rotatePoint(this.posX - 20, bottom - 4 * GRID_STEP - 6)) g.fillText("S", ...ctx.rotatePoint(this.posX + 21, this.posY)) if (this._showOp) { const opName = isUnset(this.op) ? "???" : ALUOp.shortName(this.op) const size = 25 - 13 * (opName.length - 1) g.font = `bold ${size}px sans-serif` g.fillStyle = COLOR_COMPONENT_BORDER g.fillText(opName, this.posX + 4, this.posY) } }) } private doSetShowOp(showOp: boolean) { this._showOp = showOp this.setNeedsRedraw("show op changed") } protected override makeComponentSpecificContextMenuItems(): undefined | [ContextMenuItemPlacement, ContextMenuItem][] { const icon = this._showOp ? "check" : "none" const toggleShowOpItem = ContextMenuData.item(icon, "Afficher l’opération", () => { this.doSetShowOp(!this._showOp) }) return [ ["mid", toggleShowOpItem], ["mid", this.makeForceOutputsContextMenuItem()!], ] } }
def add_to_ignorelist(self, to_ignore): to_ignore = [to_ignore] if isinstance(to_ignore, str) else to_ignore self._ignore = list(self._ignore) [self._ignore.append(i) for i in to_ignore] self._ignore = set(self._ignore) self._ignore = tuple(self._ignore)
The Role of Extracellular Matrix Proteins in the Control of Phagocytosis The phagocytic function of human‐peripheral‐blood‐derived mononuclear and polymorphonuclear leukocytes can be regulated by external stimuli. In particular, the extracellular matrix (ECM) proteins fibronectin and laminin and serum amyloid P component can increase the phagocytic activity of these cells. Phagocytosis enhancement by the ECM requires two distinct signals to the ingesting cell. First, a ligand for interaction of the target particle with phagocytic cells is required. Generally this occurs because of opsonins such as antibody or complement on the phagocytic target and is independent of the ECM proteins. The phagocytosis‐enhancing effect of the connective tissue proteins also requires direct interaction of these proteins with phagocytic cells and occurs through cell surface receptors for these molecules. In the case of neutrophils, sensitivity to the phagocytosis‐enhancing effects of connective tissue proteins requires prior stimulation with the chemotactic peptides C5a or f‐met‐leu‐phe. The present state or knowledge of the mechanism of phagocytosis enhancement by ECM proteins and the implications of the phenomenon for host defense are discussed.
package types var ( EventTypeRegisterWrkChain = RegisterAction EventTypeRecordWrkChainBlock = RecordAction AttributeValueCategory = ModuleName AttributeKeyOwner = "wrkchain_owner" AttributeKeyWrkChainId = "wrkchain_id" AttributeKeyWrkChainMoniker = "wrkchain_moniker" AttributeKeyWrkChainName = "wrkchain_name" AttributeKeyWrkChainGenesisHash = "wrkchain_genesis_hash" AttributeKeyBaseType = "wrkchain_base_type" AttributeKeyBlockHash = "wrkchain_block_hash" AttributeKeyBlockHeight = "wrkchain_block_height" AttributeKeyParentHash = "wrkchain_parent_hash" AttributeKeyHash1 = "wrkchain_hash1" AttributeKeyHash2 = "wrkchain_hash2" AttributeKeyHash3 = "wrkchain_hash3" )
/** * Execute the given task. If given task is not {@link Preemptable}, it will * preempt all outstanding preemptable tasks. */ public <P> void execute(AsyncTask<P, ?, ?> task, P... params) { if (task instanceof Preemptable) { synchronized (mPreemptable) { mPreemptable.add(new WeakReference<Preemptable>((Preemptable) task)); } task.executeOnExecutor(mNonPreemptingExecutor, params); } else { task.executeOnExecutor(this, params); } }
def update_single_repository(self, repo): if not type(repo) == Repository: return False msgt('Repository update: %s' % repo) repo_api_url = repo.get_github_api_url() request_auth = (self.github_username, self.get_api_key(repo)) msg('repo_api_url: %s' % repo_api_url) r = requests.get(repo_api_url, auth=request_auth) msg('Staus code: %s' % r.status_code) if not r.status_code == 200: err_msg = self.format_failed_response_err_msg(\ 'Bad status code. Update of repository description failed'\ , repo , repo_api_url , r) self.send_admin_error_email(err_msg) return False try: repo_dict = r.json() except: err_msg = self.format_failed_response_err_msg(\ 'r.json() failed. Update of repository description failed'\ , repo , repo_api_url , r) self.send_admin_error_email(err_msg) return False attributes_to_update = dict(description='description'\ , homepage='homepage'\ , private='is_private' , id='github_id') msg(attributes_to_update) for github_key, repo_key in attributes_to_update.items(): if repo_dict.has_key(github_key): val = repo_dict.get(github_key, '') if val is None: val = '' repo.__dict__[repo_key] = val repo.save() return True
def compute_gradient_penalty(discriminator: Callable, real_samples: Tensor, fake_samples: Tensor): device = real_samples.device alpha = torch.Tensor(np.random.random((real_samples.size(0), 1, 1, 1))).to(device) interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True) interpolates = interpolates.to(device) interpolates.requires_grad_(True) if interpolates.grad is not None: interpolates.grad.zero_() d_interpolates = discriminator(interpolates) d_interpolates.backward(torch.ones_like(d_interpolates).to(device)) gradients = interpolates.grad.data gradients = gradients.view(gradients.size(0), -1).to(device) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() return gradient_penalty
/** * Returns a Map that represents a mapping from every Clazz in the ClassPool * to its original name. This can be useful to retrieve the original name * of classes after name obfuscation has been applied. */ public Map<Clazz, String> reverseMapping() { Map<Clazz, String> reversedMap = new HashMap<Clazz, String>(classes.size()); for (String originalClassName : classes.keySet()) { Clazz processedClazz = classes.get(originalClassName); reversedMap.put(processedClazz, originalClassName); } return reversedMap; }
package example import ( "fmt" "math" ) func Example_float() { var maxFloat32 float32 = math.MaxFloat32 var minFloat32 float32 = math.SmallestNonzeroFloat32 var maxFloat64 float64 = math.MaxFloat64 var minFloat64 float64 = math.SmallestNonzeroFloat64 fmt.Printf("max float32: %v\n", maxFloat32) fmt.Printf("min float32: %v\n", minFloat32) fmt.Printf("max float64: %v\n", maxFloat64) fmt.Printf("min float64: %v\n", minFloat64) pi := math.Pi fmt.Printf("pi: %v\n", pi) var one = 1.0 fmt.Printf("one: %v\n", one) fmt.Printf("one+one: %v\n", one+one) fmt.Printf("one*one: %v\n", one*one) fmt.Printf("one==one: %v\n", one == one) // Output: // max float32: 3.4028235e+38 // min float32: 1e-45 // max float64: 1.7976931348623157e+308 // min float64: 5e-324 // pi: 3.141592653589793 // one: 1 // one+one: 2 // one*one: 1 // one==one: true }
/** * @author Antonio Prota */ public class CpuFrequency { private int cpuId; private int time; private int value; public int getCore() { return cpuId; } void setCpuId(int cpuId) { this.cpuId = cpuId; } /** * @return the time */ public int getTime() { return time; } /** * @param time the time to set */ public void setTime(int time) { this.time = time; } /** * @return the value */ public int getValue() { return value; } /** * @param value the value to set */ void setValue(int value) { this.value = value; } }
/** * Convert file. * * @param file the file * @return the file * @throws IllegalStateException the illegal state exception * @throws IOException the io exception */ public static File convert(MultipartFile file) throws IOException { FileOutputStream fos = null; try { File convFile = new File(file.getOriginalFilename()); fos = new FileOutputStream(convFile); fos.write(file.getBytes()); return convFile; } catch (Exception e) { LOGGER.error(e.getMessage()); return null; } finally { if (fos != null) { fos.close(); } } }
// Returns the given flag string (adjusting any capitalization differences), // if a valid flag was given. Else, return the empty string. func VerifyNormalizeFlag(flagStr string) string { flagLower := strings.ToLower(flagStr) value, ok := hmsFlagMap[flagLower] if ok != true { return "" } else { return value.String() } }
/************************************************************ // reads the next spectrum into spec // returns false if no more spectra are available // returns the mgf_pointer through mp, if file = -1 this means // this was a dta *************************************************************/ bool FileSet::get_next_spectrum(const FileManager& fm, Config *config, Spectrum *spec, SingleSpectrumFile **ssfp, bool perform_init_spectrum, bool set_charge_to_zero) { SingleSpectrumFile *ssf; if (next_ssf_pointer < ssf_pointers.size()) { ssf = ssf_pointers[next_ssf_pointer++]; if (ssfp) *ssfp=ssf; if (ssf->type == DTA) { if (set_charge_to_zero) { spec->read_from_dta(config,ssf->single_name.c_str(),0); } else spec->read_from_dta(config,ssf->single_name.c_str()); if (perform_init_spectrum) spec->initializeSpectrum(ssf); return true; } else if (ssf->type == MGF) { if (this->current_mgf_file_idx != ssf->file_idx) { if (mgf_stream) fclose(mgf_stream); mgf_stream=fopen(fm.mgf_files[ssf->file_idx].mgf_name.c_str(),"r"); if (! mgf_stream) { cout << "Error: Couldn't open file for reading: " << fm.mgf_files[ssf->file_idx].mgf_name << endl; exit(1); } this->current_mgf_file_idx = ssf->file_idx; } if ( fseek(mgf_stream,ssf->file_pos,0) ) { cout << "Error: could not skip in file!" << endl; exit(1); } spec->read_from_MGF_stream(config,mgf_stream); if (perform_init_spectrum) spec->initializeSpectrum(ssf); return true; } else { cout << "Error: invalid file type:" << ssf->type << endl; exit(1); } } else return false; }
Painlevé analysis of Fokas–Lenells equation with fractal temporal evolution This paper presents new optical solitons of a fractal Fokas–Lenells equation that models the dynamics of optical fibers. The Painlevé technique is employed to identify kink soliton solutions. The constraint conditions guarantee the existence of these solitons. The outcomes of this research give new solutions that are not achieved using some already defined algorithms. The derived method is efficient and its applications are promising for other nonlinear problems. The 3D graphical illustrations of obtained results are depicted for various values of the fractal parameter.
/** * Resolves enough of the result set to return the {@link Entity} at the specified {@code index}. * There is no guarantee that the result set actually has an {@link Entity} at this index, but * it's up to the caller to recognize this and respond appropriately. * * @param index The index to which we need to resolve. * @param fetchAll If {@code true}, ignores the provided index and fetches all data. */ private void resolveToIndex(int index, boolean fetchAll) { if (cleared) { return; } forceResolveToIndex(index, fetchAll); }
The ballooning posterior leaflet syndrome: Minnesota Multiphasic Personality Inventory profiles in symptomatic and asymptomatic groups. Due to a complex of vague symptoms in some patients with a ballooning posterior leaflet (BPL), a standardized personality inventory test (MMPI) was given to 14 patients exhibiting a midsystolic click and/or late systolic murmur and a positive echocardiogram for a BPL. Seven of the eight symptom-free patients had normal MMPIs. Of the six symptomatic patients, five had abnormal scores for hysteria and hypochondriasis, four abnormal scores for depression, psychopathic deviate and schizophrenia, and three abnormal scores for psychasthenia. Of these six patients, two have been resuscitated from a near-fatal arrhythmia and two have frequent premature ventricular contractions (PVCs). Since those patients with life-threatening arrhythmias showed at least four abnormal MMPI scales, it is postulated that an abnormal MMPI in a person with the BPL syndrome portends a greater risk for a potentially fatal arrhythmia. The presence of normal MMPIs in four symptomatic patients with aortic stenosis suggests that life-threatening symptoms per se do not account for the abnormalities found in patients with the BPL syndrome.
Entertainment Weekly is reporting—in a piece that doesn’t offer much in the way of further detail—that Harry Shearer will return to The Simpsons for the next two seasons, nearly two months after very publicly exiting the show. The dispute was supposedly never about money, of which there is a massive amount for the voice cast, but about some nebulous definition of Shearer’s freedom to do other projects. (Showrunner Al Jean countered that Shearer actually records his parts—including Mr. Burns, Flanders, and too many more to count—on the phone, so he ought to have plenty of free time.) Well, for the next two seasons at least, we don’t have to worry about suffering the indignity of replacing his essentially irreplaceable voice, or suffer through a thousand before-and-after-Shearer analyses. UPDATE: The show confirmed Shearer’s return on Twitter:
/* * File: umbrella_spce_hamiltonian.h * Author: <NAME> * * Created on February 1, 2012, 3:56 PM */ #ifndef UMBRELLA_SPCE_HAMILTONIAN_H #define UMBRELLA_SPCE_HAMILTONIAN_H class UmbrellaSPCEHamiltonian : public SPCEHamiltonian { private: double &WINDOW_LOWER_BOUND, &WINDOW_UPPER_BOUND; bool OVER_THE_WINDOW; virtual double energy_between_two_ions(int i, int j, WHICH_TYPE typ); public: UmbrellaSPCEHamiltonian(WaterSystem &sys); ~UmbrellaSPCEHamiltonian(); virtual void initialize_calculations(); virtual double total_energy_difference(); virtual void undo_calculations(); }; #endif /* UMBRELLA_SPCE_HAMILTONIAN_H */
Take a look at Houston, where Medicare patients are a big business. Medicare spent $11,567 on each enrollee in the Houston area in 2010, according to the Dartmouth Atlas, putting it well ahead of the national average of $9,584. It’s also the city where John McCarthy has practiced hematology for nearly three decades. Or, as he is known to me, Uncle John. He was the first person I reached out to on this topic because he always loves a good, heated health care debate. "Quality and quantity metrics are business speak, this pseudonymous lingo that is being used to talk about rationing. Some of it is good, but a lot of it is hocus pocus," he told me almost immediately when I called him. Doctors, for the most part, he argues, have always used the best evidence for treating their patients. “We take vital signs every time a patient comes in to our office. Now we have to report them to the government. But in 90 percent of my patients, their blood pressure issues are managed by other doctors, such as their primary care physician or a cardiologist. But we still have to record it, even though it doesn’t measure the quality of my assessment of the patients’ blood disorder. So we spend a little time on every patient checking off boxes that are simply misused or misunderstood by the government,” McCarthy said. And that time adds up. A 2013 Medscape survey of more than 20,000 physicians found that 51 percent spent 5 to 14 hours per week on paperwork. That figure was up from 23 percent in 2012. McCarthy points to a quality measure used within his own field, backed by the federal government, that he believes is not in his patients’ best interest. Whenever a patient presents with a certain type of low blood count, it is now a recommended government quality measure to order a bone marrow test. But McCarthy says he and other hematologists can often tell that it’s too early to do this test, making it simply unnecessary. “It’s not going to kill people to do bone marrow tests. In fact it makes money for me. It’s not the worst thing in the world, it’s incredibly safe,” says McCarthy. “But if we do one for a mildly normal blood count, we just end up having to do it again later when any treatment is necessary. That is requiring two bone marrow tests where one would do. It’s a hardship on patients.” In the end, McCarthy is not opposed to all metrics. He just doesn’t have much faith that the government can get them right. His longtime friend, internist Christopher Robben, is more of a believer. Robben is the chief quality officer for a physician group with more than 300 doctors of various specialties in Houston. Tracking health metrics is something he’s had a longstanding interest in. Robben was creating Excel spreadsheets in the 1990s to track how his patients with chronic illnesses responded to different treatments. He is actively working with his group now to implement the existing federal quality tracking programs. And Robben is a fan of Donald Berwick, the former Centers for Medicare and Medicaid Services administrator who somewhat of a modern-day Moses of the quality health metrics movement.
/** * Stores properties details of a query class. * * @author Kamran Ali Khan ([email protected]) * * @param <T> */ public class QueryBean extends AbstractBean { public QueryBean(Class<?> type) throws IntrospectionException { super(type, null, null); } }
// test che verifica il corretto numero di regioni del gioco: 8 @Test public void testCorrectNumberOfRegion(){ Setup setup = new Setup(); try{ setup.loadCard("test.json"); }catch(Exception e){} board = new Board(); assertEquals(8, board.getRegionMap().size()); }
import Item from '../item/item'; import ItemFactory from '../item/item_factory'; import { reduce } from '../reduce/reduce'; import ItemStackIterator from './stack_iterator'; export default class ItemStack<T> { private stack: Array<Item<T>> = []; private factory: ItemFactory<T>; constructor(factory: ItemFactory<T>, ...items: T[]) { this.factory = factory; this.add(...items); } public add(...items: T[]): void { if (items.length === 1) { const item: Item<T> = this.factory.new(items[0]); this.stack = this.stack.concat(item.isSome ? [item] : []); } else if (items.length > 1) { this.stack = this.stack.concat(this.sanitize(items)); } } public eject(): Array<Item<T>> { return this.stack; } public iterator(): ItemStackIterator<T> { return new ItemStackIterator<T>(this); } public getItem(index: number): Item<T> { return this.stack[index]; } public get length(): number { return this.stack.length; } private sanitize(array: T[]): Array<Item<T>> { return reduce( (acc: Array<Item<T>>, con: T): Array<Item<T>> => { const item: Item<T> = this.factory.new(con); if (item.isSome) { return acc.concat([item]); } else { return acc; } }, [], array, ); } }
<reponame>dkishere2021/scrape import logging import os DbDateFormat = "%Y-%m-%d %H:%M:%S %z" # Logger Configuration (scrapeNews) logger = logging.getLogger("scrapeNews") handler = logging.FileHandler('scrapeNews.log') formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s [Line %(lineno)d] %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.ERROR) #DATABASE CONFIG try: DB_INFO = { "host": os.environ['SCRAPER_DB_HOST'], "name": os.environ['SCRAPER_DB_NAME'], "user": os.environ['SCRAPER_DB_USER'], "password": <PASSWORD>['<PASSWORD>'] } except KeyError as e: logger.critical("KeyError: "+str(e) + " not found") exit()
// Copyright 2019 The MWC Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "s_adjuststatedlg.h" #include "ui_s_adjuststatedlg.h" #include "../bridge/wnd/swap_b.h" namespace dlg { AdjustStateDlg::AdjustStateDlg(QWidget * parent, QString _tradeId) : control::MwcDialog(parent), ui(new Ui::AdjustStateDlg), tradeId(_tradeId) { ui->setupUi(this); swap = new bridge::Swap(this); ui->title->setText("Adjust " + tradeId); ui->statesComboBox->addItem("SellerOfferCreated", QVariant("SellerOfferCreated")); ui->statesComboBox->addItem("SellerSendingOffer", QVariant("SellerSendingOffer")); ui->statesComboBox->addItem("SellerWaitingForAcceptanceMessage", QVariant("SellerWaitingForAcceptanceMessage")); ui->statesComboBox->addItem("SellerWaitingForBuyerLock", QVariant("SellerWaitingForBuyerLock")); ui->statesComboBox->addItem("SellerPostingLockMwcSlate", QVariant("SellerPostingLockMwcSlate")); ui->statesComboBox->addItem("SellerWaitingForLockConfirmations", QVariant("SellerWaitingForLockConfirmations" )); ui->statesComboBox->addItem("SellerWaitingForInitRedeemMessage", QVariant("SellerWaitingForInitRedeemMessage")); ui->statesComboBox->addItem("SellerSendingInitRedeemMessage", QVariant("SellerSendingInitRedeemMessage")); ui->statesComboBox->addItem("SellerWaitingForBuyerToRedeemMwc", QVariant("SellerWaitingForBuyerToRedeemMwc")); ui->statesComboBox->addItem("SellerRedeemSecondaryCurrency", QVariant("SellerRedeemSecondaryCurrency")); ui->statesComboBox->addItem("SellerWaitingForRedeemConfirmations", QVariant("SellerWaitingForRedeemConfirmations")); ui->statesComboBox->addItem("SellerSwapComplete", QVariant("SellerSwapComplete")); ui->statesComboBox->addItem("SellerWaitingForRefundHeight", QVariant("SellerWaitingForRefundHeight")); ui->statesComboBox->addItem("SellerPostingRefundSlate", QVariant("SellerPostingRefundSlate")); ui->statesComboBox->addItem("SellerWaitingForRefundConfirmations", QVariant("SellerWaitingForRefundConfirmations")); ui->statesComboBox->addItem("SellerCancelledRefunded", QVariant("SellerCancelledRefunded")); ui->statesComboBox->addItem("SellerCancelled", QVariant("SellerCancelled")); ui->statesComboBox->addItem("BuyerOfferCreated", QVariant("BuyerOfferCreated")); ui->statesComboBox->addItem("BuyerSendingAcceptOfferMessage", QVariant("BuyerSendingAcceptOfferMessage")); ui->statesComboBox->addItem("BuyerWaitingForSellerToLock", QVariant("BuyerWaitingForSellerToLock")); ui->statesComboBox->addItem("BuyerPostingSecondaryToMultisigAccount", QVariant("BuyerPostingSecondaryToMultisigAccount")); ui->statesComboBox->addItem("BuyerWaitingForLockConfirmations", QVariant("BuyerWaitingForLockConfirmations")); ui->statesComboBox->addItem("BuyerSendingInitRedeemMessage", QVariant("BuyerSendingInitRedeemMessage")); ui->statesComboBox->addItem("BuyerWaitingForRespondRedeemMessage", QVariant("BuyerWaitingForRespondRedeemMessage")); ui->statesComboBox->addItem("BuyerRedeemMwc", QVariant("BuyerRedeemMwc")); ui->statesComboBox->addItem("BuyerWaitForRedeemMwcConfirmations", QVariant("BuyerWaitForRedeemMwcConfirmations")); ui->statesComboBox->addItem("BuyerSwapComplete", QVariant("BuyerSwapComplete")); ui->statesComboBox->addItem("BuyerWaitingForRefundTime", QVariant("BuyerWaitingForRefundTime")); ui->statesComboBox->addItem("BuyerPostingRefundForSecondary", QVariant("BuyerPostingRefundForSecondary")); ui->statesComboBox->addItem("BuyerWaitingForRefundConfirmations", QVariant("BuyerWaitingForRefundConfirmations")); ui->statesComboBox->addItem("BuyerCancelledRefunded", QVariant("BuyerCancelledRefunded")); ui->statesComboBox->addItem("BuyerCancelled", QVariant("BuyerCancelled")); } AdjustStateDlg::~AdjustStateDlg() { delete ui; } void AdjustStateDlg::on_applyButton_clicked() { if (ui->statesComboBox->currentIndex()<0) return; QString selectedState = ui->statesComboBox->currentData().toString(); if (selectedState.isEmpty()) return; swap->adjustTradeState( tradeId, selectedState ); accept(); } void AdjustStateDlg::on_cancelButton_clicked() { reject(); } }
/** * Tries to connect to the TV. * * @return Whether the connection was successful. */ private boolean connect() { try { if (mSocket.isConnected()) { resetSocketAndStreams(); } try { mSocket.connect(mInetSocketAddress, SO_TIMEOUT); } catch (SocketException ex) { log.atWarning().log("Failed to connect to TV, retrying ..."); resetSocketAndStreams(); mSocket.connect(mInetSocketAddress, SO_TIMEOUT); } mSocket.setSoTimeout(SO_TIMEOUT); mOut = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())); mIn = new BufferedReader(new InputStreamReader(mSocket.getInputStream())); mSocketStreamCloseable.add(mOut, mIn); return true; } catch (IOException ex) { log.atWarning().withCause(ex).log("Cannot connect to TV"); return false; } }
Microdrill with variations in thickness of diamond coating In this study, microcrystalline diamond films with varied thicknesses (1·2, 2·5, 4 and 7 μm) are deposited on flat samples and microdrills. The Raman results show that the top layer of thicker diamond films on flat samples exhibit relatively lower compressive residual stress and favourable diamond purity. However, with increased thickness, the multiple radial and diagonal microcracks along with significant diamond coating detachment are easier to be formed in thicker diamond coatings. These results can be applied for analysing the mechanisms on the coating delamination for the thicker diamond coatings and the worse wear resistance for the thinner ones deposited on microdrills during graphite machining processes. The microcrystalline diamond coated microdrill with 2·5 μm coating thickness reveals the best cutting performance due to its robust rigidity for preventing the detachment of diamond films as well as the relatively good wear resistance.
<filename>repository-message-broker-core/src/main/java/org/openforis/rmb/inmemory/FindMessageProcessing.java package org.openforis.rmb.inmemory; import org.openforis.rmb.spi.*; import org.openforis.rmb.spi.MessageRepository.MessageProcessingFoundCallback; import java.util.List; final class FindMessageProcessing extends FilteringOperation<Void> { private final MessageProcessingFoundCallback callback; public FindMessageProcessing(Clock clock, MessageProcessingFilter filter, MessageProcessingFoundCallback callback) { super(clock, filter); this.callback = callback; } Void execute(ConsumerMessages consumerMessages) { List<Message> messages = findMessagesForConsumer(consumerMessages); for (Message message : messages) { MessageProcessingUpdate update = message.update; callback.found(MessageProcessing.create( new MessageDetails(update.getQueueId(), update.getMessageId(), update.getPublicationTime()), consumerMessages.consumer, new MessageProcessingStatus(update.getToState(), update.getRetries(), update.getErrorMessage(), now(), update.getToVersionId()) ), message.serializedMessage); } return null; } }
The launch of American Journal of Cardiovascular Disease. Welcome to the inaugural issue of the American Journal of Cardiovascular Disease, a new open-access journal devoted to reporting current advances in understanding, prevention, and treatment of the spectrum of cardiovascular diseases. You might ask, with all the cardiovascular journals out there, why start a new one? The answer is that the constantly expanding body of knowledge being generated by research labs and clinical groups around the world needs a constantly expanding outlet, easily accessible to those who want to hear about the results. A great deal has been learned in recent years about the root causes of vascular and cardiac dysfunction. Constantly evolving imaging modalities are making it possible to study the fine details of the human heartbeat, as well as to analyze the workings of hearts in mouse embryos and zebrafish. The role and potential therapeutic uses of microRNAs and resident adult stem/progenitor cells, and the therapeutic potential of embryonic stem cells or the repro-gramming of adult cells, are the subjects of exponentially growing research endeavors. This is just a small sampling of the explosion in cardiovascular research today. It is in this exciting atmosphere that the AJCD is being launched to help disseminate the vast amounts of knowledge being generated. AJCD is an open-access journal, which means that when results appear in this journal, there are no barriers to them reaching anyone, be it researcher, policy-maker, or the interested general public. However, the cost to contributors is moderate, so financial barriers toward access have not merely been shifted from readers to authors, who are under their own financial pressures already. Furthermore, it is an online-only journal. Now, there was a time when an online-only journal might have been viewed with some reservations; for example, would this journal be considered a “real journal” that would carry as much weight in a publication record as a print journal? These days, however, most print journals might as well be online only. Remember reprints, and reprint requests? If you want to have some fun (and you are over 35), pull open the drawer where you store the reprints of your older papers and show it to your postdocs, and watch the jaws drop! At any rate, the lack of print form means that publication can be quite rapid, with the aim of publication in one month, and this also keeps the costs down. Nonetheless, the AJCD will have the familiar feel of a print journal viewed online, in journal-formatted issue format with the volume and page numbers that we take for granted. It is peer-reviewed and will be fully PubMed-indexed after the initial obligatory waiting period, and will increase in frequency from quarterly to bi-monthly or monthly as papers of sufficient quality are submitted. As we hope that AJCD will be a forum for basic, translational, and clinical cardiovascular research, the topics will cover mechanistic basic studies as well as clinical observations. You'll notice that the first issue and the forthcoming issues include clinical research into population comparisons of vessel characteristics and impact on coronary artery disease, relationship between metabolic syndrome and left ventricular hypertrophy, effects of type 2 diabetes on the vasculature, hormonal effects on obesity and hypertension, and relationship between cardiovascular disease and periodontal disease or spinal cord injury. It also includes more basic reports about cardioprotection, anti-inflammatory effects of resveratrol and its metabolites, rodent studies of myocardial infarction-induced cytokine release, and cardiomyocyte autophagy. We hope that you enjoy reading AJCD and will consider submitting your research to AJCD for publication!
Discovery of Complex Anomalous Patterns of Sexual Violence in El Salvador When sexual violence is a product of organized crime or social imaginary, the links between sexual violence episodes can be understood as a latent structure. With this assumption in place, we can use data science to uncover complex patterns. In this paper we focus on the use of data mining techniques to unveil complex anomalous spatiotemporal patterns of sexual violence. We illustrate their use by analyzing all reported rapes in El Salvador over a period of nine years. Through our analysis, we are able to provide evidence of phenomena that, to the best of our knowledge, have not been previously reported in literature. We devote special attention to a pattern we discover in the East, where underage victims report their boyfriends as perpetrators at anomalously high rates. Finally, we explain how such analyzes could be conducted in real-time, enabling early detection of emerging patterns to allow law enforcement agencies and policy makers to react accordingly. Introduction The design of efficient policies requires a profound understanding of the phenomena it deals with. Data constitutes an invaluable source to gain such understanding, but if misused data can become obsolete or even misleading. In the case of sexual violence, data is often used at a micro level to conduct investigations by law enforcement agents, and it is also used at a macro level to produce general descriptive statistics. In this paper, we attempt to bridge the gap between these levels of analysis, using data science to uncover Discussion paper, Data for Policy 2016 -Frontiers of Data Science for Government: Ideas, Practices and Projections. Cambridge, United Kingdom, September 2016. latent structures that emerge when sexual violence episodes are not independent from each other. Dependencies occur in the presence of driving forces such as organized crime or social imaginary. These phenomena establish links between criminal episodes that can be uncovered through data mining. In this paper we focus on two levels of analysis. First, a bivariate analysis through pivot table heat maps allows us to answer questions that correspond to conditional distributions, such as who are the main perpetrators conditioned on age or location. Second, we focus on emerging spatiotemporal anomalous patterns, which can guide policy makers to points in time when frequencies of specific types of crime are rising and react accordingly. For example, a detective in a municipality might receive five rape reports that took place in the victim's house, and even though it is an increase from the average of two such cases per week, it can be easily attributed to a fluke. However, if the detective knew such increase also occurred in four neighboring municipalities, he/she would notice an emerging pattern. We propose a way of finding such systematically emerging anomalous patterns through the use of an efficient data structure that allows us to automatically perform massive multivariate queries and report results that present a significant deviation from the expected behaviour. Our approach consists of using relatively simple datarecords of reported rapes for which only six attributes are available-discovering complex anomalous patterns hidden in it, and using data visualization to present identified patterns in a way that is easy for practitioners to understand. The key assumption in our analysis is that at least a portion of sexual violence episodes are linked to organized crime, social imaginary, or other latent structure, as opposed to being completely isolated events with no common causes. El Salvador recently made it to the headlines around the globe as the murder capital of the world and the most violent peacetime country . Maras-gangs-and gang related violence are currently the primary challenge to peace in the region, threatening human rights and governments' stability . Gang rape initiation of females who join maras, and the use of sexual violence by maras as a weapon against enemies have been documented by both academics and journalists . Previous research and documentation of such phenomena in El Salvador allows us to posit an underlying latent structure among reported rapes. We aim to gain better understanding of such structure and identify emerging anomalous patterns that can be of interest to policy makers, presenting the results through data visualizations that are compelling and easy to understand by practitioners. We propose a way of implementing such anomaly discovery in real-time. Perhaps our most relevant finding, which to the best of our knowledge has not been previously discussed in literature, corresponds to evidence of a pattern in the East of the country, where victims between 12 and 14 years old (inclusive) report being raped by their boyfriends at significantly high rates, with specific points in time when this phenomenon has further escalated. In the remainder of this paper, Section 2 briefly reviews related work, Section 3 introduces the data, Section 4 explains our methodology, Section 5 follows with the results, and Section 6 presents the conclusion. Related work Sexual violence in El Salvador has been studied by multiple researchers focused on the civil conflict that ended in 1992, points at El Salvador as a country where sexual violence was distinctly low compared to other cases, with the vast majority of incidents occurring in the early stages of the war and perpetrated by the state forces. This is perhaps one of the only times in literature where El Salvador is referenced for its relatively low prevalence of sexual violence. documents the systematic use of sexual violence by gangs both as part of their modus operandi and as an initiation ritual, where women are subjected to gang rape, known as el trencito, before joining a gang. Hume has also studied the cultural legitimization of violence as an element of male gender identity in the general population , indicating it has led to the perception of sexual violence as a part of gender relations. The prevalence of child sexual abuse before age 15 has been studied in , where they conclude the most common perpetrators nationwide are neighbors or acquaintances and male family members. To the best of our knowledge, anomaly detection techniques have not been used in the past as a tool to study sexual violence. However, such techniques have been proposed for detection and prevention of crime waves and crime epidemics in general . Additionally, the use of machine learning to forecast recidivism of domestic violence incidents in particular households was proposed in . Such research, even though thematically related, differs from ours in that it deals with individual predictions rather than detection of systematic patterns. The T-Cube data structure, used in this paper to enable fast massive screening, was proposed in as a tool for fast retrieval and analysis of time series data. It has since been used to analyze large scale multidimensional spatiotemporal datasets, and it has proven to be useful in multiple surveillance and outbreak detection tasks, like monitoring food and agriculture safety and detecting disease outbreaks . A user interface known as T-Cube Web Interface, which uses the T-Cube data structure and allows practitioners to visualize results and perform drill-down analysis in real-time, was presented in . Data The data used in this paper contains a record of all 16, 965 officially reported rapes between January 2006 and December 2014 in El Salvador 12 . For each case the exact date, age and gender of the victim, municipality and state where the rape took place, location (i.e. victim's house, empty lot) and relationship between the victim and the aggressor (i.e. father, acquaintance) are reported. In 15,739 cases the victim was female and in 1,225 the victim was male. The mean age of victims is 18.15, with a standard deviation of 9.76, and 7,595 victims are under fifteen years old. Figure 1 shows a histogram of age distribution, and Figure 2 shows the rate of total reported rapes per 10,000 inhabitants for each state. Methodology Bivariate analyses through pivot table heat maps are used to visualize conditional distributions. Each row of the table represents the relative frequency of the column value conditioned on the row value, such that the sum across each row is 1. These tables give an overview where general trends and anomalies become visible. Spatiotemporal anomaly detection is achieved through the use of the T-Cube data structure, which enables fast screening to detect those queries for which the observed counts deviate from the expected behaviour. An individual query is defined as the number of counts of a given event in a specified time window, where the following parameters are given: 1. Between one to three fixed attribute values. Number of neighbouring locations to aggregate over, if one of the fixed attributes corresponds to a location. 3. An initial date for the time window. Massive screening is defined as a search over all individual queries, where the parameters for the massive screening are the size of the time window and the list of attributes to query over. An example of a massive screening is a search over the attribute subset (state, age, perpetrator) for statistically significant time windows of seven days. Within this massive screening, an example of an individual query would be (state = {Morazan, SanMiguel, LaUnion}, age = , perpetrator = boy f riend), for the week starting in 04 − 07 − 2014. In massive screening, queries that significantly deviate from their expected counts are flagged as anomalies. Statistical significance tests are done using either Fisher's exact test , if the sample is small, or Chi-square test , if the sample is big. Both rely on the analysis of a contingency table, where we take into account the total count of events for the query's time window and for a reference window that illustrates past behaviour. Results Using pivot table heat maps, we visualize the conditional distribution over relationship between victim and aggressor conditioned on victims' age range, as well as conditioned over state. Figures 3 and 4, respectively, show the results. Looking at Figure 3 we can analyse which aggressors are prevalent for each age group. Perhaps one of the most notable trends is that the most frequent aggressor of victims between 12 and 14 years old is the victim's boyfriend, which is not the case for other age ranges. Another interesting finding illustrated in this heat map is the fact that neighbours are responsible for a bigger proportion of rapes when victims are below 15 years old and above 55 years old. It is also relevant to note that, in line with findings in , perpetrator = {boy f riend} and varying attribute (States). Up to 5 states with centroids no more than 50 kilometers away are aggregated. The time window for each query is of 28 days, and the reference period is of 365 days. Conclusion We have proposed a way of analysing sexual violence through the assumption of an underlying latent structure. Such an assumption is sensible in cases where previous research has established latent causes of sexual violence. El Salvador is one of such cases but definitely not the only one. With that assumption in place, we have proposed the use of T-Cube data structure, in combination with statistical significance tests, to enable fast querying of the data and reliable discovery of anomalous spatiotemporal patterns. Using the framework we propose, we have analysed sexual violence data from El Salvador and we have found evidence of patterns that should be addressed by policy makers. The most salient of such patterns corresponds to the states in the East, where girls between 12 and 14 years old report their boyfriend as the perpetrator at rates that do not correspond to those in the rest of the country, with a peak taking place in the first half of 2008. Finally, we explain how such techniques could be implemented in real-time. The results presented in this paper demonstrate the ability of the proposed techniques to identify significant anomalies in this domain, indicating that it could potentially be used by policy makers for early detection of emerging patterns, which could enable development of effective policies and responses.
<reponame>not-kyozm/NanoUtils package com.kyozm.nanoutils.utils; import net.minecraft.client.settings.KeyBinding; import net.minecraftforge.fml.client.registry.ClientRegistry; import org.lwjgl.input.Keyboard; public class Keybinds { public static KeyBinding openGUI; public static void register() { openGUI = new KeyBinding("Open GUI", Keyboard.KEY_SEMICOLON, "NanoUtils"); ClientRegistry.registerKeyBinding(openGUI); } }
Conflict resolution strategies of nurses in a selected government tertiary hospital in the Kingdom of Saudi Arabia Background: Conflict is inevitable and can be found in all settings. It can co-exist between and among health care professionals such as doctors and nurses and their patients. The roles of the nurses in each scenario and the kind of strategies they utilized also vary. This study aimed to determine the conflict resolution strategies of nurses in a selected government tertiary hospital in the Kingdom of Saudi Arabia. Methods: Utilizing a Descriptive Correlational Research Design, 78 nurses were asked to identify their conflict resolution strategies during their day to day interaction with the patients and doctors through a 20-item questionnaire. This study was conducted in a government tertiary hospital specializing in maternity and pediatric care with 310 beds in the East of Riyadh. Results: Findings yielded a high utilization of conflict resolution strategies by nurses with patients. Accommodating (61.5%; n = 48) was ranked number one as nurses used this strategy in dealing with patients. Secondly, collaborative (60.3%; n = 47), the third is both compromising and avoiding at (57.7%; n = 45); and the least in rank is competing (56.4%; n = 44). Nurses utilized the following conflict resolution strategies with doctors such as: (1) competing (43.6%; n = 34), (2) both compromising and avoiding (42.3%; n = 33), (3) collaborative (39.7%; n = 31), and (4) accommodating (38.5%; n = 3). It shows that the number 1 priority for conflict resolution strategies is “accommodating” for patients which was regarded the least for the doctors. On the other hand, the least strategy “competing” with patients is the number 1 strategy of nurses with doctors. There is a significant relationship between nurses’ use of conflict resolution strategies consistent at collaborative with patients and doctors and their age. Findings further reveal that the overall use of conflict resolution strategies is significantly related to both patients and doctors. There is a significant relationship between nurses’ use of conflict resolution strategies at compromising with doctors and their nursing qualification. There is a significant relationship between nurses’ use of conflict resolution strategies (collaborative) with patients and their current nursing experience. The overall use of compromising as a strategy is significantly related to doctors. There is a significant positive correlation between the nurses’ scores of conflict resolution strategies for both patients and doctors. On the one hand, there is no significant difference relation between nurses’ use of conflict resolution strategies with patients and doctors and their socio-demographic variables (age, years of nursing experience) except nursing qualification. There is a significant difference between nurses’ use of conflict resolution strategies (avoiding) with patients and doctors and their qualifications. Conclusions: Consequently, conflict is inevitable and is still growing in healthcare. We have determined the importance of identifying the conflict resolution strategies being utilized by nurses when they deal with their patients and doctors. Nurses can safely identify conflict and implement systems for its management. Nurses and doctors must establish positive collegial ∗Correspondence: Olfat A. Salem; Email: [email protected]; Address: Nursing Administration and Education Department, College of Nursing, King Saud University, Riyadh, Kingdom of Saudi Arabia. Published by Sciedu Press 91 http://jnep.sciedupress.com Journal of Nursing Education and Practice 2016, Vol. 6, No. 5 relationships. The active management of conflict is an important aspect towards a positive collegial relationship. Doctors and nurses can effectively manage conflict to produce positive outcomes for patients. BACKGROUND Nursing conflict traditionally generated negative feelings that many nurses use avoidance as a coping mechanism. Conflict is one of the most experienced issues by nurses and other healthcare team members. In fact, the Nursing Administration is also faced with challenges in resolving conflicts within the units of their nurses, outside their units, with other departments and even with the Hospital Administration. Managing one's conflict in the workplace is time-consuming but necessary task for the nurses. Simple to a heavy intervention leading to litigationsin any hospital settings may occur in different types of conflicts. Conflicts have an adverse effect on the individual and organization such as productivity, morale, and patient care of all the healthcare team that might lead to a rapid turnover of employees or dissatisfaction. Viewing issues or situations from different perspectives, these relationships can be compromised by conflict. Such that, conflict is referred to as a power struggle in which a person intends to harass, neutralize, injure or eliminate a rival. According to Marshall (2006), "Conflict is neither good, nor bad, it just is", it can lead to positive and negative outcomes for nurses, their colleagues, patients and organization. If managed effectively by nurses, it can, while if ineffectively managed, teamwork, productivity and quality patient care can be compromised. There can be negative impact to the organization of the hospital and its goals. There are several types of conflicts such as intrapersonal, interpersonal, intra-group, and inter-group, conflicts. Intrapersonal conflict is discord or dissention within an individual, it occurs when one is facing with two or more incompatible demands. Inter-personal conflict occurs between two or more individuals, whose values, goals, and beliefs are incompatible. Intra-group conflict occurs regularly within an established group, it may arise due to lack of support, new problem, which necessitate changes within group member roles and relationships, imposed values and role conflict inside the group. Inter-group conflict, arises between groups with differencing goals, the achievement of which by one group can occur at the expense of the other. Conflictsituation may be identified where at least two parties are involved, with different goals and/or values, where behaviors can lead toll defeat, reduce, or suppress the opponent, or gain a victory, with opposing actions and counteractions; and create in imbalance, or favored power position. Conflict resolution requires specific leadership skills, problem solving abilities and decision making skills. When conflicts go unaddressed, they can have a negative impact on productivity and teamwork. Using conflict resolution strategies in the workplace will help maintain a healthy work environment. In a study on "workplace conflict resolution and the health of employees in the Swedish and Finnish units of an industrial company", it has been found out that new patterns of work can change the way employees work and the new environment can eliminate some risks while introducing others. In the study of Hyde, Jappinen, Theorell and Oxenstierna, importance of the psychosocial working environment for the health of employees is now well documented, but the effects of managerial strategy have received relatively little attention. These results suggested that the workplace conflict resolution is important to the traditional psychosocial work environment risk factors. Learning to respond to conflict is required in developing conflict resolution strategies. Nurses need to remember that the foundation of nursing care is the therapeutic nurse-patient relationship, which contributes to the patient's well-being and health. This therapeutic relationship can be threatened whenever there is conflict, either with the patient, the patients' family, the patients' friends, or colleagues. Nurses share the responsibility with their employers to create a healthy workplace environment, ensuring that conflict does not negatively affect the patients' health outcomes or the relationships among colleagues. Competing, Accommodating, Avoiding, Collaborating and Compromising are five modes for responding to conflict situations. A study conducted by Nayeri (2009), which aims to explore the experience of conflict as perceived by Iranian hospital nurses in Tehran, Islamic Republic of Iran. The emerging themes were: 1) the nurses' perceptions and reactions to conflict; 2) organizational structure; 3) hospital management style; 4) the nature and conditions of job assignment; 5) individual characteristics; 6) mutual understanding and interaction; and 7) the consequences of conflict. The first six themes describe the sources of the conflict as well as strategies to manage them. Further, Nayeri concluded that the sources of conflict are embedded in the characteristics of nurses and the nursing system, but at the same time these characteristics can be seen as strategies to resolve conflict. Further, Nayeri concluded that the sources of conflict can be seen as strategies to resolve conflict. Conflict is one of many issues found in any organization, including hospitals, where constant human interaction occurs. The sources of conflict among hospital nurses and health care personnel include authority positions and hierarchy, the ability to work as a team, interpersonal relationship skills, and the expectations of performing in various roles at various levels. Eason et al. and Bartol et al. emphasized on the recognition of conflict how to moderate and control them according to viewpoints. Yu opined that addressing the conflict is enhances professional development and reduces burnout among nurses. Cox concluded that inadequate communication between medical practitioners and nurses can lead to conflicts, that not all the outcomes of conflict are negative; conflict can be constructive if it enhances decision-making quality. Skeels conducted a descriptive study on disruptive sources of conflict in the nursing unit and the conflict resolution mode most frequently used by nurses. Various levels of registered nurses employed at three acute care hospitals in Beaumont, Texas, in relation to conflict source to conflict resolution mode and hospital site. The voluntary participants completed the Thomas-Kilmann Conflict Mode Instrument and ranked disruptive sources of conflict prior to a program on conflict management. The findings from which were the most disruptive source of conflict were not clearly evident with all five possible sources listed having combined medians of 3 or 4. Clinical implications on patient care may be in jeopardy with nurses using primarily the non-assertive modes of compromising, avoiding, and accommodating rather than the more effective mode of collaboration. A greater awareness and careful choice by the nurse of the most effective conflict resolution mode is important. With these literatures and studies, we aimed to determine the conflict resolution strategies of the nurses in a selected government hospital. Setting The study was carried out in a 310 beds capacity government tertiary hospital specializing in maternity and pediatric care in Riyadh City which affiliated with Ministry of Health (MOH) . Design Descriptive correlational research design was used for this study. Participants The target population consisted of all nurses working in the selected hospital. The sampling consisted of nurses who were working in the selected hospital in Riyadh, during the time of the study. The sample size was calculated to estimate a mean score of 3 or higher (out of a maximum of 6), with an absolute precision of 0.25 using the MedCalc sample size calculator. Accordingly, the required sample size was 80. This was increased to 100 to account for the design effect and a nonresponse rate of approximately 20%. Quota sampling was used with an allocation of 80 nurses from the selected hospital. A non-probability sample from all available staff nurses in these settings was recruited to fulfill the required sample sizes. Procedures Prior to data collection, an institutional review board was granted approval for the study. Before the study was conducted, the research team contacted through email the Director of the Research Center in the selected hospital and explained the study procedures. Questionnaires were emailed to the Nursing supervisors of the selected hospital to be given to nurses in the wards. The questionnaires accompanied by a letter to each participant, explaining the objectives of the researchwere self-administered. Throughout the study, protection of human rights was assured, and adherence to ethical principles was secured, and ensured that each participant's autonomy was supported. Participation was voluntary, and there was no penalty for withdrawal from or termination of the study. In addition, the research methodologies were non-invasive, and there were minimal or no anticipated risks to participants. A consent form was obtained from all participants. Total confidentiality of information was also ascertained. Data collection tool For the purpose of this study, the operational definition of Conflict according to Elliot is "an internal individual struggle resulting from incompatible or opposing needs, drives, or external and internal demands. In group interactions, competitive or opposing action of incompatibles" while, Conflict Resolution Strategies "are the approaches utilizing five styles: avoiding, competing, accommodating, compromising and collaborative." The data collection tool was adapted from Elliot (2010) with 20 items divided into five subscales namely avoiding, competing, accommodating, compromising and collaborative. Further, the conflict resolution in English form was used to determine the conflict resolution strategies of the nurses in a selected government hospital. This tool consists of 20 items that measure the five components of Conflict Resolution Strategies such as : Collaborating (4 items), items), and Accommodating (4 items). Each item is rated on a 6-point Likert scale. A section was added for the respondents' personal characteristics, specifically, age, total Nursing years of experience and the years of experience in the current job. Ethical considerations Before using questionnaire, the researcher obtained permission from the authors. The study protocol was approved by the Research and Ethics Committee. All principles of ethics in research were followed. The data collection tool had a cover page that explained the aim of the study and the participant's rights, such as refusal, confidentiality, anonymity, and the use of their information solely for research. Each participantwas then asked to sign the form as consent to participate. Statistical analysis Data entry and statistical analysis were performed using the Statistical Package for Social Sciences (SPSS) version 16.0. The data are presented using descriptive statistics in the form of frequencies and percentages for the qualitative variables and means and standard deviations and medians for the quantitative variables. Cronbach's alpha coefficient was calculated to assess the reliability of the developed tools through their internal consistency. χ 2 test and The Spearman rank correlation was used at a p-value < .05 to test its statistical significance. RESULTS From the present study sample, the profile showed a majority of age less than 30 years old, and a mean of 29.1; 51 (65.4%) as majority earned a bachelor's degree; 42 (53.8%) have more than 5 years of experience in the institution, with a mean of 4.8 and 46 (59%) with more than 5 years in nursing, a mean of 5.6 (see Table 1). We have determined the importance of identifying the conflict resolution strategies being utilized by nurses when they deal with their patients and doctors. Generally, findings yielded a high utilization of conflict resolution strategies by nurses with patients and doctors. Accommodating (61.5%; n = 48) was ranked number one as nurses used this strategy in dealing with patients. Secondly, collaborative (60.3%; n = 47), the third is both compromising and avoiding at (57.7%; n = 45 ); and the least in rank is competing (56.4%; n = 44). Nurses utilized the following conflict resolution strategies with doctors such as: first, is competing (43.6%; n = 34), second is both compromising and avoiding (42.3%; n = 33), third, collaborative (39.7%; n = 31), and the least is accommodating (38.5%; n = 3). It shows that the number 1 priority for conflict resolution strategies is "accommodating" for patients which was regarded the least for the doctors. On the other hand, the least strategy "competing" with patients is the number 1 strategy of nurses with doctors (see Table 2). Table 3 shows that there is a significant relationship between nurses' use of conflict resolution strategies consistent at collaborative with patients and doctors and their age with p values of .01, .03, respectively. Findings further reveal that the overall use of conflict resolution strategies is significantly related to both patients with χ 2 value of 6.19, p < .01 and both patients with χ 2 value of 4.63, p < .03. In Table 4, there is a significant relationship between nurses' use of conflict resolution strategies at compromising with doctors and their nursing qualification. Findings further reveal that the overall use of compromising as a strategy is significantly related to doctors with χ 2 value of 4.23. Table 5 reveals that there is no significant relationship between nurses' use of conflict resolution strategies with doctors and their total nursing experience. DISCUSSION Nurses and doctors deal with conflicts daily. The findings of this current study yielded a high utilization of conflict resolution strategies by nurses with patients (61.5%) was accommodation, followed by collaboration (60.3%), and the least strategy utilized by nurses with patients in rank was competing (56.4%). This result may provide evidence that the profession is based on collaborative relationships where nurses are able to select strategies in different situations in conflict resolution that may reflect the value they place on the importance of relationship with patients. Nurses have high concern for patients, attends very closely to their needs and ignores her or his own needs. While collaboration is the most preferred of the conflict strategies, it involves attending to others' concerns while not sacrificing one's own concerns. By using these strategies, nurses may try to avoid stress, tension, which may arise from conflict situation in order to decrease the intensity of conflict. According to Blake and Mouten, accommodation, collaboration are used by individuals who want to move away from the uncomfortable feelings of struggle, similar with the studies of Cavanagh et al. On the other hand, with regard use of conflict resolution strategies by nurses with doctors, the study's findings revealed that the number one priority for conflict resolution strategies was "accommodating" for patients which was regarded the least for the doctors. Conversely, the least strategy "competing" with patients was the number one strategy of nurses with doctors. These results may attribute to the fact that doctors conflict with nurses are due to the changing, more advanced roles and the rejection of the traditional paradigm of doctor dominance. However, competitive approaches to conflict can have positive results but more often counterproductive than productive, whereas, attempting to solve conflict with dominance and control, communication can easily become negative, creating unstable situations. Competition can create discomfort which can direct energy away from patient care objectives toward unnecessary inter-professional struggles. This result is in line with the studies of Valentine et al. Our study also revealed a significant relationship between nurses' use of conflict resolution strategies and their age, that young nurses less than 30 years old tend to make more use of the compromising conflict resolution strategies with patients and accommodating conflict resolution strategies with doctors while older generations prefer collaborative with both patients and doctors, with p-values of .01, .03, respectively. This may be attributed to the fact that young nurses seek other people approval, tend to have good or at least tolerable interpersonal relations with their patients, and disfavor having enemies in their working environment. Therefore, compromising conflict resolution strategy for both nurses and doctors, brings medium benefits by not harming anyone. Moreover, conflict does not remain unsolved as when avoiding, there are no apparent winners at the expense of others as with Competing. While, accommodation strategies with doctors, might be appropriate for the nurses if they did not feel that their goals was so important. This feeling might be due to low self confidence in their views, decreased commitment to nursing profession, or a feeling that the other party of the conflict is stronger than them. In this manner, nurses can sacrifice their needs that let the doctors win over the conflict. We found out that the priority for conflict resolu-tion strategies among nurses is accommodating specifically for patients which was regarded the least for the doctors. Competing is the least strategy of nurses with patients while highest strategy of nurses with doctors. On the same line Valentine, mentioned that the reason for women being more accommodating can be due to their inborn higher concern for others as a consequence of their inherited and historical roles may be several explanations for the findings of this study. The social cognitive theory proposes that behavior is affected by environmental influences, personal factors, and attributes of the behavior itself. Perhaps, environmental influences contribute to the accommodating conflict management strategies of the nurses with doctors in this study. In relation to old generation nurses, compromising may not result in such benefits as compared to collaborating. In this respect, managing conflict constructively, collaboration creates a win-win solution. Maximizing assertive, cooperative behaviors will promote collaboration rather than compromising. However, the findings of the current study are consistent with Antonioni's study results which showed that the older population prefer collaboration and compromising. On the other hand, the findings of this study is inconsistent with the finding of Nina, Sanja who reported that, the average score of conflict resolution strategies was for avoiding and competing, while highest in accommodating and compromising, and collaborating declines with age. Conversely, Gordon found no differences of conflict management strategies by age, all ages preferred the collaborative strategy. Additionally, the current study indicated a significant relationship between nurses' use of conflict resolution strategies and qualification. It was found that nurses holding Diploma degree used compromising with doctors, while the Bachelor's degree nurses used collaborative strategy. Such results might be attributed to those nurses with higher level of education associated with nurse's age and experience which leads to higher expectations for managing conflict constructively. Using collaborating also, might be due to interpersonal conflict in the hospital between doctors, nurses, which needs accepting and understanding one another's needs and expectation to improve the quality of the relationships. Hendel et al. (2007) in their study found that collaborating was chosen significantly more frequently among qualified nurses. But, on the other hand, the results of the current study are inconsistent with Abudahi, Fekry & Elwahab who revealed no statistical significant relationship between demographic characteristics such as age, experience and job, qualification and the used conflict management strategy. In addition, the findings of the present study indicated no sig-nificant difference between nurses' use of conflict resolution strategies with patients and doctors and their total years of experience in nursing. This result inconsistent with the results of Hendel et al. which revealed that accommodation, avoiding and competing each had a statistically significant relationship with years of experience in current position. As years of experience in current position increased, the use of the accommodation, avoiding, and competing strategies also increased. When years of experience in current position increased, the use of the compromising conflict resolution strategies is decreased, but did not show a relationship to years of experience in current position. Study limitations Actual behaviors of the nurses were not directly observed. Behavioral measures such as direct observations, peer assessment and related methods can be added in future studies in order to assess the actual conflict handling strategies. The study was conducted in only one specialized hospital accredited by the Ministry of Health, and the sample was selected conveniently. Therefore, the results cannot be generalized. A bigger sample population in more than one hospital is recommended. CONCLUSIONS AND RECOMMENDATIONS Consequently, conflict is inevitable and is still growing in healthcare. We have determined the importance of identifying the conflict resolution strategies being utilized by nurses when they deal with their patients and doctors. Nurses can safely identify conflict and implement systems for its management. Nurses and doctors must establish positive collegial relationships. The active management of conflict is an important aspect towards a positive collegial relationships. Doctors and nurses can effectively manage conflict to produces positive outcomes for patients. It is recommended for future studies. Firstly, since doctors and nurses are partners in the delivery of quality care to patients, sharing the responsibility can create a healthy workplace. Such that Conflict Resolution Strategy Model can be developed to measure extent of collaboration and compromising between and among nurses, doctors and patients. This will improve health outcomes. Secondly, more researches are recommended on the personality, organizational environment and conflict management. Exploring variables on conflict handling strategies and work measures. Lastly, exploration on conflict management abilities and skills among undergraduate and graduate students. Nurses are in a crucial role for determining the appropriate strategies in managing conflicts. A clearer understanding of the factors underlying conflict resolution strategies can be considered. Better management program, hand in hand with Human Resource Department and Nursing Service can promote positive outcomes. Finding time to contribute to the nursing knowledge while intervening in a fast-paced healthcare environment is the ultimate challenge for staff nurses but also to nursing administrators.
Simplified Approach for In-Plane Strength Capacity of URM Walls by Using Lower-Bound Limit Analysis and Predefined Damage Patterns In this study, a two-phase simplified approach is proposed to predict the in-plane strength capacity of unreinforced masonry (URM) walls. In the first phase, in-plane damage and failure patterns of URM walls are determined from available observational (field) data, experimental data and also from numerical analysis data. Then, a set of rules are proposed to estimate damage and failure patterns of URM wall panels. In the second phase, this valuable information is employed to develop a simplified numerical model with a coarse mesh for the masonry wall, which is consistent with the crack formation at the ultimate state. Then, lower-bound limit analysis approach is used to predict the failure load of the wall without any detailed micro-element analysis. At the final stage, the proposed approach is verified by comparing the numerical results with experimental data from URM wall tests. By the assistance of this approach, it becomes possible to estimate the lateral capacities of ordinary, non-engineered URM walls and buildings from damage patterns at failure state. As an ultimate goal, this structural information can be used for seismic risk assessment of regions where the building typology considered in this study governs the building stock.
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.time.*; import java.time.format.DateTimeFormatter; public class Main{ public static void main(String[] args){ // 15-1 StringBuilder sb = new StringBuilder(); for (int i=0; i<100; i++){ sb.append(i+1+","); } System.out.println(sb); String[] a = sb.toString().split(","); System.out.println(a[0]); // 15-2 System.out.println(concat("a","b")); // 15-3 // .* // A\d{1,2} // U\[A-Z]{3} // 15-4 Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); int day = c.get(Calendar.DAY_OF_MONTH); day += 100; c.set(Calendar.DAY_OF_MONTH, day); Date future = c.getTime(); SimpleDateFormat f = new SimpleDateFormat("西暦yyyy年MM月dd日"); System.out.println(f.format(future)); // 15-5 LocalDate nowTime = LocalDate.now(); LocalDate futureTime = nowTime.plusDays(100); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("西暦yyyy年MM月dd日"); System.out.println(futureTime.format(fmt)); } public static String concat(String folder, String file){ if (!folder.endsWith("\\")){ folder += "\\"; } return folder + file; } }
Game of Thrones will more than likely end as number one on this list but I want to see how the show ends. We have 2 more seasons to go before that is official though. GoT is simply put genius. It encapsulates everything I love about TV. It's gruesome, bloody, sad, heartbreaking, funny at times, and even rewarding if you pick the right character. George R.R. Martin is the author of the books that this show is based on and he is a genius. All I can say is do not get attached to many characters. More than likely they will die at some point and that is why this show is amazing. It is unpredictable. And another reason its great are the characters. According to Tech Insider there are more than 500 characters in this show. It is a lot to remember and thats intimidating but it is worth it because this show is so good. Its beautifully shot and the soundtrack is amazing. Not to mention the acting also. The actors and actresses in this show are amazing. In my opinion is it hard to find something wrong with this show. This is a must watch for everyone!
. Long-term results of surgical correction of hyperlipidemia in 46 patients with obliterating atherosclerosis of lower extremities were compared with results of conservative treatment of 41 patients with the same pathology within the terms from 6 months till 5 years. It was shown that the surgical correction of hyperlipidemia resulted in more considerable and stable decrease of the blood lipid level as compared with the conservative treatment, in better course of the concomitant IHD and arterial hypertension.
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import { FontSizes, Pivot, PivotItem } from '@fluentui/react'; import { RouteComponentProps } from 'react-router-dom'; import { AuthenticatedTemplate, UnauthenticatedTemplate, } from '@azure/msal-react'; import Repositories from '../Repositories/Repositories'; export default function Home(props: RouteComponentProps) { return ( <div> <AuthenticatedTemplate> <Pivot linkSize='large' styles={{ text: { fontSize: FontSizes.xLarge }, root: { marginBottom: '20px' }, }} defaultSelectedKey='1' > <PivotItem headerText='Samples' itemKey='1'> <Repositories type='samples' /> </PivotItem> <PivotItem headerText='SDKs' itemKey='2'> <Repositories type='sdks' /> </PivotItem> </Pivot> </AuthenticatedTemplate> <UnauthenticatedTemplate> <div>Please sign in</div> </UnauthenticatedTemplate> </div> ); }
package com.rabbitmq.exchange.direct.example; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.util.RabbitHelper; public class EmitLogDirect { private static final String EXCHANGE_NAME = "directLog"; private static final String EXCHANGE_TYPE = "direct"; public static void submitToDirectExchange(Channel channel, String message, String severity) { try { channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes("UTF-8")); System.out.println("[x] send " + severity + " \t message: " + message); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { RabbitHelper rabbitHelper = new RabbitHelper(); Channel channel = rabbitHelper.setUpChannel(); rabbitHelper.setUpExchage(channel, EXCHANGE_NAME, EXCHANGE_TYPE); String message = "hello direct"; String severity = "info"; submitToDirectExchange(channel, message, severity); String message2 = "hell direct"; String severity2 = "error"; submitToDirectExchange(channel, message2, severity2); } }
# VarLookUpDict and EvalEnvironment are taken from Patsy library. # For more info see: https://github.com/pydata/patsy/blob/master/patsy/eval.py import inspect import numbers import pandas as pd from .transformations import TRANSFORMATIONS class VarLookupDict(object): def __init__(self, dicts): self._dicts = [{}] + list(dicts) def __getitem__(self, key): for d in self._dicts: try: return d[key] except KeyError: pass raise KeyError(key) def __setitem__(self, key, value): self._dicts[0][key] = value def __contains__(self, key): try: self[key] except KeyError: return False else: return True def get(self, key, default=None): try: return self[key] except KeyError: return default def keys(self): return [list(d.keys()) for d in self._dicts] def find_modules(self): l = [key for keys in self.keys() for key in keys if inspect.ismodule(self[key])] return list(set(l)) def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._dicts) class EvalEnvironment(object): """Represents a Python execution environment. Encapsulates a namespace for variable lookup """ def __init__(self, namespaces): self._namespaces = list(namespaces) @property def namespace(self): """A dict-like object that can be used to look up variables accessible from the encapsulated environment.""" return VarLookupDict(self._namespaces) def with_outer_namespace(self, outer_namespace): return self.__class__(self._namespaces + [outer_namespace]) def eval(self, expr, inner_namespace={}): return eval(expr, {}, VarLookupDict([inner_namespace] + self._namespaces)) @classmethod def capture(cls, eval_env=0, reference=0): if isinstance(eval_env, cls): return eval_env elif isinstance(eval_env, numbers.Integral): depth = eval_env + reference else: raise TypeError( "Parameter 'eval_env' must be either an integer " "or an instance of EvalEnvironment." ) frame = inspect.currentframe() try: for i in range(depth + 1): if frame is None: raise ValueError("call-stack is not that deep!") frame = frame.f_back return cls([frame.f_locals, frame.f_globals]) finally: del frame def subset(self, names): """Creates a new, flat EvalEnvironment that contains only the variables specified.""" vld = VarLookupDict(self._namespaces) new_ns = dict((name, vld[name]) for name in names) return EvalEnvironment([new_ns], self.flags) def _namespace_ids(self): return [id(n) for n in self._namespaces] def __eq__(self, other): return ( isinstance(other, EvalEnvironment) and self._namespace_ids() == other._namespace_ids() ) def __ne__(self, other): return not self == other def __hash__(self): return hash((EvalEnvironment, self.flags, tuple(self._namespace_ids()))) def eval_in_data_mask(expr, data=None, eval_env=None): """Evaluates expression in a given environment and data mask. Variable names are first looked up in `data`. If they are not found, they are looked up in `eval_env`. Parameters ---------- expr: string A string with Python code, usually a function call. data: pandas.DataFrame or None A data frame where variables are looked up. eval_env: EvalEnvironment An execution environment where values and functions are taken from. Returns ---------- The result of the evaluation of `expr`. """ # TODO: Check name conflicts if data is not None: if isinstance(data, pd.DataFrame): data_dict_inner = data.reset_index(drop=True).to_dict("series") data_dict = {"__DATA__": data_dict_inner} else: raise ValueError("data must be a pandas.DataFrame") else: data_dict = {} return eval_env.eval(expr, {**data_dict, **TRANSFORMATIONS})
def describe_klass(obj): wi('+Class: %s' % obj.__name__) indent() count = 0 for name in obj.__dict__: item = getattr(obj, name) if inspect.ismethod(item): count += 1;describe_func(item, True) if count==0: wi('(No members)') dedent() print
// Copyright (c) 2014 The SkyDNS Authors. All rights reserved. // Use of this source code is governed by The MIT License (MIT) that can be // found in the LICENSE file. package main import ( "flag" "fmt" "log" "net" "os" "strconv" "strings" "time" "github.com/coreos/go-etcd/etcd" "github.com/miekg/dns" ) const Version = "2.0.0d" var ( tlskey = "" tlspem = "" cacert = "" config = &Config{ReadTimeout: 0, Domain: "", DnsAddr: "", DNSSEC: ""} nameserver = "" machine = "" discover = false verbose = false ) const ( SCacheCapacity = 10000 RCacheCapacity = 100000 RCacheTtl = 60 ) func env(key, def string) string { if x := os.Getenv(key); x != "" { return x } return def } func init() { flag.StringVar(&config.Domain, "domain", env("SKYDNS_DOMAIN", "skydns.local."), "domain to anchor requests to (SKYDNS_DOMAIN)") flag.StringVar(&config.DnsAddr, "addr", env("SKYDNS_ADDR", "127.0.0.1:53"), "ip:port to bind to (SKYDNS_ADDR)") flag.StringVar(&nameserver, "nameservers", env("SKYDNS_NAMESERVERS", ""), "nameserver address(es) to forward (non-local) queries to e.g. 8.8.8.8:53,8.8.4.4:53") flag.StringVar(&machine, "machines", env("ETCD_MACHINES", ""), "machine address(es) running etcd") flag.StringVar(&config.DNSSEC, "dnssec", "", "basename of DNSSEC key file e.q. Kskydns.local.+005+38250") flag.StringVar(&config.Local, "local", "", "optional unique value for this skydns instance") flag.StringVar(&tlskey, "tls-key", env("ETCD_TLSKEY", ""), "TLS Private Key path") flag.StringVar(&tlspem, "tls-pem", env("ETCD_TLSPEM", ""), "X509 Certificate") flag.StringVar(&cacert, "ca-cert", env("ECTD_CACERT", ""), "CA Certificate") flag.DurationVar(&config.ReadTimeout, "rtimeout", 2*time.Second, "read timeout") flag.BoolVar(&config.RoundRobin, "round-robin", true, "round robin A/AAAA replies") flag.BoolVar(&discover, "discover", false, "discover new machines by watching /v2/_etcd/machines") flag.BoolVar(&verbose, "verbose", false, "log queries") flag.BoolVar(&config.Systemd, "systemd", false, "bind to socket(s) activated by systemd (ignore -addr)") // TTl // Minttl flag.StringVar(&config.Hostmaster, "hostmaster", "host<EMAIL>.", "hostmaster email address to use") flag.IntVar(&config.SCache, "scache", SCacheCapacity, "capacity of the signature cache") flag.IntVar(&config.RCache, "rcache", 0, "capacity of the response cache") // default to 0 for now flag.IntVar(&config.RCacheTtl, "rcache-ttl", RCacheTtl, "TTL of the response cache") } func main() { flag.Parse() machines := strings.Split(machine, ",") client := NewClient(machines) if nameserver != "" { for _, hostPort := range strings.Split(nameserver, ",") { if err := validateHostPort(hostPort); err != nil { log.Fatalf("nameserver is invalid: %s\n", err) } config.Nameservers = append(config.Nameservers, hostPort) } } if err := validateHostPort(config.DnsAddr); err != nil { log.Fatalf("addr is invalid: %s\n", err) } config, err := loadConfig(client, config) if err != nil { log.Fatal(err) } s := NewServer(config, client) if s.config.Local != "" { s.config.Local = dns.Fqdn(s.config.Local) } if discover { go func() { recv := make(chan *etcd.Response) go s.client.Watch("/_etcd/machines/", 0, true, recv, nil) for { select { case n := <-recv: // we can see an n == nil, probably when we can't connect to etcd. if n != nil { s.UpdateClient(n) } } } }() } statsCollect() if err := s.Run(); err != nil { log.Fatal(err) } } func validateHostPort(hostPort string) error { host, port, err := net.SplitHostPort(hostPort) if err != nil { return err } if ip := net.ParseIP(host); ip == nil { return fmt.Errorf("bad IP address: %s", host) } if p, _ := strconv.Atoi(port); p < 1 || p > 65535 { return fmt.Errorf("bad port number %s", port) } return nil }
/** * Moves the shape one rows down, or freezes it in place * if it reaches the end. Does not actually perform the drop of * the shape. */ public synchronized void moveOneDown() { if (currentShape == null) { return; } if (canDrop()) { performDrop(); } else { currentShape = null; checkFullRows(); } }