content
stringlengths
10
4.9M
package io.tek256.net; import java.io.IOException; import java.net.InetAddress; public class Net { public static int MAX_TIMEOUT = 1000; //1s public static boolean ping(String addr){ try{ return InetAddress.getByName(addr).isReachable(MAX_TIMEOUT); }catch(IOException e){ e.printStackTrace(); } return false; } public static InetAddress getInet(String addr){ try{ return InetAddress.getByName(addr); }catch(IOException e){ e.printStackTrace(); } return null; } }
Control of seed born mycobiota associated with Glycine max L. Merr. seeds by a combination of traditional medicinal plants extracts Seeds from soybean collected from different commercial markets were surveyed for seed-borne fungi. Ninetyeight fungal colonies were isolated all over three monthly isolations constituting twenty-two fungal species. The isolated fungi were belonging to the genera: Alternaria, Aspergillus, Cephalosporium, Chaetomium, Cladosporium, Colletotrichum, Curvularia, Fusarium, Macrophomina, Mucor, Penicillium, Rhizoctonia, Rhizopus, Sclerotium, Stemphylium, and Verticillium. Assay of the antifungal activity of four ethanolic extracts of clove, cinnamon, garlic, and mint was carried out against the most common fungal species (Aspergillus flavus, A. niger, Fusarium solani, F. oxysporium, and F. moniliforme), which significantly reduced the growth of tested fungi. Clove extract recorded the highest antimicrobial potentiality against the seed-borne fungal species, followed by cinnamon, garlic, and mint. Clove and cinnamon achieved minimum inhibitory concentration (MIC) values less than that of the reference antifungal drug fluconazole. Simultaneously, garlic and mint recorded MIC values equal to or higher than that of control. A combination of clove and cinnamon, clove and garlic, cinnamon and garlic, cinnamon, and mint extracts increased the mean relative activity percentage. They decreased MIC values below their values when used individually; this indicated synergistic interaction between the two extracts. A combination of clove with mint and garlic with mint recorded a decrease in the percentage of mean relative activity and an increase in MIC values than their values when used individually, indicating antagonistic interaction between them. Introduction Soybean (Glycine max L.) is an essential oil-producing leguminous plant (Wu et al., 2017). Its high protein, starch, and oil content (Dhungana et al., 2017). Recently, soy protein has been considered a green and renewable substitute for petroleum or animal-derived polymers in biomedical applications (Koshy et al., 2015;Lligadas et al., 2013). Soybean production accounts for approximately 6% of arable land worldwide. The expansion of soybean progresses much faster than other large grains or oils. Soybeans are being used by buyers as modern input (de la Casa et al., 2018). They are predominantly used as intermediate food, feeding stuff, and industrial inputs, not as final consumer goods (Goldsmith, 2008). Just 2% soy protein is processed in soy products such as tofu, soy hamburger, or soy analogs directly by humans. A significant percentage of the remaining 98% is processed and fed to cattle, including poultry and pigs, in soybean meals (SBM) (Rizzo and Baroni, 2018). Seed-borne fungi can affect seed production and the food industry due to their effect on germination, growth parameters, and crop production (Ordon et al., 2009). It causes seed and seedling diseases (Seethapathy et al., 2016); it also causes biochemical changes (reduction in carbohydrate, protein, and oil content and production of mycotoxins (Ramirez et al., 2018). Soybean seeds often become loaded with many fungal species (Anwar et al., 2013). The Blotter method is frequently used to detect seedborne fungi of soybean (Mancini et al., 2016). Aspergillus, Fusarium, and Rhizoctonia are mycotoxin-producing fungal genera isolated from soybean seeds. By the time, Filtrates of Aspergillus niger reduce the seed germination of soybean and decrease the root and shoot length (Jalander and Gachande, 2012). Generally, the most common isolate fungal species in soybean cultivars is Fusarium, and the least isolated species is Scopulariopsis (Russo et al., 2016). Fungicides are the traditional solution for the treatment of seed born fungi, but it causes many environmental hazards. Plants are the primary sources of naturally abundantly novel pesticides (Cantrell et al., 2012). Treatment of seeds with many plant extracts was effective in reducing mycotoxin seed contamination (Ahmed et al., 2013). Medicinal plant extracts influence the development of novel antifungal compounds. Compounds related to many phytochemical groups were assayed for antifungal activity, such as saponins, polyphenols, peptides, and essential oils (Vila et al., 2013;Gupta and Birdi, 2017). Clove, cinnamon, garlic, and mint: essential oils (EOs) are safe antimicrobial compounds used as antifungal compounds . These are natural and complex plant secondary metabolites (Bakkali et al., 2008) with broad-spectrum antimicrobial activity (Kalemba and Kunicka, 2005). The present work was carried out to isolate, identify seedborne fungi from soybean and assay the fungal inhibitory effect of ethanolic extract of some medicinal plant clove (Syzygium aromaticum), cinnamon (Cinnamomum verum), garlic (Allium sativum), and mint (Mentha piperita). Materials and Methods Collection of seed samples Soybean seeds were collected from four markets in the Giza governorate in Egypt. Seeds were subjected immediately to mycoflora isolation in the laboratory. Isolation and identification of seed-borne fungi For detecting colony-forming units (CFU/g), twenty grams of ground soybean were soaked in 180 mL sterile water containing 0.02% Tween-80, shook on a shaker at 50 rpm for 30 min. Serial dilutions (10 −1 , 10 −2 , 10 −3 ) were prepared, and 1 mL from dilution 10 −3 was inoculated into each plate containing Czapek-Dox agar with 1% streptomycin to inhibit bacterial growth. The inoculated plates were incubated at 25°C for ten days, and the colony-forming units were counted. The isolated fungi were identified microscopically using the available references (El-Shafie, 1996;Raper and Fennell, 1965). Preparation of plant extracts Ethanolic extract 100 g of each clove (Syzygium aromaticum), cinnamon (Cinnamomum verum), garlic (Allium sativum), and mint (Mentha piperita) were soaked in 70% ethanol for 72 h at room temperature to extract active ingredients. Concentration was 5% (w/v) of each extract, the extracts were then filtered using muslin or Whatman filter paper No. 1, and the filtrates were evaporated using a lyophilizer. The final lyophilized extracts were stored in labeled sterile screwcapped bottles and kept in the refrigerator until usage. An amount of freeze-dried plant extract in addition to reference antimycotic drug was dissolved in 2 mL sterile distilled water or 10% DMSO, sterilized by filtration through a 0.45-mm membrane filter, and then mixed with the amount of sterilized medium in order to give a final concentration of 15 µg/mL (Irobi and Daramola, 1993). Determination of antifungal activity The agar disc diffusion method was used to test the antifungal activity. Potato dextrose medium was inoculated with a swab of fungal spores added to the plates. Sterile paper discs (6 mm in diameter) soaked with 10 μL of each of the plant extracts were placed on the plate's surface. Fluconazole was used as control; plates were incubated at 28°C for seven days, and the inhibition zone diameter around each disc was determined (Ranković et al., 2010). Minimum inhibitory concentration Determination of minimum inhibitory concentration (MIC) was performed by a serial agar dilution plate technique, where solutions containing reconstituted plant extracts (6.25-100 mg/mL concentrations) were incorporated into Sabouraud Dextrose Agar medium (SDA). The medium was poured into plates and allowed to solidify, then inoculated with the test fungi and incubated at 25-27°C for seven days. Control plates, which contained no plant extracts, were also used. The MIC values of each plant extract were determined after seven days, this being the lowest concentration at which no visible growth was observed (Fabry et al., 1996). Preparation of fungal filtrates The isolated fungal species were cultivated in 250 mL conical flasks containing 100 mL of potato dextrose broth and incubated at 25°C for 14 days. After incubation, cultures were filtered using Whatman no. 1 filter paper. Filtrates were stored at 4°C (Jalander and Gachande, 2012). Blotter method Sterilized blotter paper discs of 9 cm diameter were placed in sterile Petri plates (9 cm diameter) after being moistened with sterile distilled water. Seeds were transferred to the plates containing the moist blotter paper. Ten seeds per plate were placed at equidistance in a circle. Forty seeds from each sample were placed in the plates in four replications. The plates were incubated at 25 ± 2°C for seven days under alternate cycles of 12 h light and 12 h darkness for seven days (International Rules for Seed Testing 2019-ISTA Online-International Seed Testing Association, n.d.). Effect of culture filtrates on seed germination and seedling growth Soybean seeds were sterilized with 0.1% mercuric chloride. Ten seeds were added to the culture filtrates from each fungal species and then incubated at 28°C for 24 h (ISTA, 1996). After seven days of incubation, the percent of germination, radicle, and plumule lengths were estimated (International Rules for Seed Testing 2019-ISTA Online-International Seed Testing Association, n.d.). Statistical analysis Data were analyzed, and treatments were compared using variance analysis with Duncan's multiple range test (p < 0.01) (Duncan, 1955). In the present study, some medicinal plant extracts were tested for inhibiting the growth of the seed-borne fungal species affecting the soybean plant's growth. It was found that the ethanolic extract of clove recorded the highest inhibition in fungal growth with mean relative activity (RA) of 131.66%, compared to fluconazole, the standard antifungal drug. The most sensitive fungal species to clove Combination mixtures between clove with cinnamon, clove with garlic, and cinnamon with garlic recorded an increase in the mean relative activity compared to the fluconazole drug (control). On the other hand, the combination between clove and mint recorded a decrease in the mean antifungal relative activity of 38.66% below that of clove alone. Moreover, garlic and mint recorded a decrease in the mean relative activity of 32.86% below that of garlic alone (Tab. 4). Tab. 5 indicates that cinnamon extract achieved the highest effectiveness against tested fungi with the least MIC values of 12.5 mg/mL against all tested fungi, followed by clove extract that recorded MIC value equal to that of control against all tested fungi. Garlic and mint recorded the highest MIC values (100 mg/mL) against all tested fungal species. The most effective combination mixture in inhibition of the tested plant parasitic fungi was clove-cinnamon (MIC 12.5 mg/mL), followed by a clove-garlic, clove-mint, and cinnamon-garlic, where MIC value of 50 mg/mL was achieved against all tested fungal species. MIC values were not detected in the case of a combination between cinnamon-mint and garlic-mint, which indicates the antagonistic action between the two oils (Tab. 6). Discussion During three surveys, identification and isolation of mycotoxigenic fungi revealed that ninety-eight fungal colonies were obtained from soybean seeds, in which the total count constituted twenty-two fungal species. Reliant to this particular result, (Marcenaro and Valkonen, 2016) isolated 133 fungal species from surface-sterilized bean seeds. It is essential to realize that type and number of the isolated fungi depend on variations of seeds moisture and seed development conditions, harvesting, and storage (Mordecai, 2012;Begum et al., 2013). The commonly isolated soybean fungi were Aspergillus, Fusarium, Macrophomina, Pythium, Phoma, and Phomopsis (Riccioni and Petrović, 2000). The isolated seed-borne fungal species' effect on the growth parameters of soybean displayed general inhibition in seed germination when treated with culture filtrate of seed-borne fungi. Regarding radicle length, it was found that Fusarium solani, F. oxysporum, Aspergillus flavus, Fusarium moniliformis, Aspergillus niger, and Rhizoctonia solani exhibited the highest reduction in radicle length. The plumule length was also affected by the seed-borne fungal species. It was found that fungal filtrates of Aspergillus flavus, A. niger, Fusarium solani, F.oxysporium, In this respect, many microorganisms can produce toxins in growth media. These toxins include amino acids, cyclic peptides, aromatic phenols, and terpenoids. Enzymes of pathogenic fungi are involved in the hydrolysis of plant tissues (Bills and Gloer, 2016). Aspergillus, Fusarium, Penicillium, and Rhizoctonia are commonly known to produce toxins (Horn et al., 1993) that reduce the plant's growth parameters. Moreover, toxic metabolites of Aspergillus species reduced seed germination; root-shoot elongation and the filtrate of A. niger, A. flavus, and A. nidulans were the most inhibitory species to all growth parameters of plants (Pangrikar et al., 2009). Culture filtrate of Aspergillus significantly reduced root length and shoot length of cereals (Jalander and Gachande, 2012). Some medicinal plant extracts (clove, cinnamon, garlic, and mint) were tested for inhibiting the seed-borne fungal species' growth. Ethanolic extract of clove recorded the highest growth inhibition. Combination mixtures between clove with cinnamon, clove with garlic, and cinnamon with garlic recorded an increase in the mean relative activity compared to fluconazole drug (control) synergistic interaction between them than a single treatment. On the other hand, the combination between clove and mint recorded a decrease in the mean antifungal relative activity below that of clove alone, indicating antagonistic interaction between clove and mint extracts. Moreover, garlic and mint recorded a decrease in the mean relative activity below that of garlic alone, indicating antagonism. Cinnamon extract achieved the highest effectiveness against tested fungi with the least MIC values against all tested fungi, followed by clove extract that recorded MIC value equal to that of control against all tested fungi. Garlic and mint recorded the highest MIC values against all tested fungal species. The most effective combination mixture was detected between clove and cinnamon, followed by a combination between clove and garlic, clove and mint, and cinnamon and garlic. MIC values were not detected in the case of a combination between cinnamon plus mint and garlic plus mint, indicating the presence of antagonism between them. Plants synthesize secondary metabolites (phenols, phenolic acids, and others), which enable them to act as a biocontrol agent in reducing severe crop loss. Secondary metabolites of plants have shown potential antifungal and antibacterial activity (Compean and Ynalvez, 2014;Ribera and Zuñiga, 2012;Ranković et al., 2010). A compelling research study by Noreen et al. (2018) evaluated the antibacterial activity of medicinal plant extracts against pathogenic bacteria involved in urinary tract infections (UTI), and they recorded that clove with cinnamon extracts showed the best antibacterial activity against UTI. Also, Lukovic et al. (2018) investigated the antifungal activity of two essential oils, cinnamon and clove, when evaluated against Cladobotryum dendroides. They found that clove essential oil showed more potent activity than cinnamon against both tested fungi. However, cinnamon oil was more toxic to Lecanicillium fungicola than to Cladobotryum dendroides. The MIC values were found to be from 9-12 mg/mL. Mucor sp., M. gypsum, and T. rubrum were inhibited at 9 mg/mL of clove oil, followed by Aspergillus sp. and F. oxysporum at 10 mg/mL and F. monoliforme at 12 mg/mL. In vitro, clove oil exhibited an inhibitory effect against the mycelial growth of Fusarium oxysporum, F. solani, F. semitectum, and Rhizoctonia solani. Complete growth inhibition was observed in Fusarium oxysporum and Rhizoctonia solani when clove oil was applied at a concentration of 4% (Thabet and Khalifa, 2018). Medicinal and aromatic secondary metabolites are found in the structure of ketones, esters, alcohols, terpenes, phenols, aldehydes amines, and sulfides, terpineol, thujanol, myrcenol, neral, thujone, camphor, and carvone are strongly associated with their potential biocontrol and pathogenic microorganism eradications (Bakkali et al., 2008). The chemical composition of EO plants varies according to the form and geographic location of the plant species and the weather, ripening stage, and the method of EO obtaining (Nazzaro et al., 2017). Another important aspect is the plant's portion, where EO is derived from flowers, stems, leaves, and buds (Ben El Hadj Ali et al., 2015). To our expertise, and though its antibacterial and antioxidant activities are well known, it is substantial to study the antifungal and antioxidant activity of EOs thoroughly. Besides all these facts, specific techniques are needed to conserve the biological activities of food processing facilities. EOs can be quickly degraded by oxygen and variations in temperatures and volatile at room temperature (Borugă et al., 2014;Zhaveh et al., 2015). Methods are therefore crucial for improving the stability and operation of EOs, and modern technologies such as encapsulation, the use of edible coatings, and active packaging can solve these difficulties (Prakash and Kiran, 2016). In food items with some novel uses such as encapsulation, edible films, and edible coating, EOs may be used directly. The technology for encapsulation improves the stability of oxidation, heat stability, and anti-microbial and antioxidant EOs (Campos et al., 2011). The attaching of EOs to edible film and coating can also boost heat stability and breakage resistance, minimize swelling and solubility and increase and/or increase product antioxidant and anti-microbial activities (Du et al., 2011). The number of studies on other biological activities of EOs has increased significantly nowadays due to growing data on microorganism -cidal or -static effects of EOs. Regarding the mechanism of action, EOs could disrupt a bacterial and fungal culture cell membrane (Raveau et al., 2020;Khorshidian et al., 2018). The antimicrobial activity of EOs is so potent that the cell membrane can easily be disrupted and even more permeable. Also, they disrupt processes of ion transportation and interact with membrane proteins and other intracellular compounds (Kalemba and Kunicka, 2005;Nazzaro et al., 2017). Also, EOs have an adverse effect on the enzymes by interfering with their active sites. After EOs implementation, electrolyte loss was measured as assessed by K + , Ca 2+ , and Na + concentration ions levels . In short, the interaction of EO and the cell system with the plasma membrane and disruption of mitochondrial function were found to be antimicrobial effects (Hu et al., 2017). A distortion between ATP concentrations intracellular and extracellular ultimately contributes to cell death (Hu et al., 2017). Besides, the antimicrobial impacts of EOs may be associated with the usability of EOs by the cell membrane of microorganisms (diffusion coefficient, zeta potential, and droplet size of EOs) . While in many works of literature, the antimicrobial mechanisms of EOs have been well described, the antimycotoxigenic mechanism is not yet known. In recent works, however, several approaches were documented. Antimycotoxigenic EOs were linked in one study with their effect on the aflatoxin biosynthesis (Bluma et al., 2008). Conclusion Because of their low cost, availability, and wide range of biological activities, essential oils -and their components-are valuable. Another advantage is that they do not disturb the taste and scent and, therefore, enhance the foodstuff's shelf life while they are being used in adequate proportions. It is essential to find from health and economic aspects. The efficient, safe, and cost-effective anti-fungal agents to control both growth and the production of mycotoxins. However, different results were observed in various studies because of differences in crops used in antimicrobial analyses, geographical origin, harvest time, part of the plant-derived from EO, and methods of extracting and analyzing. These parameters are critical considerations while working with EO, as they influence their germicidal activities. While EOs antibacterial and antioxidant capabilities are well documented, there are still limited antifungal and anti-mycotoxin activity studies. In terms of organoleptic properties of the food, the use of essential oil mixtures, which are designed according to food characteristics, might be seen as a new particular perspective. Since EOs are unstable under environmental stresses, such as light and temperature, new technologies might protect and improve their biological characteristics. However, further research should concentrate on the synergistic influence and mechanism action between different essential oils and/or components. A further recommendation is that the anti-fungal action against polycultures should also be investigated in addition to these monoculture studies. Lastly, new techniques to improve the EOs stability and decrease the required concentration to ensure food safety with minimal sensorial changes could be an interesting research scope to explore deeply. Availability of Data and Materials: All the data supporting these findings is contained within this manuscript. Author Contribution: The author confirms sole responsibility for the following: study conception and design, data collection, analysis and interpretation of results, and manuscript preparation. Ethics Approval: Not applicable. Funding Statement: The authors received no specific funding for this study. Conflicts of Interest: The authors declare that they have no conflicts of interest to report regarding the present study.
<filename>endoscope-storage-gzip/src/test/java/com/github/endoscope/storage/gzip/GzipStorageTest.java package com.github.endoscope.storage.gzip; import com.github.storage.test.StorageTestCases; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class GzipStorageTest extends StorageTestCases { public GzipStorageTest(){ super(new GzipStorage()); try { File dir = Files.createTempDirectory("DiskStorageTest").toFile(); storage.setup(dir.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException(e); } } }
<reponame>HeinousTugboat/bitburner interface Position { row: number; column: number; } class PositionTracker { positions: Map<string, Position>; constructor() { this.positions = new Map<string, Position>(); } saveCursor(filename: string, pos: Position): void { this.positions.set(filename, pos); } getCursor(filename: string): Position { const position = this.positions.get(filename); if (!position) { return { row: -1, column: -1, }; } return position; } } export const CursorPositions: PositionTracker = new PositionTracker();
def parse_unit_results( self, results ): log = [] error_in_test = False _log = '' for l in results.split( '\n' ): if error_in_test: if l == '': error_in_test = False continue else: log[-1][2] += l + '\n' l_arr = l.split( ' ' ) if len( l_arr ) == 5 and l_arr[4] == 'PASSED': log.append( [l_arr[2], 'passed', '', 1, None, None, None, None] ) elif len( l_arr ) == 5 and l_arr[4] == 'FAILED': error_in_test = True log.append( [l_arr[2], 'failed', '', 1, None, None, None, None] ) return log
<reponame>naterivah/atriangle<gh_stars>1-10 package tech.artcoded.atriangle.api.dto; public enum EventType { MONGODB_SINK, RDF_SINK, }
<gh_stars>0 /** * frame_Test.go * Copyright (c) 2018 <NAME> * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ package rec import ( "bytes" "testing" ) func TestFrameEncode(t *testing.T) { f := Frame{ Time: 123, Type: FrameStdout, Payload: []byte{0xff, 0x23, 0x1d, 0x3c}, } o := f.Encode() v := []byte{0x00, 0x00, 0x00, 0x7b, 0x01, 0x00, 0x00, 0x00, 0x04, 0xff, 0x23, 0x1d, 0x3c} if bytes.Compare(o, v) != 0 { t.Errorf("invalid encode result") } }
/* * ApplyTransaction calls in Ratis are sequential. */ @Override public CompletableFuture<Message> applyTransaction(TransactionContext trx) { try { metrics.incNumApplyTransactionsOps(); ContainerCommandRequestProto requestProto = getRequestProto(trx.getSMLogEntry().getData()); Preconditions.checkState(!HddsUtils.isReadOnly(requestProto)); stateMachineMap.computeIfAbsent(requestProto.getContainerID(), k -> new StateMachineHelper()); long index = trx.getLogEntry() == null ? -1 : trx.getLogEntry().getIndex(); return stateMachineMap.get(requestProto.getContainerID()) .executeContainerCommand(requestProto, index); } catch (IOException e) { metrics.incNumApplyTransactionsFails(); return completeExceptionally(e); } }
void doLinkClustering(int nClusters, Vector<Integer>[] nClusterID, Node[] clusterNodes) { int nInstances = m_instances.numInstances(); PriorityQueue<Tuple> queue = new PriorityQueue<Tuple>(nClusters * nClusters / 2, new TupleComparator()); double[][] fDistance0 = new double[nClusters][nClusters]; double[][] fClusterDistance = null; if (m_bDebug) { fClusterDistance = new double[nClusters][nClusters]; } for (int i = 0; i < nClusters; i++) { fDistance0[i][i] = 0; for (int j = i + 1; j < nClusters; j++) { fDistance0[i][j] = getDistance0(nClusterID[i], nClusterID[j]); fDistance0[j][i] = fDistance0[i][j]; queue.add(new Tuple(fDistance0[i][j], i, j, 1, 1)); if (m_bDebug) { fClusterDistance[i][j] = fDistance0[i][j]; fClusterDistance[j][i] = fDistance0[i][j]; } } } while (nClusters > m_nNumClusters) { int iMin1 = -1; int iMin2 = -1; if (m_bDebug) { double fMinDistance = Double.MAX_VALUE; for (int i = 0; i < nInstances; i++) { if (nClusterID[i].size() > 0) { for (int j = i + 1; j < nInstances; j++) { if (nClusterID[j].size() > 0) { double fDist = fClusterDistance[i][j]; if (fDist < fMinDistance) { fMinDistance = fDist; iMin1 = i; iMin2 = j; } } } } } merge(iMin1, iMin2, fMinDistance, fMinDistance, nClusterID, clusterNodes); } else { Tuple t; do { t = queue.poll(); } while (t != null && (nClusterID[t.m_iCluster1].size() != t.m_nClusterSize1 || nClusterID[t.m_iCluster2].size() != t.m_nClusterSize2)); iMin1 = t.m_iCluster1; iMin2 = t.m_iCluster2; merge(iMin1, iMin2, t.m_fDist, t.m_fDist, nClusterID, clusterNodes); } for (int i = 0; i < nInstances; i++) { if (i != iMin1 && nClusterID[i].size() != 0) { int i1 = Math.min(iMin1, i); int i2 = Math.max(iMin1, i); double fDistance = getDistance(fDistance0, nClusterID[i1], nClusterID[i2]); if (m_bDebug) { fClusterDistance[i1][i2] = fDistance; fClusterDistance[i2][i1] = fDistance; } queue.add(new Tuple(fDistance, i1, i2, nClusterID[i1].size(), nClusterID[i2].size())); } } nClusters--; } }
<gh_stars>0 from typing import List def remove_par(p_list: List[str]) -> List[str]: remove_list = ["(", ")"] for symbol in remove_list: while symbol in p_list: p_list.remove(symbol) return p_list spec_mapper = { "'pars_m_t'": "'\t'", "'pars_m_n'": "'\n'", "'pars_m_dq'": '"', } def check_spec(value: str) -> str: return spec_mapper.get(value, value) def find_symbols_not_in_str(str_1: str, str_2: str) -> str: # method for development to fast search that symbols are not in parser str_1 = set(str_1) str_2 = set(str_2) not_in_str_2 = str_1 - str_2 print(f"Symbols not in str 2: {not_in_str_2}") return not_in_str_2 def find_first_unpair_closed_par(str_: str) -> int: stack = [] n = -1 for i in str_: n += 1 if i == ")": if not stack: return n else: stack.pop(-1) elif i == "(": stack.append(i) # scirnk xjbt
CJ Entus have signed two new AD carries for the upcoming 2017 Challengers Korea: Kim "Veritas" Kyoung-min and Yoo "Avenger" Seon-wu. [ENTUS News] CJ엔투스 LoL팀의 새로운 원거리 딜러 선수들을 소개합니다! We'd like to introduce our new AD Carry players!https://t.co/OxNgiAl7gK pic.twitter.com/vIH5zvaL8s — OGN ENTUS (@ENTUS_Progaming) January 5, 2017 The two AD carries will be joining the following players on the new CJ Entus lineup: Seo " Soul " Hyeon-seok (Top) " Hyeon-seok (Top) Park " Winged " Tae-jin (Jungle) " Tae-jin (Jungle) Kim " Pure " Jin-sun (Support) " Jin-sun (Support) Park " Racoon " Sung-ho (Support) " Sung-ho (Support) Kim "caNdy" Seung-ju (Mid) With Veritas, the UoL finished in 4th place by the end of the 2016 EU LCS Summer Split, but failed to qualify for Worlds 2016 after losing to Splyce in the grand finals of the EU LCS Regional Qualifiers. Recently, at IEM Oakland, Veritas, alongside UoL, emerged as the champions after defeating teams such as the LMS team Flash Wolves and the top seed in the NA LCS Team SoloMid. After an emergency last minute meeting, UoL announced that their new ADC for 2017 who will finalize their roster will be Spanish player Samuel "Samux" Fernandez Fort. Avenger began his competitive career in the EU CS playing on teams such as Pathos and the Italian organization, Team Forge. He came close to qualifying for the EU CS, but failed to qualify after ending the 2015 promotion tournament in 5th place. He signed on with SBENU Korea to play in the upcoming Challengers Korea, but became a free agent after the organization dissolved due to issues with internal management and corruption. It is uncertain which of the two players CJ Entus will decide to field as their starting AD carry next split, but it is likely that Veritas, given his experience, will be prioritized while Avenger will become the dedicated substitute. CJ Entus released their 2016 roster following a disappointing last place finish by the end of the LCK Summer Split and were relegated into Challengers Korea after losing to ESC Ever 3-0. It will be interesting to see if this new lineup will be what CJ Entus needs to make their return to the LCK and become a competitive team, but only time will tell. Image credit: OGN
from flask import Flask, render_template, abort, request,\ redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from werkzeug.utils import secure_filename import random import string import datetime app = Flask(__name__) app.config.from_object('config.DevelopmentConfig') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False IMAGE_DIR = 'static/images' ERR_NO_FILE_SPECIFIED = 'error: no file specified' from models import db, Image, add_image, get_image, get_images db.init_app(app) def randstr(): '''Creates a random string of alphanumeric characters.''' return ''.join(random.choice(string.ascii_uppercase + string.digits) \ for _ in range(30)) @app.route('/') def home(): return redirect(url_for('show_form')) @app.route('/images/', methods=['GET']) def show_form(): return render_template('form.html') @app.route('/images/', methods=['POST']) def upload_image(): '''Determines where to place the image based on the parameter 'target'. Then, we save the image and redirect to GET /images/ with a flash message provided. The form will have the following parameters. target (text): either 'db' or 'file' name (text): the name of the image file (file): the image's binary data ''' if 'file' not in request.files: return ERR_NO_FILE_SPECIFIED imgfile = request.files['file'] if imgfile.filename == '': return ERR_NO_FILE_SPECIFIED safefilename = secure_filename(randstr() + '-' + imgfile.filename) imgpath = '{}/{}'.format(IMAGE_DIR, safefilename) target = request.form['target'] add_image({ 'name': request.form['name'], 'img_filename' : safefilename if target == 'file' else None, 'img_data' : imgfile.read() if target == 'db' else None, }) if target == 'file': imgfile.save(imgpath) flash('New image "{}" created.'.format(request.form['name'])) return redirect(url_for('show_form')) @app.route('/images/db/', methods=['GET']) def get_images_from_db(): images = get_images() images = list(filter(lambda img: img.img_data != None, images)) return render_template('show_images.html', images=images, target='db') @app.route('/images/files/', methods=['GET']) def get_images_from_files(): images = get_images() images = list(filter(lambda img: img.img_filename != None, images)) return render_template('show_images.html', images=images, target='file') @app.route('/images/db/<int:the_id>', methods=['GET']) def get_image_from_db(the_id): image = get_image(the_id) return app.response_class(image.img_data, mimetype='application/octet-stream') @app.route('/images/nuke', methods=['GET']) def nuke_all_images(): Image.query.delete() db.session.commit() db.engine.execute('alter sequence images_id_seq RESTART with 1') return 'ok' if __name__ == "__main__": app.run()
""" .. module:: Pantheon :synopsis: Pantheon likelihood from Jones et al. 2018 and Scolnic et al. 2018 .. moduleauthor:: Rodrigo von Marttens <[email protected]> and Antonella Cid <[email protected]> Based on the previous JLA likelihood writted by Benjamin Audren .. code:: C00 = mag_covmat_file .. note:: Since there are a lot of file manipulation involved, the "pandas" library has to be installed -- it is an 8-fold improvement in speed over numpy, and a 2-fold improvement over a fast Python implementation. The "numexpr" library is also needed for doing the fast array manipulations, done with blas daxpy function in the original c++ code. Both can be installed with pip (Python package manager) easily. """ import numpy as np import scipy.linalg as la import montepython.io_mp as io_mp try: import numexpr as ne except ImportError: raise io_mp.MissingLibraryError( "This likelihood has intensive array manipulations. You " "have to install the numexpr Python package. Please type:\n" "(sudo) pip install numexpr --user") from montepython.likelihood_class import Likelihood_sn class Pantheon(Likelihood_sn): def __init__(self, path, data, command_line): # Unusual construction, since the data files are not distributed # alongside Pantheon (size problems) try: Likelihood_sn.__init__(self, path, data, command_line) except IOError: raise io_mp.LikelihoodError( "The Pantheon data files were not found. Please check if " "the following files are in the data/Pantheon directory: " "\n-> pantheon.dataset" "\n-> lcparam_full_long.txt" "\n-> sys_full_long.dat") # Load matrices from text files, whose names were read in the # configuration file self.C00 = self.read_matrix(self.mag_covmat_file) # Reading light-curve parameters from self.data_file (lcparam_full_long.txt) self.light_curve_params = self.read_light_curve_parameters() # Reordering by J. Renk. The following steps can be computed in the # initialisation step as they do not depend on the point in parameter-space # -> likelihood evaluation is 30% faster # Compute the covariance matrix # The module numexpr is used for doing quickly the long multiplication # of arrays (factor of 3 improvements over numpy). It is used as a # replacement of blas routines cblas_dcopy and cblas_daxpy # For numexpr to work, we need (seems like a bug, but anyway) to create # local variables holding the arrays. This cost no time (it is a simple # pointer assignment) C00 = self.C00 covm = ne.evaluate("C00") sn = self.light_curve_params # Update the diagonal terms of the covariance matrix with the # statistical error covm += np.diag(sn.dmb**2) # Whiten the residuals, in two steps. # Step 1) Compute the Cholesky decomposition of the covariance matrix, in # place. This is a time expensive (0.015 seconds) part, which is why it is # now done in init. Note that this is different to JLA, where it needed to # be done inside the loglkl function. self.cov = la.cholesky(covm, lower=True, overwrite_a=True) # Step 2) depends on point in parameter space -> done in loglkl calculation def loglkl(self, cosmo, data): """ Compute negative log-likelihood (eq.15 Betoule et al. 2014) """ # Recover the distance moduli from CLASS (a size N vector of double # containing the predicted distance modulus for each SN in the JLA # sample, given the redshift of the supernova.) redshifts = self.light_curve_params.zcmb size = redshifts.size moduli = np.empty((size, )) for index, row in self.light_curve_params.iterrows(): z_cmb = row['zcmb'] z_hel = row['zhel'] moduli[index] = (1.+z_hel)/(1.+z_cmb) * cosmo.luminosity_distance(z_cmb) moduli = 5 * np.log10(moduli) + 25 # Convenience variables: store the nuisance parameters in short named # variables M = (data.mcmc_parameters['M']['current'] * data.mcmc_parameters['M']['scale']) # Compute the residuals (estimate of distance moduli - exact moduli) residuals = np.empty((size,)) sn = self.light_curve_params # This operation loops over all supernovae! # Compute the approximate moduli residuals = sn.mb - M # Remove from the approximate moduli the one computed from CLASS residuals -= moduli # Step 2) (Step 1 is done in the init) Solve the triangular system, also time expensive (0.02 seconds) residuals = la.solve_triangular(self.cov, residuals, lower=True, check_finite=False) # Finally, compute the chi2 as the sum of the squared residuals chi2 = (residuals**2).sum() return -0.5 * chi2
The Solution Of 3-D Biomedical Electrostatic Problems On A Data Parallel Computer Many electromagnetic problems in the area of biomedical engineering can be approximated as electrostatic problems. These problems are governed by Laplace’s equation which is not ana lytically solvable for most real world problems. Often, numerical approximations are used which cast the problem in terms of a linear system of simultaneous equations. For three-dimensional problems, accurate results may require thousands of equations and may stretch the limits of available computing power. We present the finite element approximation to problems governed by Laplace’s equation on the Thinking Machines’ Connection Ma chine 2 (CM-2), a data parallel computer. Using this computer and our algorithm, problems with hundreds of thousands of equa tions can be solved in minutes. Biomedical research goals using this method are outlined including the investigation of problems in the area of defibrillation.
//===================================================// // File Name: fused_decoder_hist.cpp // Author: <NAME> // Created Date: 2017-12-3 // Description: A fused decoder + hist kernel // We don't have to write the output jpgs! //===================================================// #include "scanner/video/decoder_automata.h" #include "scanner/util/fs.h" #include "scanner/util/opencv.h" // for using OpenCV #include <fstream> #include <sys/stat.h> extern "C" { #include "libavcodec/avcodec.h" } namespace scanner { namespace internal { namespace { const i32 BINS = 16; } void checkOutputDir(std::string &dir) { struct stat st; if (stat(dir.c_str(), &st) == 0) { if (st.st_mode & S_IFDIR != 0) { printf("Output dir: %s exists!\n", dir.c_str()); } } else { printf("Creating dir: %s ...\n", dir.c_str()); const int dir_err = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (dir_err != 0) { printf("Error creating dir: %s !\n", dir.c_str()); exit(-1); } } } size_t execute_hist(const cv::Mat &img, std::ofstream &output_buff, int currFrame) { float range[] = {0, 256}; const float* histRange = {range}; size_t hist_size = BINS * 3 * sizeof(int); u8 *output_buf = new_buffer(CPU_DEVICE, hist_size); for (i32 j = 0; j < 3; ++j) { int channels[] = {j}; cv::Mat hist; cv::calcHist(&img, 1, channels, cv::Mat(), hist, 1, &BINS, &histRange); cv::Mat out(BINS, 1, CV_32SC1, output_buf + j * BINS * sizeof(int)); hist.convertTo(out, CV_32SC1); } output_buff.write((char *)output_buf, hist_size); if (output_buff.fail()) { printf("Failed to save frame%d hist to disk, size %lu KB\n", currFrame, hist_size / 1024); exit(-1); } return hist_size; } void decodeFromDisk(int argc, char *argv[]) { avcodec_register_all(); std::string output_dir = "/tmp/output"; if (argc >= 4) { output_dir = argv[3]; } checkOutputDir(output_dir); std::fstream decodeArgsFile(argv[1], std::ios::in | std::ios::binary); proto::DecodeArgs loadedDecodeArgs; if (!loadedDecodeArgs.ParseFromIstream(&decodeArgsFile)) { std::cerr << "Failed to parse address book." << std::endl; return; } std::vector<proto::DecodeArgs> args; MemoryPoolConfig config; init_memory_allocators(config, {}); VideoDecoderType decoder_type = VideoDecoderType::SOFTWARE; DeviceHandle device = CPU_DEVICE; DecoderAutomata* decoder = new DecoderAutomata(device, 1, decoder_type); // Load test data std::string videoFileName = argv[2]; std::vector<u8> video_bytes = read_entire_file(videoFileName); u8* video_buffer = new_buffer(CPU_DEVICE, video_bytes.size()); memcpy_buffer(video_buffer, CPU_DEVICE, video_bytes.data(), CPU_DEVICE, video_bytes.size()); loadedDecodeArgs.set_encoded_video((i64)video_buffer); args.push_back(loadedDecodeArgs); decoder->initialize(args); std::vector<u8> frame_buffer(loadedDecodeArgs.width() * loadedDecodeArgs.height() * 3); FrameInfo frame_info(loadedDecodeArgs.height(), loadedDecodeArgs.width(), 3, FrameType::U8); std::vector<int> encode_params; encode_params.push_back(CV_IMWRITE_JPEG_QUALITY); encode_params.push_back(100); size_t total_size = 0; int first_frame = -1; int ind = loadedDecodeArgs.valid_frames()[0]; char outFileName[100]; sprintf(outFileName, "%s/hist%d-%lu.out", output_dir.c_str(), ind, loadedDecodeArgs.valid_frames().size()); std::ofstream output_buff(outFileName, std::ios::out | std::ios::trunc | std::ios::binary); for (i64 i = 0; i < loadedDecodeArgs.valid_frames().size(); ++i) { decoder->get_frames(frame_buffer.data(), 1); int ind = loadedDecodeArgs.valid_frames()[i]; const scanner::Frame* frame = new Frame(frame_info, frame_buffer.data()); cv::Mat img = scanner::frame_to_mat(frame); auto hist_size = execute_hist(img, output_buff, ind); total_size += hist_size; delete frame; } printf("Save %lu KB to %s\n", total_size / 1024, outFileName); delete decoder; destroy_memory_allocators(); } } } int main(int argc, char *argv[]) { if (argc < 3 || argc > 4) { std::cout << "Usage: FusedDecoderHist <proto_file> <bin_file> (<output_dir>) \n"; std::cout << "Example:\n"; std::cout << "decode_args1000.proto start_frame1000.bin /tmp/output\n"; exit(-1); } scanner::internal::decodeFromDisk(argc, argv); return 0; }
def ListTableColumns(self, table): assert isinstance(table, str) if contains_metastrings(table): raise ValueError, "bad table name: contains reserved metastrings" columnlist_key = _columns_key(table) if not getattr(self.db, "has_key")(columnlist_key): return [] pickledcolumnlist = getattr(self.db, "get_bytes", self.db.get)(columnlist_key) if pickledcolumnlist: return pickle.loads(pickledcolumnlist) else: return []
/* This function merges the branches of a condition-phi-node, contained in the outermost loop, and whose arguments are already analyzed. */ static tree interpret_condition_phi (struct loop *loop, gphi *condition_phi) { int i, n = gimple_phi_num_args (condition_phi); tree res = chrec_not_analyzed_yet; for (i = 0; i < n; i++) { tree branch_chrec; if (backedge_phi_arg_p (condition_phi, i)) { res = chrec_dont_know; break; } branch_chrec = analyze_scalar_evolution (loop, PHI_ARG_DEF (condition_phi, i)); res = chrec_merge (res, branch_chrec); } return res; }
/* R denotes the type of objects you expect the store to return at a access or update call */ public abstract class BasicStore<R> implements Serializable { private static Logger LOG = Logger.getLogger(BasicStore.class); private final String _uniqId; private PrintStream _ps; protected String _objRemId; private static int _uniqIdCounter = 0; // protected MemoryManager _memoryManager; // protected StorageManager _storageManager; private ByteArrayOutputStream _baos = null; private static final long serialVersionUID = 1L; private static final String _uniqIdPrefix = "Store#"; public BasicStore(int storesizemb) { _uniqIdCounter++; this._uniqId = BasicStore._uniqIdPrefix + Integer.toString(BasicStore._uniqIdCounter); LOG.info("SquallStorage: Initializing store of size " + storesizemb + " MB with UniqStoreId: " + _uniqId); } public abstract ArrayList<R> access(Object... data); public abstract R update(Object... data); public abstract boolean contains(Object... data); public abstract boolean equals(BasicStore store); public String getContent() { String str = null; if (this._baos == null) { this._baos = new ByteArrayOutputStream(); this._ps = new PrintStream(this._baos); } else this._baos.reset(); this.printStore(this._ps, true); str = this._baos.toString(); return str.equals("") ? null : str; } public String getUniqId() { return this._uniqId; } public void insert(Object... obj) { this.onInsert(obj); /* * Check if store has exceeded it's maximum space, and if yes, removes * some elements from it and writes them to stable storage. */ // while (this._memoryManager.hasExceededMaxSpace() == true) { // final Object remObj = this.onRemove(); // _storageManager.write(_objRemId, remObj); // } } /* Functions to be implemented by all stores */ public abstract void onInsert(Object... data); /* must set _objRemId */ // public abstract Object onRemove(); public abstract void printStore(PrintStream stream, boolean printStorage); public abstract void reset(); public abstract void setSingleEntry(boolean singleEntry); }
def settings(**kwarg): return { 'interpreter_path': '/path/to/venv/bin/python3' }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ambari.infra.conf.batch; import javax.inject.Inject; import javax.sql.DataSource; import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer; import org.springframework.batch.core.explore.JobExplorer; import org.springframework.batch.core.explore.support.JobExplorerFactoryBean; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.SimpleJobLauncher; import org.springframework.batch.core.repository.ExecutionContextSerializer; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; public class InfraManagerBatchConfigurer extends DefaultBatchConfigurer { @Inject private DataSource dataSource; @Inject private ExecutionContextSerializer executionContextSerializer; @Override public JobRepository createJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource); factory.setTransactionManager(getTransactionManager()); factory.setSerializer(executionContextSerializer); factory.afterPropertiesSet(); return factory.getObject(); } @Override public PlatformTransactionManager getTransactionManager() { return new ResourcelessTransactionManager(); } @Override protected JobLauncher createJobLauncher() throws Exception { SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); jobLauncher.setJobRepository(getJobRepository()); jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor()); jobLauncher.afterPropertiesSet(); return jobLauncher; } @Override protected JobExplorer createJobExplorer() throws Exception { JobExplorerFactoryBean factoryBean = new JobExplorerFactoryBean(); factoryBean.setSerializer(executionContextSerializer); factoryBean.setDataSource(dataSource); factoryBean.afterPropertiesSet(); return factoryBean.getObject(); } }
/* This function notifies the Volume Status Handlers that the * AFS client service is stopping. */ long cm_VolStatus_Service_Stopped(void) { long code = 0; osi_Log1(afsd_logp,"cm_VolStatus_Service_Stopped handle 0x%x", hVolStatus); if (hVolStatus == NULL) return 0; code = dll_funcs.dll_VolStatus_Service_Stopped(); return code; }
// CreateImage create ogp image API func (app *App) CreateImage(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { return } words := r.Form.Get("words") id := uuid.New() log.Printf("%s, %s", words, id) filename := fmt.Sprintf("%s.png", id.String()) filepath := path.Join("data", filename) wi, he, fs := app.Config.DefaultImageWidth, app.Config.DefaultImageHeight, app.Config.DefaultFontSize bk := image.NewRGBA(image.Rect(0, 0, wi, he)) draw.Draw(bk, bk.Bounds(), image.White, image.ZP, draw.Src) face := truetype.NewFace(app.KoruriBold, &truetype.Options{ Size: fs, }) dr := &font.Drawer{ Dst: bk, Src: image.Black, Face: face, Dot: fixed.Point26_6{}, } dOpt := &DrawStringOpts{ ImageWidth: fixed.I(wi), ImageHeight: fixed.I(he), Verbose: false, FontSize: fixed.I(int(fs)), LineSpace: fixed.I(5), VerticalMargin: fixed.I(10), HorizontalMargin: fixed.I(40), } DrawStringWrapped(dr, words, dOpt) outfile, err := os.Create(filepath) if err != nil { return } defer outfile.Close() if err := png.Encode(outfile, bk); err != nil { return } redirectURL := fmt.Sprintf("%s/p/%s", app.Config.BaseURL, id.String()) log.Print(redirectURL) http.Redirect(w, r, redirectURL, http.StatusFound) return }
/** * @tpTestDetails Locator returns resource which inherits annotations from an interface. * @tpSince RESTEasy 3.0.20 */ @Test @DisplayName("Test Annotation Free Subresource") public void testAnnotationFreeSubresource() throws Exception { { Response response = client.target(generateURL("/collection/annotation_free_subresource")).request().get(); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals(response.readEntity(String.class), "got"); Assertions.assertNotNull(response.getHeaderString("Content-Type")); Assertions.assertEquals("text/plain;charset=UTF-8", response.getHeaderString("Content-Type")); } { Builder request = client.target(generateURL("/collection/annotation_free_subresource")).request(); Response response = request.post(Entity.entity("hello!".getBytes(), MediaType.TEXT_PLAIN)); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals("posted: hello!", response.readEntity(String.class)); } }
Optimizing network traffic by generating association rules using hybrid apriori-genetic algorithm Association rule mining is a technique of generating frequent item sets so that the analysis on the basis of these sets can be used for different application areas such as analysis of network traffic. Although the frequent sets generated using apriori algorithm provides less computational time and provides less frequent sets, but the technique that we are implemented here provides less computational time as compared as well generated less sets and provides less rules for the network traffics. These frequent sets are used for the analysis of traffic in the network so that the analysis of different spams or any unwanted issues can be detected easily.
<reponame>applifactory/research-rpa import { SubscribeMessage, WebSocketGateway, OnGatewayConnection, OnGatewayInit } from '@nestjs/websockets'; import { UnauthorizedException, UseGuards } from '@nestjs/common'; import { AuthService } from 'src/auth/auth.service'; import { User } from 'src/user/user.entity'; import { Server } from 'socket.io'; import { WsJwtAuthGuard } from 'src/auth/guards/ws-jwt-auth.guard'; import { SocketEvent } from './models/socket-event'; import { SocketEventType } from './models/socket-event-type'; @WebSocketGateway() export class SocketGateway implements OnGatewayInit, OnGatewayConnection { private server: Server; constructor(private readonly authService: AuthService) {} async afterInit(server: Server) { this.server = server; } async handleConnection(client: any) { let user: User; if ( !client.handshake.query.hasOwnProperty('token') || !await this.authService.validate(client.handshake.query.token) ) { client.error( (new UnauthorizedException('You are not authorized')).getResponse() ); client.client.close(); } } @UseGuards(WsJwtAuthGuard) @SubscribeMessage('event') handleMessage(client: any, event: SocketEvent) { if ( event.type == SocketEventType.MESSAGE ) { client.emit('event', { type: SocketEventType.MESSAGE, message: `hello! [${event.message}]` }); } } }
export interface SwaggerDocumentOptions { include?: Function[]; }
/** * Test that we don't register a service when the unit and * context don't match */ @Test public void testAddDifferentContext() throws InvalidSyntaxException { reg1 = registerUnit(emf1, "unit", TRUE); assertNoContextRegistered(); mgr.registerContext("context", client1, new HashMap<String, Object>()); assertNoContextRegistered(); }
What COVID-19 has introduced into education: challenges Facing Higher Education Institutions (HEIs) ABSTRACT The effect of the latest novel Coronavirus (COVID-19) on higher education, specifically the transition from face-to-face sessions to online and interactive learning systems, is investigated in this study. The paper discusses the difficulties that higher education institutions face in transitioning to ‘online pedagogy,’ including mobility issues, technology connectivity, digital learning, and differential access to education. The key obstacles of a shift to distance learning during COVID-19, according to the findings, are technical resources and differential access to education. Though COVID-19 was challenging for students, it also served as a springboard for realistic alternatives such as artificial intelligence (AI), public-private educational collaborations, and digitalization. Universities should study policies to mitigate the detrimental effects of COVID-19, according to the findings, while maintaining a dedication to creativity and large-scale changes in practice. Introduction The novel Coronavirus, or COVID-19, has precipitated monumental changes to HEIs, higher learning institutions, forcing them to shift from traditional face-to-face learning to digital systems, including remote learning. As Coronavirus continues its spree globally, as part of their physical distancing policy. The WHO (2021) recommends physical distancing as a concrete safety precaution, as outbreaks have occurred in restaurants, offices, and classes (WHO, 2021), which is relevant for this discussion. The U.N. Educational, Scientific, and Cultural Organization (UNESCO) estimates that nearly 130 countries have closed educational institutions nationwide, and several have implemented regional or local closures. School closures have affected more than 80% of students, thereby spurring debate on the impact of lockdown on the education system (Lancker & Parolin, 2020). Researchers are worried about the long-term consequences of lockdown on academic happenings, learning, experience, and children's overall development because online education cannot entirely replace all educational activities with the same efficacy. With the advent of e-learning, academics face challenges in acquiring and implementing I.T. skills for teaching purposes. Though the matter has gained heft among educators, policymakers, and researchers, studies are comparatively less, particularly in the context of Higher Education Institutions (HEIs). The researcher aims to explore the challenges that impact HEIs during their transition into online/distance learning because of COVID-19, contributing to an existing body of knowledge. Pulsipher (2020) notes COVID-19 'represents an immediate crisis for higher education, creating challenges for enrolled students and traditional institutions' (Pulsipher, 2020). El-Azar and Nelson (2020) suggests that the disruption to traditional ways of teaching may be so high that Universities that view conventional teaching as a go-to strategy after COVID-19 may be unlikely to even survive. The authors say that higher education has a future in blended learning programs that include asynchronous and synchronous communication methodologies, experiential teaching and both in-person and digital instruction. Institutions failing to embrace the new changes may not survive (El-Azar & Nelson, 2020). Essentially, experts are saying that the changes precipitated by COVID-19 and restrictions, which have almost put an end to in-person instruction in some cases, may be permanent. The paper is important because while it aims to reveal some of the fundamental problems associated with COVID-19 and restrictions, it also talks about some of the ways in which COVID-19 may develop new strategies for pedagogy, ones that are more in-line with the 21st century digital world. It positions technology as something positive. The paper makes salient contributions to literature that already details the negative impacts COVID-19 has had on post-secondary learning and HEIs. Much of the discourse surrounding COVID-19 and HEIs/post-secondary education has been negative and mostly about the difficulties of such transitions to virtual learning. The following study delves into some of the new possibilities presented by COVID-19, which include the use of AI, public-private partnerships in education and increased digitalization. There are opportunities for students to build new skills and innovate with technology. Gupta (2017) notes some benefits of digital or e-learning include greater accommodation of personal needs, capacity to repeat lectures if needed, accessing updated/upgraded content, reduction in costs, scalability (transferability to new settings), as well as lower environmental impact (Gupta, 2017). The paper aims to show how students transition into building lifelong skills, and how institutions offer students capacities in talent rather than skill learning. The study is structured in the following way. It provides a narrative overview or review of literature related to COVID-19, beginning with challenges to pedagogy, real world cases and examples (including Africa, which has low internet adoption rates), possible future pathways and broader implications of moving HEIs to the digital sphere. The study aims to inform readers about the ways in which HEIs are adapting to COVID-19, while revealing new opportunities that may bridge global inequity gaps. The last part of the study details potential recommendations that would assist HEIs in making these difficult transitions into virtual/remote learning. Background of the study The unprecedented and rapidly evolving nature of the COVID-19 global pandemic has shifted many HEIs to the online world, precipitating large-scale changes that some HEIs have been unable to deal with, or have had a difficult time handling. The fact that HEIs have newly developed emergency systems to help them transition into online learning does not mean they are ready for such systems, nor does it mean they are effective. While learner-centered education and online pedagogy has increased in scope within the past several decades, and especially since 2000, there are reasons for why HEIs continue to struggle. Zalat, Hamed, and Bolbol (2021) conducted a study on the perceptions of University medical staff at an Arabic post-secondary institution, finding that 36% of instructors had inadequate facilities and equipment, while 40% did not have proper internet connectivity. Technical problems were also common (Zalat et al., 2021). Younger instructors or those unfamiliar with technology may have a difficult time transitioning to e-learning. Coman, Țîru, Meseșan-Schmitz, Stanciu, and Bularca (2020) studied Romanian Universities and how they dealt with the transition to e-learning during COVID-19, finding that instructors had issues with adapting content to the online format, as well as technical problems with equipment (Coman et al., 2020). Issues in students included possible decreased motivation, feedback delays and learning obstacles (Coman et al., 2020). Emergency-based online content delivery to full-time online pedagogy Pedagogy refers to the best way to achieve learning. Successful pedagogy needs teachers to comprehend and decide the optimized way of delivering the course lectures to help students learn appropriately. E-learning requires altogether different pedagogy, especially in online assessment and individual and group interactions. E-learning is not just about stuffing the websites with information; it is also about developing new ICT skills as well (Islam, Beer, & Slack, 2015). While many institutions have shifted to an emergency-based online system, it does not mean that they are prepared for an 'online pedagogy' in the long run. Many scholars have questioned if HEIs are well-prepared for the forthcoming digital era of learning. There is no conclusive answer to this question as of now, but there is no denying that ongoing physical isolation is impacting the academic workforce (Crawford et al., 2020). Transforming to online teaching mechanisms, adopting a student-centered learning model and interactive sessions coupled with high chances of students' distractions, call for an innovative pedagogy in HEIs, thereby putting faculty members in a difficult situation. For the last decade, there has been a call to replace teacher-centered methods with learner-centered instructions (Moate & Cox, 2015). Learner-centered content delivery is multidimensional, non-linear, and happens in relation to social contexts. This learnercentered pedagogy revolves around a democratic approach, which enhances students' active participation and self-direction but leaves room for student distraction. Learner-centered pedagogy emerges from constructivist learning theory, making educators view education in relational and social spheres (Crawford et al., 2020). Power differentials between teachers and students get diffused, and educators intentionally create opportunities for students to share their experiences and participate in activities. While online learning tools can facilitate interactive learning, it is challenging for educators to keep students engaged and reduce the scope of distraction and misuse of technology. With digital platforms, educators will have to design the content not to fill the purpose of content delivery solely, but also to foster their creative thinking and implementing capabilities. It is a tremendous transformation and a challenge because an inclusive classroom is still an embryonic concept; current education approaches fall short of running student-centered classrooms (Modan, 2020). The advent of digital platforms is expected to create an urgency for this modification in the education system. Still, it is hard to predict how these transformations will affect traditional institutions that were explicitly designed to bring researchers, students, and teachers in proximity. While technological advances can offer them to shift to online programs gradually, significant differences between face-to-face interactions and online content delivery need to be managed effectively. Cornard (2004), cited in Islam et al. (2015), highlighted four different areas of expertise for an online instructor: pedagogical, social, technical, and managerial. Cornard (2004) conducted a questionnaire, which highlighted significant concerns of academics (Islam et al., 2015): • Loss of control over students • Lack of concentration compared to the traditional mode • Difficulty using online platforms • Felt 'left in the dark' because they could not observe students Migration from traditional or blended system to entirely virtual networks will not happen overnight. Lack of home office infrastructure and problems with the general skillset needed to design online virtual education are just a few issues. An analysis of responses by higher education systems across the world reveals that many universities do not have the resources and academic capabilities to transition to an online delivery system. They are just adopting a short-term approach that might prove unviable in the long-run (Crawford et al., 2020). Methodology The study is a narrative review of literature detailing the challenges students and teachers have faced with HEIs transitioning into the online sphere. It will select and use relevant literature, primarily from academic databases and government/non-government, credible organizations. The study will first reveal findings in a results table, and then proceed to describe these findings, subsequently providing recommendations. The study opens discourse for future opportunities in research, as well as recommendations. The following is a rationale for the literature review as a methodology. According to Western Sydney University (2017), literature reviews build knowledge in a field, convey important ideas and show readers new insights that apply to the real-world. They illuminate the direction that research takes in a subject (Western Sydney University, 2017). A literature review allows for appropriately engaging with and assessing key research within a given topic and can allow the researcher to familiarize himself/herself with the opinions of experts. It can assist the researcher in coming up with new questions for study (UNF, 2021). This is optimal for the research at hand because it will deal with uncovering relevant data and sources about COVID-19 and opportunities/challenges inherent in transitioning to e-learning for post-secondary instructors. The paper is also meant to provide an overview to readers, rather than serve as an experimental methodology, meaning the reader should gain a surface-level understanding of a variety of factors, including challenges in online pedagogy, consequences, methods and impacts. Challenges in online pedagogy Shifting learning paradigms to online platforms has become a 'new normal' for schools and higher educational institutions. Nonetheless, the integration of technology into the educational system depends on a myriad of aspects. Other than basic technological features, including accessing technical infrastructure, the quality of the network, and computers' availability, several subtle facets might facilitate or hamper teacher-student interaction via digital platforms. Previous studies have suggested that the successful incorporation of technology into education relies on the interaction between three key players: students, teachers, and technology. Learning competencies Teachers' perspectives on teaching and teaching methodology have a colossal impact on teacher-student interaction. Suppose they view teaching as a means of knowledge exchange and employ a teacher-centered approach. In that case, they will communicate the information to students and use different assessment techniques to evaluate their grasp of knowledge or comprehension of data. If they see teaching as a means of conceptual change and use a student-centered approach by encouraging independent learning, they will prefer to facilitate debates, cross-questioning, discussion among students, and assessment forms to evaluate conceptual clarity. Teachers' competencies have a significant role in the successful transition from offline to digital mediums. As research has already highlighted negative impacts on students' output and motivation, teachers must explore different interactive ways to engage students. They can also employ a mix of teacher and student-centric methods to assert the benefits of both approaches. Resistance to change Using an online medium for delivering education is optimal in the changing environment, but nobody can deny the possibilities of resistance to change. As per a study (which analyzed psychological factors affecting teachers' ability to be a part of the change), teachers mentioned discomfort, doubts, worries, feelings of being lost, and moving towards something unusual. Shifting to technological means is not comfortable for all. Teachers, who are experienced enough and enjoy traditional ways of imparting education, might feel it difficult to adapt to the changes (Duraku & Hoxha, 2020). Resistance to change is a natural product of dealing with unfamiliar circumstances. Field of study The requirement of technical equipment varies from one field to another. Clinical medicine, veterinary studies, and several other disciplines need laboratory access; education in such areas cannot be replaced entirely by distance learning. Many creative areas as art, music, and design need required equipment and negatively affect students' performance in work from home settings. A challenge is ensuring all necessary equipment. Transition from degree-based to skill-based talent Covid-19 has escalated several disruptive trends related to higher education. Online has become 'increasingly mainstream' after decades of its slow adoption in higher education spheres. Still, one of the most debilitating disruptions will be the fast-paced transition from degree-based to skill-based talent. The idea that a college degree automatically prepares students to join the workforce is already outdated. The coronavirus outbreak has dramatically increased the need for upskilling and mid-career reskilling. These upskilling and reskilling programs must ensure smart learning, not just learning. With the survey highlighting that over a third of workers would need additional education if they lost their existing jobs, program design and instruction delivery challenges are not beyond imagination (Pulsipher, 2020). Even those who retain their jobs would need to learn new skills to adapt and integrate into the new normal. There is no denying that these disruptions are powerful enough to facilitate innovation, which can lower cost for students and enhance the value of their degrees by aligning them with workforce imperatives. Still, the merits and demerits of these modifications depend on how a country or institution embraces the change. Universities must align their courses according to industry needs. It is challenging now, and the results depend on several aspects, including students' learning behavior and quality of upskilling programs. Gaps in educational attainment There is no denying that COVID-19 has broadened inequalities concerning educational opportunities. While developed nations can easily plan to switch to virtual learning and pacify the pandemic's adverse effects, the situation is not-so-easy for developing countries. Poor and emerging nations have a shortage of technological infrastructure, and their access to low-cost networking options is inadequate. Statistics highlight that only 60% of the population is the world is online. While internet penetration is 95% in North America, it is only 39.3% in Africa (Internet World Stats, n.d.). As such, the transition to online classes can affect a large chunk of people because of their inaccessibility to expensive data plans and digital devices (World Economic Forum, 2020). A regional survey analysis (Table 1, Table 2 and Table 3) has further exposed substantial differences between Africa and other countries. The table clearly shows significant differences between Africa and other continents concerning the adoption of virtual learning models. In Africa, the lack of access to technology has caused many universities to cancel their programs, as compared to other global regions. Universities in Africa have found it challenging to implement alternatives to in-person learning, which has detrimental impacts courses (International Association of Universities, 2020). The issue of inequality is also not restricted to Africa. It has created divisions among HEIs even if they are operating in the same geographical region. Approximately half of HEIs in the U.S., Europe, and the Asia Pacific have stated that COVID-19 has strengthened their community engagements. In contrast, the other half on the same continents have noted a weakening of community engagement. Inequalities are also not limited to a country or state; they equally hold at an individual level. Financially sound students have access to the most and highest quality resources, while students from low socioeconomic backgrounds are likely to suffer the most. Impact on less-proficient students There is mounting evidence that online sessions hurt a critical group: the group of less proficient students who are in dire need of classroom teachers. A growing body of research has suggested that students with different learning levels and achievements fare well in the blended model. The online model does not replace traditional classes; it supplements the latter (The New York Times, 2018). The scenario can be completely different in the fully online model because it can create more learning issues for less proficient students. In these sessions, students have more distractions that can affect their motivation and enthusiasm to learn further. The bottom line is that the outcomes of online classes vary from person to person. There might be no distinction for a few pupils, but for some, the in-person method is more beneficial. Still, students from the weakest academic backgrounds are likely to suffer from the negative impacts of e-learning, which is decidedly more impersonal (The New York Times, 2018). Impact on Students' Learning and Training: A Case of Medical Students Several teaching hospitals in the U.K. have suspended internship and clerkship students from attending clinical attachments. The ongoing suspension in hospitals might become more aggressive if the situation continues unabated. It will reduce medical students' exposure in specific specialties and cause a detrimental impact on their performance and competencies. It will also cause financial loss to students, as they might miss the opportunity to work outside the U.K. (Ahmed, Allaf, & Elghazaly, 2020). The shifting of in-person classes with online equivalents has disrupted the collaborative environments in which a medical student needs to work. Cancellation of clerkships is a serious matter because it is crucial for skill acquisition and relationship building. The pandemic has curtailed students' opportunities for personal development and the scope of participation in conference presentations. Effects on international mobility of learners The cross-border movement of students is a defining aspect of the global higher education landscape. There has been an average annual growth of 10% in international student mobility in the last two decades. Nearly 5 million students move to different nations every year for tertiary education; the organization for Economic Co-operation and Development (OECD) has predicted that the numbers will rise to 8 million by 2025 (BizED, 2020). However, this trend has been severely affected by the current pandemic. A recent survey conducted by the Institute of International Education (IIE) has raised concerns about students' mobility between the U.S. and China. Around 95% of HEIs in Europe and 91% in America have reported that their student mobility has been affected due to COVID-19 (International Association of Universities, 2020). It has been suspected that the decreasing number of university partnerships with other nations can significantly affect the number of students studying abroad. The Trump administration had barred international students from the country if their respective institutions have moved to the only online curriculum; however, the rule was rescinded because several universities sued the Trump administration over this rule (Quintana, 2020). Still, there is no denying that chaos and confusion over international mobility persists, and the chances of students going abroad have been significantly affected. Impact on Students' Health Learning and collaborating in online and virtual environments might not arrive naturally. Policymakers must think about balancing digital with screen-free activities. In recent times, education has become online, but parents and teachers are equally concerned about the physical and emotional health of students. A current government directive in India shortened the length and duration of online classes considering their impact on students' overall health and well-being. Undoubtedly, online programs provide flexibility and ease to join classes from the comforts of home, but continuous classes are harmful to eyes, ears, and brains (Anand, 2020). Sleep disorders are already burgeoning, and researchers are still exploring the harm screen time can cause students' sleep and creativity. Prolonged classes can take a toll on students' health, and they can suffer from watery eyes, headaches, and burning sensation. A senior eye surgeon from India has confirmed that daily screen time for hours can cause several issues because blood circulation becomes stagnant, and oxygen supply reduces. Computer Vision Syndrome, as it is known in medical terms, can become worse because students are likely to watch T.V. or mobile after their classes (Anand, 2020). Many students are continuing courses on smartphones than laptops, which can further worsen watery eyes and burning sensations. Impacts on academic output of students Online education has been growing at a fast pace in the past few decades. In 2011, more than 6,00,000 students took one or more courses online, and the percentage of online enrollments increased from 9.6% in 2002 to 32% (Internet World Stats,n.d.). This trend motivated researchers to explore the promises and pitfalls of the online medium of instructions and content delivery. The topic was explored from multiple angles and provided some conflicting yet useful insights. Scholars have endorsed that achievement in online sessions can be affected by age, marital status, learning styles (audio vs. visual learning), and learners' maturity levels. Evidence also suggests that cheating is four times more in online sessions than traditional in-person classes. These factors affect reported differences between students' achievements (Dr, 2015). Scholars have raised several concerns, including the engagement of students and their concentration in the online mode of learning. Research has revealed that students earning B grade in in-person classes would have received C grade in online courses. Additionally, taking a course online is likely to reduce their GPA by 0.15 points. Students are more likely to drop out because of a lack of engagement and motivation (Bettinger & Loeb, 2017). On the contrary, some studies have denied any significant difference in students' performance between online and traditional models. Nonetheless, it is essential to mention that online students are more likely to cheat (in the unsupervised environment), which might affect the level of their assessment and provide unsatisfactory results. Low achievement reported in online classes might be due to technical malfunctions during the examination. This leads to lower output, because students have difficulty expressing themselves on examinations, and proving results. Precisely, researchers are not unanimous about students' output in online settings. COVID-19 can be seen as an opportunity to spur such research and provide insightful findings down the line. Innovation in digitalization Coronavirus has changed the whole orientation of education and learning in the world. While the most pressing concerns have been the digital divide, unequal access, and rising inequalities, one must also remember opportunities in innovation and a monumental shift in educational approaches. Several academic institutions have been running with outmoded classrooms and lecture-based approaches for a long time, and COVID-19 can be seen as a catalyst for educational institutions to explore and imbibe innovation via technological solutions. Examples from over the world have shown that HEIs are fast-pacing to find adequate answers to academic issues. For example, students in Hong Kong started home learning via interactive applications, and China facilitated approximately 120 million students' access to learning material through live television broadcasts (World Economic Forum, 2020). Likewise, a school in Lebanon initiated online learning even for physical education. Google Meet platform was implemented in Georgia in a private school with 950 students. The analysis highlights that the transition was successful, and the experiences could be modelled in other countries (Basilaia & Kvavadze, 2020). This indicates that there are emerging opportunities in digital communication, which facilitate a new kind of learning that may be useful for students in the future. With the penetration of 5 G technologies in several countries, including China, the U.S., and Japan, the concept of learning anywhere and anytime is expected to grow. As of now, there are challenges because of a lack of infrastructure and digital capacity/equipment, but the crisis has paved the way for further research and innovation in 5 G technologies. Furthermore, it can demonstrate several enticing ways to successfully combine offline and online mediums in the coming years. The crises have facilitated educational institutions to connect students worldwide via different means such as Zoom, Microsoft Teams, and interactive webinars. As of now, these changes seem uncomfortable, but there is a silver lining too. These initiatives will quicken the pace of research in advanced educational platforms and methodologies and have a lasting impact on innovation and digitization. It would reshape schooling and align it with the most effective technology channels. Public-private educational partnerships COVID-19 has provided an excellent opportunity for learning consortiums and coalitions among diverse stakeholders, including educators, publishers, technology providers, and network operators. Two positives will be emerging out of this scenario. First, there will be increased trust and mutual relationships between citizens and their governments, particularly during a time when people are growing mistrustful of the government. Second, the free tech sector will play a notable role in developing new cloud-based online learning platforms to upgrade the existing infrastructure. In emerging nations, where government plays a substantial role in imparting education, public-private partnerships can become a new trend in the education sector. An excellent example of such initiatives is readtogether.hk in Hong Kong, a consortium of more than 60 educational institutions, media, publishers, educators, providing over 900 educational assets such as books and videos for free (El-Azar & Nelson, 2020). The consortium intends to continue these services even after the restrictions with COVID-19 ease. Though these examples are few and isolated, good chances exist of beneficial partnerships in the next couple of years. Artificial intelligence The need to adopt new technologies in the current pandemic could encourage educators to use tools powered by artificial intelligence (A.I.). AI-enabled tools can help HEIs estimate class size, planning curricula, and allocating resources such as facilities and financial aid. It can also be used in student guidance, such as recommending courses and suggesting possible career paths. Traditionally, institutions use several factors, including GPA or attendance, to identify the risk level of students. Still, A.I. software systems can utilize more subtle information to assess student risks by determining their overall behavior (Pranam, 2019). Some software even incorporates data such as when a student stops going to the cafeteria for lunch. Wollowski, Neller, and Boerkoel (2017) note there are opportunities for students to explore their own perceptions of ethics with AI. In one paper, authors talk about using real-world projects to introduce students to AI within academic and nonacademic contexts. Lessons can be supplemented by intelligent agents, video lessons and digitalized tutors. It also means broadening experiences to include non-academic students (Wollowski et al., 2017). The implication is that the potential for AI to include a diverse range of learners, even from non-academic backgrounds, is massive. It also means the possibility of using AI chat bot tutors as replacement for face-to-face tutors, cutting down on transportation and service cost for students. In remote learning, A.I. tools can help teachers forego repetitive and time-intensive tasks and help them concentrate on higher-value education work. These tools can also break down assignments into smaller components that are easily understandable. These systems are of much help for international students who have language barriers. The cutting-edge research in text translation can help teachers translate the content in students' native tongue. Likewise, voice recognition tools can help teachers deliver lectures with stunning accuracy (Pranam, 2019). The current time has made it an urgency to develop such systems, as they will help mitigate some of the negative consequences of online learning. Future research in A. I. systems and rapid deployment into the education sector can usher into an altogether transformative era marked by excellent efficiency and high productivity. Implications of migration from face-to-face teaching to digital learning Shifting from traditional to face-to-face to online models need universities to work on several aspects. These include (U.S. Department of Education, 2012): • Individualized Instructions: based on the different academic level of students and their learning trajectory • Personalized learning: developing students' interest and motivation to fetch better learning outcomes • Optimizing opportunities for economies of scale: by reuse of material and largescale distribution • Broadening access: reducing the cost of providing access to educational resources, particularly in remote areas • Cutting down fixed costs: by utilizing home and community spaces in addition to school buildings These paths suggest that educational institutions need to focus on benefits and cost strategies to optimize the merits of remote and online models. Merely developing the equivalent of existing teaching practices might not be sufficient, and there is a need to redesign core educational processes. Instructions should be tailored to individual needs and supported by feedback. These systems will be based on competency, wherein students will exhibit the desired level of mastery and show inclination in learning new skills. The present crisis could lead to the following three scenarios in education: • The emergence of technological innovations in response to the shift in students' behavior • The reluctance of students to join traditional courses after experiencing online education at a lower cost • Alterations in job markets can encourage people to use their skills in similar profiles (for example, students form aviation and hospitality can apply in other patterns using related skills and knowledge These changes would need universities to tackle situations by adopting a multi-pronged approach. Rather than merely initiating the migration of existing courses online, they must look at the possible combinations of the subject domain, technological affordance, and assessment approaches that can work best for a particular group of students. Underserved students would need special attention, and the present scenario is not catering to their needs adequately. These students will need excellent access, adult supervision, technical aptitude, and independent learning skills for full engagement in online courses. To reduce the risk of dropping out of online programs, using online learning for credit recovery is a viable option that can be explored further. Last but not least, educational institutions must engage in continuous research and development to fuel innovation. They must identify the barriers the slow down the adoption of online learning models and explore practical strategies to overcome those barriers. Conclusion, recommendation and future work The discussion presents a complete overview of the strengths and weaknesses of the current scenario. This study found that the main challenges that impact online learning in COVID19 situation are related to unequal access to education, technological infrastructure issues, mobility, as well as the need to adapt to new systems of learning/teaching. Poor and developing economies have substantially less access to low-cost infrastructure and networking options, making their transition to the online sphere more difficult. Some studies show that education can become inequitable for poorer-performing students, who require additional face-to-face assistance. Plagiarism and cheating also increases vastly under e-learning systems. Teachers must find new ways to deliver instruction, and some may be resistant to change. Students also may have a difficult time accessing important class-related equipment, such as musical instruments or art equipment. While the shift from degree-based to talent-based learning is a positive step in the right direction, it also means large-scale attitudinal and practical changes in implementation. There is also the risk that international activity in education will decrease as a result of the current scenario. There is no denying that COVID-19 has made the education industry take surprising turns. These changes disrupt the general 'comfort zone' of teachers who have had practices solidly embedded in their pedagogical repertoire, and who have been teaching students in-person for a long time. Scholars are right in highlighting the negative consequences of this shift in the long run, but opportunities ahead should not be denied or ignored. Some of the opportunities and examples provided here are also significant and are congruent with trends toward increased globalization and interconnectedness, while there are pushes toward cohesion. There are ways to engage a broad range of learners that no longer face geographical or proximal limitations. Dimitriadis, McCarthy, Sultana, and Blackmore (1998) note one of the challenges of the 21 st century is aligning processes of globalization with nation states' natural desire for social and ideological cohesion. Postmodernity and globalization are effectively channeled and mediated through education (Dimitriadis et al., 1998). E-learning offers opportunities for nation states to build themselves, as well as to potentially explore meaningful cultural connections with others. Market imperatives continue to drive post-secondary education, particularly with increased openness to international education, and e-learning can only serve as a bridge, rather than barrier, between different cultures, religions, ethnicities and nations. Learning Management Systems or LMS have several benefits as noted by literature. They can adapt to changing circumstances, be delivered by instructors through mobile devices, and keep things efficient by having everything contained in a single online system (De Angelis, 2014). The paper discovered that there are inequalities in the delivery of online education, especially for areas of poverty and in Africa. With the correct infrastructure, e-learning can help permanently transition developing nations into the global technological framework and society, so that marginalized ethnic groups can participate in meaningful economic activities and social discourse. The situation is chaotic because the shortcomings of online classes are more visible than the benefits. Over time, the right technological elements will be used to create a seamless mix of online and offline programs. It is time to embrace the change via collaboration and cooperation. The digital divide can be mitigated to a significant extent if developed nations, partner with developing and emerging countries in providing infrastructural and technical assistance. Succinctly, collaboration is the way of fighting the pandemic. If the world succeeds in collaborating, it will likely experience several positive changes in the years to come. The current wave of isolation, work from home, and online education proffers an excellent opportunity amidst all odds. If exploited effectively, it will pave the way for altogether new educational models and approaches. Nonetheless, universities need to: Explore security options for taking an examination from home This would be necessary to combat plagiarism and cheating which, as literature indicates, is easier for students to do from home, on a computer, where plagiarism materials are easier to access Explore different time and schooling models. It may be necessary to examine how instructors can provide both synchronous and asynchronous communication and instructional methods Empower teachers to make the best use of technological advances. As current literature stands, teachers may have a difficult time implementing digital learning because of limitations on knowledge and capacity limits with infrastructure. This approach involves meaningfully integrating training, development and support programs to assist teachers in broad-range and more focused online activities. They need to devise and implement the best strategies to reduce costs and leverage maximum benefits. Adequate interventions can reduce current concerns to a significant extent. It is high time that educators, government authorities, HEIs, and other stakeholders accept the situation and join hands to fetch the best out of the pandemic. Availability of data and material Not applicable Ethical approval This work received a research grant from Walailak University with a Ref. Consent for publication The corresponding author has got copyright to publish the paper
// Return the average value of int[] grades public static double average() { int total = 0; for(int i = 0;i < grades.length; i++){ total += grades[i]; } return (double) (total / grades.length); }
<reponame>LtPeriwinkle/robbb use super::*; /// Set your role. Use without arguments to see available roles. #[command] #[only_in(guilds)] #[usage("role [role-name]")] #[aliases("roles")] pub async fn role(ctx: &client::Context, msg: &Message, args: Args) -> CommandResult { let config = ctx.get_config().await; if let Some(chosen_role_name) = args.remains() { let guild = msg.guild(&ctx).await.context("Failed to load guild")?; let chosen_role = config .roles_color .iter() .filter_map(|r| guild.roles.get(r)) .find(|r| { r.name == chosen_role_name || Some(r.id) == chosen_role_name.parse::<RoleId>().ok() }) .user_error("Unknown color role")?; let mut member = guild.member(&ctx, msg.author.id).await?; let old_roles = member.roles.clone(); member.remove_roles(&ctx, &config.roles_color).await?; if !old_roles.contains(&chosen_role.id) { member.add_role(&ctx, chosen_role.id).await?; msg.reply_success( &ctx, format!("Success! You're now {}", chosen_role.id.mention()), ) .await?; } else { msg.reply_success(&ctx, "Success! Removed your role!") .await?; } } else { msg.reply_embed(&ctx, |e| { e.title("Available roles"); e.description(config.roles_color.iter().map(|r| r.mention()).join("\n")); e.footer(|f| f.text(format!("Usage: {}", &ROLE_COMMAND_OPTIONS.usage.unwrap()))); }) .await?; } Ok(()) }
Interiorization Phenomenon within the Plots of the Fantastic Tales by F. V. Bulgarin (1820–1840s) The paper focuses on the analyses of the interiorization phenomena in the fantastic (utopian and dystopian) tales by Faddey Bulgarin that he wrote and published between 1825 and 1846. The tales came out in such periodicals as Severnyy archiv, Literturnye zapiski, Syn otechestva. The study of the texts allows to assume that Rus-sian mass literature born within magazine prose was characterized by the interiorization of plots. The latter led to the formation of an adaptive hab-itus entirely assimilated by the Russian cultural and social discourses around the 1830–1840s. The study of the texts by Bulgarin (which in terms of genre can be identified either as journal manifestos or literary works of different genres) indicates his conscious orientation on the reader, the intended involvement of the reader into the literary and would-be-literary life of an artistic word. On the one hand, that could be the echo of the tradition established by the Enlighteners who educated the reader via literary words, thus shaping his or her ethics and esthetics. On the other hand, that could be the reflection of the interiorization phenomenon that is the structural transposition of a text (text structure) into the internal structure of the reader’s mind. We suggest that the interiorization phenomenon and the shaping of the mass literature are interconnected; the adaptive habitus born in the magazine prose in the mid-1820s – the early 1840s determined the energy of mind and the peculiarities of thinking of the mass reader. Despite almost no narrator addressing the reader in the fantastic tales, the reader finds him- or herself indirectly present throughout the texts as an addressee of the interiorization. The discursive strategy adopted by Bulgarin consists of the transformation of the reader’s mind patterns into the adaptive habitus of mass literature.
use crate::facades::QuickJsRuntimeFacade; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use hirofa_utils::js_utils::adapters::JsRuntimeAdapter; use hirofa_utils::js_utils::facades::{JsRuntimeBuilder, JsRuntimeFacade}; use hirofa_utils::js_utils::modules::{NativeModuleLoader, ScriptModuleLoader}; use hirofa_utils::js_utils::JsError; use hirofa_utils::js_utils::ScriptPreProcessor; use std::time::Duration; pub type EsRuntimeInitHooks = Vec<Box<dyn FnOnce(&QuickJsRuntimeFacade) -> Result<(), JsError> + Send + 'static>>; /// the EsRuntimeBuilder is used to init an EsRuntime /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// // init a rt which may use 16MB of memory /// let rt = QuickJsRuntimeBuilder::new() /// .memory_limit(1024*1024*16) /// .build(); /// ``` pub struct QuickJsRuntimeBuilder { pub(crate) script_module_loaders: Vec<Box<dyn ScriptModuleLoader + Send>>, pub(crate) native_module_loaders: Vec<Box<dyn NativeModuleLoader<QuickJsRealmAdapter> + Send>>, pub(crate) opt_memory_limit_bytes: Option<u64>, pub(crate) opt_gc_threshold: Option<u64>, pub(crate) opt_max_stack_size: Option<u64>, pub(crate) opt_gc_interval: Option<Duration>, pub(crate) runtime_init_hooks: EsRuntimeInitHooks, pub(crate) script_pre_processors: Vec<Box<dyn ScriptPreProcessor + Send>>, pub(crate) interrupt_handler: Option<Box<dyn Fn(&QuickJsRuntimeAdapter) -> bool + Send>>, } impl QuickJsRuntimeBuilder { /// build an EsRuntime pub fn build(self) -> QuickJsRuntimeFacade { QuickJsRuntimeFacade::new(self) } /// init a new EsRuntimeBuilder pub fn new() -> Self { Self { script_module_loaders: vec![], native_module_loaders: vec![], opt_memory_limit_bytes: None, opt_gc_threshold: None, opt_max_stack_size: None, opt_gc_interval: None, runtime_init_hooks: vec![], script_pre_processors: vec![], interrupt_handler: None, } } /// add a script loaders which will be used to load modules when they are imported from script /// # Example /// ```rust /// use hirofa_utils::js_utils::Script; /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// use hirofa_utils::js_utils::modules::ScriptModuleLoader; /// struct MyModuleLoader {} /// impl ScriptModuleLoader for MyModuleLoader { /// fn normalize_path(&self,ref_path: &str,path: &str) -> Option<String> { /// Some(path.to_string()) /// } /// /// fn load_module(&self, absolute_path: &str) -> String { /// "export const foo = 12;".to_string() /// } /// } /// /// let rt = QuickJsRuntimeBuilder::new() /// .script_module_loader(Box::new(MyModuleLoader{})) /// .build(); /// rt.eval_module_sync(Script::new("test_module.es", "import {foo} from 'some_module.mes';\nconsole.log('foo = %s', foo);")).ok().unwrap(); /// ``` pub fn script_module_loader<M: ScriptModuleLoader + Send + 'static>( mut self, loader: Box<M>, ) -> Self { self.script_module_loaders.push(loader); self } /// add a ScriptPreProcessor which will be called for all scripts which are evaluated and compiled pub fn script_pre_processor<S: ScriptPreProcessor + Send + 'static>( mut self, processor: S, ) -> Self { self.script_pre_processors.push(Box::new(processor)); self } pub fn runtime_init_hook<H>(mut self, hook: H) -> Self where H: FnOnce(&QuickJsRuntimeFacade) -> Result<(), JsError> + Send + 'static, { self.runtime_init_hooks.push(Box::new(hook)); self } /// add a module loader which can load native functions and proxy classes /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::valueref::JSValueRef; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// use quickjs_runtime::quickjs_utils::functions; /// use quickjs_runtime::quickjs_utils::primitives::{from_bool, from_i32}; /// use quickjs_runtime::reflection::Proxy; /// use hirofa_utils::js_utils::Script; /// use hirofa_utils::js_utils::modules::NativeModuleLoader; /// /// struct MyModuleLoader{} /// impl NativeModuleLoader<QuickJsRealmAdapter> for MyModuleLoader { /// fn has_module(&self, _q_ctx: &QuickJsRealmAdapter,module_name: &str) -> bool { /// module_name.eq("my_module") /// } /// /// fn get_module_export_names(&self, _q_ctx: &QuickJsRealmAdapter, _module_name: &str) -> Vec<&str> { /// vec!["someVal", "someFunc", "SomeClass"] /// } /// /// fn get_module_exports(&self, q_ctx: &QuickJsRealmAdapter, _module_name: &str) -> Vec<(&str, JSValueRef)> { /// /// let js_val = from_i32(1470); /// let js_func = functions::new_function_q( /// q_ctx, /// "someFunc", |_q_ctx, _this, _args| { /// return Ok(from_i32(432)); /// }, 0) /// .ok().unwrap(); /// let js_class = Proxy::new() /// .name("SomeClass") /// .static_method("doIt", |_q_ctx, _args|{ /// return Ok(from_i32(185)); /// }) /// .install(q_ctx, false) /// .ok().unwrap(); /// /// vec![("someVal", js_val), ("someFunc", js_func), ("SomeClass", js_class)] /// } /// } /// /// let rt = QuickJsRuntimeBuilder::new() /// .native_module_loader(Box::new(MyModuleLoader{})) /// .build(); /// /// rt.eval_module_sync(Script::new("test_native_mod.es", "import {someVal, someFunc, SomeClass} from 'my_module';\nlet i = (someVal + someFunc() + SomeClass.doIt());\nif (i !== 2087){throw Error('i was not 2087');}")).ok().expect("script failed"); /// ``` pub fn native_module_loader<M: NativeModuleLoader<QuickJsRealmAdapter> + Send + 'static>( mut self, loader: Box<M>, ) -> Self { self.native_module_loaders.push(loader); self } /// set max memory the runtime may use pub fn memory_limit(mut self, bytes: u64) -> Self { self.opt_memory_limit_bytes = Some(bytes); self } /// number of allocations before gc is run pub fn gc_threshold(mut self, size: u64) -> Self { self.opt_gc_threshold = Some(size); self } /// set a max stack size pub fn max_stack_size(mut self, size: u64) -> Self { self.opt_max_stack_size = Some(size); self } /// set a Garbage Collection interval, this will start a timer thread which will trigger a full GC every set interval pub fn gc_interval(mut self, interval: Duration) -> Self { self.opt_gc_interval = Some(interval); self } /// add an interrupt handler, this will be called several times during script execution and may be used to cancel a running script pub fn set_interrupt_handler<I: Fn(&QuickJsRuntimeAdapter) -> bool + Send + 'static>( mut self, interrupt_handler: I, ) -> Self { self.interrupt_handler = Some(Box::new(interrupt_handler)); self } } impl Default for QuickJsRuntimeBuilder { fn default() -> Self { QuickJsRuntimeBuilder::new() } } impl JsRuntimeBuilder for QuickJsRuntimeBuilder { type JsRuntimeFacadeType = QuickJsRuntimeFacade; fn js_build(self) -> QuickJsRuntimeFacade { self.build() } fn js_runtime_init_hook< H: FnOnce(&QuickJsRuntimeFacade) -> Result<(), JsError> + Send + 'static, >( mut self, hook: H, ) -> Self { self.runtime_init_hooks.push(Box::new(hook)); self } fn js_script_pre_processor<S: ScriptPreProcessor + Send + 'static>( mut self, preprocessor: S, ) -> Self { self.script_pre_processors.push(Box::new(preprocessor)); self } fn js_script_module_loader<S: ScriptModuleLoader + Send + 'static>( mut self, module_loader: S, ) -> Self { self.script_module_loaders.push(Box::new(module_loader)); self } fn js_native_module_loader< S: NativeModuleLoader<<<<Self as JsRuntimeBuilder>::JsRuntimeFacadeType as JsRuntimeFacade>::JsRuntimeAdapterType as JsRuntimeAdapter>::JsRealmAdapterType> + Send + 'static, >(mut self, module_loader: S) -> Self where Self: Sized{ self.native_module_loaders.push(Box::new(module_loader)); self } } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use hirofa_utils::js_utils::modules::ScriptModuleLoader; use hirofa_utils::js_utils::Script; #[test] fn test_module_loader() { struct MyModuleLoader {} impl ScriptModuleLoader for MyModuleLoader { fn normalize_path(&self, _ref_path: &str, path: &str) -> Option<String> { Some(path.to_string()) } fn load_module(&self, _absolute_path: &str) -> String { "export const foo = 12;".to_string() } } let rt = QuickJsRuntimeBuilder::new() .script_module_loader(Box::new(MyModuleLoader {})) .build(); match rt.eval_module_sync(Script::new( "test_module.es", "import {foo} from 'some_module.mes';\nconsole.log('foo = %s', foo);", )) { Ok(_) => {} Err(e) => panic!("script failed {}", e), } } }
<reponame>gabrielribeirof/chatter export enum ViolationReasons { REQUIRED = 'REQUIRED', BAD_LENGTH = 'BAD_LENGTH', MAX_LENGTH = 'MAX_LENGTH', MIN_LENGTH = 'MIN_LENGTH', CHOICES = 'CHOICES', INVALID_EMAIL = 'INVALID_EMAIL', EMAIL_ALREADY_REGISTERED = 'EMAIL_ALREADY_REGISTERED', NAME_ALREADY_REGISTERED = 'NAME_ALREADY_REGISTERED', }
import React, { Fragment } from 'react'; import { Icon } from 'antd'; import classNames from 'classnames'; import { StyleProps, WithFalse } from '@/typings'; import Link, { LinkProps } from '@/components/Link'; import './style.less'; export interface Render { copyrightRender: WithFalse<() => CopyrightProps>; } export interface FooterProps extends Partial<StyleProps>, Partial<Render> { links?: WithFalse<LinkProps[]>; copyright?: WithFalse<CopyrightProps>; } export interface CopyrightProps extends Partial<StyleProps>, Partial<Render> { prefix?: WithFalse<React.ReactNode>; year?: number; copyright?: React.ReactNode; defaultCopyright?: React.ReactNode; } const Copyright: React.FC<CopyrightProps> = ({ prefix, year, copyright, defaultCopyright, copyrightRender, }: CopyrightProps) => { if (copyrightRender) { return copyrightRender(); } return ( <> {prefix && ( <> <span>{prefix} </span> <span>{year} </span> </> )} <span>{copyright || defaultCopyright}</span> </> ); }; export const defaultCopyrightPrefix = () => ( <Fragment> Copyright <Icon type="copyright" /> </Fragment> ); Copyright.defaultProps = { prefix: ( <> Copyright <Icon type="copyright" /> </> ), year: new Date().getFullYear(), defaultCopyright: '咖啡之音工作室出品', }; const Footer: React.FC<FooterProps> = props => { const { links, copyright, copyrightRender, style, className } = props; return ( <footer className={classNames('ant-pro-global-footer', className)} style={{ padding: 0, ...style }} > {links && ( <div className="ant-pro-global-footer-links"> {Array.isArray(links) && links.map((linkProps, index) => <Link key={index} {...linkProps} />)} </div> )} {copyright && ( <div className="ant-pro-global-footer-copyright"> <Copyright {...copyright} copyrightRender={copyrightRender} /> </div> )} </footer> ); }; Footer.defaultProps = { copyrightRender: false, } as FooterProps; export default Footer;
module HsFp1.ParsePerson where import Data.String import Data.List(all) import Data.Text(pack, unpack, splitOn) import Text.Read (readMaybe) data Error = ParsingError | IncompleteDataError | IncorrectDataError String deriving (Show) data Person = Person { firstName :: String, lastName :: String, age :: Int } deriving (Show) parsePerson :: String -> Either Error Person parsePerson s = let l = splitOn (pack "\n") (pack s) d = map (splitOn (pack " = ")) l isValid (k:v:[]) = True isValid _ = False value n = loop d where loop [] = Nothing loop ((name:val:[]):ds) = if name == pack n then Just (unpack val) else loop ds personInfo = case (value "firstName", value "lastName", value "age") of (Just a, Just b, Just c) -> Just (a,b,c) _ -> Nothing getPerson = case personInfo of Nothing -> Left $ IncompleteDataError Just (fn, ln, age) -> case readMaybe age :: Maybe Int of Nothing -> Left $ IncorrectDataError age Just ageInt -> Right $ Person fn ln ageInt parse | not $ all isValid d = Left $ ParsingError | otherwise = getPerson in parse test1 = "firstName = John\nlastName = Connor\nage = 30" splitTest = splitOn (pack "\n") (pack test1) dataTest = fmap (splitOn (pack " = ")) splitTest
/** * Given a feature type name, figure out if the warehouse thinks it should * *NOT* be drawn. * * @param warehouse the warehouse to build the graphics. * @param featureName the VPF name of the feature (polbndl, for example). * @return SKIP_FEATURETYPE if the feature should not be drawn. */ protected char whatFeatureType(VPFWarehouse warehouse, String featureName) { char featureType = SKIP_FEATURETYPE; FeatureClassInfo fci = getFeatureClassInfo(featureName); if (fci == null) { return featureType; } char type = fci.getFeatureType(); if ((type == AREA_FEATURETYPE && warehouse.drawAreaFeatures()) || (type == TEXT_FEATURETYPE && warehouse.drawTextFeatures()) || (type == EDGE_FEATURETYPE && warehouse.drawEdgeFeatures()) || (type == EPOINT_FEATURETYPE && warehouse.drawEPointFeatures()) || (type == CPOINT_FEATURETYPE && warehouse.drawCPointFeatures())) { featureType = type; } return featureType; }
/** * Determines, if input file is VDLt or VDLx. Parses VDLt into a temporary VDLx file. Adds VDLx * into the VDC. Skips to next file on error. * * @param args is the argument vector of main * @param start is the start of filenames in the argument vector. * @param define is a VDC connector to add to the VDC * @param reject is a writer to gather definitions that were reject from the VDC, depending on * the overwrite mode. If <code>null</code>, no rejects will be gathered. * @param overwrite determines insert or update mode. * @return a set of filenames which reported errors. * @see #addFileToVDC( String, Define, Writer, boolean ) */ public Set addFilesToVDC( String[] args, int start, Define define, Writer reject, boolean overwrite) { Set result = new TreeSet(); for (int i = start; i < args.length; ++i) { m_logger.log("app", 1, "parsing \"" + args[i] + "\""); try { if (!addFileToVDC(args[i], define, reject, overwrite)) { m_logger.log("default", 0, "XML parsing error, skipping to next file"); result.add(args[i]); } } catch (VDLtParserException e) { m_logger.log("default", 0, "syntactical error, skipping to next file"); System.err.println(e.getMessage()); result.add(args[i]); } catch (VDLtScannerException e) { m_logger.log("default", 0, "lexical error, skipping to next file"); System.err.println(e.getMessage()); result.add(args[i]); } catch (IOException e) { m_logger.log("default", 0, "I/O error, skipping to next file"); System.err.println(e.getMessage()); result.add(args[i]); } } return result; }
/** True if our request has the given selector */ private boolean hasSelector(SlingHttpServletRequest req, String selectorToCheck) { for (String selector : req.getRequestPathInfo().getSelectors()) { if (selectorToCheck.equals(selector)) { return true; } } return false; }
from unittest import TestCase from mock import Mock from .car import Car class CarTests(TestCase): def setUp(self): self.car = Car() def test_init_car(self): self.assertEqual(self.car.speed, 0) def test_stop(self): # Is directly accessing a private attribute ok? self.car.speed = 10 self.car.stop() self.assertEqual(self.car.speed, 0) def test__accelerate(self): self.car._accelerate() self.assertEqual(self.car.speed, 1) def test__decelerate_when_moving(self): self.car._accelerate() # 1 self.car._accelerate() # 2 self.car._decelerate() self.assertEqual(self.car.speed, 1) def test__decelerate_when_stopped(self): self.car._decelerate() self.assertEqual(self.car.speed, 0) def test_crash_over_100(self): self.car.speed = 100 self.car._accelerate() self.assertEqual(self.car.speed, 0) self.assertTrue(self.car.destroyed)
def open_eyes_session( self, runner=None, apikey=None, appname=None, testname=None, library=None, width=None, height=None, matchlevel=None, enable_eyes_log=None, batch=None, serverurl=None, force_full_page_screenshot=None ): if appname is None: appname = self.library_arguments["appname"] if testname is None: testname = self.library_arguments["testname"] if apikey is None: apikey = self.library_arguments["apikey"] if library is None: library = self.library_arguments["library"] if matchlevel is None: matchlevel = self.library_arguments["matchlevel"] if enable_eyes_log is None: enable_eyes_log = self.library_arguments["enable_eyes_log"] if serverurl is None: serverurl = self.library_arguments["serverurl"] if runner is None: runner = self.library_arguments["runner"] mode = None if runner is None or runner == 'ClassicRunner': print("\nRunning ClassicRunner...\n") mode = ClassicRunner() if runner == 'VisualGridRunner': print("\nRunning VisualGridRunner...\n") mode = VisualGridRunner(variables.concurrency) variables.eyes = Eyes(mode) try: libraryInstance = BuiltIn().get_library_instance(library) if library == "AppiumLibrary": driver = libraryInstance._current_application() else: driver = libraryInstance.driver except RuntimeError: raise Exception("%s instance not found" % library) if enable_eyes_log is not None: logger.set_logger(StdoutLogger(True)) if batch is not None: new_batch = BatchInfo(batch) sequence_name = batch else: new_batch = BatchInfo(variables.batch_default_name) sequence_name = variables.batch_default_name new_batch.sequence_name = sequence_name new_batch.id = variables.batchid config = Configuration() config.api_key = apikey config.app_name = str(appname) config.test_name = str(testname) if width is not None and height is not None: config.set_viewport_size({'width': int(width), 'height': int(height)}) config.batch = new_batch config.server_url = serverurl config.set_match_level(utils.get_match_level(matchlevel)) config.force_full_page_screenshot = force_full_page_screenshot or True if runner == 'VisualGridRunner': config = variables.visual_grid_browsers(config) variables.eyes.set_configuration(config) else: variables.eyes.set_configuration(config) variables.eyes.open(driver)
def coeff_string_check(text): try: [float(a) for a in text.split()] except: return Pmw.PARTIAL return Pmw.OK
/** * copy the incoming message requested to buff and return the bytes received */ int HTTP_conn::receiveRequest(SOCKET* clientSock, std::string& result) { char recvbuf[DEFAULT_BUFLEN]; int res = recv(*clientSock, recvbuf, DEFAULT_BUFLEN, 0); if (res > 0) { result = std::string(recvbuf, res); } else { result = ""; } return res; }
<filename>ejercicios/primer_nombre_repeticiones.py """ Escribir un código que solicite: - El nombre completo de una persona. - Un número entero. Con dicha información, el programa debe imprimir el primer nombre del usuario, repetido la cantidad de veces correspondiente al número entero TODO: add tests """ def solucion_a(): # solucion propuesta autocompletada por github copilot nombre = input("Ingrese su nombre completo: ") numero = int(input("Ingrese un número entero: ")) print(nombre[0:nombre.find(" ")] * numero) def solucion_b(): nombre_completo = input("Ingrese su nombre completo: ") repeticiones = int(input("Ingrese un número entero: ")) primer_nombre, _ = nombre_completo.split(" ") for _ in range(repeticiones): print(primer_nombre) def solucion_c(): nombre_completo = input("Ingrese su nombre completo: ") repeticiones = int(input("Ingrese un número entero: ")) primer_nombre, _ = nombre_completo.split(" ") print((primer_nombre + "\n") * repeticiones) def solucion_d(): nombre_completo = input("Ingrese su nombre completo: ") repeticiones = int(input("Ingrese un número entero: ")) primer_nombre = nombre_completo.split(" ")[0] for _ in range(repeticiones): print(primer_nombre) if __name__ == "__main__": solucion_a()
// MarshalJSON is the custom marshaler for CreateScopeJobParameters. func (csjp CreateScopeJobParameters) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if csjp.Tags != nil { objectMap["tags"] = csjp.Tags } if csjp.Name != nil { objectMap["name"] = csjp.Name } if csjp.DegreeOfParallelism != nil { objectMap["degreeOfParallelism"] = csjp.DegreeOfParallelism } if csjp.Priority != nil { objectMap["priority"] = csjp.Priority } if csjp.LogFilePatterns != nil { objectMap["logFilePatterns"] = csjp.LogFilePatterns } if csjp.Related != nil { objectMap["related"] = csjp.Related } if csjp.Type != "" { objectMap["type"] = csjp.Type } objectMap["properties"] = csjp.Properties return json.Marshal(objectMap) }
Utilization of a Clinical Decision Support Tool to Reduce Child Tobacco Smoke Exposure in the Urgent Care Setting Background Clinical decision support systems (CDSS) may facilitate caregiver tobacco screening and counseling by pediatric urgent care (UC) nurses. Objective This study aimed to assess the feasibility of a CDSS to address caregivers' tobacco use and child tobacco smoke exposure (TSE). Methods We conducted a 3-month prospective study on caregivers screened using a CDSS. Nurses used the CDSS to advise, assess, and assist caregivers to quit. We assessed caregiver sociodemographics, smoking habits, and child TSE. Results We screened 185 caregivers whose children were exposed to TSE for study inclusion; 155 (84%) met the eligibility criteria, and 149 (80.5%) were included in the study. Study nurses advised 35.2% of the caregivers to quit, assessed 35.9% for readiness to quit, and assisted 32.4%. Of the 149 participants, 83.1% were female; 47.0% were white and 45.6% African American; 84.6% had public insurance or were self-pay; 71.1% were highly nicotine dependent; 50.0% and 50.7% allowed smoking in the home and car, respectively; and 81.3% of children were biochemically confirmed to be exposed to tobacco smoke. At follow-up (86.6% retention), 58.9% reported quit attempts at 3 months. There was a significant decrease in nicotine dependence and a significant increase in motivation to quit. Self-reported quit rate was 7.8% at 3 months. Conclusions An electronic health record–embedded CDSS was feasible to incorporate into busy UC nurses' workloads and was associated with encouraging changes in the smoking behavior of caregivers. More research on the use of CDSS to screen and counsel caregivers who smoke in the UC and other acute care settings is warranted.
package io.rong.imkit.config; import android.app.Application; import android.content.Context; import android.content.res.Resources; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.rong.common.RLog; import io.rong.imkit.GlideKitImageEngine; import io.rong.imkit.IMCenter; import io.rong.imkit.KitImageEngine; import io.rong.imkit.R; import io.rong.imkit.feature.quickreply.IQuickReplyProvider; import io.rong.imlib.model.Conversation; public class FeatureConfig { private final static String TAG = "FeatureConfig"; private static String KIT_VERSION = "4.1.0.98"; //<!--是否支持消息引用功能,默认打开,聊天页面长按消息支持引用(目前仅支持文本消息、文件消息、图文消息、图片消息、引用消息的引用)--> private boolean isReferenceEnable; //引用 private boolean isDestructEnable; //阅后即焚 private boolean isQuickReplyEnable; //快捷回复 private IQuickReplyProvider quickReplyProvider; private IMCenter.VoiceMessageType voiceMessageType; private List<Conversation.ConversationType> readReceiptSupportTypes; //设置 AMR_NB 语音消息的码率 (单位 bps)[rc_audio_encoding_bit_rate] private int audioNBEncodingBitRate; //设置 AMR_WB 语音消息的码率 (单位 bps)[rc_audio_wb_encoding_bit_rate] private int audioWBEncodingBitRate; private KitImageEngine mKitImageEngine; private int userCacheMaxCount; private int groupCacheMaxCount; private int groupMemberCacheMaxCount; private boolean preLoadUserCache = true; public boolean rc_wipe_out_notification_message = true; public boolean rc_set_java_script_enabled = true; // 在前台非会话页面时,接收到新消息是否响铃 public boolean rc_sound_in_foreground = true; public FeatureConfig() { isReferenceEnable = true; isDestructEnable = false; voiceMessageType = IMCenter.VoiceMessageType.HighQuality; readReceiptSupportTypes = new ArrayList<>(); readReceiptSupportTypes.add(Conversation.ConversationType.PRIVATE); readReceiptSupportTypes.add(Conversation.ConversationType.GROUP); isQuickReplyEnable = false; audioNBEncodingBitRate = 7950; audioWBEncodingBitRate = 12650; mKitImageEngine = new GlideKitImageEngine(); userCacheMaxCount = 500; groupCacheMaxCount = 200; groupMemberCacheMaxCount = 500; } public void initConfig(Context context) { if (context != null) { Resources resources = context.getResources(); try { rc_wipe_out_notification_message = resources.getBoolean(R.bool.rc_wipe_out_notification_message); } catch (Exception e) { RLog.e(TAG, "rc_wipe_out_notification_message not get value", e); } try { rc_set_java_script_enabled = resources.getBoolean(R.bool.rc_set_java_script_enabled); } catch (Exception e) { RLog.e(TAG, "rc_set_java_script_enabled not get value", e); } try { isDestructEnable = resources.getBoolean(R.bool.rc_open_destruct_plugin); } catch (Exception e) { RLog.e(TAG, "rc_open_destruct_plugin not get value", e); } try { rc_sound_in_foreground = resources.getBoolean(R.bool.rc_sound_in_foreground); } catch (Exception e) { RLog.e(TAG, "rc_sound_in_foreground not get value", e); } } } public boolean isReferenceEnable() { return isReferenceEnable; } public boolean isDestructEnable() { return isDestructEnable; } public boolean isQuickReplyEnable() { return isQuickReplyEnable; } public boolean isQuickReplyType() { return isQuickReplyEnable; } public void setAudioNBEncodingBitRate(int audioNBEncodingBitRate) { this.audioNBEncodingBitRate = audioNBEncodingBitRate; } public void setAudioWBEncodingBitRate(int audioWBEncodingBitRate) { this.audioWBEncodingBitRate = audioWBEncodingBitRate; } public void setKitImageEngine(KitImageEngine engine) { if (engine != null) this.mKitImageEngine = engine; } public void setVoiceMessageType(IMCenter.VoiceMessageType type) { this.voiceMessageType = type; } public int getAudioNBEncodingBitRate() { return audioNBEncodingBitRate; } public KitImageEngine getKitImageEngine() { return mKitImageEngine; } public int getAudioWBEncodingBitRate() { return audioWBEncodingBitRate; } public IQuickReplyProvider getQuickReplyProvider() { return quickReplyProvider; } public boolean isReadReceiptConversationType(Conversation.ConversationType type) { if (readReceiptSupportTypes != null) { return readReceiptSupportTypes.contains(type); } return false; } public IMCenter.VoiceMessageType getVoiceMessageType() { return voiceMessageType; } public void enableReadReceipt(Conversation.ConversationType... supportedTypes) { if (supportedTypes != null) { readReceiptSupportTypes.clear(); readReceiptSupportTypes.addAll(Arrays.asList(supportedTypes)); } } public void enableReference(Boolean value) { isReferenceEnable = value; } public void enableDestruct(Boolean value) { isDestructEnable = value; } /** * 开启快捷回复功能。需要在{@link IMCenter#init(Application, String, boolean)} 之前调用。 * * @param provider 快捷回复短语的内容提供模板。 */ public void enableQuickReply(IQuickReplyProvider provider) { isQuickReplyEnable = true; quickReplyProvider = provider; } /** * @return 用户信息内存最大值 */ public int getUserCacheMaxCount() { return userCacheMaxCount; } /** * @param userCacheMaxCount 设置用户信息最大值,sdk 初始化前有效 */ public void setUserCacheMaxCount(int userCacheMaxCount) { this.userCacheMaxCount = userCacheMaxCount; } /** * @return 群组信息内存最大值 */ public int getGroupCacheMaxCount() { return groupCacheMaxCount; } /** * @param groupCacheMaxCount 设置群组信息最大值,sdk 初始化前有效 */ public void setGroupCacheMaxCount(int groupCacheMaxCount) { this.groupCacheMaxCount = groupCacheMaxCount; } /** * @return 群成员信息内存最大值 */ public int getGroupMemberCacheMaxCount() { return groupMemberCacheMaxCount; } /** * @param groupMemberCacheMaxCount 设置群成员信息最大值,sdk 初始化前有效 */ public void setGroupMemberCacheMaxCount(int groupMemberCacheMaxCount) { this.groupMemberCacheMaxCount = groupMemberCacheMaxCount; } /** * @return 是否预加载用户缓存 */ public boolean isPreLoadUserCache() { return preLoadUserCache; } /** * @param preLoadUserCache 是否预加载用户缓存 */ public void setPreLoadUserCache(boolean preLoadUserCache) { this.preLoadUserCache = preLoadUserCache; } }
/** * @param ldifFile to create with * @param ldifSortedFile to compare with * * @throws Exception On test failure. */ @Parameters( { "ldifEntry", "ldifSortedEntry" }) @Test(groups = {"ldif"}) public void readAndCompareSortedLdif(final String ldifFile, final String ldifSortedFile) throws Exception { final String ldifStringSorted = TestUtils.readFileIntoString(ldifSortedFile); final LdifReader ldifReader = new LdifReader( new StringReader(TestUtils.readFileIntoString(ldifFile)), SortBehavior.SORTED); final SearchResult result = ldifReader.read(); final StringWriter writer = new StringWriter(); final LdifWriter ldifWriter = new LdifWriter(writer); ldifWriter.write(result); AssertJUnit.assertEquals(ldifStringSorted, writer.toString()); }
Only a few days after media outlets erroneously reported that Bernie Sanders supporters chanted “English only” during the Democratic Nevada caucus, TIME Magazine went a step further and erroneously claimed that Sanders himself yelled “English only.” TIME‘s preface to an interview of Clinton supporter David Brock contains the following paragraph: All the pushback on misleading news reports that Bernie Sanders won the Latino vote (he didn’t) in Nevada, trackers following Sanders catching his every gaffe like when he yelled “English, only!” into a mic at a Nevada event or pushing polling showing Clinton winning amongst African Americans in South Carolina—those all come from from Brock. Simply put, the bolded section is 100% wrong. At no point did anyone accuse Sanders of personally yelling into a microphone “English only,” a fact a simple Google search would have verified. Sanders supporters were accused of chanting “English only,” but that accusation was soon cast into doubt. The two celebrities who levied that charge were both outspoken Clinton supporters, and video taken of the caucus seemed to show that Sanders supporters didn’t chant anything. The urban legend-busting website Snopes rated the Clinton supporters’ claim false. UPDATE (7:52 PM ET): The offending correction has been appended to the TIME piece: Correction: The original version of this story incorrectly attributed a statement from a Feb. 20 caucus event in Nevada to Bernie Sanders. Sanders was not present. [Image via screengrab] —— >>Follow Alex Griswold (@HashtagGriswold) on Twitter Have a tip we should know? [email protected]
<filename>rbatis-core/src/connection.rs<gh_stars>0 //! Contains the `Connection` and `Connect` traits. use std::convert::TryInto; use futures_core::future::BoxFuture; use crate::executor::Executor; use crate::pool::{Pool, PoolConnection}; use crate::transaction::Transaction; use crate::url::Url; /// Represents a single database connection rather than a pool of database connections. /// /// Connections can be manually established outside of a [`Pool`] with [`Connect::connect`]. /// /// Prefer running queries from [`Pool`] unless there is a specific need for a single, sticky /// connection. pub trait Connection where Self: Send + 'static, Self: Executor, { /// Starts a new transaction. /// 从conn启动一个事务,因为conn的所有权移动给了Transaction,直到Transaction commit 或者 rollback完成时返回原来的conn连接 /// /// Wraps this connection in [`Transaction`] to manage the transaction lifecycle. To get the /// original connection back, explicitly [`commit`] or [`rollback`] and this connection will /// be returned. /// /// ```rust,ignore /// let mut tx = conn.begin().await?; /// // conn is now inaccessible as its wrapped in a transaction /// /// let conn = tx.commit().await?; /// // conn is back now and out of the transaction /// ``` /// /// /// [`commit`]: crate::transaction::Transaction::commit /// [`rollback`]: crate::transaction::Transaction::rollback fn begin(self) -> BoxFuture<'static, crate::Result<Transaction<Self>>> where Self: Sized, { Box::pin(Transaction::new(0, self)) } /// Explicitly close this database connection. /// /// This method is **not required** for safe and consistent operation. However, it is /// recommended to call it instead of letting a connection `drop` as the database server /// will be faster at cleaning up resources. fn close(self) -> BoxFuture<'static, crate::Result<()>>; /// Checks if a connection to the database is still valid. fn ping(&mut self) -> BoxFuture<crate::Result<()>>; } /// Represents a type that can directly establish a new connection. pub trait Connect: Connection { /// Establish a new database connection. fn connect<T>(url: T) -> BoxFuture<'static, crate::Result<Self>> where T: TryInto<Url, Error = url::ParseError>, Self: Sized; } #[allow(dead_code)] pub(crate) enum ConnectionSource<'c, C> where C: Connect, { ConnectionRef(&'c mut C), Connection(C), PoolConnection(Pool<C>, PoolConnection<C>), Pool(Pool<C>), } impl<'c, C> ConnectionSource<'c, C> where C: Connect, { #[allow(dead_code)] pub(crate) async fn resolve(&mut self) -> crate::Result<&'_ mut C> { if let ConnectionSource::Pool(pool) = self { let conn = pool.acquire().await?; *self = ConnectionSource::PoolConnection(pool.clone(), conn); } Ok(match self { ConnectionSource::ConnectionRef(conn) => conn, ConnectionSource::PoolConnection(_, ref mut conn) => conn, ConnectionSource::Connection(ref mut conn) => conn, ConnectionSource::Pool(_) => unreachable!(), }) } } impl<'c, C> From<C> for ConnectionSource<'c, C> where C: Connect, { fn from(connection: C) -> Self { ConnectionSource::Connection(connection) } } impl<'c, C> From<PoolConnection<C>> for ConnectionSource<'c, C> where C: Connect, { fn from(connection: PoolConnection<C>) -> Self { ConnectionSource::PoolConnection(Pool(connection.pool.clone()), connection) } } impl<'c, C> From<Pool<C>> for ConnectionSource<'c, C> where C: Connect, { fn from(pool: Pool<C>) -> Self { ConnectionSource::Pool(pool) } }
<reponame>procrash/cpp-sc2 #include "sc2api/sc2_api.h" #include "sc2utils/sc2_manage_process.h" #include <iostream> #include <string> #include <random> #include <cmath> static uint32_t c_text_size = 8; static std::string GetAbilityText(sc2::AbilityID ability_id) { std::string str; str += sc2::AbilityTypeToName(ability_id); str += " ("; str += std::to_string(uint32_t(ability_id)); str += ")"; return str; } class EchoActionsBot : public sc2::Agent { public: void OnGameStart() override { last_echoed_gameloop_ = 0; } void EchoAction(const sc2::RawActions& actions, sc2::DebugInterface* debug, const sc2::Abilities&) { if (actions.size() < 1) { debug->DebugTextOut(last_action_text_); return; } last_action_text_ = ""; // For now, just show the first action. const std::shared_ptr<sc2::ActionRaw> action = actions[0]; const sc2::ActionRawUnitCommand* ptrActionRawUnitCommand=dynamic_cast<const sc2::ActionRawUnitCommand*>(action.get()); if (ptrActionRawUnitCommand!=nullptr) { // Show the index of the ability being used. last_action_text_ = GetAbilityText(ptrActionRawUnitCommand->ability_id); // Add targeting information. switch (ptrActionRawUnitCommand->target_type) { case sc2::ActionRawUnitCommand::TargetUnitTag: last_action_text_ += "\nTargeting Unit: " + std::to_string(ptrActionRawUnitCommand->target_tag); break; case sc2::ActionRawUnitCommand::TargetPosition: last_action_text_ += "\nTargeting Pos: " + std::to_string(ptrActionRawUnitCommand->target_point.x) + ", " + std::to_string(ptrActionRawUnitCommand->target_point.y); break; case sc2::ActionRawUnitCommand::TargetNone: default: last_action_text_ += "\nTargeting self"; } } else { const sc2::ActionRawCameraMove* ptrActionCameraMove = dynamic_cast<const sc2::ActionRawCameraMove*>(action.get()); if (ptrActionCameraMove!=nullptr) { last_action_text_ = "Raw Camera Move\n"; last_action_text_ = "("+std::to_string(ptrActionCameraMove->x)+","+std::to_string(ptrActionCameraMove->y)+ ")\n"; } else { const sc2::ActionRawToggleAutocast* ptrActionToggleAutocast = dynamic_cast<const sc2::ActionRawToggleAutocast*>(action.get()); if (ptrActionToggleAutocast!=nullptr) { last_action_text_ = "Raw Toggle Autocast\n"+GetAbilityText(ptrActionToggleAutocast->ability_id)+"\n"; } } } debug->DebugTextOut(last_action_text_); } void OnStep() final { Control()->GetObservation(); const sc2::ObservationInterface* obs = Observation(); sc2::QueryInterface* query = Query(); sc2::DebugInterface* debug = Debug(); if (Control()->GetLastStatus() != SC2APIProtocol::Status::in_game) return; if (last_echoed_gameloop_ == obs->GetGameLoop()) return; last_echoed_gameloop_ = obs->GetGameLoop(); const sc2::UnitTypes& unit_types = obs->GetUnitTypeData(); if (unit_types.size() < 1) { std::cout << "Unit types requested but not yet available." << std::endl; return; } const sc2::Abilities& abilities = obs->GetAbilityData(); if (abilities.size() < 1) { std::cout << "Abilities requested but not yet available." << std::endl; return; } // Find a selected unit. { const sc2::Unit* unit = nullptr; for (const auto& try_unit : obs->GetUnits()) { if (try_unit->is_selected && try_unit->alliance == sc2::Unit::Self) { unit = try_unit; break; } } if (!unit) return; // Actions. EchoAction(obs->GetRawActions(), debug, abilities); // Show names for the selected unit. std::string debug_txt; { debug_txt = UnitTypeToName(unit->unit_type); if (debug_txt.length() < 1) { debug_txt = "(Unknown name)"; assert(0); } debug_txt += " (" + std::to_string(unit->unit_type) + ")"; } sc2::AvailableAbilities available_abilities = query->GetAbilitiesForUnit(unit); if (available_abilities.abilities.size() < 1) { std::cout << "No abilities available for this unit" << std::endl; } else { for (const sc2::AvailableAbility& available_ability : available_abilities.abilities) { assert(uint32_t(available_ability.ability_id) < abilities.size()); const sc2::AbilityData& ability = abilities[available_ability.ability_id]; assert(available_ability.ability_id == ability.ability_id); debug_txt += GetAbilityText(ability.ability_id) + "\n"; } } debug->DebugTextOut(debug_txt, unit->pos, sc2::Colors::Green, c_text_size); // Show the direction of the unit. sc2::Point3D p1; // Use this to show target distance. { const float length = 5.0f; sc2::Point3D p0 = unit->pos; p0.z += 0.1f; // Raise the line off the ground a bit so it renders more clearly. p1 = unit->pos; assert(unit->facing >= 0.0f && unit->facing < 6.29f); p1.x += length * std::cos(unit->facing); p1.y += length * std::sin(unit->facing); debug->DebugLineOut(p0, p1, sc2::Colors::Yellow); } // Box around the unit. { sc2::Point3D p_min = unit->pos; p_min.x -= 2.0f; p_min.y -= 2.0f; p_min.z -= 2.0f; sc2::Point3D p_max = unit->pos; p_max.x += 2.0f; p_max.y += 2.0f; p_max.z += 2.0f; debug->DebugBoxOut(p_min, p_max, sc2::Colors::Blue); } // Sphere around the unit. { sc2::Point3D p = unit->pos; p.z += 0.1f; // Raise the line off the ground a bit so it renders more clearly. debug->DebugSphereOut(p, 1.25f, sc2::Colors::Purple); } // Pathing query to get the target. bool has_target = false; sc2::Point3D target; std::string target_info; for (const sc2::UnitOrder& unit_order : unit->orders) { // TODO: Need to determine if there is a target point, no target point, or the target is a unit/snapshot. target.x = unit_order.target_pos.x; target.y = unit_order.target_pos.y; target.z = p1.z; has_target = true; target_info = "Target:\n"; if (unit_order.target_unit_tag != sc2::NullTag) { target_info += "Tag: " + std::to_string(unit_order.target_unit_tag) + "\n"; } if (unit_order.progress != 0.0f && unit_order.progress != 1.0f) { target_info += "Progress: " + std::to_string(unit_order.progress) + "\n"; } // Perform the pathing query. { float distance = query->PathingDistance(unit->pos, target); target_info += "\nPathing dist: " + std::to_string(distance); } break; } if (has_target) { sc2::Point3D p = target; p.z += 0.1f; // Raise the line off the ground a bit so it renders more clearly. debug->DebugSphereOut(target, 1.25f, sc2::Colors::Blue); debug->DebugTextOut(target_info, p1, sc2::Colors::Yellow, c_text_size); } debug->SendDebug(); } private: uint32_t last_echoed_gameloop_; std::string last_action_text_; }; //************************************************************************************************* int main(int argc, char* argv[]) { sc2::Coordinator coordinator; if (!coordinator.LoadSettings(argc, argv)) { return 1; } coordinator.SetRealtime(true); // Add the custom bot, it will control the players. EchoActionsBot bot; coordinator.SetParticipants({ CreateParticipant(sc2::Race::Terran, &bot), CreateComputer(sc2::Race::Zerg) }); // Start the game. coordinator.LaunchStarcraft(); coordinator.StartGame(sc2::kMapBelShirVestigeLE); // Step forward the game simulation. while (coordinator.Update()) { sc2::SleepFor(10); } return 0; }
""" You are given an HTML code snippet of N lines. Your task is to detect and print all the HTML tags, attributes and attribute values. """ from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for attr in attrs: print("-> {} > {}".format(attr[0], attr[1])) html = "" for i in range(int(input())): html += input().rstrip() html += '\n' parser = MyHTMLParser() parser.feed(html) parser.close()
/** * Created by stackcode on 9/19/17. */ public class LogDetails { private String TAG = "SUPER EASY"; public void d(){ Log.d(TAG,"Hey!!! Its my first android Lib Ever"); } }
/* * CTxtPtr::GetPrevChar() * * @mfunc * Return character just before this text pointer, NULL if text pointer * beginning of text * * @rdesc * Character just before this text ptr */ TCHAR CTxtPtr::GetPrevChar() { TRACEBEGIN(TRCSUBSYSBACK, TRCSCOPEINTERN, "CTxtPtr::GetPrevChar"); LONG cchValid; const TCHAR *pch = GetPchReverse(cchValid); return pch ? *(pch - 1) : 0; }
import { Either, eitherArrayReduce, eitherMapRight, optionFold, optionFromNullable, Right, } from 'trimop'; import { ActionTrigger, GetDoc, GetTransactionCommitError, TransactionCommit, TriggerSnapshot, UpdateDocCommit, } from './type'; /** * Magic HAHA! * @param param0 * @returns */ export function getTransactionCommit<S extends TriggerSnapshot>({ actionTrigger, snapshot, getDoc, }: { readonly actionTrigger: ActionTrigger<S>; readonly getDoc: GetDoc; readonly snapshot: S; }): Promise<Either<GetTransactionCommitError, TransactionCommit>> { return Promise.all( actionTrigger.getTransactionCommits.map((gtc) => gtc({ getDoc, snapshot })) ).then((transactionCommits) => eitherArrayReduce< TransactionCommit, GetTransactionCommitError, Either<GetTransactionCommitError, TransactionCommit> >(transactionCommits, Right({}), (accTC, tc) => eitherMapRight(tc, (tc) => // tc vs tc eitherArrayReduce(Object.entries(tc), Right(accTC), (accTC, [colName, colTC]) => Right({ ...accTC, [colName]: optionFold( optionFromNullable(accTC[colName]), () => colTC, (accColTC) => // colTc vs colTc Object.entries(colTC).reduce( (accColTC, [docId, docCommit]) => ({ ...accColTC, [docId]: optionFold( optionFromNullable(accColTC[docId]), // ignored since currently no way of making 2 docCommit on a same collection /* istanbul ignore next */ () => docCommit, (accDocCommit) => UpdateDocCommit({ onDocAbsent: docCommit.onDocAbsent, writeDoc: { ...docCommit.writeDoc, ...accDocCommit.writeDoc }, }) ), }), accColTC ) ), }) ) ) ) ); }
<reponame>Commander-lol/EntwaCourse /* Copyright (c) 2015, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of EntwaSums nor the names of its associated properties or contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package co.louiscap.entwasums.ctrl; import co.louiscap.entwasums.bus.IdeaService; import co.louiscap.entwasums.ents.Idea; import co.louiscap.entwasums.ents.Staff; import java.util.List; import javax.ejb.EJB; import javax.inject.Named; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; /** * * @author <NAME> */ @Named(value = "ideaController") @RequestScoped public class IdeaController { private String ideaName; private String ideaDescription; private Staff firstStaff, secondStaff, thirdStaff; @EJB private IdeaService is; @Inject UserManagerBean umb; /** * Creates a new instance of IdeaController */ public IdeaController() { } public String getIdeaName() { return ideaName; } public void setIdeaName(String ideaName) { this.ideaName = ideaName; } public String getIdeaDescription() { return ideaDescription; } public void setIdeaDescription(String ideaDescription) { this.ideaDescription = ideaDescription; } public List<Idea> getAvailableIdeas() { return is.getAvailableIdeas(); } public String newIdea() { Idea i = new Idea(); i.setCreator(umb.getUser()); i.setTitle(ideaName); i.setDescription(ideaDescription); is.submitIdea(i); System.out.println("oiansd"); return umb.getUserSlug() + "/index"; } }
/** * {@link Disassembler} is a class responsible for disassembling binary files. * * @author <a href="mailto:[email protected]">Andrei Tatarnikov</a> */ public final class Disassembler { public static interface Output { void add(final IsaPrimitive primitive); void close(); } public static interface OutputFactory { Output createOutput(final Model model); } public static boolean disassemble( final Options options, final String modelName, final String fileName, final OutputFactory outputFactory) { InvariantChecks.checkNotNull(options); InvariantChecks.checkNotNull(modelName); InvariantChecks.checkNotNull(fileName); InvariantChecks.checkNotNull(outputFactory); final Model model = loadModel(modelName); if (null == model) { Logger.error("Failed to load the model."); return false; } final boolean bigEndian = options.getValueAsBoolean(Option.BINARY_FILE_BIG_ENDIAN); final BinaryReader reader = newReader(fileName, bigEndian); if (null == reader) { Logger.error("Failed to create a reader."); return false; } Output output = null; try { output = outputFactory.createOutput(model); if (null == output) { Logger.error("Failed to create an output."); return false; } return decode(model.getDecoder(), reader, output); } finally { reader.close(); if (null != output) { output.close(); } } } public static boolean disassemble( final Options options, final String modelName, final String fileName) { InvariantChecks.checkNotNull(options); InvariantChecks.checkNotNull(modelName); InvariantChecks.checkNotNull(fileName); final String fileExt = options.getValueAsString(Option.CODE_FILE_EXTENSION); final String fileShortName = FileUtils.getShortFileNameNoExt(fileName); final PrintWriter writer; try { writer = FileUtils.newPrintWriter(getOutDir(options), fileShortName, fileExt); } catch (final IOException e) { Logger.error("Failed to create an output file. Reason: %s.", e.getMessage()); return false; } final OutputFactory outputFactory = new OutputFactory() { @Override public Output createOutput(final Model model) { InvariantChecks.checkNotNull(model); final TemporaryVariables tempVars = model.getTempVars(); return new OutputImpl(writer, tempVars); } }; return disassemble(options, modelName, fileName, outputFactory); } private static final class OutputImpl implements Output { private final PrintWriter writer; private final TemporaryVariables tempVars; private OutputImpl(final PrintWriter writer, final TemporaryVariables tempVars) { InvariantChecks.checkNotNull(writer); InvariantChecks.checkNotNull(tempVars); this.writer = writer; this.tempVars = tempVars; } @Override public void add(final IsaPrimitive primitive) { final String text = primitive.text(tempVars); Logger.debug(text); writer.println(text); } @Override public void close() { writer.close(); } } private static Model loadModel(final String modelName) { try { return SysUtils.loadModel(modelName); } catch (final Exception e) { Logger.error("Failed to load the %s model. Reason: %s.", modelName, e.getMessage()); return null; } } private static String getOutDir(final Options options) { return options.hasValue(Option.OUTPUT_DIR) ? options.getValueAsString(Option.OUTPUT_DIR) : SysUtils.getHomeDir(); } private static BinaryReader newReader(final String fileName, final boolean bigEndian) { final File file = new File(fileName); if (!file.exists()) { Logger.error("The %s file does not exists.", fileName); return null; } try { return new BinaryReader(file, bigEndian); } catch (final IOException e) { Logger.error("Failed to open input file. Reason: %s.", e.getMessage()); return null; } } private static boolean decode( final Decoder decoder, final BinaryReader reader, final Output output) { InvariantChecks.checkNotNull(decoder); InvariantChecks.checkNotNull(reader); InvariantChecks.checkNotNull(output); final int maxImageSize = decoder.getMaxImageSize(); final boolean imageSizeFixed = decoder.isImageSizeFixed(); InvariantChecks.checkTrue(0 == maxImageSize % 8); final int byteSize = maxImageSize / 8; BitVector data = null; while ((data = reader.read(byteSize)) != null) { final DecoderResult result = decoder.decode(data); if (null == result) { Logger.error("Unrecognized instruction encoding: %d'b%s", data.getBitSize(), data); return false; } final IsaPrimitive primitive = result.getPrimitive(); output.add(primitive); if (!imageSizeFixed) { final int bitsRead = result.getBitSize(); InvariantChecks.checkTrue(0 == bitsRead % 8); final int bytesRead = bitsRead / 8; reader.retreat(byteSize - bytesRead); } } return true; } }
<gh_stars>1-10 import React from "react"; import { IAppView } from "./IAppView"; import { Styled } from "../styled"; import "antd/dist/antd.css"; import MovingPictureShowcase from "../../moving-picture-showcase/container/MovingPictureShowcase"; import ParticleVortexShowcase from "../../particle-vortex-showcase/container/ParticleVortexShowcase"; const AppView: React.FC<IAppView> = ({ switchShowcase, showcase, switchButtonTitle }) => { const componentToDisplay = showcase === "moving-picture" ? ( <MovingPictureShowcase /> ) : ( <ParticleVortexShowcase /> ); return ( <Styled.TopContainer> <Styled.ShowcaseSwitch onClick={switchShowcase}> {switchButtonTitle} </Styled.ShowcaseSwitch> {componentToDisplay} </Styled.TopContainer> ); }; export default AppView;
def _index_key(self, sig, codegen): codebytes = self._py_func.__code__.co_code if self._py_func.__closure__ is not None: cvars = tuple([x.cell_contents for x in self._py_func.__closure__]) cvarbytes = dumps(cvars) else: cvarbytes = b'' hasher = lambda x: hashlib.sha256(x).hexdigest() return (sig, codegen.magic_tuple(), (hasher(codebytes), hasher(cvarbytes),))
/** * Enables the (thread-local) TFileRegistry, so that every call to the createXX() or register() static methods * will result in the relevant TFile to be stored for further cleaning of TrueZip internal resources. * <p>The actual cleaning must be performed by calling the {@link #close()} static method on TFileRegistry. */ public static TFileRegistry open() { if (THREAD_LOCAL.get() == null) { TFileRegistry registry = new TFileRegistry(); THREAD_LOCAL.set(registry); return registry; } else { throw new IllegalStateException("TFileRegistry.open() should not be called twice without calling close() in-between."); } }
def create_symptoms( person, time, start_symp_key, end_symp_key, start_symp_unique, end_symp_unique, viral_load_unique, max_num_days_since_infection, ): viral_load_threshold = 0.5 dsi_threshold = 5 not_infected_dsi = 0 person_suffix = index_name(person) time_person_suffix = index_name(time, person) symptomatic_key = f'symptomatic_{person_suffix}' viral_load_key = f'viral_load_{time_person_suffix}' symptomatic_time_key = f'symptomatic_{time_person_suffix}' dsi_key = f'dsi_{time_person_suffix}' parameters = { symptomatic_key: [0, 1], symptomatic_time_key: [0, 1], start_symp_key: start_symp_unique, end_symp_key: end_symp_unique, viral_load_key: viral_load_unique, dsi_key: list(range(0, max_num_days_since_infection)) } dtypes = { symptomatic_key: 'int8', symptomatic_time_key: 'int8', start_symp_key: 'int8', end_symp_key: 'int8', viral_load_key: 'float64', dsi_key: 'int8' } df = mega_join_cross_product(parameters, dtypes) get_symptoms = ( (df[symptomatic_key] == 1) & ( (df[viral_load_key] > viral_load_threshold) | ( (df[dsi_key] < dsi_threshold) & (df[dsi_key] != not_infected_dsi) ) | ( ( df[start_symp_key] <= df[dsi_key] ) & ( df[end_symp_key] + df[start_symp_key] > df[dsi_key] ) ) ) ) df['value'].mask( (df[symptomatic_time_key] == 1), 0.05, inplace=True ) df['value'].mask( (df[symptomatic_time_key] == 0), 0.95, inplace=True ) df['value'].mask( (df[symptomatic_time_key] == 1) & get_symptoms, 0.95, inplace=True ) df['value'].mask( (df[symptomatic_time_key] == 0) & get_symptoms, 0.05, inplace=True ) return df, symptomatic_time_key
<filename>models/subscription.go package models import ( "encoding/json" "time" ) // Subscription - code representation of a users subscription to a tag type Subscription struct { ID int `db:"id" json:"-"` Tag Tag `db:"-" json:"tag"` TagName string `db:"-" json:"tagName"` TagID int `db:"tag_id" json:"-"` User User `db:"-" json:"-"` UserID int `db:"user_id" json:"-"` CreatedAt time.Time `db:"created_at" json:"-"` } // MarshalJSON custom JSON builder for Tag structs func (s *Subscription) MarshalJSON() ([]byte, error) { // hydrate the tag if s.Tag.ID == 0 { s.Tag.FindByID(s.TagID) } // return the custom JSON for this post return json.Marshal(&struct { Tag string `json:"tag"` }{ Tag: s.Tag.Name, }) } // ToJSON - get a string representation of this Tag in JSON func (s *Subscription) ToJSON() string { jsonData, err := json.Marshal(s) if err != nil { return err.Error() } return string(jsonData) } /************************************************/ /******************** CREATE ********************/ /************************************************/ // CreateSubscription - create a subscription in the database for a tag func (u *User) CreateSubscription(tag Tag) (Subscription, error) { s := Subscription{} now := time.Now().Format("2006-01-02 15:04:05") _, err := DBConn.Exec("INSERT INTO subscriptions (tag_id, user_id, created_at) VALUES (?, ?, ?)", tag.ID, u.ID, now) if err != nil { return s, err } err = s.FindSubscription(tag.ID, u.ID) return s, err } /************************************************/ /********************* READ *********************/ /************************************************/ // FindSubscription - find a given tag in the database by the tag/user pairing func (s *Subscription) FindSubscription(tagID int, userID int) error { dbSubscription := Subscription{} err := DBConn.Get(&dbSubscription, "SELECT * FROM subscriptions WHERE tag_id = ? AND user_id = ?", tagID, userID) if err != nil { return err } *s = dbSubscription return nil } // GetSubscriptions will return the user's tag subscriptions func (u *User) GetSubscriptions() ([]Subscription, error) { subscriptions := []Subscription{} // run the correct sql query var query = "SELECT * FROM subscriptions WHERE user_id = ?" err := DBConn.Select(&subscriptions, query, u.ID) if err != nil { return subscriptions, err } return subscriptions, nil } /************************************************/ /******************** UPDATE ********************/ /************************************************/ // Not needed /************************************************/ /******************** DELETE ********************/ /************************************************/ // DeleteSubscription - create a subscription in the database for a tag func (u *User) DeleteSubscription(tag Tag) error { _, err := DBConn.Exec("DELETE FROM subscriptions WHERE tag_id = ? AND user_id = ?", tag.ID, u.ID) return err }
/** * 任务分析状态 * 值为后端返回的任务分析状态 * * --目前不全,后期需要用到请新增 */ export enum TaskStatus { Created = 'Created', Waiting = 'Waiting', Sampling = 'Sampling', Analyzing = 'Analyzing', Stopping = 'Stopping', Aborted = 'Aborted', Failed = 'Failed', Completed = 'Completed', On = 'on', Off = 'off', Cancelled = 'Cancelled', Cancelling = 'Cancelling' }
/*BanChatSender bans a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.*/ func (cm *ChatManager) BanChatSender(senderChatId int) (*objs.LogicalResult, error) { return cm.bot.apiInterface.BanOrUnbanChatSenderChat( cm.chatIdInt, cm.chatIdString, senderChatId, true, ) }
/// Returns the entire text of the `Rope` as a newly allocated String. pub fn to_string(&self) -> String { use iter::Chunks; let mut text = String::with_capacity(self.len_bytes()); for chunk in Chunks::new(&self.root) { text.push_str(chunk); } text }
package us.kbase.workspace.listener; import java.time.Instant; import java.util.List; import com.google.common.base.Optional; import us.kbase.workspace.database.ObjectInformation; import us.kbase.workspace.database.Permission; import us.kbase.workspace.database.WorkspaceUser; /** A listener for workspace events. * @author <EMAIL> * * @see WorkspaceEventListenerFactory * */ public interface WorkspaceEventListener { /** Notification that a workspace was created. * @param user the user that created the workspace. * @param id the workspace ID. * @param time the time the create event occurred. */ void createWorkspace(WorkspaceUser user, long id, Instant time); /** Notification that a workspace was cloned. * @param user the user that cloned the workspace. * @param id the workspace ID. * @param isPublic true if the workspace is public, false otherwise. * @param time the time the clone event occurred. */ void cloneWorkspace(WorkspaceUser user, long id, boolean isPublic, Instant time); /** Notification that a workspace's meta data was altered. * @param user the user that altered the workspace. * @param id the id of the workspace. * @param time the time the metadata event occurred. */ void setWorkspaceMetadata(WorkspaceUser user, long id, Instant time); /** Notification that a workspace has been locked. * @param user the user that locked the workspace. * @param id the id of the workspace. * @param time the time the lock event occurred. */ void lockWorkspace(WorkspaceUser user, long id, Instant time); /** Notification that a workspace has been renamed. * @param user the user that renamed the workspace. * @param id the id of the workspace. * @param newname the new name of the workspace. * @param time the time the rename event occurred. */ void renameWorkspace(WorkspaceUser user, long id, final String newname, Instant time); /** Notification that the global permission for a workspace has been altered. * @param user the user that altered the workspace. * @param id the id of the workspace. * @param permission the new global permission. * @param time the time the permission event occurred. */ void setGlobalPermission(WorkspaceUser user, long id, Permission permission, Instant time); /** Notification that the permissions for a workspace have been altered. * @param user the user that altered the workspace. May be null if the user is an admin. * @param id the id of the workspace. * @param permission the new permission. * @param users the users that have been assigned the new permission. * @param time the time the permissions event occurred. */ void setPermissions( WorkspaceUser user, long id, Permission permission, List<WorkspaceUser> users, Instant time); /** Notification that the workspace description has been set or altered. * @param user the user that altered the workspace. May be null if the user is an admin. * @param id the id of the workspace. * @param time the time the description change event occurred. */ void setWorkspaceDescription(WorkspaceUser user, long id, Instant time); /** Notification that the owner of a workspace has been changed. * @param user the user that changed the owner. Will be null if the user is an admin. * @param id the id of the workspace. * @param newUser the new owner of the workspace. * @param newName the new name for the workspace, if any. * @param time the time the owner change event occurred. */ void setWorkspaceOwner( WorkspaceUser user, long id, WorkspaceUser newUser, Optional<String> newName, Instant time); /** Notification that a workspace has been deleted or undeleted. * @param user the user that altered the workspace. May be null if the user is an admin. * @param id the id of the workspace. * @param delete true for a delete event, false for an undelete event. * @param maxObjectID the maximum ID for any object in the workspace. * @param time the time the deletion event occurred. */ void setWorkspaceDeleted( WorkspaceUser user, long id, boolean delete, long maxObjectID, Instant time); /** Notification that an object has been renamed. * @param user the user that renamed the object. * @param workspaceId the id of the workspace containing the object. * @param objectId the id of the object. * @param newName the object's new name. * @param time the time the rename event occurred. */ void renameObject( final WorkspaceUser user, final long workspaceId, final long objectId, final String newName, final Instant time); /** Notification that an object has been reverted. * @param object information about the reverted object. * @param isPublic true if the object is in a public workspace, false otherwise. */ void revertObject(ObjectInformation object, boolean isPublic); /** Notification that an object was deleted or undeleted. * @param user the user that changed the deletion state of the object. * @param workspaceId the workspace id. * @param objectId the object id. * @param delete true if the object was deleted, false if it was undeleted. * @param time the time the delete event occurred. */ void setObjectDeleted( WorkspaceUser user, long workspaceId, long objectId, boolean delete, Instant time); /** Notification that a single version of an object was copied. * @param object information about the new object version. * @param isPublic true if the new object version is in a public workspace, false otherwise. */ void copyObject(ObjectInformation object, boolean isPublic); /** Notification that all the versions of an object were copied. * @param user the user that copied the object. * @param workspaceId the workspace id of the new object. * @param objectId the object id of the new object. * @param latestVersion the latest version of the new object. * @param time the time the last version was copied. * @param isPublic true if the new object is in a public workspace, false otherwise. */ void copyObject( WorkspaceUser user, long workspaceId, long objectId, int latestVersion, Instant time, boolean isPublic); /** Notification that an object has been saved. * @param object information about the object. * @param isPublic true if the object is in a public workspace, false otherwise. */ void saveObject(ObjectInformation object, boolean isPublic); }
def make_ref2(args): watson = open(args.watson,'r') crick = open(args.crick,'r') out = open(args.consensus, 'w') count = 0 try: while True: w = [watson.readline()[1:-1],watson.readline()[:-1].upper()] c = [crick.readline()[1:-1],crick.readline()[:-1].upper()] if w[0] == '': break while True: if w[0] == c[0]: break else: if int(w[0]) > int(c[0]): c = [crick.readline()[1:-1],crick.readline().upper()[:-1]] else: w = [watson.readline()[1:-1],watson.readline().upper()[:-1]] if w == []: break out_seq = '' count +=1 if not count%1000: print count for wb, cb in izip(w[1], c[1]): if wb == cb: out_seq += wb elif wb == 'T' and cb == 'C': out_seq += 'C' elif wb == 'G' and cb == 'A': out_seq += 'G' elif wb == 'N': out_seq += cb elif cb == 'N': out_seq += wb else: out_seq += 'N' record_out = '>%s\n%s\n'%(w[0],out_seq) out.write(record_out) except ValueError: return None
<reponame>chegojs/chego-mongodb<gh_stars>1-10 import { MongoClientOptions } from 'mongodb'; import { Table } from '@chego/chego-api'; import { IQueryContext } from '@chego/chego-database-boilerplate'; export interface IMongoConfig { url:string; database?:string; clientOptions?:MongoClientOptions; } export interface IPipelineBuilder { with(queryContext:IQueryContext, defaultTable:Table): IPipelineBuilder; build(): object[] }
<reponame>shazz/pygase<gh_stars>10-100 # -*- coding: utf-8 -*- import curio from freezegun import freeze_time from helpers import assert_timeout from pygase.backend import Server, GameStateMachine, GameStateStore from pygase.client import Client from pygase.gamestate import GameState, GameStatus class TestIntegration: def test_client_server_connection(self): server = Server(GameStateStore()) client = Client() async def test_task(): await curio.spawn(server.run) await assert_timeout(1, lambda: server.port is not None) await curio.spawn(client.connect, server.port) await assert_timeout(1, lambda: server.connections != {}) assert client.connection.remote_address == (server.hostname, server.port) await curio.sleep(0) await server.shutdown() return True assert curio.run(test_task) def test_connect_disconnect(self): init_gamestate = GameState(counter=0, test="foobar") state_store = GameStateStore(init_gamestate) state_machine = GameStateMachine(state_store) def test_update(game_state, dt): counter = game_state.counter + 1 test = "foobar" if counter % 2 == 0 else "barfoo" return {"test": test, "counter": counter} state_machine.time_step = test_update server = Server(state_store) client = Client() async def test_task(client_shutdown): server_task = await curio.spawn(server.run) await assert_timeout(1, lambda: server._port is not None) client_task = await curio.spawn(client.connect, server.port, server.hostname) await assert_timeout(1, lambda: client.connection is not None) state_machine_task = await curio.spawn(state_machine.run_game_loop) await assert_timeout(1, lambda: state_store.get_game_state().game_status == GameStatus.get("Active")) await state_machine.stop() await state_machine_task.join() await client.disconnect(shutdown_server=client_shutdown) await client_task.join() if not client_shutdown: await server.shutdown() await server_task.join() return True assert curio.run(test_task, True, with_monitor=True) assert curio.run(test_task, False, with_monitor=True)
/** * The result of a call to {@link LineReaderTask#handleLine(String)}. Allows implementations of that method to * indicate whether a particular invocation of that method produced a return for this task or not. If a return value * doesn't exist the {@link #call()} method will continue to the next line. * * @param <V> */ protected class HandleLineResult<V> { private boolean hasReturnValue; private V returnValue; HandleLineResult() { this.hasReturnValue = false; } HandleLineResult(V returnValue) { this.hasReturnValue = true; this.returnValue = returnValue; } boolean hasReturnValue() { return this.hasReturnValue; } V returnValue() { if (hasReturnValue()) { return this.returnValue; } else { throw new RuntimeException("There was no value to return."); } } }
/** * Twitch API Client (Helix) * @return TwitchHelix */ public TwitchPubSub build() { log.debug("PubSub: Initializing Module ..."); TwitchPubSub twitchChat = new TwitchPubSub(this.eventManager); return twitchChat; }
By THERESA HARRINGTON, EdSource After hours of testimony, the state Board of Education rejected two history textbooks from Houghton Mifflin Harcourt, but approved 10 others based on new history social sciences guidelines. Following nearly eight hours of emotional pleas from Hindus and Indian American, as well as advocates for the LGBTQ community requesting fair historical representations in K-8 textbooks, the state Board of Education endorsed the recommendations of an advisory panel. When Board President Mike Kirst declared the public hearing closed after about 500 people spoke, he said: “That was the longest in the history of the state Board of Education.” But that wasn’t the only historical moment. The board also said it was making history by approving new textbooks they expect to be models for other states across the nation — for their new content related to diverse populations as well as for robust lessons in civic engagement. “Part of what we’re trying to do is get more people engaged in civic participation — and we certainly had a lot today,” Kirst said, calling the meeting “in some ways a model” of the types of opportunities that they are encouraging for people’s voices to be heard. The vote marked the first time textbooks were adopted in the state under the FAIR Education Act, passed in 2011, which required California’s history-social sciences texts to provide fair, accurate, inclusive and respectful representations of people with disabilities and those who are lesbian, gay, bisexual or transgender. In addition, texts are also required to portray people from different backgrounds and religions fairly and accurately based on “social content” regulations. The state board agreed with recommendations of its Instructional Quality Commission to reject the Houghton Mifflin Harcourt texts because the volume of corrections needed would amount to “rewrites,” which are not allowed in the state’s process. The board also agreed with the commission’s recommendations to approve K-8 texts by National Geographic, McGraw-Hill, Pearson and other publishers, saying they adhered to the new History-Social Sciences Framework adopted by the board last year. Several speakers from the LGBTQ community, along with hundreds of speakers from the Hindu and Indian American communities expressed objections to the Houghton Mifflin Harcourt texts for “adverse reflections.” But a spokesman for the publisher urged the board to recommend the middle school text, saying most corrections were minor. He did not address the K-6 text. Ted Levine, CEO of Kids Discover, which partnered with Houghton Mifflin Harcourt on the texts, asked the board to adopt the K-6 text, saying his company had worked tirelessly on the materials. “The public commentary that has been voiced over the last several months forces a company like mine to look at itself in the mirror, to pay close and special attention to the sentences we have written, the images we have chosen, and the art we have created to promote inclusion and support communities across California,” he said. “I stand before you to say that you have been heard, and that adjustments have been made to the program, within the parameters and procedures that the state affords us, that ensures that our program is in full compliance with the California Education Code and state framework.” Carolyn Laub of the FAIR Act Implementation Coalition that reviewed the books praised the process. “We are now poised to make history” by approving the first textbooks highlighting LGBT contributions in the nation,” she said, adding that her group supported the commission’s recommendation to reject the Houghton Mifflin Harcourt texts. “Your historic decision today will ensure that only adopted materials ensure a full and accurate account of LGBT people in history.” No one spoke against the LGBT references, but several people submitted written comments opposing the inclusion of the sexual orientation of historical figures. Districts are free to choose their own materials, but they must also ensure they teach history and social science according to the new guidelines. Some speakers said they would next approach their local school district boards to ensure that materials meet the needs of their children. Several speakers expressed reservations about National Geographic and McGraw-Hill texts, but said that if recent corrections submitted were included in the final versions of the texts, they would support them. Many of these suggested edits were accepted by the publishers, who will have 60 days to make their revisions before finalizing the texts, said Stephanie Gregson, executive director Instructional Quality Commission, adding that the corrected versions should be done by January or February. Although many members of the Hindu community have participated in the instructional review process for months, some Indian Americans and academics from a group called South Asian Histories For All, or SAHFA spoke against some of the changes made to reflect Hindus in a more positive light, saying the caste system is “alive and well” and that many members of lower castes are still persecuted. But other Hindu speakers disputed that and criticized the SAHFA group for not getting involved in the process sooner. Some lawyers in the SAHFA group threatened litigation if the board didn’t postpone its vote, saying the state was not adhering as closely to its framework as it should. Before adopting the texts, board members acknowledged that differences of opinion about history remain, but said it’s up to teachers to allow students to debate their types of issues. “This adoption is different because it’s a personal history — it’s her story, his story, our story,” said board member Patricia Rucker. “This does not resolve the conflicts that many people feel are inherent in our history or history-social science. The purpose of our adoption is not to solve all family problems.” She and other board members thanked the members of the public and advocacy groups for their input, which they said improved the final texts. “I feel the California Department of Education and thousands of members of the public have really made a profound and positive difference in the materials,” said board member Nicki Sandoval, who was liaison to the review process, along with Rucker. “Stakeholders, thank you for using your strong and loud voices, which informed the process, and your agile minds” to ensure “we’re fulfilling our responsibility to provide materials that are inclusive, accurate and respectful” and that will “help to build key understandings for young people” and ultimately to improve school climate and “foster a stronger sense of social responsibility.” Board member Ilene Straus said this was only the first step in improving classroom history social science instruction. “We have a commitment that teachers will get the training they need to understand these issues and that districts will,” she said. “So, this process is not over at all.” This story originally appeared on EdSource.org. EdSource is an independent journalism organization that works to engage Californians on key education challenges with the goal of enhancing learning success.
/** * Converts the given field to its getter. Example: * <li> myWidgetX = get_myWidgetX() * <li> f_html1 = get_f_html1() */ public String convertFieldToGetter(String fieldName) { if (!useLazyWidgetBuilders) { return fieldName; } incrementFieldCounter(fieldName); return getFieldGetter(fieldName); }
import * as React from 'react' import { MemoryRouter, Route, Switch } from 'react-router-dom' import { when } from 'jest-when' import { renderWithProviders } from '@opentrons/components' import { i18n } from '../../../i18n' import { useRobot, useRunCreatedAtTimestamp, } from '../../../organisms/Devices/hooks' import { mockConnectableRobot } from '../../../redux/discovery/__fixtures__' import { getStoredProtocol } from '../../../redux/protocol-storage' import { storedProtocolData as storedProtocolDataFixture } from '../../../redux/protocol-storage/__fixtures__' import { usePathCrumbs } from '../hooks' import { Breadcrumbs } from '..' jest.mock('../../../organisms/Devices/hooks') jest.mock('../../../redux/protocol-storage') jest.mock('../hooks') const mockUsePathCrumbs = usePathCrumbs as jest.MockedFunction< typeof usePathCrumbs > const mockUseRobot = useRobot as jest.MockedFunction<typeof useRobot> const mockUseRunCreatedAtTimestamp = useRunCreatedAtTimestamp as jest.MockedFunction< typeof useRunCreatedAtTimestamp > const mockGetStoredProtocol = getStoredProtocol as jest.MockedFunction< typeof getStoredProtocol > const PATH_CRUMBS = [ { pathSegment: 'devices', crumbName: 'Devices' }, { pathSegment: 'otie', crumbName: 'otie' }, { pathSegment: '10/21/2021 08:00:09', crumbName: '10/21/2021 08:00:09' }, ] const ROBOT_NAME = 'otie' const RUN_ID = '95e67900-bc9f-4fbf-92c6-cc4d7226a51b' const CREATED_AT = '03/03/2022 19:08:49' const render = (path = '/') => { return renderWithProviders( <MemoryRouter initialEntries={[path]} initialIndex={0}> <Breadcrumbs /> <Switch> <Route exact path="/devices/otie"> <div>path matched</div> </Route> </Switch> </MemoryRouter>, { i18nInstance: i18n, } ) } describe('Breadcrumbs', () => { beforeEach(() => { when(mockUsePathCrumbs).calledWith().mockReturnValue(PATH_CRUMBS) when(mockUseRobot) .calledWith(ROBOT_NAME) .mockReturnValue(mockConnectableRobot) when(mockUseRunCreatedAtTimestamp) .calledWith(RUN_ID) .mockReturnValue(CREATED_AT) when(mockGetStoredProtocol).mockReturnValue(storedProtocolDataFixture) }) it('renders an array of breadcrumbs', () => { const [{ getByText }] = render() getByText('Devices') getByText('otie') getByText('10/21/2021 08:00:09') }) it('does nothing when the active breadcrumb is clicked', () => { const [{ getByText, queryByText }] = render() const timestampBreadcrumb = getByText('10/21/2021 08:00:09') timestampBreadcrumb.click() expect(queryByText('path matched')).toBeFalsy() }) it('goes to the correct path when an inactive breadcrumb is clicked', () => { const [{ getByText }] = render() const otieBreadcrumb = getByText('otie') otieBreadcrumb.click() getByText('path matched') }) })
/** * Created by govind on 8/14/16. */ public class ExifJSON { public static JSONObject getExifJSON(File file) { JSONObject jsonObject = new JSONObject("{\"exif\":{}}"); try { Metadata metadata = ImageMetadataReader.readMetadata(file); for (Directory directory : metadata.getDirectories()) { // // Each Directory stores values in Tag objects // for (Tag tag : directory.getTags()) { if (jsonObject.getJSONObject("exif").isNull(tag.getDirectoryName())) { // If JSON property is not present create it jsonObject.getJSONObject("exif").put(tag.getDirectoryName(), new JSONObject("{}")); } jsonObject.getJSONObject("exif").getJSONObject(tag.getDirectoryName()).put(tag.getTagName(), tag.getDescription()); } // // Each Directory may also contain error messages // if (directory.hasErrors()) { for (String error : directory.getErrors()) { System.err.println("ERROR: " + error); } } } } catch (ImageProcessingException e) { // handle exception System.err.println(e); } catch (IOException e) { // handle exception System.err.println(e); } return jsonObject; } }
def add_employee(*args,emp_id,emp_name,emp_phone,payment_amnt): try: cursor = sql.cursor() cursor.execute(f"INSERT INTO employees VALUES ({emp_id},'{emp_name}','{emp_phone}',{payment_amnt});") sql.commit() cursor.close() return "Successfully Added" except: return "Failed - Employee exist"
# params for model RPLP RPLP_config = { "train_gat": True, "train_conv": True, "evaluate": True, 'data': "./data/FB15k-237/", 'output_folder': './checkpoints/fb/out/', 'get_2hop': False, 'use_2hop': True, 'partial_2hop': True, 'epochs_gat': 20, 'epochs_conv': 20, 'batch_size_gat': 280000, 'batch_size_conv': 128, 'weight_decay_gat':1e-5, 'weight_decay_conv': 1e-6, 'pretrained_emb': True, 'embedding_size': 50, 'entity_out_dim': [100, 200], 'relation_out_dim': [100, 200], 'conv_out_channels': 50, 'lr': 1e-3, # Ratio of valid to invalid triples for GAT training 'valid_invalid_ratio_gat': 2, 'drop_GAT': 0.3, # LeakyRelu alphs in GAT 'alpha': 0.2, # Multihead attention 'nheads_GAT': [2, 2], # Margin in hingle-loss 'margin': 1, # LeakyRelu alphs in Conv 'alpha_conv': 0.2, # Ratio of valid to invalid triples for Conv training 'valid_invalid_ratio_conv': 40, # Number of output channels in conv layer 'drop_conv':0.3 }
def main(): version = get_local_version() with open(sys.argv[1], "w") as fptr: fptr.write(version) with open(sys.argv[2], "w") as fptr: fptr.write(str(is_new_release(version)))
The Mets are monitoring Brewers' infielders Aramis Ramirez and Jean Segura in advance of the trade deadline at the end of July, according to a report from Ken Rosenthal of FOXSports.com. The team is also interested in Ben Zobrist, who is likely to be traded by the Athletics at some point this summer. Rosenthal notes that the Mets and Brewers have not spoken about a trade in weeks, although top Mets officials have been spotted at recent Brewers games. Ramirez is thought of as a "more practical target" to replace the injured David Wright for the rest of the season due to his pending retirement and his current lack of a no-trade clause. Segura would solve the Mets' ongoing shortstop problem, though he may come at a high price due to his age (25) and status as controllable through the 2018 season. Zobrist has also drawn interest from the Yankees, Nationals and Cubs, and his versatility makes him attractive to every contender looking to add a valuable piece. Rosenthal reports that the Mets believe they will be outbid in talks for Zobrist, potentially increasing their interest in Ramirez and Segura. In Wright's absence, the Mets have been using a combination of Ruben Tejada and Eric Campbell at the hot corner, with Wilmer Flores manning shortstop despite constantly-swirling rumors about the Mets looking to trade for a shortstop. With the Troy Tulowitzki saga likely to continue into July, the Mets will likely be linked to the Rockies' star and seem positioned to finally make a move to bolster a banged-up infield.
<filename>src/main/cpp/Util/UtilityFunctions.h /****************************** Header ******************************\ Class Name: - File Name: UtilityFunctions.h Summary: File of static utility functions for auto use. Project: FRC2019CPP Copyright (c) BroncBotz. All rights reserved. Author(s): <NAME>, <NAME> Comments added by <NAME> Email: <EMAIL>, <EMAIL> \********************************************************************/ #pragma once #ifndef SRC_UTIL_UTILITYFUNCTIONS_H_ #define SRC_UTIL_UTILITYFUNCTIONS_H_ /* * THIS CLASS IS FOR SETTING AND RETREIVING AND SENDING DATA, AND SIMPLE CALCULATIONS */ #include "../Config/ActiveCollection.h" #include "LoopChecks.h" #include <frc/DriverStation.h> using namespace std; using namespace Util; using namespace Configuration; using namespace Components; /**********************************DRIVE METHODS**********************///SetDrive() static void SetDrive(double left, double right, ActiveCollection *activeCollection) //set left and right motor power. range: [0,1] { VictorSPXItem *left_0 = (VictorSPXItem*)activeCollection->Get("left_0"); //creates pointers to motor objects. This robot has three left motors and three right motors VictorSPXItem *left_1 = (VictorSPXItem*)activeCollection->Get("left_1"); VictorSPXItem *right_0 = (VictorSPXItem*)activeCollection->Get("right_0"); VictorSPXItem *right_1 = (VictorSPXItem*)activeCollection->Get("right_1"); left_0->Set(left); //sets left and right motors to desired power left_1->Set(left); right_0->Set(-right); right_1->Set(-right); } static void SetNeoDrive(double left, double right, ActiveCollection *activeCollection) { SparkMaxItem *left_0 = (SparkMaxItem*)activeCollection->Get("left0"); //creates pointers to motor objects. This robot has three left motors and three right motors SparkMaxItem *left_1 = (SparkMaxItem*)activeCollection->Get("left1"); SparkMaxItem *right_0 = (SparkMaxItem*)activeCollection->Get("right0"); SparkMaxItem *right_1 = (SparkMaxItem*)activeCollection->Get("right1"); left_0->Set(left); //sets left and right motors to desired power left_1->Set(left); right_0->Set(right); right_1->Set(right); } static void StopNeoDrive(ActiveCollection *activeCollection) //sets drive power to zero { SetNeoDrive(0, 0, activeCollection); } static void StopDrive(ActiveCollection *activeCollection) //sets drive power to zero { SetDrive(0, 0, activeCollection); } static void DriveWithTimer(double left, double right, double sec, ActiveCollection *activeCollection) //drives for desired amount of time at specified power. { //this method may not drive straight SetDrive(left, right, activeCollection); Wait(sec); StopDrive(activeCollection); } /***********************OPERATOR METHODS************************/ static void SetElevator(double power, ActiveCollection* activeCollection) { Log::General("util " + to_string(power)); frc::SmartDashboard::PutNumber("util", power); ((VictorSPXItem*)activeCollection->Get("elevator_0"))->Set(-power); ((VictorSPXItem*)activeCollection->Get("elevator_1"))->Set(-power); ((VictorSPXItem*)activeCollection->Get("elevator_2"))->Set(-power); ((VictorSPXItem*)activeCollection->Get("elevator_3"))->Set(-power); } static void StopElevator(ActiveCollection* activeCollection) { SetElevator(0, activeCollection); } /********************************AUTON METHODS********************************/ static void SlowStop(double left, double right, ActiveCollection *activeCollection) //sets motor power and decreases it over time until robot comes to a stop { while ( (abs(right)) > .05 && (abs(left) > .05) ) //while motors still have significant power { left /= 1.02; //decrease by small amount right /= 1.02; SetDrive(left, right, activeCollection); //set drive to new power Wait(.005); } StopDrive(activeCollection); } static char GetSelectedColor() { if(frc::DriverStation::GetInstance().GetGameSpecificMessage().length() > 0) { return frc::DriverStation::GetInstance().GetGameSpecificMessage()[0]; } else { return 'N'; } } static double ABSValue(double val) { if (val < 0) val *= -1; return val; } static double roundValue(double val) { return round((float)val); } static bool Inrange(double a, double v, double T) { if (ABSValue(roundValue(a)) < ABSValue(v) + T && ABSValue(roundValue(a)) > ABSValue(v) - T) { return true; } return false; } static bool Inrange(double Target, double Value) { if(Value <= Target) { return true; } return false; } static double Sign(double Value){ if(Value < 0){ return -1; } else{ return 1; } } static double Scale(double Value, double Min, double MaxValue) { double A = (ABSValue(Value) / MaxValue) + Min; return A * Sign(Value); } static double Constrain(double Value, double Min, double Max) { if((Value) < Min) { return Min;// * Sign(Value); } else if((Value) > Max) { return Max;// * Sign(Value); } else { return Value; } } static double PIDCalculae(double P, double I, double D, double& TotalError, double Error, double PrevE, double ChangeInTime) { TotalError += Error * ChangeInTime; return ((P * Error) + (I * TotalError) + (D * ((Error - PrevE) / ChangeInTime))); } static double PIDCalculae(double P, double I, double D, double& TotalError, double Error, double PrevE, double ChangeInTime, double& ErrorTo, double Target) { TotalError += Error * ChangeInTime; ErrorTo += (Error - Target) * ChangeInTime; return ((P * Error) + (I * TotalError) + (D * (ErrorTo))); } static bool BelowMaxRate(double Val1, double Val2, double MaxRate) { return ABSValue(ABSValue(Val1) - ABSValue(Val2)) < MaxRate; } static double GetMax(double V1, double V2) { return (V1 > V2 ? V1 : V2); } static double GetMin(double V1, double V2) { return (V1 < V2 ? V1 : V2); } static double PIDCal(double P, double I, double D, double& TotalError, double Error, double& PrevError, double ChangeInTime, double MaxPower, double MaxChange, double& LastResult, double Bias) { double Result = PIDCalculae(P, I, D, TotalError, Error, PrevError, ChangeInTime); PrevError = Error; Result = Constrain(Scale(Result, 0, (Bias)), -MaxPower, MaxPower); if(!BelowMaxRate(Result, LastResult, MaxChange)) { Log::General("PIDCal went over max change, Change = " + to_string(ABSValue(ABSValue(Result) - ABSValue(LastResult)))); Result = LastResult; } LastResult = Result; return Result; } static double PIDCal(double P, double I, double D, double& TotalError, double Error, double& PrevError, double ChangeInTime, double MaxPower, double MaxChange, double& LastResult, double Bias, double& ErrorTo, double Target) { double Result = PIDCalculae(P, I, D, TotalError, Error, PrevError, ChangeInTime, ErrorTo, Target); PrevError = Error; Result = Constrain(Scale(Result, 0, (Bias)), -MaxPower, MaxPower); if(!BelowMaxRate(Result, LastResult, MaxChange)) { Log::General("PIDCal went over max change, Change = " + to_string(ABSValue(ABSValue(Result) - ABSValue(LastResult)))); Result = LastResult; } LastResult = Result; return Result; } static double PIDCal(double P, double I, double D, double& TotalError, double Error, double& PrevError, double ChangeInTime, double MaxPower, double MinPower, double MaxChange, double& LastResult, double Bias, double& ErrorTo, double Target) { double Result = PIDCalculae(P, I, D, TotalError, Error, PrevError, ChangeInTime, ErrorTo, Target); PrevError = Error; Result = Constrain(Scale(Result, 0, (Bias)), MinPower, MaxPower); if(!BelowMaxRate(Result, LastResult, MaxChange)) { Log::General("PIDCal went over max change, Change = " + to_string(ABSValue(ABSValue(Result) - ABSValue(LastResult)))); Result = LastResult; } LastResult = Result; return Result; } /* DriveForward * This method uses two PID loops to drive straight and the requesred encoder distance * The first PID loop runs for the 60% of requested distance, using the navx to correct angle * the second PID loop runs for the remaining distance, at at a lower speed to improve accuracy. * * What is a PID loop? * A PID loop is a feedback loop that uses an input stream to control an output stream. In our case, the NavX angle controls left/right motor speeds. * P - Proportion * outputs a value proportional to error (desired value minus expected value). 6 For our code: We want to be facing at the same direction the whole time, so any deviation from that value is error. 9 I - Integral 6 The general term for integral is area under a graph. If you think of a graph of time versus error, integral would be the area between 9 the x-axis and the graph. Integral is used for error correction. Integral is not always neccessary, so you may see its scalar value (ki) * set to zero. * For our code: Say we wanted to drive a specified distance and our robot was alrealy only 1 encoder tick away. The kp and kd values would not * provide enough power to push that last bit, because the values are so small and in the real world there's friction and stuff that would stop it. * The ki value, will observe error over time and, if it is high enough, provide that small boost that the robot needs. * D - Derivative * Another way to think of derivative is slope. Derivate is the slope of the line tangent to a graph at a specific point. * Going back to the graph described above, derivitive will find how steep our error line is, aka the rate of change of error. * If we did not have kd, then kp would always overshoot the desired value, then start swinging back towards it, and overshoot again, * kinda like a pendulum trying to be at 0 degrees, it would always overshoot. Think of the kd value like a finger pushing against the pendulum. * When the pendulum isn't moving, the finger doesn't push at all, but the faster the pendulum moves, the more kd pushes back. Once tuned properly, kd * will stop the pendulum exactly at zero degrees, without it overshooting or pushing the pendulum back away. * For our code: with only ki, the robot would oscillate around zero degress while driving forward and never stay there. With kd, the derivate will push against * ki to hopefully stop turning exactly at zero degrees. * derivative = current error - error prior. */ /* static double DriveForward(double dist, double power, ActiveCollection *activeCollection, double T) { NavX *navx = activeCollection->GetNavX(); navx -> Reset(); EncoderItem *enc0 = activeCollection->GetEncoder("enc0"); bool IsNegative = (dist < 0); cout << "initial angle = " << navx->GetAngle() << endl; double killTime = 10, elapsedTime = 0; //killTime is the time allowed before Turn method times out. Used in case robot is stuck or code messes up. double left, right = 0; //left and right motor powers, and default pwoer double currentValue = navx->GetAngle(); //get current navx angle double P = 5; //PID constants double I = -0.0005; double D = 8; double PE = 0.07; //PID constants double IE = 0.08; double DE = 0.0005; double F = (0.0) * ABSValue(dist); double Limit = 0.5; double MinPower = 0; double ChangeInTime = 0.004; double PrevE = 0, totalE = 0; double PrevEncoder = 0, totalEncoder = 0, PrevEncoderTrack = 10000; double enc = 0; double distTo = ABSValue(dist); double NumberAtTarget = 0; while((elapsedTime < killTime) && (NumberAtTarget < 400)) { currentValue = navx->GetAngle(); //get new navx angle enc = ABSValue(enc0->Get()); //get new encoder distance //Angle PIDF double Error = 0 - currentValue; totalE += Error * ChangeInTime; double Result = ((PE * Error) + (IE * totalE) + (DE * ((Error - PrevE) / ChangeInTime))); PrevE = Error; //Distance Traveled PIDF double ErrorEncoder = distTo - enc; totalEncoder += ErrorEncoder * ChangeInTime; double ResultEncoder = ((P * ErrorEncoder) + (I * totalEncoder) + (D * ((ErrorEncoder - PrevEncoder) / ChangeInTime)) + F); PrevEncoder = ErrorEncoder; PrevEncoderTrack = ABSValue(PrevEncoder); if(power != 0) { if (ABSValue(ResultEncoder) > power) { ResultEncoder = power * Sign(ResultEncoder); } else if (ABSValue(ResultEncoder) < MinPower) { ResultEncoder = MinPower * Sign(ResultEncoder); } } if(!IsNegative){ if(ErrorEncoder > 0){ if(ResultEncoder < 0){ ResultEncoder = MinPower; } } else { if(ResultEncoder > 0){ ResultEncoder = MinPower; } } } else{ if(ErrorEncoder > 0){ if(ResultEncoder > 0){ ResultEncoder = MinPower; } } else { if(ResultEncoder < 0){ ResultEncoder = MinPower; } } } if(Limit != 0) { if (Result > Limit) { Result = Limit; } else if (Result < -Limit) { Result = -Limit; } } if(!IsNegative) { left = -ResultEncoder - Result; right = ResultEncoder - Result; } else { left = ResultEncoder - Result; right = -ResultEncoder - Result; } SetDrive(left, right, activeCollection); //set drive to new powers if(Inrange(enc, dist, T)){ NumberAtTarget++; } Wait(ChangeInTime); elapsedTime += ChangeInTime; //add time to elapsed //cout << "EncoderPos: " << to_string(enc) << " : Encoder To: " << to_string(distTo) << " : Result: " << to_string(ResultEncoder) << endl; } StopDrive(activeCollection); //once finished, stop drive Wait(.5); return 0; } static void MoveForwardPIDF(double Dist, double MaxPowerInput, ActiveCollection *activeCollection){ double RealTarget = Dist * 89; // 85 was working yesterday double MaxPower = MaxPowerInput; double x = 10; EncoderItem *enc0 = activeCollection->GetEncoder("enc0"); //gets encoder from active collection enc0 -> Reset(); DriveForward(RealTarget, MaxPower, activeCollection, x); Log::General("ENC 0: " + to_string(enc0->Get())); Wait(0.5); Log::General("Final Error: " + to_string(RealTarget)); }*/ /* * * POWER UP 2018 * * @#####@ * @%&/#%# * /%%%%%%%%%%%%%%%%%%@%&%%##%%%%%%%%%%%%%%%%%%% * @@@@@@@@@@@@@@@@@/@%&&&&%@%&&&@//@&&@%%@#%#&&&%&%&&&&/@@&&&@@%@@@@@@@@@@@@@@@@@@@@ * /@%&%%##\ * / @%%@#%# \ * / @%&%%## \ * / @%#%/@# \ * / @%#%@/# \ * / (/#@%(%&%#(@% \ * / *%%*#@%#%@/#*@@%#@ \ * ///#/@/,/@@(//@/#/,@@&///@/,/%@@//*\ * @@@/#//@/@/@/@/@//@/@/@/@//(/@/@/@/#//@/@/@/@ * * BEGIN TRANSMISSION...======================= * RIP C#; Born: May 2014; Death Feb 5, 2018 * The Day the Codebase died. It was a hard day * for BroncBotz, a hard day for the world. * =========================...END TRANSMISSION * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * | You will be missed OJ. -- Watson | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * */ /* * , * _=|_ DEEP SPACE 2019 * _[_## ]_ * _ +[_[_+_]P/ _ |_ ____ _=--|-~ * ~---\_I_I_[=\--~ ~~--[o]--==-|##==]-=-~~ o]H * -~ /[_[_|_]_]\\ -_ [[=]] |====] __ !j]H * / "|" \ ^U-U^ - | - ~ .~ U/~ * ~~--__~~~--__~~-__ H_H_ |_ -- _H_ * -. _ ~~~#######~~~ ~~~- ~~-- ._ - ~~-= * ~~~=~~ -~~-- _ . - _ _ - * * ---------------------------------- * | June, 20th, 1969 | * | Here Men from the Planet Earth | * | First set Foot upon the Moon | * | We came in Peace for all Mankind | * ---------------------------=apx=-- */ /* * INFINITE RECHARGE 2020 *____ ____ *|\/|\_______________________________________________________/|\/| *|\/|_/__/__/__/__/__/__/__/__/_()_/__/__/__/__/__/__/__/__/__|\/| *|\/| || |\/| *|/\| /##########\ |\/| *|\/| /#####/ || \#####\ |\/| *|/\| |#####__________8||8__________#####| |\/| *|\/| \/ |\/| *|/\| || |\/| *|\/| || |\/| *|/\| +==\\ ---- *|\/| [---]\\ 0 _ ---- *|/\| {/\/\_|_| 0| ---- *|\/| 0--0--0 || ---- *|/\| __/||\\___.\ *|\/|___________________________________________________|_0__0__0_| 0____________ * =============================================================================== * It's over BroncBotz... * I HAVE THE HIGH GROUND. * -Any other Robot with a hang * */ /* Turn * Uses a PID loop to turn the desired amount of degrees. PID input: Navx, output: motor power * What's a PID loop? Read the explanation above DriveForward() */ /* static double Turn(double target, ActiveCollection *activeCollection, double T) { bool IsNegative = (target < 0); target = ABSValue(target); NavX *navx = activeCollection->GetNavX(); navx->ResetNav(); //reset navx angle Wait(.25); cout << "initial angle = " << navx->GetAngle() << endl; double killTime = 2, elapsedTime = 0; //killTime is the time allowed before Turn method times out. Used in case robot is stuck or code messes up. double left, right = 0; //left and right motor powers, and default pwoer double power = 0; double currentValue = navx->GetAngle(); //get current navx angle double P = 0.06; //PID constants double I = 0.008; double D = 0.0005; double F = (0.09 * target); double Limit = 0.25; double MinLimit = 0.05; double ChangeInTime = 0.004; double PrevE, totalE = 0; double PerErrorTrack = 10000; double thres = T; while((PerErrorTrack > thres) && (elapsedTime < killTime)) { currentValue = ABSValue(navx->GetAngle()); //get new navx angle double Error = target - currentValue; totalE += Error * ChangeInTime; double Result = ((P * Error) + (I * totalE) + (D * ((Error - PrevE) / ChangeInTime)) + F); PrevE = Error; PerErrorTrack = Error; if(Limit != 0) { if (ABSValue(Result) > Limit) { Result = Limit * Sign(Result); } else if (ABSValue(Result) < MinLimit) { Result = MinLimit * Sign(Result); } } PerErrorTrack = ABSValue(PerErrorTrack); if(!IsNegative){ left = power - Result; //set left motor to desired power + output //might have to make postive right = power - Result; //set right motor to desired power - output (+ and - to make robot turn slightly) //might have to make negative again for auto } else if (IsNegative) { left = power + Result; //set left motor to desired power + output //might have to make postive right = power + Result; //set right motor to desired power - output (+ and - to make robot turn slightly) //might have to make negative again for auto } if(target == 0) { left = 0; right = 0; Log::General("What are you doing trying to go to 0 using turn, a method that resets the value of the navx"); PerErrorTrack = 0; } SetDrive(left, right, activeCollection); //set drive to new powers Wait(ChangeInTime); elapsedTime += ChangeInTime; //add time to elapsed } StopDrive(activeCollection); //once finished, stop drive Wait(.5); currentValue = navx->GetAngle(); //get final navx angle return currentValue; } static void TurnPIDF(double Target, ActiveCollection *activeCollection){ //This is used for turning NOT TURN() double TheTarget = 0; double RealTarget = 0; double Kill = 10; double TotalTimeSpent = 0; TheTarget = RealTarget = Target; TheTarget *= 0.8; RealTarget -= Turn(TheTarget, activeCollection, RealTarget * 0.1); Log::General("Error: " + to_string(RealTarget)); double x = 10; while((RealTarget > 0.5) && (TotalTimeSpent < Kill)) { RealTarget -= Turn(RealTarget, activeCollection, x); Log::General("Error: " + to_string(RealTarget)); x -= 1.5; if(x < 0.2){ x = 0.2; } TotalTimeSpent++; } Wait(0.5); Log::General("Final Error: " + to_string(RealTarget)); if(ABSValue(RealTarget) > 1){ TurnPIDF(-RealTarget, activeCollection); } }*/ #endif /* SRC_UTIL_UTILITYFUNCTIONS_H_ */
def action(self, book): entry = BookShelf.objects.get(user=self.request.user, book=book) entry.delete() messages.success(self.request, "You have removed this book from your bookshelf.")
<reponame>kix/django<filename>django/contrib/flatpages/tests/urls.py<gh_stars>100-1000 from django.conf.urls import patterns, include # special urls for flatpage test cases urlpatterns = patterns('', (r'^flatpage_root', include('django.contrib.flatpages.urls')), (r'^accounts/', include('django.contrib.auth.urls')), )
// Find the previous entity stored if one is available. func (entity *Treatment) Find(context DatabaseService) error { context.Find(&Treatment{ID: entity.ID}, func(result interface{}) { previous := result.(*Treatment) if entity.Name == nil { entity.Name = &Text{} } entity.NameID = previous.NameID entity.Name.ID = previous.NameID if entity.Phone == nil { entity.Phone = &Telephone{} } entity.PhoneID = previous.PhoneID entity.Phone.ID = previous.PhoneID if entity.Address == nil { entity.Address = &Location{} } entity.AddressID = previous.AddressID entity.Address.ID = previous.AddressID }) return nil }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _OE_HOST_CRYPTO_RSA_H #define _OE_HOST_CRYPTO_RSA_H #include <openenclave/internal/rsa.h> /* Caller is responsible for freeing public key. */ oe_result_t oe_rsa_get_public_key_from_private( const oe_rsa_private_key_t* private_key, oe_rsa_public_key_t* public_key); #endif /* _OE_HOST_CRYPTO_RSA_H */
<reponame>go-toolbelt/clock<gh_stars>0 package clock_test import ( "testing" "time" "github.com/go-toolbelt/clock" ) func TestNow(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) assertClockAt(t, start, clock) } func TestAdvance(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) clock.Advance(1 * time.Second) assertClockAt(t, start.Add(1*time.Second), clock) } func TestSince_Positive(t *testing.T) { start := time.Unix(2, 0) clock := clock.NewFakeClockAt(start) expected := 1 * time.Second actual := clock.Since(start.Add(-expected)) if actual != expected { t.Errorf("expected %s got %s", expected, actual) } } func TestSince_Negative(t *testing.T) { start := time.Unix(2, 0) clock := clock.NewFakeClockAt(start) expected := -1 * time.Second actual := clock.Since(start.Add(-expected)) if actual != expected { t.Errorf("expected %s got %s", expected, actual) } } func TestNewTimer(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(2 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(2*time.Second), c) } func TestNewTimer_CallCTwice(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(1 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) c = timer.C() assertNotSent(t, c) } func TestNewTimer_Stop(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(2 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) if !timer.Stop() { t.Error("expected stop to return true") } if timer.Stop() { t.Error("expected stop to return false") } clock.Advance(1 * time.Second) assertNotSent(t, c) } func TestNewTimer_Stop_NeverCalledC(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(2 * time.Second) clock.Advance(1 * time.Second) if !timer.Stop() { t.Error("expected stop to return true") } if timer.Stop() { t.Error("expected stop to return false") } } func TestNewTimer_Stop_AfterFired(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(1 * time.Second) c := timer.C() clock.BlockUntil(1) clock.Advance(1 * time.Second) if timer.Stop() { t.Error("expected stop to return false") } if timer.Stop() { t.Error("expected stop to return false") } assertSent(t, start.Add(1*time.Second), c) } func TestNewTimer_Reset_Positive(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(1 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) if timer.Reset(2 * time.Second) { t.Error("expected stop to return false") } c = timer.C() assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(3*time.Second), c) } func TestNewTimer_Reset_Zero(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(1 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) if timer.Reset(0) { t.Error("expected stop to return false") } c = timer.C() assertSent(t, start.Add(1*time.Second), c) } func TestNewTimer_Reset_Negative(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(1 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) if timer.Reset(-1) { t.Error("expected stop to return false") } c = timer.C() assertSent(t, start.Add(1*time.Second), c) } func TestNewTimer_Reset_Stopped(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(2 * time.Second) c := timer.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) if !timer.Stop() { t.Error("expected stop to return true") } if timer.Reset(2 * time.Second) { t.Error("expected stop to return false") } c = timer.C() assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(3*time.Second), c) } func TestNewTimer_Reset_Stopped_AfterFired(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) timer := clock.NewTimer(1 * time.Second) c := timer.C() clock.BlockUntil(1) clock.Advance(1 * time.Second) if timer.Stop() { t.Error("expected stop to return false") } assertSent(t, start.Add(1*time.Second), c) if timer.Reset(2 * time.Second) { t.Error("expected stop to return false") } c = timer.C() assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(3*time.Second), c) } func TestSleep_Positive(t *testing.T) { start := time.Unix(2, 0) clock := clock.NewFakeClockAt(start) woke := make(chan struct{}) go func() { defer close(woke) clock.Sleep(1 * time.Second) }() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertClosed(t, woke) } func TestSleep_Positive_TwoSleepers(t *testing.T) { start := time.Unix(2, 0) clock := clock.NewFakeClockAt(start) woke0 := make(chan struct{}) go func() { defer close(woke0) clock.Sleep(1 * time.Second) }() woke1 := make(chan struct{}) go func() { defer close(woke1) clock.Sleep(2 * time.Second) }() assertClockUntil(t, 2, clock) clock.Advance(1 * time.Second) assertClosed(t, woke0) assertNotClosed(t, woke1) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertClosed(t, woke1) } func TestSleep_Zero(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) clock.Sleep(0) // should return immediately } func TestSleep_Negative(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) clock.Sleep(-1) // should return immediately } func TestAfter_Positive(t *testing.T) { start := time.Unix(2, 0) clock := clock.NewFakeClockAt(start) after := clock.After(1 * time.Second) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), after) } func TestAfter_Positive_TwoSleepers(t *testing.T) { start := time.Unix(2, 0) clock := clock.NewFakeClockAt(start) after0 := clock.After(1 * time.Second) after1 := clock.After(2 * time.Second) assertClockUntil(t, 2, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), after0) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(2*time.Second), after1) } func TestAfter_Zero(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) after := clock.After(0) assertSent(t, start, after) } func TestAfter_Negative(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) after := clock.After(-1) assertSent(t, start, after) } func TestAfterFunc(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) clock.AfterFunc(2*time.Second, func() { c <- clock.Now() }) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(2*time.Second), c) } func TestAfterFunc_Stop(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) timer := clock.AfterFunc(2*time.Second, func() { c <- clock.Now() }) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) if !timer.Stop() { t.Error("expected stop to return true") } if timer.Stop() { t.Error("expected stop to return false") } clock.Advance(1 * time.Second) assertNotSent(t, c) } func TestAfterFunc_Stop_AfterFired(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) timer := clock.AfterFunc(1*time.Second, func() { c <- clock.Now() }) clock.BlockUntil(1) clock.Advance(1 * time.Second) if timer.Stop() { t.Error("expected stop to return false") } if timer.Stop() { t.Error("expected stop to return false") } assertSent(t, start.Add(1*time.Second), c) } func TestAfterFunc_Reset_Positive(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) getter := func() chan time.Time { return c } timer := clock.AfterFunc(1*time.Second, func() { getter() <- clock.Now() }) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) if timer.Reset(2 * time.Second) { t.Error("expected stop to return false") } c = make(chan time.Time) assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(3*time.Second), c) } func TestAfterFunc_Reset_Zero(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) getter := func() chan time.Time { return c } timer := clock.AfterFunc(1*time.Second, func() { getter() <- clock.Now() }) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) c = make(chan time.Time) if timer.Reset(0) { t.Error("expected stop to return false") } assertSent(t, start.Add(1*time.Second), c) } func TestAfterFunc_Reset_Negative(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) getter := func() chan time.Time { return c } timer := clock.AfterFunc(1*time.Second, func() { getter() <- clock.Now() }) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) c = make(chan time.Time) if timer.Reset(-1) { t.Error("expected stop to return false") } assertSent(t, start.Add(1*time.Second), c) } func TestAfterFunc_Reset_Stopped(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) getter := func() chan time.Time { return c } timer := clock.AfterFunc(2*time.Second, func() { getter() <- clock.Now() }) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) if !timer.Stop() { t.Error("expected stop to return true") } if timer.Reset(2 * time.Second) { t.Error("expected stop to return false") } c = make(chan time.Time) assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(3*time.Second), c) } func TestAfterFunc_Reset_Stopped_AfterFired(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) c := make(chan time.Time) getter := func() chan time.Time { return c } timer := clock.AfterFunc(1*time.Second, func() { getter() <- clock.Now() }) clock.BlockUntil(1) clock.Advance(1 * time.Second) if timer.Stop() { t.Error("expected stop to return false") } assertSent(t, start.Add(1*time.Second), c) if timer.Reset(2 * time.Second) { t.Error("expected stop to return false") } c = make(chan time.Time) assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(3*time.Second), c) } func TestNewTicker(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) ticker := clock.NewTicker(2 * time.Second) c := ticker.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(2*time.Second), c) c = ticker.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertNotSent(t, c) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(4*time.Second), c) } func TestNewTicker_Double(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) ticker := clock.NewTicker(1 * time.Second) c := ticker.C() assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(1*time.Second), c) // c = ticker.C() // assertClockUntil(t, 1, clock) // assertSent(t, start.Add(2 * time.Second), c) } func TestNewTicker_Stop(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) ticker := clock.NewTicker(1 * time.Second) c := ticker.C() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(1*time.Second), c) ticker.Stop() c = ticker.C() clock.Advance(1 * time.Second) assertNotSent(t, c) } func TestNewTicker_Stop_NeverCalledC(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) ticker := clock.NewTicker(1 * time.Second) clock.Advance(1 * time.Second) ticker.Stop() c := ticker.C() clock.Advance(1 * time.Second) assertNotSent(t, c) } func TestTick_Positive(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) tick := clock.Tick(2 * time.Second) c := tick() assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertClockUntil(t, 1, clock) clock.Advance(1 * time.Second) assertSent(t, start.Add(2*time.Second), c) c = tick() assertClockUntil(t, 1, clock) clock.Advance(2 * time.Second) assertSent(t, start.Add(4*time.Second), c) } func TestTick_Zero(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) tick := clock.Tick(0) if tick() != nil { t.Error("expected tick to return nil") } } func TestTick_Negative(t *testing.T) { start := time.Unix(1, 0) clock := clock.NewFakeClockAt(start) tick := clock.Tick(-1) if tick() != nil { t.Error("expected tick to return nil") } } func assertClockAt(t *testing.T, expected time.Time, clock clock.FakeClock) { if actual := clock.Now(); actual != expected { t.Errorf("expected %s got %s", expected, actual) } } const untilTimeout = 100 * time.Millisecond func assertClockUntil(t *testing.T, n int, clock clock.FakeClock) { timer := time.NewTimer(untilTimeout) defer timer.Stop() select { case <-clock.Until(n): case <-timer.C: t.Errorf("timeout: after %s waiting for %d", untilTimeout, n) } } const closedTimeout = 100 * time.Millisecond func assertClosed(t *testing.T, c chan struct{}) { timer := time.NewTimer(closedTimeout) defer timer.Stop() select { case _, open := <-c: if open { t.Error("channel open") } case <-timer.C: t.Errorf("timeout: after %s", closedTimeout) } } const notClosedTimeout = 100 * time.Millisecond func assertNotClosed(t *testing.T, c <-chan struct{}) { timer := time.NewTimer(notClosedTimeout) defer timer.Stop() select { case <-c: t.Error("channel closed unexpectedly") case <-timer.C: } } const sentTimeout = 100 * time.Millisecond func assertSent(t *testing.T, expected time.Time, c <-chan time.Time) { timer := time.NewTimer(sentTimeout) defer timer.Stop() select { case actual := <-c: if actual != expected { t.Errorf("expected %s got %s", expected, actual) } case <-timer.C: t.Errorf("timeout: after %s", notClosedTimeout) } } const notSentTimeout = 100 * time.Millisecond func assertNotSent(t *testing.T, c <-chan time.Time) { timer := time.NewTimer(notSentTimeout) defer timer.Stop() select { case <-c: t.Error("time sent unexpectedly") case <-timer.C: } }
/** * The app that use async mode to run a parallel task, and then poll the progress * and show an aggregation */ public class HttpBasicAsyncRunProgressPollingApp { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { ParallelClient pc = new ParallelClient(); ParallelTask task = pc.prepareHttpGet("").async() .setConcurrency(500) .setTargetHostsFromLineByLineText("http://www.parallec.io/userdata/sample_target_hosts_top100_old.txt", HostsSourceType.URL) .execute(new ParallecResponseHandler() { public void onCompleted(ResponseOnSingleTask res, Map<String, Object> responseContext) { System.out.println("Responose Code:" + res.getStatusCode() + " host: " + res.getHost()); } }); while (!task.isCompleted()) { try { Thread.sleep(100L); System.err.println(String.format( "POLL_JOB_PROGRESS (%.5g%%) PT jobid: %s", task.getProgress(), task.getTaskId())); pc.logHealth(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out .println("Result Summary\n " + PcStringUtils.renderJson(task .getAggregateResultFullSummary())); System.out .println("Result Brief Summary\n " + PcStringUtils.renderJson(task .getAggregateResultCountSummary())); pc.releaseExternalResources(); } }
def _report_sighting(self, msg: str): try: sighting: Sighting = parse(msg, allow_custom=True) except Exception as e: self.opencti_helper.log_error( f"Error parsing message from Threat Bus. Expected a STIX-2 Sighting: {e}" ) return if type(sighting) is not Sighting: self.opencti_helper.log_error( f"Error parsing message from Threat Bus. Expected a STIX-2 Sighting: {sighting}" ) return entity_id = self._get_threatbus_entity().get("id", None) resp = self.opencti_helper.api.stix_sighting_relationship.create( fromId=sighting.sighting_of_ref, toId=entity_id, createdBy=entity_id, first_seen=sighting.first_seen.astimezone().strftime("%Y-%m-%dT%H:%M:%SZ") if sighting.get("first_seen") else None, last_seen=sighting.last_seen.astimezone().strftime("%Y-%m-%dT%H:%M:%SZ") if sighting.get("last_seen") else None, confidence=50, externalReferences=[sighting.sighting_of_ref], count=1, ) self.opencti_helper.log_info(f"Created sighting {resp}")
Dear Reader, As you can imagine, more people are reading The Jerusalem Post than ever before. Nevertheless, traditional business models are no longer sustainable and high-quality publications, like ours, are being forced to look for new ways to keep going. Unlike many other news organizations, we have not put up a paywall. We want to keep our journalism open and accessible and be able to keep providing you with news and analysis from the frontlines of Israel, the Middle East and the Jewish World. Jerusalem responded to the UN Security Council’s special debate on the settlements on Friday by saying that characterizing the settlements as the “obstacle to peace” recycles the “scandalous Palestinian demand that Palestine be cleansed of any Jews.” “In any other case, a demand such as this would be completely rejected by the international community,” senior sources in Jerusalem said. “No one, for instance, would even think about saying that a condition of peace would be that Israel be without Arabs.” These comments came in response to a discussion in the Security Council, where left-wing Israeli NGOs Peace Now and B’Tselem joined an informal meeting, held under a process known as the Arria Formula, which focused on the question of whether West Bank settlements are a stumbling block to peace. The debate was convened at the request of Angola, Malaysia, Venezuela, Senegal and Egypt.“There is an endless list of human rights violations that the Palestinian people are victims of, and we are convinced that Israel has committed war crimes against Palestinians that have to be investigated and punished,” Venezuela’s Ambassador Rafael Ramirez said.Sources in Jerusalem said that the claim that the settlements are illegal and an obstacle to peace are baseless, and deny the deep connection between the Jewish people and its land, similar to what UNESCO did last week in its resolution denying a Jewish connection to the Temple Mount.The sources continued, saying, “The settlements are not the root of the conflict, nor an obstacle to its coming to a conclusion.The true obstacle to peace is the continued Palestinian refusal to recognize a Jewish state in any borders. This refusal is expressed by the demand to cleanse Judea and Samaria of Jews, and in the endless Palestinian incitement toward terror.”By stating that objection to settlements stemmed from a Palestinian desire to have a state cleansed of Jews, the sources in Jerusalem were echoing a controversial video Prime Minister Benjamin Netanyahu released last month. In that video, Netanyahu said that while Israel has nearly two million Arabs living inside its borders, the Palestinian leadership “actually demands a Palestinian state with one precondition: no Jews.”At the UN, Ramirez vowed to “put an end to Israeli occupation, saying, “We say we reject any terrorist acts, but we are using that argument to establish an equivalency between the disproportionate violence of Israel against the Palestinian people and the isolated acts of violent reactions of the Palestinian people against Israel.“Here, certainly there can’t be a double standard. We cannot allow the continuation of settlements and killings of Palestinian people,” Ramirez continued. “We believe the time has come for this Security Council to do something specific and concrete.We have had enough rhetoric and declarations... Israeli settlements are illegal, everything Israel has done in Palestine is illegal.”Ambassador to the UN Danny Danon responded that Ramirez’s statement is “hypocritical and laced with anti-Israel hatred.”Back in May, during another informal Security Council meeting on the Palestinian question, Ramirez asked if Israel aims to perpetrate a “final solution” against the Palestinian people, Danon recalled.“Nothing is more ludicrous than accusing Israel of war crimes. Our record on behalf of human rights and democracy speaks for itself. We do not accept hypocritical criticism from countries whose own record on human rights can only be described as horrendous,” he said.Representatives from Peace Now and B’Tselem urged the international community to act to stop settlement expansion.Lara Friedman, director of policy and government relations for Americans for Peace Now, accused the Israeli government of conducting an “ugly campaign” against “courageous” NGOs and activists who are against the country’s settlement policy.“The occupation is a threat to Israel’s security and Israel’s existence,” she said.“If these policies are not rolled back, they will destroy the possibility of ever reaching a political agreement between Israel and Palestine.”The executive director of B’Tselem, Hagai El-Ad, added that the Security Council has “a moral responsibility” to act on the issue.“Israel cannot have it both ways,” he said.“You cannot occupy a people for 50 years and call yourself a democracy.”Netanyahu slammed both of the organizations for taking part in the “mudslinging choir” against Israel. Citing El-Ad’s appeal to the UN to take action against Israel on the issue, he said that “what these organizations did not succeed in achieving through democratic elections in Israel, they are trying to achieve through international coercion.“We will continue to defend the righteousness of our cause and our state against all international pressure,” he said.Netanyahu spoke Saturday night with coalition chairman David Bitan about amending the National Service law to prohibit women doing national service from doing it for B’Tselem.Danon harshly criticized the statements to the council. “Just two days after anti-Israel forces approved a resolution intending to sever the historical bond between the Jewish people and Jerusalem, Israeli organizations chose to slander and besmirch Israel’s good name at an event organized by the Palestinian delegation,” he said. “We will continue to fight and tell the truth about Israel, despite the attempts to spread lies about us.”Another panelist invited to speak was François Dubuisson, a law professor at the Université libre de Bruxelles. He urged the international community and member states of the UN to take economic measures to ensure the end of settlement activities and called on them to ban imports of products coming from the settlements, end the financing of entities established there and adopt measures to sanction national companies carrying out economic activities linked to the settlements.Dubuisson then compared the situation in Israel to the one in South Africa in the 1970s.“Apartheid was a violation of international law, a situation which was condemned universally,” he said. “But because of certain political alliances, no binding measure was able to be adopted by the Security Council for a long time.“It’s only with the pressure of certain states within the United Nations and pressure by civil society around the world that the Security Council put an arms embargo and adopted a resolution asking states to take economic measures against the apartheid regime,” he said. “Today we should be inspired by that precedent.” Join Jerusalem Post Premium Plus now for just $5 and upgrade your experience with an ads-free website and exclusive content. Click here>>
<gh_stars>1-10 class OpenItem { //! WIll open the 'item_target' by spawning a new entity and transferring item variables to the new one static void OpenAndSwitch(ItemBase item_tool, ItemBase item_target, PlayerBase player, float specialty_weight = 0) { ref array<int> spill_range = new array<int>; if( item_tool.ConfigIsExisting("OpenItemSpillRange") ) { item_tool.ConfigGetIntArray("OpenItemSpillRange", spill_range ); } else { Debug.LogError("OpenItemSpillRange config parameter missing, default values used ! "); Error("OpenItemSpillRange config parameter missing, default values used !"); spill_range.Insert(0); spill_range.Insert(100); } float spill_modificator = Math.RandomIntInclusive( spill_range.Get(0),spill_range.Get(1) ) / 100; OpenItem.SwitchItems(item_target, player, spill_modificator, specialty_weight); } //! Will switch the 'item' for a new game entity, the new entity's classname will be formed by adding the 'suffix' to the classname of the old 'item' static void SwitchItems (EntityAI old_item, PlayerBase player, float spill_modificator, float specialty_weight) { string old_name = old_item.GetType(); string new_name = old_name + "_Opened"; OpenAndSwitchLambda l = new OpenAndSwitchLambda(old_item, new_name, player, spill_modificator, specialty_weight); l.SetTransferParams(true, false); MiscGameplayFunctions.TurnItemIntoItemEx(player, l); } }; class OpenAndSwitchLambda : TurnItemIntoItemLambda { float m_SpillModifier; float m_SpecialtyWeight; void OpenAndSwitchLambda (EntityAI old_item, string new_item_type, PlayerBase player, float spill_modificator, float specialty_weight) { m_SpillModifier = spill_modificator; m_SpecialtyWeight = specialty_weight; } override void CopyOldPropertiesToNew (notnull EntityAI old_item, notnull EntityAI new_item) { super.CopyOldPropertiesToNew(old_item, new_item); ItemBase ib = ItemBase.Cast(new_item); if ( new_item ) { float quantity_old = ib.GetQuantity(); float spill_amount = quantity_old * m_SpillModifier; spill_amount = m_Player.m_SoftSkillsManager.SubtractSpecialtyBonus(spill_amount, m_SpecialtyWeight); float quantity_new = quantity_old - spill_amount; Debug.Log("quantity before spill: "+quantity_old.ToString()); Debug.Log("spill_amount: "+spill_amount.ToString()); Debug.Log("quantity_new: "+quantity_new.ToString()); ib.SetQuantity(quantity_new); } } };
/** * Created by maxiaoxin on 17-6-21. */ public class FDSProgressInputStream extends FilterInputStream{ private ProgressListener listener; private long lastNotifyTime; public FDSProgressInputStream(InputStream in, ProgressListener listener) { super(in); this.listener = listener; this.lastNotifyTime = System.currentTimeMillis(); } private void notifyListener(boolean needsCheckTime) { if (listener != null) { long now = System.currentTimeMillis(); if (!needsCheckTime || now - lastNotifyTime >= listener.progressInterval()) { lastNotifyTime = now; listener.onProgress(listener.getTransferred(), listener.getTotal()); } } } @Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { int bytesRead = super.read(buffer, byteOffset, byteCount); if (bytesRead != -1 && listener != null) { listener.transfer(bytesRead); notifyListener(true); } return bytesRead; } @Override public int read() throws IOException { int data = super.read(); if (data != -1 && listener != null) { listener.transfer(1); notifyListener(true); } return data; } @Override public void close() throws IOException { super.close(); notifyListener(false); } public ProgressListener getListener() { return listener; } public void setListener(ProgressListener listener) { this.listener = listener; } }
// ----------------------------------------------------------------------------- // Functions used for calculating probability distribution function (pdf) and // cumulative distribution function (cdf). // ----------------------------------------------------------------------------- float gaussian_pdf( float x) { float ret = exp(-x * x / 2.0f) / sqrt(2.0f * PI); return ret; }
#pragma once #include <list> #include <vector> #include "Hash.h" using namespace std; struct col_texture { string name; vector<string> includes; vector<string> excludes; bool compare(char *textureName) { if(!textureName || textureName[0] == '\0') return false; if(name.empty() || strstr(textureName, name.c_str())) { for(int i = 0; i < includes.size(); i++) { if(strstr(textureName, includes[i].c_str())) return false; } for(int i = 0; i < excludes.size(); i++) { if(strstr(textureName, excludes[i].c_str())) return false; } if(name.empty()) return false; return true; } return false; } }; struct col_shader { unsigned int nameHash; unsigned int gtaNameHash; bool has_texture; col_texture texture; bool compare(unsigned int shaderHash, char *textureName) { if(nameHash == shaderHash || gtaNameHash == shaderHash) { if(has_texture) return texture.compare(textureName); return true; } return false; } }; struct col_material { unsigned int id; vector<col_shader> shaders; vector<col_texture> textures; bool compare(unsigned int shaderHash, char *textureName) { for(int i = 0; i < shaders.size(); i++) { if(shaders[i].compare(shaderHash, textureName)) return true; } for(int i = 0; i < textures.size(); i++) { if(textures[i].compare(textureName)) return true; } return false; } }; class col_materials { public: vector<col_material> materials; col_material skip; public: col_materials() { FILE *f = fopen("col_gen_materials.dat", "rt"); if(!f) return; char line[1024]; while(fgets(line, 1024, f)) { if(*line != '\n' && *line != '\r') { if(!strncmp(line, "skip", 4)) { while(fgets(line, 1024, f) && strncmp(line, "end", 3)) { if(!strncmp(line, "shader:", 7)) { char *pLine = &line[7]; char name[128]; if(sscanf(pLine, "%s", name) == 1) { col_shader shader; unsigned int i = skip.shaders.size(); skip.shaders.push_back(shader); if(name[0] == '0' && name[1] == 'x') { unsigned int hashValue; sscanf(&name[2], "%X", &hashValue); skip.shaders[i].nameHash = hashValue; skip.shaders[i].gtaNameHash = hashValue; } else { skip.shaders[i].nameHash = HASH(name); char gtaName[128]; sprintf(gtaName, "gta_%s", name); skip.shaders[i].gtaNameHash = HASH(gtaName); } skip.shaders[i].has_texture = false; pLine = strstr(pLine, "texture:"); if(pLine) { pLine = &pLine[8]; if(sscanf(pLine, "%s", name) == 1) { skip.shaders[i].has_texture = true; if(*name != '+' && *name != '-') skip.shaders[i].texture.name = name; for(int c = 0; c < strlen(pLine); c++) { if(pLine[c] == '+') { if(sscanf(&pLine[c + 1], "%s", name) == 1) skip.shaders[i].texture.includes.push_back(name); else break; } else if(pLine[c] == '-') { if(sscanf(&pLine[c + 1], "%s", name) == 1) skip.shaders[i].texture.excludes.push_back(name); else break; } } } } } } else if(!strncmp(line, "texture:", 8)) { char *pLine = &line[8]; char name[128]; if(sscanf(pLine, "%s", name) == 1) { col_texture texture; unsigned int i = skip.textures.size(); skip.textures.push_back(texture); if(*name != '+' && *name != '-') skip.textures[i].name = name; for(int c = 0; c < strlen(pLine); c++) { if(pLine[c] == '+') { if(sscanf(&pLine[c + 1], "%s", name) == 1) skip.textures[i].includes.push_back(name); else break; } else if(pLine[c] == '-') { if(sscanf(&pLine[c + 1], "%s", name) == 1) skip.textures[i].excludes.push_back(name); else break; } } } } } } else if(!strncmp(line, "material:", 9)) { char *pLine = &line[9]; unsigned int mtlId; if(sscanf(pLine, "%u", &mtlId) == 1) { int m = materials.size(); col_material material; materials.push_back(material); materials[m].id = mtlId; while(fgets(line, 1024, f) && strncmp(line, "end", 3)) { if(!strncmp(line, "shader:", 7)) { pLine = &line[7]; char name[128]; if(sscanf(pLine, "%s", name) == 1) { col_shader shader; unsigned int i = materials[m].shaders.size(); materials[m].shaders.push_back(shader); if(name[0] == '0' && name[1] == 'x') { unsigned int hashValue; sscanf(&name[2], "%X", &hashValue); materials[m].shaders[i].nameHash = hashValue; materials[m].shaders[i].gtaNameHash = hashValue; } else { materials[m].shaders[i].nameHash = HASH(name); char gtaName[128]; sprintf(gtaName, "gta_%s", name); materials[m].shaders[i].gtaNameHash = HASH(gtaName); } materials[m].shaders[i].has_texture = false; pLine = strstr(pLine, "texture:"); if(pLine) { pLine = &pLine[8]; if(sscanf(pLine, "%s", name) == 1) { materials[m].shaders[i].has_texture = true; if(*name != '+' && *name != '-') materials[m].shaders[i].texture.name = name; for(int c = 0; c < strlen(pLine); c++) { if(pLine[c] == '+') { if(sscanf(&pLine[c + 1], "%s", name) == 1) materials[m].shaders[i].texture.includes.push_back(name); else break; } else if(pLine[c] == '-') { if(sscanf(&pLine[c + 1], "%s", name) == 1) materials[m].shaders[i].texture.excludes.push_back(name); else break; } } } } } } else if(!strncmp(line, "texture:", 8)) { char *pLine = &line[8]; char name[128]; if(sscanf(pLine, "%s", name) == 1) { col_texture texture; unsigned int i = materials[m].textures.size(); materials[m].textures.push_back(texture); if(*name != '+' && *name != '-') materials[m].textures[i].name = name; for(int c = 0; c < strlen(pLine); c++) { if(pLine[c] == '+') { if(sscanf(&pLine[c + 1], "%s", name) == 1) materials[m].textures[i].includes.push_back(name); else break; } else if(pLine[c] == '-') { if(sscanf(&pLine[c + 1], "%s", name) == 1) materials[m].textures[i].excludes.push_back(name); else break; } } } } } } } } } fclose(f); } bool skip_material(unsigned int shaderHash, char *textureName) { return skip.compare(shaderHash, textureName); } unsigned int match_material(unsigned int shaderHash, char *textureName) { for(int i = 0; i < materials.size(); i++) { if(materials[i].compare(shaderHash, textureName)) return materials[i].id; } return 0; } void print() { printf("skip\n"); for(int i = 0; i < skip.shaders.size(); i++) { printf("shader: 0x%X", skip.shaders[i].nameHash); if(skip.shaders[i].has_texture) { if(skip.shaders[i].texture.name.empty()) printf("texture:"); else printf("texture: %s", skip.shaders[i].texture.name.c_str()); for(int j = 0; j < skip.shaders[i].texture.includes.size(); j++) printf(" +%s", skip.shaders[i].texture.includes[j].c_str()); for(int j = 0; j < skip.shaders[i].texture.excludes.size(); j++) printf(" -%s", skip.shaders[i].texture.excludes[j].c_str()); } printf("\n"); } for(int i = 0; i < skip.textures.size(); i++) { if(skip.textures[i].name.empty()) printf("texture:"); else printf("texture: %s", skip.textures[i].name.c_str()); for(int j = 0; j < skip.textures[i].includes.size(); j++) printf(" +%s", skip.textures[i].includes[j].c_str()); for(int j = 0; j < skip.textures[i].excludes.size(); j++) printf(" -%s", skip.textures[i].excludes[j].c_str()); printf("\n"); } printf("end\n"); for(int m = 0; m < materials.size(); m++) { printf("material:%u\n", materials[m].id); for(int i = 0; i < materials[m].shaders.size(); i++) { printf("shader: 0x%X", materials[m].shaders[i].nameHash); if(materials[m].shaders[i].has_texture) { if(materials[m].shaders[i].texture.name.empty()) printf("texture:"); else printf("texture: %s", materials[m].shaders[i].texture.name.c_str()); for(int j = 0; j < materials[m].shaders[i].texture.includes.size(); j++) printf(" +%s", materials[m].shaders[i].texture.includes[j].c_str()); for(int j = 0; j < materials[m].shaders[i].texture.excludes.size(); j++) printf(" -%s", materials[m].shaders[i].texture.excludes[j].c_str()); } printf("\n"); } for(int i = 0; i < materials[m].textures.size(); i++) { if(materials[m].textures[i].name.empty()) printf("texture:"); else printf("texture: %s", materials[m].textures[i].name.c_str()); for(int j = 0; j < materials[m].textures[i].includes.size(); j++) printf(" +%s", materials[m].textures[i].includes[j].c_str()); for(int j = 0; j < materials[m].textures[i].excludes.size(); j++) printf(" -%s", materials[m].textures[i].excludes[j].c_str()); printf("\n"); } printf("end\n"); } } }; col_materials colMats;
<commit_msg>Include participant in outgoing ack <commit_before>from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> ''' def __init__(self, _id, _class, _type, _to): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to) def setOutgoingData(self, _type, _to): self._type = _type self._to = _to def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), node.getAttributeValue("to") ) return entity <commit_after>from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}"> </ack> ''' def __init__(self, _id, _class, _type, _to, _participant = None): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to, _participant) def setOutgoingData(self, _type, _to, _participant): self._type = _type self._to = _to self._participant = _participant def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) if self._participant: node.setAttribute("participant", self._participant) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to if self._participant: out += "Participant: %s\n" % self._participant return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), node.getAttributeValue("to"), node.getAttributeValue("participant") ) return entity
Hot Dog Johnny's is located on Route 46 in the tee-hee inducingly named area known as Buttzville New Jersey, a part of Belvidere. (I pause here to allow your internal 3rd-grader to recover from the gigglefits, and then proceed ;-)) While you would be right in thinking that hot dogs are on the menu here (my internal 3rd grader says, "duh!") one thing that Johnny's is most well known for is their offering of...BUTTERMILK as a drink to go along with said dog. (3rd grade Betty / current Mod B says, "that sounds gross!" ) Since this isn't one of those EXTREME TV shows and I'm not an extreme gal, I did not try the buttermilk. Sorry folks but we were on a road trip and that sounded like an upset stomach waiting to happen! We instead downgraded our adventure and opted for Birch Beer as our drink of choice. Started in 1944 by John "Johnny" Kovalsky in a tiny shack (displayed on the current property), it is now run by his daughter Patricia Fotopoulos. On this location since 1945 alongside the Pequest river, this incarnation dates to the 1960s. We ordered our dogs and soda at one of the walkup windows and decided to sit inside, though there are picnic tables on the grass near the river and also on the patio outside. Open seasonally, in the warmer weather it's great to hang outside and see the kiddies enjoy something as simple as a swingset. Let me know if you were daring enough to drink the buttermilk on your visit to Hot Dog Johnny's! Mr. Kovalsky would be proud and your internal 3rd grader might be impressed!
// Copyright 2019 Google LLC. 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 smt import ( "crypto" "encoding/hex" "fmt" "math/rand" "reflect" "strings" "testing" "github.com/google/trillian/merkle/coniks" "github.com/google/trillian/merkle/smt/node" ) type emptyNodes struct { h mapHasher ids map[node.ID]bool } func (e *emptyNodes) Get(id node.ID) ([]byte, error) { if e.ids != nil { if !e.ids[id] { return nil, fmt.Errorf("not found or read twice: %v", id) } delete(e.ids, id) // Allow getting this ID only once. } return e.h.hashEmpty(id), nil } func (e *emptyNodes) Set(id node.ID, hash []byte) {} func BenchmarkHStar3Root(b *testing.B) { hasher := coniks.New(crypto.SHA256) for i := 0; i < b.N; i++ { nodes := leafNodes(b, 512) hs, err := NewHStar3(nodes, hasher.HashChildren, 256, 0) if err != nil { b.Fatalf("NewHStar3: %v", err) } acc := &emptyNodes{h: bindHasher(hasher, 42)} if _, err := hs.Update(acc); err != nil { b.Fatalf("Update: %v", err) } } } // This test checks HStar3 implementation against HStar2-generated result. func TestHStar3Golden(t *testing.T) { hasher := coniks.New(crypto.SHA256) nodes := leafNodes(t, 500) hs, err := NewHStar3(nodes, hasher.HashChildren, 256, 0) if err != nil { t.Fatalf("NewHStar3: %v", err) } acc := &emptyNodes{h: bindHasher(hasher, 42)} rootNodes, err := hs.Update(acc) if err != nil { t.Fatalf("Update: %v", err) } if ln := len(rootNodes); ln != 1 { t.Fatalf("Update returned %d nodes, want 1", ln) } want := "daf17dc2c83f37962bae8a65d294ef7fca4ffa02c10bdc4ca5c4dec408001c98" if got := hex.EncodeToString(rootNodes[0].Hash); got != want { t.Errorf("Root: got %x, want %v", rootNodes[0].Hash, want) } } func TestNewHStar3(t *testing.T) { id1 := node.NewID("01234567890000000000000000000001", 256) id2 := node.NewID("01234567890000000000000000000002", 256) id3 := node.NewID("01234567890000000000000000000003", 256) id4 := node.NewID("01234567890000000000000001111111", 256) hasher := coniks.Default for _, tc := range []struct { desc string nodes []Node top uint want []Node wantErr string }{ {desc: "depth-err", nodes: []Node{{ID: id1.Prefix(10)}}, wantErr: "invalid depth"}, {desc: "dup-err1", nodes: []Node{{ID: id1}, {ID: id1}}, wantErr: "duplicate ID"}, {desc: "dup-err2", nodes: []Node{{ID: id1}, {ID: id2}, {ID: id1}}, wantErr: "duplicate ID"}, {desc: "top-vs-depth-err", nodes: []Node{{ID: id1}}, top: 300, wantErr: "top > depth"}, { desc: "ok1", nodes: []Node{{ID: id2}, {ID: id1}, {ID: id4}, {ID: id3}}, want: []Node{{ID: id1}, {ID: id2}, {ID: id3}, {ID: id4}}, }, { desc: "ok2", nodes: []Node{{ID: id4}, {ID: id3}, {ID: id2}, {ID: id1}}, want: []Node{{ID: id1}, {ID: id2}, {ID: id3}, {ID: id4}}, }, } { t.Run(tc.desc, func(t *testing.T) { nodes := tc.nodes // No need to copy it here. // Note: NewHStar3 potentially shuffles nodes. _, err := NewHStar3(tc.nodes, hasher.HashChildren, 256, tc.top) got := "" if err != nil { got = err.Error() } if want := tc.wantErr; !strings.Contains(got, want) { t.Errorf("NewHStar3: want error containing %q, got %v", want, err) } if want := tc.want; want != nil && !reflect.DeepEqual(nodes, want) { t.Errorf("NewHStar3: want nodes:\n%v\ngot:\n%v", nodes, want) } }) } } func TestHStar3Prepare(t *testing.T) { hasher := coniks.Default nodes := leafNodes(t, 512) hs, err := NewHStar3(nodes, hasher.HashChildren, 256, 0) if err != nil { t.Fatalf("NewHStar3: %v", err) } rs := idsToMap(t, hs.Prepare()) acc := &emptyNodes{h: bindHasher(hasher, 42), ids: rs} if _, err = hs.Update(acc); err != nil { t.Errorf("Update: %v", err) } if got := len(acc.ids); got != 0 { t.Errorf("%d ids were not read", got) } } func TestHStar3PrepareAlternative(t *testing.T) { // This is the intuitively simpler alternative Prepare implementation. prepare := func(nodes []Node, depth, top uint) map[node.ID]bool { ids := make(map[node.ID]bool) // For each node, add all its ancestors' siblings, down to the given depth. for _, n := range nodes { for id, d := n.ID, depth; d > top; d-- { pref := id.Prefix(d) if _, ok := ids[pref]; ok { // Delete the prefix node because its original hash does not contribute // to the updates, so should not be read. delete(ids, pref) // All the upper siblings have been added already, so skip them. break } ids[pref.Sibling()] = true } } return ids } for n := 0; n <= 32; n++ { t.Run(fmt.Sprintf("n:%d", n), func(t *testing.T) { nodes := leafNodes(t, n) hs, err := NewHStar3(nodes, nil, 256, 8) if err != nil { t.Fatalf("NewHStar3: %v", err) } ids := prepare(nodes, 256, 8) got := idsToMap(t, hs.Prepare()) if !reflect.DeepEqual(got, ids) { t.Error("IDs mismatch") } }) } } func BenchmarkHStar3Prepare(b *testing.B) { for i := 0; i < b.N; i++ { nodes := leafNodes(b, 512) hs, err := NewHStar3(nodes, nil, 256, 0) if err != nil { b.Fatalf("NewHStar3: %v", err) } _ = hs.Prepare() } } // leafNodes generates n pseudo-random leaf nodes at depth 256. The returned // data depends only on n. The algorithm is the same as in HStar2 tests, which // allows cross-checking their results. func leafNodes(t testing.TB, n int) []Node { t.Helper() // Use a random sequence that depends on n. r := rand.New(rand.NewSource(int64(n))) nodes := make([]Node, n) for i := range nodes { nodes[i].Hash = make([]byte, 32) if _, err := r.Read(nodes[i].Hash); err != nil { t.Fatalf("Failed to make random leaf hash: %v", err) } path := make([]byte, 32) if _, err := r.Read(path); err != nil { t.Fatalf("Failed to make random path: %v", err) } nodes[i].ID = node.NewID(string(path), 256) } return nodes } func idsToMap(t testing.TB, ids []node.ID) map[node.ID]bool { t.Helper() res := make(map[node.ID]bool, len(ids)) for _, id := range ids { if res[id] { t.Errorf("ID duplicate: %v", id) } res[id] = true } return res }
<reponame>fregaham/KiWi<gh_stars>1-10 /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the KiWi Project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Contributor(s): * * */ package kiwi.webservice; /** * This class is just a very temporal solution, quick and dirty. * It will be deleted again soon. Don't use it! * @author <NAME> * */ public class DataSpecialFormat { private String employeeName; private String employeeNo; private String employeeInitials; private String employeeWorkhoursprweek; private String employeeComment; private String organizationalunitName; private String organizationalunitNumber; private String organizationalunitManagername; private String organizationalunitSupername; private String projectStart; private String projectEnd; private String projectName; private String calendarFrom; private String calendarTo; private String calendarCause; private String skillActuallevelofskill; private String skillCategory; private String skillComment; /** * */ public DataSpecialFormat() { super(); } /** * @return the employeeName */ public String getEmployeeName() { return employeeName; } /** * @param employeeName the employeeName to set */ public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } /** * @return the employeeNo */ public String getEmployeeNo() { return employeeNo; } /** * @param employeeNo the employeeNo to set */ public void setEmployeeNo(String employeeNo) { this.employeeNo = employeeNo; } /** * @return the employeeInitials */ public String getEmployeeInitials() { return employeeInitials; } /** * @param employeeInitials the employeeInitials to set */ public void setEmployeeInitials(String employeeInitials) { this.employeeInitials = employeeInitials; } /** * @return the employeeWorkhoursprweek */ public String getEmployeeWorkhoursprweek() { return employeeWorkhoursprweek; } /** * @param employeeWorkhoursprweek the employeeWorkhoursprweek to set */ public void setEmployeeWorkhoursprweek(String employeeWorkhoursprweek) { this.employeeWorkhoursprweek = employeeWorkhoursprweek; } /** * @return the employeeComment */ public String getEmployeeComment() { return employeeComment; } /** * @param employeeComment the employeeComment to set */ public void setEmployeeComment(String employeeComment) { this.employeeComment = employeeComment; } /** * @return the organizationalunitName */ public String getOrganizationalunitName() { return organizationalunitName; } /** * @param organizationalunitName the organizationalunitName to set */ public void setOrganizationalunitName(String organizationalunitName) { this.organizationalunitName = organizationalunitName; } /** * @return the organizationalunitNumber */ public String getOrganizationalunitNumber() { return organizationalunitNumber; } /** * @param organizationalunitNumber the organizationalunitNumber to set */ public void setOrganizationalunitNumber(String organizationalunitNumber) { this.organizationalunitNumber = organizationalunitNumber; } /** * @return the organizationalunitManagername */ public String getOrganizationalunitManagername() { return organizationalunitManagername; } /** * @param organizationalunitManagername the organizationalunitManagername to set */ public void setOrganizationalunitManagername( String organizationalunitManagername) { this.organizationalunitManagername = organizationalunitManagername; } /** * @return the organizationalunitSupername */ public String getOrganizationalunitSupername() { return organizationalunitSupername; } /** * @param organizationalunitSupername the organizationalunitSupername to set */ public void setOrganizationalunitSupername(String organizationalunitSupername) { this.organizationalunitSupername = organizationalunitSupername; } /** * @return the projectStart */ public String getProjectStart() { return projectStart; } /** * @param projectStart the projectStart to set */ public void setProjectStart(String projectStart) { this.projectStart = projectStart; } /** * @return the projectEnd */ public String getProjectEnd() { return projectEnd; } /** * @param projectEnd the projectEnd to set */ public void setProjectEnd(String projectEnd) { this.projectEnd = projectEnd; } /** * @return the projectName */ public String getProjectName() { return projectName; } /** * @param projectName the projectName to set */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return the calendarFrom */ public String getCalendarFrom() { return calendarFrom; } /** * @param calendarFrom the calendarFrom to set */ public void setCalendarFrom(String calendarFrom) { this.calendarFrom = calendarFrom; } /** * @return the calendarTo */ public String getCalendarTo() { return calendarTo; } /** * @param calendarTo the calendarTo to set */ public void setCalendarTo(String calendarTo) { this.calendarTo = calendarTo; } /** * @return the calendarCause */ public String getCalendarCause() { return calendarCause; } /** * @param calendarCause the calendarCause to set */ public void setCalendarCause(String calendarCause) { this.calendarCause = calendarCause; } /** * @return the skillActuallevelofskill */ public String getSkillActuallevelofskill() { return skillActuallevelofskill; } /** * @param skillActuallevelofskill the skillActuallevelofskill to set */ public void setSkillActuallevelofskill(String skillActuallevelofskill) { this.skillActuallevelofskill = skillActuallevelofskill; } /** * @return the skillCategory */ public String getSkillCategory() { return skillCategory; } /** * @param skillCategory the skillCategory to set */ public void setSkillCategory(String skillCategory) { this.skillCategory = skillCategory; } /** * @return the skillComment */ public String getSkillComment() { return skillComment; } /** * @param skillComment the skillComment to set */ public void setSkillComment(String skillComment) { this.skillComment = skillComment; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "The Data included: " + employeeName + ", " + employeeNo + ", " + employeeInitials + ", " + employeeWorkhoursprweek + ", " + employeeComment + ", " + organizationalunitName + ", " + organizationalunitNumber + ", " + organizationalunitManagername + ", " + organizationalunitSupername + ", " + projectStart + ", " + projectEnd + ", " + projectName + ", " + calendarFrom + ", " + calendarTo + ", " + calendarCause + ", " + skillActuallevelofskill + ", " + skillCategory + ", " + skillComment + "!"; } }
// Copyright 2014 The Cockroach Authors. // // 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. See the AUTHORS file // for names of contributors. // // Author: <NAME> (<EMAIL>) package server import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "regexp" "github.com/cockroachdb/cockroach/client" "github.com/cockroachdb/cockroach/keys" "github.com/cockroachdb/cockroach/proto" "github.com/cockroachdb/cockroach/storage" "github.com/cockroachdb/cockroach/util" "github.com/cockroachdb/cockroach/util/log" gogoproto "github.com/gogo/protobuf/proto" ) // Gets a friendly name for output based on the passed in config prefix. func getFriendlyNameFromPrefix(prefix string) string { switch prefix { case acctPathPrefix: return "accounting" case permPathPrefix: return "permission" case zonePathPrefix: return "zone" default: return "unknown" } } // runGetConfig invokes the REST API with GET action and key prefix as path. func runGetConfig(ctx *Context, prefix, keyPrefix string) { friendlyName := getFriendlyNameFromPrefix(prefix) req, err := http.NewRequest("GET", fmt.Sprintf("%s://%s%s/%s", ctx.RequestScheme(), ctx.Addr, prefix, keyPrefix), nil) if err != nil { log.Errorf("unable to create request to admin REST endpoint: %s", err) return } req.Header.Add("Accept", "text/yaml") b, err := sendAdminRequest(ctx, req) if err != nil { log.Errorf("admin REST request failed: %s", err) return } fmt.Fprintf(os.Stdout, "%s config for key prefix %q:\n%s\n", friendlyName, keyPrefix, string(b)) } // RunGetAcct gets the account from the given key. func RunGetAcct(ctx *Context, keyPrefix string) { runGetConfig(ctx, acctPathPrefix, keyPrefix) } // RunGetPerm gets the permission from the given key. func RunGetPerm(ctx *Context, keyPrefix string) { runGetConfig(ctx, permPathPrefix, keyPrefix) } // RunGetZone gets the zone from the given key. func RunGetZone(ctx *Context, keyPrefix string) { runGetConfig(ctx, zonePathPrefix, keyPrefix) } // runLsConfigs invokes the REST API with GET action and no path, which // fetches a list of all configuration prefixes. // The type of config that is listed is based on the passed in prefix. // The optional regexp is applied to the complete list and matching prefixes // displayed. func runLsConfigs(ctx *Context, getPrefix, pattern string) { friendlyName := getFriendlyNameFromPrefix(getPrefix) req, err := http.NewRequest("GET", fmt.Sprintf("%s://%s%s", ctx.RequestScheme(), ctx.Addr, getPrefix), nil) if err != nil { log.Errorf("unable to create request to admin REST endpoint: %s", err) return } b, err := sendAdminRequest(ctx, req) if err != nil { log.Errorf("admin REST request failed: %s", err) return } type strWrapper struct { Data []string `json:"d"` } var wrapper strWrapper if err = json.Unmarshal(b, &wrapper); err != nil { log.Errorf("unable to parse admin REST response: %s", err) return } prefixes := wrapper.Data var re *regexp.Regexp if len(pattern) > 0 { if re, err = regexp.Compile(pattern); err != nil { log.Warningf("invalid regular expression %q; skipping regexp match and listing all %s prefixes", pattern, friendlyName) re = nil } } for _, prefix := range prefixes { if re != nil { if unescaped, err := url.QueryUnescape(prefix); err != nil || !re.MatchString(unescaped) { continue } } if prefix == "" { prefix = "[default]" } fmt.Fprintf(os.Stdout, "%s\n", prefix) } } // RunLsAcct lists accounts. func RunLsAcct(ctx *Context, pattern string) { runLsConfigs(ctx, acctPathPrefix, pattern) } // RunLsPerm lists permissions. func RunLsPerm(ctx *Context, pattern string) { runLsConfigs(ctx, permPathPrefix, pattern) } // RunLsZone lists zones. func RunLsZone(ctx *Context, pattern string) { runLsConfigs(ctx, zonePathPrefix, pattern) } // runRmConfig invokes the REST API with DELETE action and key prefix as path. // The type of config that is removed is based on the passed in prefix. func runRmConfig(ctx *Context, prefix, keyPrefix string) { friendlyName := getFriendlyNameFromPrefix(prefix) req, err := http.NewRequest("DELETE", fmt.Sprintf("%s://%s%s/%s", ctx.RequestScheme(), ctx.Addr, prefix, keyPrefix), nil) if err != nil { log.Errorf("unable to create request to admin REST endpoint: %s", err) return } _, err = sendAdminRequest(ctx, req) if err != nil { log.Errorf("admin REST request failed: %s", err) return } fmt.Fprintf(os.Stdout, "removed %s config for key prefix %q\n", friendlyName, keyPrefix) } // RunRmAcct removes the account with the given key. func RunRmAcct(ctx *Context, keyPrefix string) { runRmConfig(ctx, acctPathPrefix, keyPrefix) } // RunRmPerm removes the permission with the given key. func RunRmPerm(ctx *Context, keyPrefix string) { runRmConfig(ctx, permPathPrefix, keyPrefix) } // RunRmZone removes the zone with the given key. func RunRmZone(ctx *Context, keyPrefix string) { runRmConfig(ctx, zonePathPrefix, keyPrefix) } // runSetConfig invokes the REST API with POST action and key prefix as // path. The specified configuration file is read from disk and sent // as the POST body. // The type of config that is set is based on the passed in prefix. func runSetConfig(ctx *Context, prefix, keyPrefix, configFileName string) { friendlyName := getFriendlyNameFromPrefix(prefix) // Read in the config file. body, err := ioutil.ReadFile(configFileName) if err != nil { log.Errorf("unable to read %s config file %q: %s", friendlyName, configFileName, err) return } // Send to admin REST API. req, err := http.NewRequest("POST", fmt.Sprintf("%s://%s%s/%s", ctx.RequestScheme(), ctx.Addr, prefix, keyPrefix), bytes.NewReader(body)) if err != nil { log.Errorf("unable to create request to admin REST endpoint: %s", err) return } req.Header.Add("Content-Type", "text/yaml") _, err = sendAdminRequest(ctx, req) if err != nil { log.Errorf("admin REST request failed: %s", err) return } fmt.Fprintf(os.Stdout, "set %s config for key prefix %q\n", friendlyName, keyPrefix) } // RunSetAcct sets the account to the key given the yaml filename. func RunSetAcct(ctx *Context, keyPrefix, configFileName string) { runSetConfig(ctx, acctPathPrefix, keyPrefix, configFileName) } // RunSetPerm sets the permission to the key given the yaml filename. func RunSetPerm(ctx *Context, keyPrefix, configFileName string) { runSetConfig(ctx, permPathPrefix, keyPrefix, configFileName) } // RunSetZone sets the zone to the key given the yaml filename. func RunSetZone(ctx *Context, keyPrefix, configFileName string) { runSetConfig(ctx, zonePathPrefix, keyPrefix, configFileName) } // putConfig writes a config for the specified key prefix (which is // treated as a key). The config is parsed from the input "body". The // config is stored proto-encoded. The specified body must validly // parse into a config struct and must pass a given validation check (if // validate is not nil). func putConfig(db *client.KV, configPrefix proto.Key, config gogoproto.Message, path string, body []byte, r *http.Request, validate func(gogoproto.Message) error) error { if len(path) == 0 { return util.Errorf("no path specified for Put") } if err := util.UnmarshalRequest(r, body, config, util.AllEncodings); err != nil { return util.Errorf("config has invalid format: %+v: %s", config, err) } if validate != nil { if err := validate(config); err != nil { return err } } key := keys.MakeKey(configPrefix, proto.Key(path[1:])) if err := db.Run(client.PutProto(key, config)); err != nil { return err } return nil } // getConfig retrieves the configuration for the specified key. If the // key is empty, all configurations are returned. Otherwise, the // leading "/" path delimiter is stripped and the configuration // matching the remainder is retrieved. Note that this will retrieve // the default config if "key" is equal to "/", and will list all // configs if "key" is equal to "". The body result contains a listing // of keys and retrieval of a config. The output format is determined // by the request header. func getConfig(db *client.KV, configPrefix proto.Key, config gogoproto.Message, path string, r *http.Request) (body []byte, contentType string, err error) { // Scan all configs if the key is empty. if len(path) == 0 { sr := &proto.ScanResponse{} if err = db.Run(client.Call{ Args: &proto.ScanRequest{ RequestHeader: proto.RequestHeader{ Key: configPrefix, EndKey: configPrefix.PrefixEnd(), User: storage.UserRoot, }, MaxResults: maxGetResults, }, Reply: sr}); err != nil { return } if len(sr.Rows) == maxGetResults { log.Warningf("retrieved maximum number of results (%d); some may be missing", maxGetResults) } var prefixes []string for _, kv := range sr.Rows { trimmed := bytes.TrimPrefix(kv.Key, configPrefix) prefixes = append(prefixes, url.QueryEscape(string(trimmed))) } // Encode the response. body, contentType, err = util.MarshalResponse(r, prefixes, util.AllEncodings) } else { configkey := keys.MakeKey(configPrefix, proto.Key(path[1:])) if err = db.Run(client.GetProto(configkey, config)); err != nil { return } body, contentType, err = util.MarshalResponse(r, config, util.AllEncodings) } return } // deleteConfig removes the config specified by key. func deleteConfig(db *client.KV, configPrefix proto.Key, path string, r *http.Request) error { if len(path) == 0 { return util.Errorf("no path specified for config Delete") } if path == "/" { return util.Errorf("the default configuration cannot be deleted") } configKey := keys.MakeKey(configPrefix, proto.Key(path[1:])) return db.Run(client.Call{ Args: &proto.DeleteRequest{ RequestHeader: proto.RequestHeader{ Key: configKey, User: storage.UserRoot, }, }, Reply: &proto.DeleteResponse{}}) }
from collections import Counter for _ in range(int(input())): # read line as an integer a,b,k = map(int,input().split()) arr1 = list(map(int,input().split())) arr2 = list(map(int,input().split())) hori = [0]*k verti = [0]*k hori,verti = Counter(arr1),Counter(arr2) coun = 0 for i in range(k): coun+= k - hori[arr1[i]] +1 - verti[arr2[i]] print(coun//2)
def quit_app(): conn.send(("close").encode()) sleep(2) app.terminate() app.wait() conn.close()
<filename>source/core/unitlib/helpers/constants_private.h // Copyright 2018-19 <NAME> #pragma once // Dimensionless, private namespace _units_private { constexpr double constexpr_sqr(double a) { return a * a; } constexpr double constexpr_power(double a, std::size_t n) { return n == 0 ? 1 : constexpr_sqr(constexpr_power(a, n / 2)) * (n % 2 == 0 ? 1 : a); } namespace Detail { double constexpr sqrtNewtonRaphson(double x, double curr, double prev) { return curr == prev ? curr : sqrtNewtonRaphson(x, 0.5 * (curr + x / curr), curr); } } /* * Constexpr version of the square root * Return value: * - For a finite and non-negative value of "x", returns an approximation for the square root of "x" * - Otherwise, returns NaN */ double constexpr constexpr_sqrt(double x) { return x >= 0 && x < std::numeric_limits<double>::infinity() ? Detail::sqrtNewtonRaphson(x, x, 0) : std::numeric_limits<double>::quiet_NaN(); } namespace _constants { constexpr double pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679; constexpr double c = 299792458.0; // Speed of light, m s-1 [L1 T-1] constexpr double h = 6.62607015e-34; // Planck constant, rot J Hz-1 = rot kg m2 s-1 constexpr double k = 1.380649e-23; // Boltzmann constant, J K-1 = kg m2 K-1 s-2 constexpr double G = 6.6743015e-11; // Gravitational constant, m3 kg-1 s-2 constexpr double vacuum_permitivity = 8.854187812813e-12; // F m-1 = // Derived units/conversion factors constexpr double e = 1.602176634e-19; // elementary charge, C unit-1 constexpr double h_bar = h / (2.0 * pi); // Reduced Planck constant, rad J Hz-1 = rad kg m2 s-1 = rad J s constexpr double avogadro = 6.02214076e23; // Avogadro's number, unit mol-1 [A1 A-1] constexpr double coulomb = 6.2415090744607626077762409809304e18; // Coulomb constant, unit C-1 [A1 Q-1] constexpr double faraday = avogadro / coulomb;// Faraday constant, C mol-1 [Q A-1] // These are scaling factors for convenience as opposed to actual constants; note that the radian unit disappears constexpr double Planck_length = constexpr_sqrt(_constants::h_bar * _constants::G / constexpr_power(_constants::c, 3)); constexpr double Planck_mass = constexpr_sqrt(_constants::h_bar * _constants::c / _constants::G); constexpr double Planck_time = constexpr_sqrt(_constants::h_bar * _constants::G / constexpr_power(_constants::c, 5)); constexpr double Planck_temperature = constexpr_sqrt(_constants::h_bar * constexpr_power(_constants::c, 5) / (_constants::G * constexpr_power(_constants::k, 2))); } }
/* Copyright (c) 2013-2017 <NAME> (jrxie at ucdavis dot edu) 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. */ #ifndef _QUATERNION_H_ #define _QUATERNION_H_ #pragma once #include "vec3f.h" #include "vec4f.h" /* * Quaternions always obey: a^2 + b^2 + c^2 + d^2 = 1.0 * If they don't add up to 1.0, dividing by their magnitude will * re-normalize them. * * Note: See the following for more information on quaternions: * * - <NAME>., Animating rotation with quaternion curves, Computer * Graphics 19, No 3 (Proc. SIGGRAPH'85), 245-254, 1985. * - <NAME>., Quaternion calculus as a basic tool in computer * graphics, The Visual Computer 5, 2-13, 1989. */ namespace davinci{ class Quaternion { public: Quaternion(void); Quaternion(float w, float x, float y, float z); Quaternion(float w, const vec3f &nv); ~Quaternion(void); void setW(float w){ m_w = w;} void setX(float x){ m_vec3d.setX(x);} void setY(float y){ m_vec3d.setY(y);} void setZ(float z){ m_vec3d.setZ(z);} void setVector(const vec3f& v){ m_vec3d[0] = v.x(); m_vec3d[1] = v.y(); m_vec3d[2] = v.z(); } void setIdentity(){ setVector(vec3f(0.0f)); setW(1.0f); } float x() const{ return m_vec3d.x();} float y() const{ return m_vec3d.y();} float z() const{ return m_vec3d.z();} float w() const{ return m_w;} vec3f vector3d() const { return m_vec3d;} vec4f vector4d() const; void normalized(); Quaternion conjugate() const; // Quaternion& operator*=(float factor); // /* * Quaternion multiplication * http://en.wikipedia.org/wiki/Quaternion#Multiplication_of_basis_elements * * Given two quaternions, multiply them together to get a third quaternion. * Multiplying quaternions to get a compound rotation is analogous to adding * translations to get a compound translation. When incrementally * Multiplying rotations, the first argument here should be the new * rotation, the return quaternion is the total rotation (which will be * over-written with the resulting new total rotation). */ Quaternion& operator*=(const Quaternion &q); Quaternion& operator+=(const Quaternion &q); Quaternion operator* (const float factor) const; Quaternion operator+ (const Quaternion &q) const; friend ostream& operator << (ostream& os, const Quaternion& q) { os<<"("<<q.x()<<", "<<q.y()<<", "<<q.z()<<q.w()<<")\n"; return os; }; static Quaternion fromAxisAndAngle( const vec3f& axis, float angle); static Quaternion fromAxisAndAngle( float x, float y, float z, float angle); static Quaternion nlerp(const Quaternion& q1, const Quaternion& q2, float t); static Quaternion slerp(const Quaternion& q1, const Quaternion& q2, float t); private: vec3f m_vec3d; float m_w; }; } #endif