text
stringlengths
1
22.8M
Lucumayo (possibly from Quechua luq'u old hat that has lost ist form; hollow, depression (of an area), mayu river) is a river in Peru located in the Cusco Region, La Convención Province, Huayopata District. Its waters flow to the Urubamba River. Lucumayo river originates in the Urubamba mountain range near mount Veronica. It crosses the district from southeast to northwest along the villages of Chachayoc, Alfamayo, Lucumayo, Huacarumiyoc, Huamanpata, Incatambo, Sarasarayoc, Huamanmarca and Huyro. Some of its numerous little affluents from the right are Alfamayo, Chaquimayo, Incatambo and Sirinayoc. Its main tributary is Huamanmarca. The village of Wamanmarka lies near the confluence of these rivers, on the right bank of the Luq'umayu. This is where the archaeological site of Huamanmarca is situated. Tunkimayo is one of the left tributaries. East of Wamanmarka the river turns to the west and keeps this direction up to the confluence with the Vilcanota River as a right affluent. It is east of Pampayoc on the border of the districts of Huayopata, Maranura and Santa Teresa. See also Inka Tampu Quchapata References Rivers of Peru Rivers of Cusco Region
```objective-c //===- LiveDebugVariables.h - Tracking debug info variables -----*- C++ -*-===// // // See path_to_url for license information. // //===your_sha256_hash------===// // // This file provides the interface to the LiveDebugVariables analysis. // // The analysis removes DBG_VALUE instructions for virtual registers and tracks // live user variables in a data structure that can be updated during register // allocation. // // After register allocation new DBG_VALUE instructions are emitted to reflect // the new locations of user variables. // //===your_sha256_hash------===// #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVARIABLES_H #define LLVM_LIB_CODEGEN_LIVEDEBUGVARIABLES_H #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/Support/Compiler.h" namespace llvm { template <typename T> class ArrayRef; class LiveIntervals; class VirtRegMap; class LLVM_LIBRARY_VISIBILITY LiveDebugVariables : public MachineFunctionPass { void *pImpl = nullptr; public: static char ID; // Pass identification, replacement for typeid LiveDebugVariables(); ~LiveDebugVariables() override; /// splitRegister - Move any user variables in OldReg to the live ranges in /// NewRegs where they are live. Mark the values as unavailable where no new /// register is live. void splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS); /// emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes /// that happened during register allocation. /// @param VRM Rename virtual registers according to map. void emitDebugValues(VirtRegMap *VRM); /// dump - Print data structures to dbgs(). void dump() const; private: bool runOnMachineFunction(MachineFunction &) override; void releaseMemory() override; void getAnalysisUsage(AnalysisUsage &) const override; MachineFunctionProperties getSetProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::TracksDebugUserValues); } }; } // end namespace llvm #endif // LLVM_LIB_CODEGEN_LIVEDEBUGVARIABLES_H ```
```objective-c /* * query.h -- manipulation with the queries * * * See LICENSE for the license. * */ #ifndef QUERY_H #define QUERY_H #include <assert.h> #include <string.h> #include "namedb.h" #include "nsd.h" #include "packet.h" #include "tsig.h" struct ixfr_data; enum query_state { QUERY_PROCESSED, QUERY_DISCARDED, QUERY_IN_AXFR, QUERY_IN_IXFR }; typedef enum query_state query_state_type; /* Query as we pass it around */ typedef struct query query_type; struct query { /* * Memory region freed whenever the query is reset. */ region_type *region; /* * The address the query was received from. */ #ifdef INET6 struct sockaddr_storage remote_addr; #else struct sockaddr_in remote_addr; #endif socklen_t remote_addrlen; /* if set, the request came through a proxy */ int is_proxied; /* the client address * the same as remote_addr if not proxied */ #ifdef INET6 struct sockaddr_storage client_addr; #else struct sockaddr_in client_addr; #endif socklen_t client_addrlen; /* * Maximum supported query size. */ size_t maxlen; /* * Space reserved for optional records like EDNS. */ size_t reserved_space; /* EDNS information provided by the client. */ edns_record_type edns; /* TSIG record information and running hash for query-response */ tsig_record_type tsig; /* tsig actions can be overridden, for axfr transfer. */ int tsig_prepare_it, tsig_update_it, tsig_sign_it; int tcp; uint16_t tcplen; buffer_type *packet; /* Normalized query domain name. */ const dname_type *qname; /* Query type and class in host byte order. */ uint16_t qtype; uint16_t qclass; /* The zone used to answer the query. */ zone_type *zone; /* The delegation domain, if any. */ domain_type *delegation_domain; /* The delegation NS rrset, if any. */ rrset_type *delegation_rrset; /* Original opcode. */ uint8_t opcode; /* * The number of CNAMES followed. After a CNAME is followed * we no longer clear AA for a delegation and do not REFUSE * or SERVFAIL if the destination zone of the CNAME does not exist, * or is configured but not present. * Also includes number of DNAMES followed. */ int cname_count; /* Used for dname compression. */ uint16_t compressed_dname_count; domain_type **compressed_dnames; /* * Indexed by domain->number, index 0 is reserved for the * query name when generated from a wildcard record. */ uint16_t *compressed_dname_offsets; size_t compressed_dname_offsets_size; /* number of temporary domains used for the query */ size_t number_temporary_domains; /* * Used for AXFR processing. */ int axfr_is_done; zone_type *axfr_zone; domain_type *axfr_current_domain; rrset_type *axfr_current_rrset; uint16_t axfr_current_rr; /* Used for IXFR processing, * indicates if the zone transfer is done, connection can close. */ int ixfr_is_done; /* the ixfr data that is processed */ struct ixfr_data* ixfr_data; /* the ixfr data that is the last segment */ struct ixfr_data* ixfr_end_data; /* ixfr count of newsoa bytes added, 0 none, len means done */ size_t ixfr_count_newsoa; /* ixfr count of oldsoa bytes added, 0 none, len means done */ size_t ixfr_count_oldsoa; /* ixfr count of del bytes added, 0 none, len means done */ size_t ixfr_count_del; /* ixfr count of add bytes added, 0 none, len means done */ size_t ixfr_count_add; /* position for the end of SOA record, for UDP truncation */ size_t ixfr_pos_of_newsoa; #ifdef RATELIMIT /* if we encountered a wildcard, its domain */ domain_type *wildcard_domain; #endif }; /* Check if the last write resulted in an overflow. */ static inline int query_overflow(struct query *q); /* * Store the offset of the specified domain in the dname compression * table. */ void query_put_dname_offset(struct query *query, domain_type *domain, uint16_t offset); /* * Lookup the offset of the specified domain in the dname compression * table. Offset 0 is used to indicate the domain is not yet in the * compression table. */ static inline uint16_t query_get_dname_offset(struct query *query, domain_type *domain) { return query->compressed_dname_offsets[domain->number]; } /* * Remove all compressed dnames that have an offset that points beyond * the end of the current answer. This must be done after some RRs * are truncated and before adding new RRs. Otherwise dnames may be * compressed using truncated data! */ void query_clear_dname_offsets(struct query *query, size_t max_offset); /* * Clear the compression tables. */ void query_clear_compression_tables(struct query *query); /* * Enter the specified domain into the compression table starting at * the specified offset. */ void query_add_compression_domain(struct query *query, domain_type *domain, uint16_t offset); /* * Create a new query structure. */ query_type *query_create(region_type *region, uint16_t *compressed_dname_offsets, size_t compressed_dname_size, domain_type **compressed_dnames); /* * Reset a query structure so it is ready for receiving and processing * a new query. */ void query_reset(query_type *query, size_t maxlen, int is_tcp); /* * Process a query and write the response in the query I/O buffer. */ query_state_type query_process(query_type *q, nsd_type *nsd, uint32_t *now_p); /* * Prepare the query structure for writing the response. The packet * data up-to the current packet limit is preserved. This usually * includes the packet header and question section. Space is reserved * for the optional EDNS record, if required. */ void query_prepare_response(query_type *q); /* * Add EDNS0 information to the response if required. */ void query_add_optional(query_type *q, nsd_type *nsd, uint32_t *now_p); /* * Write an error response into the query structure with the indicated * RCODE. */ query_state_type query_error(query_type *q, nsd_rc_type rcode); static inline int query_overflow(query_type *q) { return buffer_position(q->packet) > (q->maxlen - q->reserved_space); } #endif /* QUERY_H */ ```
Sabar Lal Melma was a citizen of Afghanistan who was held in extrajudicial detention in the United States Guantanamo Bay detainment camps, in Cuba. Sabar Lal Melma's Guantanamo Internment Serial Number was 801. American intelligence analysts estimate that Sabar Lal Melma was born in 1962, Darya-e-Pech, Afghanistan. According to Ray Riviera of the New York Times, Sabar's killing angered officials on the Afghanistan High Peace Council, a body appointed by Afghanistan President Hamid Karzai to address Taliban fighters. The Peace Council believed they had secured assurances that coalition forces would stop bothering Sabar Lal Melma, and they believed his killing would frighten other Taliban fighters from defecting. A spokesman for the NATO-led military coalition said that security forces had never "detained him or had him in custody" until the operation that resulted in his death. Combatant Status Review Tribunal Initially the Bush administration asserted that they could withhold all the protections of the Geneva Conventions to captives from the war on terror. This policy was challenged before the Judicial branch. Critics argued that the USA could not evade its obligation to conduct a competent tribunal to determine whether captives are, or are not, entitled to the protections of prisoner of war status. Subsequently the Department of Defense instituted the Combatant Status Review Tribunals. The Tribunals, however, were not authorized to determine whether the captives were lawful combatants—rather they were merely empowered to make a recommendation as to whether the captive had previously been correctly determined to match the Bush administration's definition of an enemy combatant. Sabar Lal Melma chose to participate in his Combatant Status Review Tribunal. Allegations The allegations Sabar Lal Melma faced during his Tribunal were: Administrative Review Board hearing Detainees who were determined to have been properly classified as "enemy combatants" were scheduled to have their dossier reviewed at annual Administrative Review Board hearings. The Administrative Review Boards weren't authorized to review whether a detainee qualified for POW status, and they weren't authorized to review whether a detainee should have been classified as an "enemy combatant". They were authorized to consider whether a detainee should continue to be detained by the United States, because they continued to pose a threat—or whether they could safely be repatriated to the custody of their home country, or whether they could be set free. Sabar Lal Melma chose to participate in his Administrative Review Board hearing. Factors for continued detention The detainee is a Brigadier General in the Afghan military. He is suspected of assisting al Qaeda members to escape from Tora Bora into Pakistan. He was a commander of 600 border security troops in Konar, Afghanistan. The detainee is a member of Jamiat-e-Dawa-el-al-Qurani Wasouna (JDQ). The detainee has met with Haji Rohullah, leader of Jamiat-e-Dawa-el-al Qurani Wasouna , and Loya Jirga, representative for the Konar region, on numerous occasions. Jamiat-ul-Dawa-ul-Qurani , an Islamic extremist group with ties to the Pakistani Inter-Service Intelligence Directorate, consisted of Afghan refugees from camps in the Peshawar area. This organization supported the continued war in Kashmir. The detainee’s military service includes being appointed the title of Brigadier General due to his experience fighting against the Soviet Union and the Taliban. During the fight against the Taliban, the detainee was Nasruldeen’s commander. Nasruldeen was allegedly responsible for attacks on government and coalition entities. The detainee knew Faquirullah. He knew Faquirullah was possibly involved with the Jam’ at Islami, was a high level commander for the Hezb-e Islami Gulbuddin (HIG), and a dedicated Mujahideen. HIG has long-established ties with Osama bin Laden. In the early 1990s, it ran several terrorist training camps in Afghanistan and pioneered sending mercenary fighters to other Islamic conflicts. It offered shelter to Osama bin Laden after the latter fled Sudan in 1996. The detainee met Ali (NFT) twice in the Konar region, and twice in Jalalabad, Afghanistan. The detainee confirmed Ali was a member of the Hezb-e Islami Khalis under Yunis Khalis. Around 15–16 November 2001, nine Arabs, two of whom were wounded, fled Tora Bora for Konar Province, Afghanistan. The detainee assigned one of his leaders to personally handle the security for the Arabs. The detainee arranged for the nine men to be transferred to his fort, where they awaited the arrival of Haji Rohullah. When he arrived, Rohullah provided the detainee with an unspecified amount of money and instructions to smuggle the Arabs in Pakistan. The Arabs’ weapons and the truck were given to the detainee as a reward. Factors against continued detention The detainee denied having any knowledge of the attacks in the United States prior to their execution on September 11 and also denied having knowledge of any rumors or plans of future attacks on the United States. Repatriation Sabar Lal Melma was repatriated on September 28, 2007, along with five other Afghans, a Libyan captive and a Yemeni captive. The Center for Constitutional Rights reports that all of the Afghans repatriated to Afghanistan from April 2007 were sent to Afghan custody in the American built and supervised wing of the Pul-e-Charkhi prison near Kabul. McClatchy interview On June 15, 2008 the McClatchy News Service published articles based on interviews with 66 former Guantanamo captives. McClatchy reporters interviewed Sabar Lal. Sabar Lal said he had been an anti-Taliban fighter during their administration, that he suffered a gunshot wound during his opposition to the Taliban, and that he had helped oust the Taliban during the American invasion. Lal reported being subjected to sleep deprivation in Bagram. The McClatchy report quoted an Afghan official named Mohammed Roze, who acknowledged Lal had served as the commander of a border patrol, but that he nevertheless belonged in Guantanamo, because he had bombarded settlements full of civilians during regional disputes. The report quoted Mateullah Khan, the chief of police of Konar Province who asserted Sabar Lal had helped militants escape. But the report also quoted Jonathan Horowitz, an investigator with a human rights group, who had secured access to Lal's confidential file. He said it contained practically no evidence to back up the allegations against him. Sabar was killed by Afghan and NATO security forces in Kabul, Afghanistan on 9/3/11. As of September 4, 2011 Sabar Lal Melma could no longer be located on the McClatchy Guantanamo Inmate Database. Accounts of his death on Friday September 3 NATO officials reported that an individual named Sabar Lal Melma was shot dead during a night raid on his home in Jalalabad on September 3, 2011. According to those officials he emerged from his home carrying an AK-47. The officials went on to say Mr. Lal Melma had been organizing attacks and financing al Qaeda operations. However, in a CNN interview with Haji Sahib Rohullah Wakil, a tribal leader who had been captured with Sabar in 2002, Mr. Wakil asserted Lal Melma "chose a civilian life" after his release from Guantanamo. Ray Riviera, writing in the New York Times on September 4, 2011, reported that Sabar's killing came just two days after coalition forces had promised the Afghanistan High Peace Council that they would quit harassing him. Riviera reported that Sabar had been apprehended by NATO forces as recently as one month earlier. However NATO forces denied both promising to stop harassing Sabar, or that they had recently taken him into custody. Riviera of the New York Times quoted Haji Deen Muhammad of the Peace Council about how the killing of Sabar would affect efforts to get members of the Taliban to defect. "It really hurts the prestige of the Peace Council among the people of Afghanistan. More importantly, those Taliban members who were released through our process are going to have big concerns that this will happen to them." In September 2011, the International Security Assistance Force (ISAF) issued a press release stating they had knowledge that Lal Melma was "in contact with several senior al Qaeda members throughout Kunar and Pakistan" References External links McClatchy News Service - video The Anonymous Victims Of Guantánamo: Eight More Wrongly Imprisoned Men Are Quietly Released Andy Worthington Guantanamo detainees known to have been released 2011 deaths Afghan extrajudicial prisoners of the United States Block D, Pul-e-Charkhi prison Year of birth uncertain 1962 births
The Embassy of the State of Palestine in Qatar () is the diplomatic mission of the Palestine in Qatar. It is located in Doha. See also List of diplomatic missions in Qatar. List of diplomatic missions of Palestine. References Doha Palestine State of Palestine–Qatar relations
```xml <FrameLayout xmlns:android="path_to_url" xmlns:tools="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.moxun.tagcloud.TestFragment"> <com.moxun.tagcloudlib.view.TagCloudView xmlns:app="path_to_url" android:id="@+id/fragment_tagcloud" android:layout_width="wrap_content" android:layout_height="wrap_content" app:autoScrollMode="uniform" app:darkColor="#FF0000" app:lightColor="#00FF00" app:radiusPercent="0.6"/> </FrameLayout> ```
The Fort Bliss Pershing House was initially created as 'Army Plan Number 243, Field Officers Quarters', and is located at 228 Sheridan Road, Fort Bliss Texas built in 1910, and its National Register of Historic Places designation refers to its original designation of "Building 228 Commanding Officers Quarters / Garrison Commanders Quarters". The home was electrified in 1911, and from 1910 to 1914 was the residence of the post commander General Edgar Zell Steever II. During the Mexican Revolution it became the primary residence of General John J. "Black Jack" Pershing as both the General of the Armies and the Post Commander from the January 1914 to 1917. The home has hosted a number of famous guests, including Buffalo Bill Cody, Pancho Villa, Mexican General Álvaro Obregón, and former Mexican President General Victoriano Huerta. While the home was used as the Post Commanders residence for many years. Since its creation the house has been the residence of the post commander, up until alternate commanding general quarters were relocated during the World War 2 years, when the house was used to house members of the WAC (Women's Army Corps). Post World War 2, the home was delegated to house the Post Assistant Commander which it does to this day. References History of El Paso, Texas Buildings and structures in El Paso, Texas Houses on the National Register of Historic Places in Texas National Register of Historic Places in El Paso County, Texas Fort Bliss
```ruby class OhMyPosh < Formula desc "Prompt theme engine for any shell" homepage "path_to_url" url "path_to_url" sha256 your_sha256_hash license "MIT" head "path_to_url", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_sonoma: your_sha256_hash sha256 cellar: :any_skip_relocation, arm64_ventura: your_sha256_hash sha256 cellar: :any_skip_relocation, arm64_monterey: your_sha256_hash sha256 cellar: :any_skip_relocation, sonoma: your_sha256_hash sha256 cellar: :any_skip_relocation, ventura: your_sha256_hash sha256 cellar: :any_skip_relocation, monterey: your_sha256_hash sha256 cellar: :any_skip_relocation, x86_64_linux: your_sha256_hash end depends_on "go" => :build def install ldflags = %W[ -s -w -X github.com/jandedobbeleer/oh-my-posh/src/build.Version=#{version} -X github.com/jandedobbeleer/oh-my-posh/src/build.Date=#{time.iso8601} ] cd "src" do system "go", "build", *std_go_args(ldflags:) end prefix.install "themes" pkgshare.install_symlink prefix/"themes" end test do assert_match "oh-my-posh", shell_output("#{bin}/oh-my-posh --init --shell bash") assert_match version.to_s, shell_output("#{bin}/oh-my-posh --version") end end ```
Deer Lodge is an unincorporated community in Morgan County, Tennessee, United States. It is located along Tennessee State Route 329 west-southwest of Sunbright. Deer Lodge has a post office with ZIP code 37726, which opened on April 16, 1886. The community was established as a health resort in the 1880s by Rugby colonist Abner Ross. History Deer Lodge was originally situated around a tract of land acquired by the Davidson family in the early 1800s. In 1845, James Davidson built a grist mill and saw mill on the land. In 1876, Peter Fox purchased the land and attempted to establish a sheep ranch, but was unsuccessful. In 1884, Fox sold the land to Abner Ross, a former Rugby colonist. Ross, who had been the proprietor of Rugby's Tabard Inn, decided to convert the tract into a mountain resort. He constructed a Victorian-style house, Walnut Knoll, which was soon followed by a string of similarly-styled houses built by new residents. He also constructed a printer works, which has since been relocated to Rugby. By the end of the 1890s, Deer Lodge had two hotels (the Mountain View and Summit Park), a newspaper (the Southern Enterprise), a theater, a band, a planing mill, and numerous clubs and civic organizations. By the mid-20th century, the community had declined, however, as many children and grandchildren of the original settlers moved away. The population of Deer Lodge was just 155 in 1930. Geography Deer Lodge is located in a remote section of the Cumberland Plateau in western Morgan County. State Route 329 connects the community with U.S. Route 27 and Sunbright to the northeast and the east-west oriented State Route 62 to the south. Beyond SR 62 is the vast Catoosa Wildlife Management Area. Deer Lodge straddles the Tennessee Valley Divide, with waters in the northern part of the community flowing toward the Big South Fork of the Cumberland River, and waters in the southern half flowing toward the Obed River. References External links Unincorporated communities in Morgan County, Tennessee Unincorporated communities in Tennessee
```c++ //======================================================================= // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // accompanying file LICENSE_1_0.txt or copy at // path_to_url //======================================================================= #include <boost/config.hpp> #include <iostream> #include <vector> #include <utility> #include <string> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_utility.hpp> #include <boost/property_map/property_map.hpp> /* Sample Output graph name: foo 0 --joe--> 1 1 --joe--> 0 --curly--> 2 --dick--> 3 2 --curly--> 1 --tom--> 4 3 --dick--> 1 --harry--> 4 4 --tom--> 2 --harry--> 3 (0,1) (1,2) (1,3) (2,4) (3,4) removing edge (1,3): 0 --joe--> 1 1 --joe--> 0 --curly--> 2 2 --curly--> 1 --tom--> 4 3 --harry--> 4 4 --tom--> 2 --harry--> 3 (0,1) (1,2) (2,4) (3,4) */ struct EdgeProperties { EdgeProperties(const std::string& n) : name(n) { } std::string name; }; struct VertexProperties { std::size_t index; boost::default_color_type color; }; int main(int , char* []) { using namespace boost; using namespace std; typedef adjacency_list<vecS, listS, undirectedS, VertexProperties, EdgeProperties> Graph; const int V = 5; Graph g(V); property_map<Graph, std::size_t VertexProperties::*>::type id = get(&VertexProperties::index, g); property_map<Graph, std::string EdgeProperties::*>::type name = get(&EdgeProperties::name, g); boost::graph_traits<Graph>::vertex_iterator vi, viend; int vnum = 0; for (boost::tie(vi,viend) = vertices(g); vi != viend; ++vi) id[*vi] = vnum++; add_edge(vertex(0, g), vertex(1, g), EdgeProperties("joe"), g); add_edge(vertex(1, g), vertex(2, g), EdgeProperties("curly"), g); add_edge(vertex(1, g), vertex(3, g), EdgeProperties("dick"), g); add_edge(vertex(2, g), vertex(4, g), EdgeProperties("tom"), g); add_edge(vertex(3, g), vertex(4, g), EdgeProperties("harry"), g); graph_traits<Graph>::vertex_iterator i, end; graph_traits<Graph>::out_edge_iterator ei, edge_end; for (boost::tie(i,end) = vertices(g); i != end; ++i) { cout << id[*i] << " "; for (boost::tie(ei,edge_end) = out_edges(*i, g); ei != edge_end; ++ei) cout << " --" << name[*ei] << "--> " << id[target(*ei, g)] << " "; cout << endl; } print_edges(g, id); cout << endl << "removing edge (1,3): " << endl; remove_edge(vertex(1, g), vertex(3, g), g); ei = out_edges(vertex(1, g), g).first; cout << "removing edge (" << id[source(*ei, g)] << "," << id[target(*ei, g)] << ")" << endl; remove_edge(ei, g); for(boost::tie(i,end) = vertices(g); i != end; ++i) { cout << id[*i] << " "; for (boost::tie(ei,edge_end) = out_edges(*i, g); ei != edge_end; ++ei) cout << " --" << name[*ei] << "--> " << id[target(*ei, g)] << " "; cout << endl; } print_edges(g, id); return 0; } ```
Iron Road is the name of: Iron Road (film), a 2009 Canada/China television miniseries Iron Road Railways, a former railroad company in Maine, Quebec, New Brunswick and Nova Scotia from 1994 to 2002 Iron Road Limited, an Australian iron ore exploration and mining company established in 2008 Iron Road (opera), a 2001 Canadian opera in two acts See also Via ferrata, the Italian words for "iron road", a kind of protected climbing route
Cardiff Greyhounds was the greyhound racing operation held at Cardiff Arms Park in Cardiff from 1927 to 1977. It is not to be confused with the greyhound racing held from 1928 to 1937 at the White City Stadium, Cardiff. Origins and opening To assist with maintenance of the site, a greyhound track was built around the rugby pitch in 1927. The first meeting was held on 7 April 1928. Pre war history The Arms Park (Cardiff) Greyhound Racing Company Limited signed a 50-year lease in 1937, with Cardiff Athletic Club (the owners of the Arms Park) and having no rights to break the agreement or to review the rental until 50 years expired. The circumference of the track was a large 452 yards with long straights of 160 yards. An 'Outside Sumner' hare was used and race distances consisted of 300, 500, 525 and 700 yards. The kennel facilities were at nearby Cefn Mably in St Mellons and the leading event was the Glamorgan Cup held over 500 yards. 1991 In 1932 a notable greyhound called Beef Cutlet made his debut at the track. Beef Cutlet won the Glamorgan Cup and set a new track record, in 28.41 seconds. His Waterhall kennels based trainer John Hegarty would later become a Racing Manager at the track. In 1937 the Greyhound Racing Association closed the nearby White City stadium, leaving the Arms Park as the sole Cardiff venue. John Jolliffe was Racing Manager here in 1937 arriving from Aberdeen before he secured the Racing Manager's position at Wembley. Post war history After the war the Welsh Greyhound Derby was transferred to the Arms Park from White City. This was one of the three competitions that formed the triple crown along with the English Greyhound Derby and Scottish Greyhound Derby. The track continued to host the race annually. Racing was held on Monday and Saturday evenings. The greyhound company introduced floodlights in 1958 which upset the rugby fans. The Welsh Derby was won by the likes of Trev's Perfection (who completed the Triple Crown in 1947), Local Interprize, Ballycurreen Garrett, Ballylanigan Tanist, Endless Gossip, Rushton Mac and Mile Bush Pride in a golden era. The event was so popular that despite the stadium being taken over for the 1958 British Empire and Commonwealth Games the track was re-laid in time for the Welsh Derby to take place in October. In 1971 the Welsh Greyhound Derby was given 'classic' status. Problems for greyhound racing started after Glamorgan County Cricket Club moved out of the cricket ground (known as the north ground) to Sophia Gardens in 1966. The north ground was subsequently demolished and a new rugby union stadium built in its place for Cardiff RFC, who would move out of the Arms Park because Cardiff Athletic Club had transferred the freehold of the Arms Park (south ground) to the Welsh Rugby Union in July 1968. This still left a greyhound track around the Arms Park but despite the Welsh Derby gaining classic status there was no place for greyhound racing when the plans for the new National Stadium were drawn up on the site in 1977 by the Cardiff City Council. The council had taken less than ten minutes to reject a plan to switch greyhound racing to nearby Maindy Stadium. Closure The last Welsh Greyhound Derby was on 9 July. The last meeting was held on 30 July 1977 which attracted just 1,128 greyhound fans who witnessed Lillyput Queen, owned by Cardiff butcher Malcolm Davies and trained by Freddie Goodman, win the last race. After the closure, greyhound racing in Wales remained on only three flapping (unlicensed) tracks, Swansea, Bedwellty Greyhound Track and Ystrad Mynach. Harry George secretary of Greyhound Company Cardiff failed in a bid for Oxford Stadium following Cardiff's closure. Competitions Welsh Greyhound Derby Glamorgan Cup Track records See also Cardiff Arms Park References Greyhound racing in the United Kingdom Defunct greyhound racing venues in the United Kingdom Greyhound racing in Wales 1927 establishments in Wales Sports venues completed in 1927 Sports venues demolished in 1977 Sport in Cardiff 1977 disestablishments in Wales
Steve Wembi (born 20 July 1984) is a criminologist and investigative journalist based in Kinshasa, Democratic Republic of the Congo and in Nairobi, Kenya. He has worked as a contributor for the New York Times, Al Jazeera and Xinhua (commonly known as the "New China News Agency") and he is the Managing Director of the Consulting Media Agency (CMA). Biography Steve Wembi was born on 20 July 1984 in Kindu, in the province of Maniema in Zaire (now Democratic Republic of the Congo). In 1997, he underwent military training in Kamalenge when the rebellion Alliance of Democratic Forces for the Liberation of Congo (AFDL or ADFLC), led by Laurent-Désiré Kabila, before returning to secondary school at Ibanda Institute in Bukavu. He graduated from high school and moved to Kinshasa in 2007 to continue his university studies, the first two years at the University of Kinshasa (UNIKIN) at the Faculty of Law. There he started his journalistic career as a correspondent in Kinshasa for the New China News Agency and worked for the agency media for ten years. He has also worked for Al Jazeera Television, Cable News Network (CNN) and as a reporter for Integrated Regional Information Networks (IRIN), The Economist, Financial Times, Norwegian Broadcasting Corporation and The Wall Street Journal. In the eastern Democratic Republic of the Congo, Wembi covered several rebellions, including that of the March 23 Movement (M23) and the National Congress for the Defense of the People (French: Congrès national pour la défense du peuple, CNDP) but also, he frequented high risk areas, particular in Kasaï Province, a region where the two UN experts Zaida Catalan and Michael Sharp were killed in March 2017. That same year, he discovered more than 100 mass graves in Ngaza commune. Wembi holds a master's degree in criminology from Kenya Institute of Security and Criminal Justice and since 2019, he is communication advisor to the president of the Senate of the Democratic Republic of the Congo, senator Alexis Thambwe Mwamba. Disappearance On October 24, 2022, Wembi went missing after a meeting at the Léon hotel in Kinshasa. The government, and in particular, the National Intelligence Agency (Democratic Republic of the Congo), were blamed for his abduction, but Patrick Muyaya, the government's spokesperson, has denied knowledge of his whereabouts, leading his family to fear he has been killed. Personal life Wembi is married to Belinda Zamundu and has six children. References External links LinkedIn profile Al Jazeera profile 1984 births Living people Democratic Republic of the Congo journalists People from Kindu Financial Times people The Economist people NRK people CNN people Al Jazeera people The New York Times visual journalists University of Kinshasa alumni Democratic Republic of the Congo criminologists
Martina Rašková Veličková (born 17 February 1989), is a Slovak women’s ice hockey forward, most recently of ŽHK Šarišanka Prešov in the 2017–18 season of the Slovak Women's Extraliiga. She served as captain of the Slovak national team in the women's ice hockey tournament at the 2010 Olympic Winter Games in Vancouver. Playing career Veličková, along with fellow Slovak national team members Zuzana Tomčíková, and Iveta Karafiátová played on boys' teams until Slovak league rules prevented them from continuing with those teams once they turned 16. All three continued their careers by playing hockey in Saskatchewan for head coach Barrett Kropf at Caronport High School in 2004. Karafiátová, Tomčíková, and Veličková played for the Caronport Lady Cougars but Karafiátová and Tomčíková also played on the boys team. She was part of the Slovak roster that defeated by an 82–0 score in September 2008 in the Olympic Pre-Qualification tournament in Latvia. In the win, she accumulated 17 points. In 2009, she competed in the 2009 IIHF World Women’s Championship Division I, which was played in Graz, Austria. She was part of the Slovak team that qualified for the top division of the 2011 World Women's Championships. At the 2011 IIHF Women's World Championships, Slovakia played in a best of three relegation series. In the second game, Veličková beat Daria Obydennova for the only goal in the shootout as Slovakia won the relegation series. Vancouver Winter Games She played for in the 2010 Olympics. It was the first time that Slovakia competed in women's ice hockey outside of Europe. Of note, she was the captain of the Slovak national team at the 2010 Vancouver Winter Games. Her first Olympic women's ice hockey game came on February 13, 2010 against . Slovakia lost the game by an 18-0 mark. Her first Olympic points came on February 20, 2010. Veličková assisted on both goals in a 4-2 loss to . She would finish with three assists in the Olympic tournament as Slovakia finished in eighth place. Career stats Winter Olympics References External links 1989 births Living people Ice hockey players at the 2010 Winter Olympics Olympic ice hockey players for Slovakia Sportspeople from Prešov Ice hockey people from the Prešov Region Slovak women's ice hockey forwards Universiade medalists in ice hockey Universiade bronze medalists for Slovakia Competitors at the 2011 Winter Universiade
Stymie is an obsolete golf rule. Stymie or Stymies may also refer to: Stymies, men's second team at Cambridge University Golf Club founded in 1869 Stymie Beard (1925–1981), American child actor in Our Gang Stymie (horse) (1941–1962), American Thoroughbred racehorse
Dane A. Miller ( – February 10, 2015) was an American business executive. Miller was co-founder of the orthopedic company Biomet and was its president and chief executive from 1978 to 2006. Miller was brought up in Springfield, Ohio, and obtained a Bachelor of Science degree in Mechanical Materials Science Engineering in 1969 from the General Motors Institute (now Kettering University) from which he received the Distinguished Alumnus award in 2010. He subsequently obtained a master's degree and a doctorate in Materials Science (Biomedical Engineering) from the University of Cincinnati. After working for rival companies Zimmer and Cutter Laboratories, Miller joined with Niles Noblitt, Jerry L. Ferguson and M. Ray Harroff, to found Biomet in 1977. Miller's own grandmother, Grace Shumaker, was the first recipient of a Biomet hip implant. To encourage public confidence in titanium as a material for implants, Miller arranged for a surgeon to introduce a piece into his own arm, which he left there for ten years to test its safety. In March 2006, Miller was removed from the company's board of directors, and his retirement was announced. A few months later, he headed a private equity consortium that bought back the business for $11.4 billion and still owned it in 2014. Miller became a consultant to the new company in addition to resuming the role of a director. The company later announced a merger with Zimmer Holdings. References Further reading Patrick Kavanaugh - The Maverick CEO; Dane Miller and the Story of Biomet (privately printed, 2008) Engineers from Ohio 1940s births 2015 deaths People from Springfield, Ohio Kettering University alumni University of Cincinnati alumni Place of birth missing
Battle Point may refer to: Battle Point, Antarctica, a coastal headland on the east coast of Graham Land Battle Point, Bainbridge Island, Washington, a community of Bainbridge Island Battle Point Site, an archaeological site in Crockery Township, Ottawa County, Michigan
```javascript // See LICENSE.txt for license information. /* eslint-disable no-console, camelcase, no-process-env */ const axios = require('axios'); const fse = require('fs-extra'); const xml2js = require('xml2js'); const {ARTIFACTS_DIR} = require('./constants'); const MAX_FAILED_TITLES = 5; function convertXmlToJson(xml) { const platform = process.env.IOS === 'true' ? 'ios' : 'android'; const jsonFile = `${ARTIFACTS_DIR}/${platform}-junit.json`; // Convert XML to JSON xml2js.parseString(xml, {mergeAttrs: true}, (err, result) => { if (err) { throw err; } // Convert result to a JSON string const json = JSON.stringify(result, null, 4); // Save JSON in a file fse.writeFileSync(jsonFile, json); }); return readJsonFromFile(jsonFile); } function getAllTests(testSuites) { const suites = []; const tests = []; let skipped = 0; let failures = 0; let errors = 0; let duration = 0; let firstTimestamp; let incrementalDuration = 0; testSuites.testsuite.forEach((testSuite) => { skipped += parseInt(testSuite.skipped[0], 10); failures += parseInt(testSuite.failures[0], 10); errors += parseInt(testSuite.errors[0], 10); duration += parseFloat(testSuite.time[0] * 1000); if (!firstTimestamp) { firstTimestamp = testSuite.timestamp[0]; } suites.push({ name: testSuite.name[0], errors: parseInt(testSuite.errors[0], 10), failures: parseInt(testSuite.failures[0], 10), skipped: parseInt(testSuite.skipped[0], 10), timestamp: testSuite.timestamp[0], time: parseFloat(testSuite.time[0] * 1000), tests: testSuite.tests[0], }); testSuite.testcase.filter((test) => !test.name[0].startsWith(' Test execution failure:')).forEach((test) => { const time = parseFloat(test.time[0] * 1000); incrementalDuration += time; let state = 'passed'; let pass = 'true'; let fail = 'false'; let pending = 'false'; if (test.failure) { state = 'failed'; fail = 'true'; pass = 'false'; } else if (test.skipped) { state = 'skipped'; pending = 'true'; pass = 'false'; } tests.push({ classname: test.classname[0], name: test.name[0], time, failure: test.failure ? test.failure[0] : '', skipped: test.skipped ? test.skipped[0] : '', incrementalDuration, state, pass, fail, pending, }); }); }); const startDate = new Date(firstTimestamp); const start = startDate.toISOString(); startDate.setTime(startDate.getTime() + duration); const end = startDate.toISOString(); return { suites, tests, skipped, failures, errors, duration, start, end, }; } function generateStats(allTests) { const suites = allTests.suites.length; const tests = allTests.tests.length; const skipped = allTests.skipped; const failures = allTests.failures; const errors = allTests.errors; const duration = allTests.duration; const start = allTests.start; const end = allTests.end; const passes = tests - (failures + errors + skipped); const passPercent = tests > 0 ? ((passes / tests) * 100).toFixed(2) : 0; return { suites, tests, skipped, failures, errors, duration, start, end, passes, passPercent, }; } function generateStatsFieldValue(stats, failedFullTitles) { let statsFieldValue = ` | Key | Value | |:---|:---| | Passing Rate | ${stats.passPercent}% | | Duration | ${(stats.duration / (60 * 1000)).toFixed(4)} mins | | Suites | ${stats.suites} | | Tests | ${stats.tests} | | :white_check_mark: Passed | ${stats.passes} | | :x: Failed | ${stats.failures} | | :fast_forward: Skipped | ${stats.skipped} | `; // If present, add full title of failing tests. // Only show per maximum number of failed titles with the last item as "more..." if failing tests are more than that. let failedTests; if (failedFullTitles && failedFullTitles.length > 0) { const re = /[:'"\\]/gi; const failed = failedFullTitles; if (failed.length > MAX_FAILED_TITLES) { failedTests = failed.slice(0, MAX_FAILED_TITLES - 1).map((f) => `- ${f.replace(re, '')}`).join('\n'); failedTests += '\n- more...'; } else { failedTests = failed.map((f) => `- ${f.replace(re, '')}`).join('\n'); } } if (failedTests) { statsFieldValue += '###### Failed Tests:\n' + failedTests; } return statsFieldValue; } function generateShortSummary(allTests) { const failedFullTitles = allTests.tests.filter((t) => t.failure).map((t) => t.name); const stats = generateStats(allTests); const statsFieldValue = generateStatsFieldValue(stats, failedFullTitles); return { stats, statsFieldValue, }; } function removeOldGeneratedReports() { const platform = process.env.IOS === 'true' ? 'ios' : 'android'; [ 'environment.json', 'summary.json', `${platform}-junit.json`, ].forEach((file) => fse.removeSync(`${ARTIFACTS_DIR}/${file}`)); } function writeJsonToFile(jsonObject, filename, dir) { fse.writeJson(`${dir}/${filename}`, jsonObject). then(() => console.log('Successfully written:', filename)). catch((err) => console.error(err)); } function readJsonFromFile(file) { try { return fse.readJsonSync(file); } catch (err) { return {err}; } } const result = [ {status: 'Passed', priority: 'none', cutOff: 100, color: '#43A047'}, {status: 'Failed', priority: 'low', cutOff: 98, color: '#FFEB3B'}, {status: 'Failed', priority: 'medium', cutOff: 95, color: '#FF9800'}, {status: 'Failed', priority: 'high', cutOff: 0, color: '#F44336'}, ]; function generateTestReport(summary, isUploadedToS3, reportLink, environment, testCycleKey) { const { FULL_REPORT, IOS, TEST_CYCLE_LINK_PREFIX, } = process.env; const platform = IOS === 'true' ? 'iOS' : 'Android'; const {statsFieldValue, stats} = summary; const { detox_version, device_name, device_os_version, headless, os_name, os_version, node_version, npm_version, } = environment; let testResult; for (let i = 0; i < result.length; i++) { if (stats.passPercent >= result[i].cutOff) { testResult = result[i]; break; } } const title = generateTitle(); const envValue = `detox@${detox_version} | node@${node_version} | npm@${npm_version} | ${device_name}@${device_os_version}${headless ? ' (headless)' : ''} | ${os_name}@${os_version}`; if (FULL_REPORT === 'true') { let reportField; if (isUploadedToS3) { reportField = { short: false, title: `${platform} Test Report`, value: `[Link to the report](${reportLink})`, }; } let testCycleField; if (testCycleKey) { testCycleField = { short: false, title: `${platform} Test Execution`, value: `[Recorded test executions](${TEST_CYCLE_LINK_PREFIX}${testCycleKey})`, }; } return { username: 'Mobile Detox Test', icon_url: 'path_to_url attachments: [{ color: testResult.color, author_name: 'Mobile End-to-end Testing', author_icon: 'path_to_url author_link: 'path_to_url title, fields: [ { short: false, title: 'Environment', value: envValue, }, reportField, testCycleField, { short: false, title: `Key metrics (required support: ${testResult.priority})`, value: statsFieldValue, }, ], }], }; } let quickSummary = `${stats.passPercent}% (${stats.passes}/${stats.tests}) in ${stats.suites} suites`; if (isUploadedToS3) { quickSummary = `[${quickSummary}](${reportLink})`; } let testCycleLink = ''; if (testCycleKey) { testCycleLink = testCycleKey ? `| [Recorded test executions](${TEST_CYCLE_LINK_PREFIX}${testCycleKey})` : ''; } return { username: 'Mobile Detox Test', icon_url: 'path_to_url attachments: [{ color: testResult.color, author_name: 'Mobile End-to-end Testing', author_icon: 'path_to_url author_link: 'path_to_url title, text: `${quickSummary} | ${(stats.duration / (60 * 1000)).toFixed(4)} mins ${testCycleLink}\n${envValue}`, }], }; } function generateTitle() { const { BRANCH, COMMIT_HASH, DETOX_AWS_S3_BUCKET, IOS, PULL_REQUEST, RELEASE_BUILD_NUMBER, RELEASE_DATE, RELEASE_VERSION, TYPE, REPORT_PATH, } = process.env; const platform = IOS === 'true' ? 'iOS' : 'Android'; const lane = `${platform} Build`; const appExtension = IOS === 'true' ? 'ipa' : 'apk'; const appFileName = `Mattermost_Beta.${appExtension}`; const appBuildType = 'mattermost-mobile-beta'; const s3Folder = `${platform.toLocaleLowerCase()}/${REPORT_PATH}`; const appFilePath = IOS === 'true' ? 'Mattermost-simulator-x86_64.app.zip' : 'android/app/build/outputs/apk/release/app-release.apk'; let buildLink = ''; let releaseDate = ''; let title; switch (TYPE) { case 'PR': buildLink = ` with [${lane}:${COMMIT_HASH}](path_to_url{DETOX_AWS_S3_BUCKET}.s3.amazonaws.com/${s3Folder}/${appFilePath})`; title = `${platform} E2E for Pull Request Build: [${BRANCH}](${PULL_REQUEST})${buildLink}`; break; case 'RELEASE': if (RELEASE_VERSION && RELEASE_BUILD_NUMBER) { buildLink = ` with [${RELEASE_VERSION}:${RELEASE_BUILD_NUMBER}](path_to_url{appBuildType}/${RELEASE_VERSION}/${RELEASE_BUILD_NUMBER}/${appFileName})`; } if (RELEASE_DATE) { releaseDate = ` for ${RELEASE_DATE}`; } title = `${platform} E2E for Release Build${buildLink}${releaseDate}`; break; case 'MAIN': title = `${platform} E2E for Main Nightly Build (Prod tests)${buildLink}`; break; default: title = `${platform} E2E for Build${buildLink}`; } return title; } async function sendReport(name, url, data) { const requestOptions = {method: 'POST', url, data}; try { const response = await axios(requestOptions); if (response.data) { console.log(`Successfully sent ${name}.`); } return response; } catch (er) { console.log(`Something went wrong while sending ${name}.`, er); return false; } } module.exports = { convertXmlToJson, generateShortSummary, generateTestReport, getAllTests, removeOldGeneratedReports, sendReport, readJsonFromFile, writeJsonToFile, }; ```
```javascript 'use client' export { default } from './client' export * from './client' ```
```php <?php declare(strict_types=1); /** */ namespace OCA\DAV\Events; use OCP\EventDispatcher\Event; /** * Class SubscriptionDeletedEvent * * @package OCA\DAV\Events * @since 20.0.0 */ class SubscriptionDeletedEvent extends Event { /** @var int */ private $subscriptionId; /** @var array */ private $subscriptionData; /** @var array */ private $shares; /** * SubscriptionDeletedEvent constructor. * * @param int $subscriptionId * @param array $subscriptionData * @param array $shares * @since 20.0.0 */ public function __construct(int $subscriptionId, array $subscriptionData, array $shares) { parent::__construct(); $this->subscriptionId = $subscriptionId; $this->subscriptionData = $subscriptionData; $this->shares = $shares; } /** * @return int * @since 20.0.0 */ public function getSubscriptionId(): int { return $this->subscriptionId; } /** * @return array * @since 20.0.0 */ public function getSubscriptionData(): array { return $this->subscriptionData; } /** * @return array * @since 20.0.0 */ public function getShares(): array { return $this->shares; } } ```
Thomas Antony Olajide, sometimes also credited as Thomas Olajide, is a Canadian actor from Vancouver, British Columbia. He is most noted for his performance in the 2021 film Learn to Swim, for which he received a Canadian Screen Award nomination for Best Actor at the 10th Canadian Screen Awards in 2022, and as co-creator with Tawiah M'carthy and Stephen Jackman-Torkoff of Black Boys, a theatrical show about Black Canadian LGBTQ+ identities which was staged by Buddies in Bad Times in 2016. Olajide, M'carthy, and Jackman-Torkoff were collectively nominated for Outstanding Ensemble Performance at the Dora Mavor Moore Awards in 2017. His other stage roles have included productions of William Shakespeare's The Winter's Tale for The Dream in High Park; King Lear, A Midsummer Night's Dream and Love's Labour's Lost for the Stratford Festival; Lynn Nottage's Ruined for Canadian Stage; and Michel Nadeau's And Slowly Beauty for the Belfry Theatre and the National Arts Centre. In film he also starred in the short film Mariner and the feature film White Lie. In television he had regular roles in the web series Inhuman Condition and Nomades, and received a Prix Gémeaux nomination for Best Actor in a Youth Digital Series in 2020 for Nomades. In 2023, he played a regular supporting role in the television series The Spencer Sisters as police officer Zane Graham. He is a graduate of the National Theatre School of Canada, and of the Actors Conservatory at the Canadian Film Centre. References External links 21st-century Canadian male actors 21st-century Canadian dramatists and playwrights 21st-century Canadian male writers Canadian male film actors Canadian male stage actors Canadian male television actors Canadian male Shakespearean actors Canadian male dramatists and playwrights Black Canadian male actors Male actors from Vancouver Canadian Film Centre alumni National Theatre School of Canada alumni LGBT male actors Canadian LGBT actors Canadian LGBT dramatists and playwrights Writers from Vancouver Black Canadian LGBT people Living people Queer actors Queer dramatists and playwrights 21st-century Canadian LGBT people Year of birth missing (living people)
```java package io.jpress.web.cpatcha; import com.anji.captcha.model.common.Const; import com.anji.captcha.service.CaptchaService; import com.anji.captcha.service.impl.CaptchaServiceFactory; import io.jboot.aop.annotation.Bean; import io.jboot.aop.annotation.Configuration; import java.util.Properties; @Configuration public class CaptchaConfig { @Bean public static CaptchaService getCaptchaService() { Properties config = new Properties(); // jboot // resources/META-INF/services com.anji.captcha.service.CaptchaCacheService config.put(Const.CAPTCHA_CACHETYPE, "jboot"); // config.put(Const.CAPTCHA_WATER_MARK, ""); config.put(Const.CAPTCHA_WATER_FONT, ""); config.put(Const.CAPTCHA_FONT_TYPE, ""); config.put(Const.CAPTCHA_TYPE, "default"); config.put(Const.CAPTCHA_INTERFERENCE_OPTIONS, "0"); config.put(Const.CAPTCHA_SLIP_OFFSET, "5"); config.put(Const.CAPTCHA_AES_STATUS, "true"); config.put(Const.CAPTCHA_CACAHE_MAX_NUMBER, "1000"); config.put(Const.CAPTCHA_TIMING_CLEAR_SECOND, "180"); return CaptchaServiceFactory.getInstance(config); } } ```
It's Your Move () is a 1968 Italian comedy film directed by Robert Fiz and starring Edward G. Robinson and Terry-Thomas. Cast Edward G. Robinson as Sir George McDowell Adolfo Celi as Insp. Vogel Maria Grazia Buccella as Monique Terry-Thomas as Jerome George Rigaud Manuel Zarzo Loris Bazzocchi José Bódalo Rossella Como References External links 1968 films 1968 comedy films Italian comedy films 1960s Italian-language films 1960s Italian films
```objective-c #pragma once #include <Core/Defines.h> #include <Core/BaseSettings.h> namespace Poco::Util { class AbstractConfiguration; } namespace DB { class ASTStorage; #define LIST_OF_DISTRIBUTED_SETTINGS(M, ALIAS) \ M(Bool, fsync_after_insert, false, "Do fsync for every inserted. Will decreases performance of inserts (only for background INSERT, i.e. distributed_foreground_insert=false)", 0) \ M(Bool, fsync_directories, false, "Do fsync for temporary directory (that is used for background INSERT only) after all part operations (writes, renames, etc.).", 0) \ /** This is the distributed version of the skip_unavailable_shards setting available in src/Core/Settings.h */ \ M(Bool, skip_unavailable_shards, false, "If true, ClickHouse silently skips unavailable shards. Shard is marked as unavailable when: 1) The shard cannot be reached due to a connection failure. 2) Shard is unresolvable through DNS. 3) Table does not exist on the shard.", 0) \ /** Inserts settings. */ \ M(UInt64, bytes_to_throw_insert, 0, "If more than this number of compressed bytes will be pending for background INSERT, an exception will be thrown. 0 - do not throw.", 0) \ M(UInt64, bytes_to_delay_insert, 0, "If more than this number of compressed bytes will be pending for background INSERT, the query will be delayed. 0 - do not delay.", 0) \ M(UInt64, max_delay_to_insert, 60, "Max delay of inserting data into Distributed table in seconds, if there are a lot of pending bytes for background send.", 0) \ /** Async INSERT settings */ \ M(UInt64, background_insert_batch, 0, "Default - distributed_background_insert_batch", 0) ALIAS(monitor_batch_inserts) \ M(UInt64, background_insert_split_batch_on_failure, 0, "Default - distributed_background_insert_split_batch_on_failure", 0) ALIAS(monitor_split_batch_on_failure) \ M(Milliseconds, background_insert_sleep_time_ms, 0, "Default - distributed_background_insert_sleep_time_ms", 0) ALIAS(monitor_sleep_time_ms) \ M(Milliseconds, background_insert_max_sleep_time_ms, 0, "Default - distributed_background_insert_max_sleep_time_ms", 0) ALIAS(monitor_max_sleep_time_ms) \ M(Bool, flush_on_detach, true, "Flush data to remote nodes on DETACH/DROP/server shutdown", 0) \ DECLARE_SETTINGS_TRAITS(DistributedSettingsTraits, LIST_OF_DISTRIBUTED_SETTINGS) /** Settings for the Distributed family of engines. */ struct DistributedSettings : public BaseSettings<DistributedSettingsTraits> { void loadFromConfig(const String & config_elem, const Poco::Util::AbstractConfiguration & config); void loadFromQuery(ASTStorage & storage_def); }; } ```
Tirto Samudro beach or Bandengan Beach is located north of downtown Jepara, Central Java, Indonesia. It has a concentration of Hotel and Resort and quite popular for Beach tourism in Central Java. References Tourism in Jepara Beaches of Central Java Landforms of Central Java Landforms of Java
Puzzle Mountain is a twin-summit mountain on Vancouver Island, British Columbia, Canada, located east of Gold River and northwest of Mount Colonel Foster. History Puzzle Mountain is named for the maze of snow patches on its northeast face. See also List of mountains in Canada References Vancouver Island Ranges One-thousanders of British Columbia Nootka Land District
The 1932 Utah gubernatorial election was held on November 8, 1932. Democratic nominee Henry H. Blood defeated Republican nominee William W. Seegmiller with 56.39% of the vote. General election Candidates Major party candidates Henry H. Blood, Democratic William W. Seegmiller, Republican Other candidates A.L. Porter, Socialist Marvin P. Bales, Communist Results References 1932 Utah Gubernatorial
Don Bosco is a Mexican telenovela produced by Televisa and transmitted by Telesistema Mexicano. Cast Rafael Bertrand Alicia Montoya Nicolás Rodríguez Alberto Galán Josefina Escobedo Antonio Passy Pepito Morán Luis Gimeno Roberto Araya Armando Gutierrez 1961 telenovelas Televisa telenovelas 1961 Mexican television series debuts 1961 Mexican television series endings Spanish-language telenovelas
```c++ //===- COFFImportFile.cpp - COFF short import file implementation ---------===// // // See path_to_url for license information. // //===your_sha256_hash------===// // // This file defines the writeImportLibrary function. // //===your_sha256_hash------===// #include "llvm/Object/COFFImportFile.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ArchiveWriter.h" #include "llvm/Object/COFF.h" #include "llvm/Support/Error.h" #include "llvm/Support/Path.h" #include <cstdint> #include <string> #include <vector> using namespace llvm::COFF; using namespace llvm::object; using namespace llvm; namespace llvm { namespace object { static bool is32bit(MachineTypes Machine) { switch (Machine) { default: llvm_unreachable("unsupported machine"); case IMAGE_FILE_MACHINE_ARM64: case IMAGE_FILE_MACHINE_AMD64: return false; case IMAGE_FILE_MACHINE_ARMNT: case IMAGE_FILE_MACHINE_I386: return true; } } static uint16_t getImgRelRelocation(MachineTypes Machine) { switch (Machine) { default: llvm_unreachable("unsupported machine"); case IMAGE_FILE_MACHINE_AMD64: return IMAGE_REL_AMD64_ADDR32NB; case IMAGE_FILE_MACHINE_ARMNT: return IMAGE_REL_ARM_ADDR32NB; case IMAGE_FILE_MACHINE_ARM64: return IMAGE_REL_ARM64_ADDR32NB; case IMAGE_FILE_MACHINE_I386: return IMAGE_REL_I386_DIR32NB; } } template <class T> static void append(std::vector<uint8_t> &B, const T &Data) { size_t S = B.size(); B.resize(S + sizeof(T)); memcpy(&B[S], &Data, sizeof(T)); } static void writeStringTable(std::vector<uint8_t> &B, ArrayRef<const std::string> Strings) { // The COFF string table consists of a 4-byte value which is the size of the // table, including the length field itself. This value is followed by the // string content itself, which is an array of null-terminated C-style // strings. The termination is important as they are referenced to by offset // by the symbol entity in the file format. size_t Pos = B.size(); size_t Offset = B.size(); // Skip over the length field, we will fill it in later as we will have // computed the length while emitting the string content itself. Pos += sizeof(uint32_t); for (const auto &S : Strings) { B.resize(Pos + S.length() + 1); strcpy(reinterpret_cast<char *>(&B[Pos]), S.c_str()); Pos += S.length() + 1; } // Backfill the length of the table now that it has been computed. support::ulittle32_t Length(B.size() - Offset); support::endian::write32le(&B[Offset], Length); } static ImportNameType getNameType(StringRef Sym, StringRef ExtName, MachineTypes Machine, bool MinGW) { // A decorated stdcall function in MSVC is exported with the // type IMPORT_NAME, and the exported function name includes the // the leading underscore. In MinGW on the other hand, a decorated // stdcall function still omits the underscore (IMPORT_NAME_NOPREFIX). // See the comment in isDecorated in COFFModuleDefinition.cpp for more // details. if (ExtName.startswith("_") && ExtName.contains('@') && !MinGW) return IMPORT_NAME; if (Sym != ExtName) return IMPORT_NAME_UNDECORATE; if (Machine == IMAGE_FILE_MACHINE_I386 && Sym.startswith("_")) return IMPORT_NAME_NOPREFIX; return IMPORT_NAME; } static Expected<std::string> replace(StringRef S, StringRef From, StringRef To) { size_t Pos = S.find(From); // From and To may be mangled, but substrings in S may not. if (Pos == StringRef::npos && From.startswith("_") && To.startswith("_")) { From = From.substr(1); To = To.substr(1); Pos = S.find(From); } if (Pos == StringRef::npos) { return make_error<StringError>( StringRef(Twine(S + ": replacing '" + From + "' with '" + To + "' failed").str()), object_error::parse_failed); } return (Twine(S.substr(0, Pos)) + To + S.substr(Pos + From.size())).str(); } static const std::string NullImportDescriptorSymbolName = "__NULL_IMPORT_DESCRIPTOR"; namespace { // This class constructs various small object files necessary to support linking // symbols imported from a DLL. The contents are pretty strictly defined and // nearly entirely static. The details of the structures files are defined in // WINNT.h and the PE/COFF specification. class ObjectFactory { using u16 = support::ulittle16_t; using u32 = support::ulittle32_t; MachineTypes Machine; BumpPtrAllocator Alloc; StringRef ImportName; StringRef Library; std::string ImportDescriptorSymbolName; std::string NullThunkSymbolName; public: ObjectFactory(StringRef S, MachineTypes M) : Machine(M), ImportName(S), Library(S.drop_back(4)), ImportDescriptorSymbolName(("__IMPORT_DESCRIPTOR_" + Library).str()), NullThunkSymbolName(("\x7f" + Library + "_NULL_THUNK_DATA").str()) {} // Creates an Import Descriptor. This is a small object file which contains a // reference to the terminators and contains the library name (entry) for the // import name table. It will force the linker to construct the necessary // structure to import symbols from the DLL. NewArchiveMember createImportDescriptor(std::vector<uint8_t> &Buffer); // Creates a NULL import descriptor. This is a small object file whcih // contains a NULL import descriptor. It is used to terminate the imports // from a specific DLL. NewArchiveMember createNullImportDescriptor(std::vector<uint8_t> &Buffer); // Create a NULL Thunk Entry. This is a small object file which contains a // NULL Import Address Table entry and a NULL Import Lookup Table Entry. It // is used to terminate the IAT and ILT. NewArchiveMember createNullThunk(std::vector<uint8_t> &Buffer); // Create a short import file which is described in PE/COFF spec 7. Import // Library Format. NewArchiveMember createShortImport(StringRef Sym, uint16_t Ordinal, ImportType Type, ImportNameType NameType); // Create a weak external file which is described in PE/COFF Aux Format 3. NewArchiveMember createWeakExternal(StringRef Sym, StringRef Weak, bool Imp); }; } // namespace NewArchiveMember ObjectFactory::createImportDescriptor(std::vector<uint8_t> &Buffer) { const uint32_t NumberOfSections = 2; const uint32_t NumberOfSymbols = 7; const uint32_t NumberOfRelocations = 3; // COFF Header coff_file_header Header{ u16(Machine), u16(NumberOfSections), u32(0), u32(sizeof(Header) + (NumberOfSections * sizeof(coff_section)) + // .idata$2 sizeof(coff_import_directory_table_entry) + NumberOfRelocations * sizeof(coff_relocation) + // .idata$4 (ImportName.size() + 1)), u32(NumberOfSymbols), u16(0), u16(is32bit(Machine) ? IMAGE_FILE_32BIT_MACHINE : C_Invalid), }; append(Buffer, Header); // Section Header Table const coff_section SectionTable[NumberOfSections] = { {{'.', 'i', 'd', 'a', 't', 'a', '$', '2'}, u32(0), u32(0), u32(sizeof(coff_import_directory_table_entry)), u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section)), u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section) + sizeof(coff_import_directory_table_entry)), u32(0), u16(NumberOfRelocations), u16(0), u32(IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)}, {{'.', 'i', 'd', 'a', 't', 'a', '$', '6'}, u32(0), u32(0), u32(ImportName.size() + 1), u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section) + sizeof(coff_import_directory_table_entry) + NumberOfRelocations * sizeof(coff_relocation)), u32(0), u32(0), u16(0), u16(0), u32(IMAGE_SCN_ALIGN_2BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)}, }; append(Buffer, SectionTable); // .idata$2 const coff_import_directory_table_entry ImportDescriptor{ u32(0), u32(0), u32(0), u32(0), u32(0), }; append(Buffer, ImportDescriptor); const coff_relocation RelocationTable[NumberOfRelocations] = { {u32(offsetof(coff_import_directory_table_entry, NameRVA)), u32(2), u16(getImgRelRelocation(Machine))}, {u32(offsetof(coff_import_directory_table_entry, ImportLookupTableRVA)), u32(3), u16(getImgRelRelocation(Machine))}, {u32(offsetof(coff_import_directory_table_entry, ImportAddressTableRVA)), u32(4), u16(getImgRelRelocation(Machine))}, }; append(Buffer, RelocationTable); // .idata$6 auto S = Buffer.size(); Buffer.resize(S + ImportName.size() + 1); memcpy(&Buffer[S], ImportName.data(), ImportName.size()); Buffer[S + ImportName.size()] = '\0'; // Symbol Table coff_symbol16 SymbolTable[NumberOfSymbols] = { {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(1), u16(0), IMAGE_SYM_CLASS_EXTERNAL, 0}, {{{'.', 'i', 'd', 'a', 't', 'a', '$', '2'}}, u32(0), u16(1), u16(0), IMAGE_SYM_CLASS_SECTION, 0}, {{{'.', 'i', 'd', 'a', 't', 'a', '$', '6'}}, u32(0), u16(2), u16(0), IMAGE_SYM_CLASS_STATIC, 0}, {{{'.', 'i', 'd', 'a', 't', 'a', '$', '4'}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_SECTION, 0}, {{{'.', 'i', 'd', 'a', 't', 'a', '$', '5'}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_SECTION, 0}, {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_EXTERNAL, 0}, {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_EXTERNAL, 0}, }; // TODO: Name.Offset.Offset here and in the all similar places below // suggests a names refactoring. Maybe StringTableOffset.Value? SymbolTable[0].Name.Offset.Offset = sizeof(uint32_t); SymbolTable[5].Name.Offset.Offset = sizeof(uint32_t) + ImportDescriptorSymbolName.length() + 1; SymbolTable[6].Name.Offset.Offset = sizeof(uint32_t) + ImportDescriptorSymbolName.length() + 1 + NullImportDescriptorSymbolName.length() + 1; append(Buffer, SymbolTable); // String Table writeStringTable(Buffer, {ImportDescriptorSymbolName, NullImportDescriptorSymbolName, NullThunkSymbolName}); StringRef F{reinterpret_cast<const char *>(Buffer.data()), Buffer.size()}; return {MemoryBufferRef(F, ImportName)}; } NewArchiveMember ObjectFactory::createNullImportDescriptor(std::vector<uint8_t> &Buffer) { const uint32_t NumberOfSections = 1; const uint32_t NumberOfSymbols = 1; // COFF Header coff_file_header Header{ u16(Machine), u16(NumberOfSections), u32(0), u32(sizeof(Header) + (NumberOfSections * sizeof(coff_section)) + // .idata$3 sizeof(coff_import_directory_table_entry)), u32(NumberOfSymbols), u16(0), u16(is32bit(Machine) ? IMAGE_FILE_32BIT_MACHINE : C_Invalid), }; append(Buffer, Header); // Section Header Table const coff_section SectionTable[NumberOfSections] = { {{'.', 'i', 'd', 'a', 't', 'a', '$', '3'}, u32(0), u32(0), u32(sizeof(coff_import_directory_table_entry)), u32(sizeof(coff_file_header) + (NumberOfSections * sizeof(coff_section))), u32(0), u32(0), u16(0), u16(0), u32(IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)}, }; append(Buffer, SectionTable); // .idata$3 const coff_import_directory_table_entry ImportDescriptor{ u32(0), u32(0), u32(0), u32(0), u32(0), }; append(Buffer, ImportDescriptor); // Symbol Table coff_symbol16 SymbolTable[NumberOfSymbols] = { {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(1), u16(0), IMAGE_SYM_CLASS_EXTERNAL, 0}, }; SymbolTable[0].Name.Offset.Offset = sizeof(uint32_t); append(Buffer, SymbolTable); // String Table writeStringTable(Buffer, {NullImportDescriptorSymbolName}); StringRef F{reinterpret_cast<const char *>(Buffer.data()), Buffer.size()}; return {MemoryBufferRef(F, ImportName)}; } NewArchiveMember ObjectFactory::createNullThunk(std::vector<uint8_t> &Buffer) { const uint32_t NumberOfSections = 2; const uint32_t NumberOfSymbols = 1; uint32_t VASize = is32bit(Machine) ? 4 : 8; // COFF Header coff_file_header Header{ u16(Machine), u16(NumberOfSections), u32(0), u32(sizeof(Header) + (NumberOfSections * sizeof(coff_section)) + // .idata$5 VASize + // .idata$4 VASize), u32(NumberOfSymbols), u16(0), u16(is32bit(Machine) ? IMAGE_FILE_32BIT_MACHINE : C_Invalid), }; append(Buffer, Header); // Section Header Table const coff_section SectionTable[NumberOfSections] = { {{'.', 'i', 'd', 'a', 't', 'a', '$', '5'}, u32(0), u32(0), u32(VASize), u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section)), u32(0), u32(0), u16(0), u16(0), u32((is32bit(Machine) ? IMAGE_SCN_ALIGN_4BYTES : IMAGE_SCN_ALIGN_8BYTES) | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)}, {{'.', 'i', 'd', 'a', 't', 'a', '$', '4'}, u32(0), u32(0), u32(VASize), u32(sizeof(coff_file_header) + NumberOfSections * sizeof(coff_section) + VASize), u32(0), u32(0), u16(0), u16(0), u32((is32bit(Machine) ? IMAGE_SCN_ALIGN_4BYTES : IMAGE_SCN_ALIGN_8BYTES) | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)}, }; append(Buffer, SectionTable); // .idata$5, ILT append(Buffer, u32(0)); if (!is32bit(Machine)) append(Buffer, u32(0)); // .idata$4, IAT append(Buffer, u32(0)); if (!is32bit(Machine)) append(Buffer, u32(0)); // Symbol Table coff_symbol16 SymbolTable[NumberOfSymbols] = { {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(1), u16(0), IMAGE_SYM_CLASS_EXTERNAL, 0}, }; SymbolTable[0].Name.Offset.Offset = sizeof(uint32_t); append(Buffer, SymbolTable); // String Table writeStringTable(Buffer, {NullThunkSymbolName}); StringRef F{reinterpret_cast<const char *>(Buffer.data()), Buffer.size()}; return {MemoryBufferRef{F, ImportName}}; } NewArchiveMember ObjectFactory::createShortImport(StringRef Sym, uint16_t Ordinal, ImportType ImportType, ImportNameType NameType) { size_t ImpSize = ImportName.size() + Sym.size() + 2; // +2 for NULs size_t Size = sizeof(coff_import_header) + ImpSize; char *Buf = Alloc.Allocate<char>(Size); memset(Buf, 0, Size); char *P = Buf; // Write short import library. auto *Imp = reinterpret_cast<coff_import_header *>(P); P += sizeof(*Imp); Imp->Sig2 = 0xFFFF; Imp->Machine = Machine; Imp->SizeOfData = ImpSize; if (Ordinal > 0) Imp->OrdinalHint = Ordinal; Imp->TypeInfo = (NameType << 2) | ImportType; // Write symbol name and DLL name. memcpy(P, Sym.data(), Sym.size()); P += Sym.size() + 1; memcpy(P, ImportName.data(), ImportName.size()); return {MemoryBufferRef(StringRef(Buf, Size), ImportName)}; } NewArchiveMember ObjectFactory::createWeakExternal(StringRef Sym, StringRef Weak, bool Imp) { std::vector<uint8_t> Buffer; const uint32_t NumberOfSections = 1; const uint32_t NumberOfSymbols = 5; // COFF Header coff_file_header Header{ u16(Machine), u16(NumberOfSections), u32(0), u32(sizeof(Header) + (NumberOfSections * sizeof(coff_section))), u32(NumberOfSymbols), u16(0), u16(0), }; append(Buffer, Header); // Section Header Table const coff_section SectionTable[NumberOfSections] = { {{'.', 'd', 'r', 'e', 'c', 't', 'v', 'e'}, u32(0), u32(0), u32(0), u32(0), u32(0), u32(0), u16(0), u16(0), u32(IMAGE_SCN_LNK_INFO | IMAGE_SCN_LNK_REMOVE)}}; append(Buffer, SectionTable); // Symbol Table coff_symbol16 SymbolTable[NumberOfSymbols] = { {{{'@', 'c', 'o', 'm', 'p', '.', 'i', 'd'}}, u32(0), u16(0xFFFF), u16(0), IMAGE_SYM_CLASS_STATIC, 0}, {{{'@', 'f', 'e', 'a', 't', '.', '0', '0'}}, u32(0), u16(0xFFFF), u16(0), IMAGE_SYM_CLASS_STATIC, 0}, {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_EXTERNAL, 0}, {{{0, 0, 0, 0, 0, 0, 0, 0}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_WEAK_EXTERNAL, 1}, {{{2, 0, 0, 0, IMAGE_WEAK_EXTERN_SEARCH_ALIAS, 0, 0, 0}}, u32(0), u16(0), u16(0), IMAGE_SYM_CLASS_NULL, 0}, }; SymbolTable[2].Name.Offset.Offset = sizeof(uint32_t); //__imp_ String Table StringRef Prefix = Imp ? "__imp_" : ""; SymbolTable[3].Name.Offset.Offset = sizeof(uint32_t) + Sym.size() + Prefix.size() + 1; append(Buffer, SymbolTable); writeStringTable(Buffer, {(Prefix + Sym).str(), (Prefix + Weak).str()}); // Copied here so we can still use writeStringTable char *Buf = Alloc.Allocate<char>(Buffer.size()); memcpy(Buf, Buffer.data(), Buffer.size()); return {MemoryBufferRef(StringRef(Buf, Buffer.size()), ImportName)}; } Error writeImportLibrary(StringRef ImportName, StringRef Path, ArrayRef<COFFShortExport> Exports, MachineTypes Machine, bool MinGW) { std::vector<NewArchiveMember> Members; ObjectFactory OF(llvm::sys::path::filename(ImportName), Machine); std::vector<uint8_t> ImportDescriptor; Members.push_back(OF.createImportDescriptor(ImportDescriptor)); std::vector<uint8_t> NullImportDescriptor; Members.push_back(OF.createNullImportDescriptor(NullImportDescriptor)); std::vector<uint8_t> NullThunk; Members.push_back(OF.createNullThunk(NullThunk)); for (COFFShortExport E : Exports) { if (E.Private) continue; ImportType ImportType = IMPORT_CODE; if (E.Data) ImportType = IMPORT_DATA; if (E.Constant) ImportType = IMPORT_CONST; StringRef SymbolName = E.SymbolName.empty() ? E.Name : E.SymbolName; ImportNameType NameType = E.Noname ? IMPORT_ORDINAL : getNameType(SymbolName, E.Name, Machine, MinGW); Expected<std::string> Name = E.ExtName.empty() ? SymbolName : replace(SymbolName, E.Name, E.ExtName); if (!Name) return Name.takeError(); if (!E.AliasTarget.empty() && *Name != E.AliasTarget) { Members.push_back(OF.createWeakExternal(E.AliasTarget, *Name, false)); Members.push_back(OF.createWeakExternal(E.AliasTarget, *Name, true)); continue; } Members.push_back( OF.createShortImport(*Name, E.Ordinal, ImportType, NameType)); } return writeArchive(Path, Members, /*WriteSymtab*/ true, object::Archive::K_GNU, /*Deterministic*/ true, /*Thin*/ false); } } // namespace object } // namespace llvm ```
```go // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package index import ( "testing" "github.com/stretchr/testify/assert" ) func TestQueryOptions(t *testing.T) { opts := QueryOptions{ DocsLimit: 10, SeriesLimit: 20, } assert.False(t, opts.SeriesLimitExceeded(19)) assert.True(t, opts.SeriesLimitExceeded(20)) assert.False(t, opts.DocsLimitExceeded(9)) assert.True(t, opts.DocsLimitExceeded(10)) assert.True(t, opts.LimitsExceeded(19, 10)) assert.True(t, opts.LimitsExceeded(20, 9)) assert.False(t, opts.LimitsExceeded(19, 9)) assert.False(t, opts.Exhaustive(19, 10)) assert.False(t, opts.Exhaustive(20, 9)) assert.True(t, opts.Exhaustive(19, 9)) } ```
Carpenter is a small unincorporated community located in western Wake County, North Carolina, United States. Carpenter is centered on the intersection of Carpenter-Upchurch Road and Morrisville-Carpenter Road just east of North Carolina Highway 55. Most of Carpenter has been annexed by the Town of Cary. The community was named for William Carpenter, the first settler in the area, in 1865 . Carpenter was a stop on the former Durham and Southern Railway. Part of the community also includes the Carpenter Historic District, which was created in 2000. Carpenter Elementary was named for the community but lies in a recently annexed part of Cary. References Unincorporated communities in Wake County, North Carolina Unincorporated communities in North Carolina Populated places established in 1865
```objective-c #pragma once #include <Core/Names.h> #include <Core/Types.h> #include <Parsers/IAST_fwd.h> namespace DB { class ASTQueryParameter; /// Visit substitutions in a query, replace ASTQueryParameter with ASTLiteral. /// Rebuild ASTIdentifiers if some parts are ASTQueryParameter. class ReplaceQueryParameterVisitor { public: explicit ReplaceQueryParameterVisitor(const NameToNameMap & parameters) : query_parameters(parameters) {} void visit(ASTPtr & ast); size_t getNumberOfReplacedParameters() const { return num_replaced_parameters; } private: const NameToNameMap & query_parameters; size_t num_replaced_parameters = 0; const String & getParamValue(const String & name); void visitIdentifier(ASTPtr & ast); void visitQueryParameter(ASTPtr & ast); void visitChildren(ASTPtr & ast); }; } ```
```c++ // // experimental/detail/has_signature.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // // file LICENSE_1_0.txt or copy at path_to_url // #ifndef BOOST_ASIO_EXPERIMENTAL_DETAIL_HAS_SIGNATURE_HPP #define BOOST_ASIO_EXPERIMENTAL_DETAIL_HAS_SIGNATURE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace experimental { namespace detail { template <typename S, typename... Signatures> struct has_signature; template <typename S, typename... Signatures> struct has_signature; template <typename S> struct has_signature<S> : false_type { }; template <typename S, typename... Signatures> struct has_signature<S, S, Signatures...> : true_type { }; template <typename S, typename Head, typename... Tail> struct has_signature<S, Head, Tail...> : has_signature<S, Tail...> { }; } // namespace detail } // namespace experimental } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_EXPERIMENTAL_DETAIL_HAS_SIGNATURE_HPP ```
```python Double ended queues with `deque` `Module`s everywhere! Immutable sets with `frozenset` There is more to copying How to count ```
```python # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import unittest import numpy as np import paddle from paddle import base from paddle.base import core from paddle.pir_utils import test_with_pir_api class TestBatchNorm(unittest.TestCase): def test_name(self): places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): places.append(base.CUDAPlace(0)) for p in places: with base.dygraph.guard(p): batch_norm1d = paddle.nn.BatchNorm1D(1, name="test") def test_error(self): places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): places.append(base.CUDAPlace(0)) for p in places: # paddle.disable_static() x_data_4 = np.random.random(size=(2, 1, 3, 3)).astype('float32') x_data_3 = np.random.random(size=(2, 1, 3)).astype('float32') def error1d_dataformat(): x_data_4 = np.random.random(size=(2, 1, 3, 3)).astype('float32') batch_norm1d = paddle.nn.BatchNorm1D(1, data_format='NCDHW') batch_norm1d(paddle.to_tensor(x_data_4)) def error2d_dataformat(): x_data_3 = np.random.random(size=(2, 1, 3)).astype('float32') batch_norm2d = paddle.nn.BatchNorm2D(1, data_format='NCDHW') batch_norm2d(paddle.to_tensor(x_data_3)) def error3d_dataformat(): x_data_4 = np.random.random(size=(2, 1, 3, 3)).astype('float32') batch_norm3d = paddle.nn.BatchNorm3D(1, data_format='NCL') batch_norm3d(paddle.to_tensor(x_data_4)) def error1d(): x_data_4 = np.random.random(size=(2, 1, 3, 3)).astype('float32') batch_norm1d = paddle.nn.BatchNorm1D(1) batch_norm1d(paddle.to_tensor(x_data_4)) def error2d(): x_data_3 = np.random.random(size=(2, 1, 3)).astype('float32') batch_norm2d = paddle.nn.BatchNorm2D(1) batch_norm2d(paddle.to_tensor(x_data_3)) def error3d(): x_data_4 = np.random.random(size=(2, 1, 3, 3)).astype('float32') batch_norm3d = paddle.nn.BatchNorm3D(1) batch_norm3d(paddle.to_tensor(x_data_4)) with base.dygraph.guard(p): self.assertRaises(ValueError, error1d) self.assertRaises(ValueError, error2d) self.assertRaises(ValueError, error3d) self.assertRaises(ValueError, error1d_dataformat) self.assertRaises(ValueError, error2d_dataformat) self.assertRaises(ValueError, error3d_dataformat) def test_large_batch(self): def compute_baseline(x): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm(shape[1]) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() def compute_1d(x): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm1D(shape[1]) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): places.append(base.CUDAPlace(0)) for p in places: # [N, C] shape = [200000, 4] x = np.random.randn(*shape).astype("float32") y1, g1 = compute_baseline(x) y2, g2 = compute_1d(x) np.testing.assert_allclose(g1, g2, rtol=1e-05) np.testing.assert_allclose(y1, y2, rtol=1e-05) # [N, C, L] shape = [1000000, 4, 4] x = np.random.randn(*shape).astype("float32") y1, g1 = compute_baseline(x) y2, g2 = compute_1d(x) np.testing.assert_allclose(g1, g2, rtol=1e-05) np.testing.assert_allclose(y1, y2, rtol=1e-05) def test_eager_api(self): places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): places.append(base.CUDAPlace(0)) for p in places: shape = [4, 10, 4, 4] def compute_v1(x): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm(shape[1]) # bn = paddle.nn.BatchNorm2D(shape[1]) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() def compute_v2(x): with base.dygraph.guard(p): print("v2") bn = paddle.nn.BatchNorm2D(shape[1]) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() x = np.random.randn(*shape).astype("float32") y1, g1 = compute_v1(x) y2, g2 = compute_v2(x) np.testing.assert_allclose(g1, g2, rtol=1e-05) np.testing.assert_allclose(y1, y2, rtol=1e-05) def test_dygraph(self): places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): places.append(base.CUDAPlace(0)) for p in places: shape = [4, 10, 4, 4] def compute_v1(x, is_test, trainable_statistics): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm( shape[1], is_test=is_test, trainable_statistics=trainable_statistics, ) y = bn(paddle.to_tensor(x)) return y.numpy() def compute_v2(x): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm2D(shape[1]) y = bn(paddle.to_tensor(x)) bn = paddle.nn.BatchNorm2D(shape[1]) eag_y = bn(paddle.to_tensor(x)) np.testing.assert_allclose(eag_y.numpy(), y.numpy()) return y.numpy() def compute_v3(x, is_test, trainable_statistics): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm( shape[1], is_test=is_test, param_attr=base.ParamAttr( initializer=paddle.nn.initializer.Constant(1.0), trainable=False, ), bias_attr=base.ParamAttr( initializer=paddle.nn.initializer.Constant(0.0), trainable=False, ), trainable_statistics=trainable_statistics, ) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() def compute_v3_1(x, is_test, trainable_statistics): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm( shape[1], is_test=is_test, param_attr=False, bias_attr=False, trainable_statistics=trainable_statistics, ) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() def compute_v3_2(x, is_test, trainable_statistics): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm( shape[1], is_test=is_test, param_attr=False, bias_attr=base.ParamAttr( initializer=paddle.nn.initializer.Constant(0.0), trainable=False, ), trainable_statistics=trainable_statistics, ) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() def compute_v3_3(x, is_test, trainable_statistics): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm( shape[1], is_test=is_test, param_attr=base.ParamAttr( initializer=paddle.nn.initializer.Constant(1.0), trainable=False, ), bias_attr=False, trainable_statistics=trainable_statistics, ) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() def compute_v4(x): with base.dygraph.guard(p): bn = paddle.nn.BatchNorm2D( shape[1], weight_attr=False, bias_attr=False ) x1 = paddle.to_tensor(x) x1.stop_gradient = False y = bn(x1) y.backward() return y.numpy(), x1.gradient() x = np.random.randn(*shape).astype("float32") y1 = compute_v1(x, False, False) y2 = compute_v2(x) y3, g3 = compute_v3(x, False, False) y3_1, g3_1 = compute_v3_1(x, False, False) y3_2, g3_2 = compute_v3_2(x, False, False) y3_3, g3_3 = compute_v3_3(x, False, False) y4, g4 = compute_v4(x) np.testing.assert_allclose(y1, y2, rtol=1e-05) np.testing.assert_allclose(y3, y4, rtol=1e-05) np.testing.assert_allclose(y3_1, y4, rtol=1e-05) np.testing.assert_allclose(y3_2, y4, rtol=1e-05) np.testing.assert_allclose(y3_3, y4, rtol=1e-05) np.testing.assert_allclose(g3, g4, rtol=1e-05) np.testing.assert_allclose(g3_1, g4, rtol=1e-05) np.testing.assert_allclose(g3_2, g4, rtol=1e-05) np.testing.assert_allclose(g3_3, g4, rtol=1e-05) @test_with_pir_api def test_static(self): places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): places.append(base.CUDAPlace(0)) for p in places: exe = base.Executor(p) shape = [4, 10, 16, 16] def compute_v1(x_np, is_test, trainable_statistics): main_program = paddle.static.Program() startup_program = paddle.static.Program() with base.program_guard(main_program, startup_program): bn = paddle.nn.BatchNorm( shape[1], is_test=is_test, trainable_statistics=trainable_statistics, ) x = paddle.static.data( name='x', shape=x_np.shape, dtype=x_np.dtype ) y = bn(x) exe.run(startup_program) r = exe.run(feed={'x': x_np}, fetch_list=[y])[0] return r def compute_v2(x_np): main_program = paddle.static.Program() startup_program = paddle.static.Program() with base.program_guard(main_program, startup_program): bn = paddle.nn.BatchNorm2D(shape[1]) x = paddle.static.data( name='x', shape=x_np.shape, dtype=x_np.dtype ) y = bn(x) exe.run(startup_program) r = exe.run(feed={'x': x_np}, fetch_list=[y])[0] return r x = np.random.randn(*shape).astype("float32") y1 = compute_v1(x, False, False) y2 = compute_v2(x) np.testing.assert_allclose(y1, y2, rtol=1e-05) class TestBatchNormChannelLast(unittest.TestCase): def setUp(self): self.original_dtyep = paddle.get_default_dtype() # MIOPEN not support data type of double if core.is_compiled_with_rocm(): paddle.set_default_dtype("float32") else: paddle.set_default_dtype("float64") self.places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): self.places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): self.places.append(base.CUDAPlace(0)) def tearDown(self): paddle.set_default_dtype(self.original_dtyep) def test_1d(self): for p in self.places: with base.dygraph.guard(p): x = paddle.randn([2, 6, 4]) net1 = paddle.nn.BatchNorm1D(4, data_format="NLC") net2 = paddle.nn.BatchNorm1D(4) net2.weight = net1.weight net2.bias = net1.bias y1 = net1(x) channel_first_x = paddle.transpose(x, [0, 2, 1]) y2 = net2(channel_first_x) y2 = paddle.transpose(y2, [0, 2, 1]) if core.is_compiled_with_rocm(): # HIP will fail if no atol np.testing.assert_allclose( y1.numpy(), y2.numpy(), rtol=1e-05, atol=1e-07 ) else: np.testing.assert_allclose( y1.numpy(), y2.numpy(), rtol=1e-05 ) def test_2d(self): for p in self.places: with base.dygraph.guard(p): x = paddle.randn([2, 6, 6, 4]) net1 = paddle.nn.BatchNorm2D(4, data_format="NHWC") net2 = paddle.nn.BatchNorm2D(4) net2.weight = net1.weight net2.bias = net1.bias y1 = net1(x) channel_first_x = paddle.transpose(x, [0, 3, 1, 2]) y2 = net2(channel_first_x) y2 = paddle.transpose(y2, [0, 2, 3, 1]) if core.is_compiled_with_rocm(): # HIP will fail if no atol np.testing.assert_allclose( y1.numpy(), y2.numpy(), rtol=1e-05, atol=1e-07 ) else: np.testing.assert_allclose( y1.numpy(), y2.numpy(), rtol=1e-05 ) def test_3d(self): for p in self.places: with base.dygraph.guard(p): x = paddle.randn([2, 6, 6, 6, 4]) net1 = paddle.nn.BatchNorm3D(4, data_format="NDHWC") net2 = paddle.nn.BatchNorm3D(4) net2.weight = net1.weight net2.bias = net1.bias y1 = net1(x) channel_first_x = paddle.transpose(x, [0, 4, 1, 2, 3]) y2 = net2(channel_first_x) y2 = paddle.transpose(y2, [0, 2, 3, 4, 1]) if core.is_compiled_with_rocm(): # HIP will fail if no atol np.testing.assert_allclose( y1.numpy(), y2.numpy(), rtol=1e-05, atol=1e-07 ) else: np.testing.assert_allclose( y1.numpy(), y2.numpy(), rtol=1e-05 ) def test_1d_opt(self): with base.dygraph.guard(): batch_size = 13700 channels = 16 shape = (batch_size, channels) x = paddle.randn(shape) x_4d = x.reshape((batch_size, channels, 1, 1)) x.stop_gradient = False x_4d.stop_gradient = False bn1d = paddle.nn.BatchNorm1D(channels) bn2d = paddle.nn.BatchNorm2D(channels) y = bn1d(x) y2 = bn2d(x_4d) y.backward() y2.backward() np.testing.assert_allclose( y.numpy().flatten(), y2.numpy().flatten(), atol=1e-5, rtol=1e-5 ) np.testing.assert_allclose( bn1d.weight.grad.numpy().flatten(), bn2d.weight.grad.numpy().flatten(), atol=1e-5, rtol=1e-5, ) class TestBatchNormUseGlobalStats(unittest.TestCase): def setUp(self): self.places = [] if ( os.environ.get('FLAGS_CI_both_cpu_and_gpu', 'False').lower() in ['1', 'true', 'on'] or not core.is_compiled_with_cuda() ): self.places.append(base.CPUPlace()) if core.is_compiled_with_cuda(): self.places.append(base.CUDAPlace(0)) self.init_test() # train mode def init_test(self): self.use_global_stats = True self.trainable_statistics = False def test_global_stats(self): for p in self.places: with base.dygraph.guard(p): x = paddle.randn([2, 6, 6, 4]) net1 = paddle.nn.BatchNorm( 6, param_attr=base.ParamAttr( initializer=paddle.nn.initializer.Constant(1.0) ), use_global_stats=self.use_global_stats, trainable_statistics=self.trainable_statistics, ) net2 = paddle.nn.BatchNorm2D( 6, use_global_stats=self.use_global_stats ) net2.weight = net1.weight net2.bias = net1.bias if self.trainable_statistics: net1.training = False net2.training = False y1 = net1(x) y2 = net2(x) np.testing.assert_allclose(y1.numpy(), y2.numpy(), rtol=1e-05) class TestBatchNormUseGlobalStatsCase1(TestBatchNormUseGlobalStats): # test mode def init_test(self): self.use_global_stats = False self.trainable_statistics = True class TestBatchNormUseGlobalStatsCase2(TestBatchNormUseGlobalStats): # train mode def init_test(self): self.use_global_stats = False self.trainable_statistics = False class TestBatchNormUseGlobalStatsCase3(TestBatchNormUseGlobalStats): # test mode def init_test(self): self.use_global_stats = True self.trainable_statistics = True if __name__ == '__main__': paddle.enable_static() unittest.main() ```
Plainview is an unincorporated community in Morgan County, Georgia, United States, located approximately three miles from Madison. History Plainview has historically been a farming community. Plainview contains Plainview Baptist Church and Plainview Baptist Church Cemetery. In 1930 and 1934 respectively, artist Benny Andrews and writer Raymond Andrews were born in Plainview. In 1966, Sports Illustrated published an article about the introduction of football to Plainview. In 1979, the Supreme Court of Georgia the upheld the conviction of a person convicted of the murder and armed robbery of John Garrison, who was a grocery store operator in Plainview. Notable people Benny Andrews (1930–2006), painter and printmaker Raymond Andrews (1934–1991), novelist References Unincorporated communities in Morgan County, Georgia Unincorporated communities in Georgia (U.S. state)
Larmin Ousman (born June 15, 1981) is a Liberian former footballer who played for Ljungskile SK. He was a member of the Liberia national football team. External links 1981 births Living people Liberian men's footballers Liberia men's international footballers Men's association football defenders Ljungskile SK players Footballers from Monrovia
Nawfia is a town in Njikoka Local Government Area of Anambra State, Nigeria. Nawfia is surrounded by neighbouring towns namely Enugwu Ukwu, Awka (Umuokpu), Nise, Amawbia and Enugwu Agidi. It is predominantly occupied by the Igbo ethnic group and is believed to be one of the towns that make up the ancestral home of Igbo people. Most of its inhabitants are Traditionalists and Christians (with Anglicians and Roman Catholics making up the vast majority). Igbo, English and Pigeon-English are the predominant languages spoken in Nawfia. The town is made up of two wards which are namely: Ifite (Ward 1) and Ezimezi (Ward 2). The town also compromises of ten villages which include: Adagbe Mmimi, Enugo Mmimi, Eziakpaka, Iridana, Urualor/Uruejimofor, Uruorji, Urukpaleri, Umuriam, Umuezunu and Umukwa. The government presiding and running the affairs of Nawfia are made up of three main authorities namely the Igwe of Nawfia, the President General of Nawfia Progressive Union and the Nze/Ozo Council. The Igwe of Nawfia is the custodian of the culture and traditions and is in charge of security and land matters. The President General is in charge of the general administration of the town (in conjunction with the village Chairmen of each village) and legislative duties. The Nze/Ozo council is a group of "titled" elders who help Igwe to maintain culture and tradition and also resolve conflicts. The immediate past traditional ruler of the town was His Royal Majesty, Igwe Sir F. F. B. C. Nwankwo (Osuofia na Nawfia). The current traditional ruler is His Royal Majesty Dr. Shadrach Moguluwa The immediate past President General was Chief Sir Nonyelu Okoye (Eze Udo). The current President General of Nawfia Progressive Union is Chief Sir Nathan Enemuo (Eze Ego). Nawfia is one of the towns that make up the Umunri clan. Nawfia along with Enugwu Ukwu, Enugwu Agidi, and Agu Ukwu, are widely believed to be where the beginning of Igbo lineage is traced to. According to Igbo folklore, Nawfia (pronounced as Nnọfvịa in the local dialect), was the second son of Nri and a hunter by profession. Nri's father, Eri is widely believed to be the father of all Igbos. References Towns in Anambra State
Fossan is a village in the municipality of Selbu in Trøndelag county, Norway. It is located about north of the municipal center of Mebonden, across the lake Selbusjøen. Fossan is located about halfway between the villages of Selbustrand and Tømra. References Villages in Trøndelag Selbu
Granger is a town along Blacks Fork near the western edge of Sweetwater County, Wyoming, United States. The population was 139 at the 2010 census. It is located near the confluence of the Blacks Fork and the Hams Fork rivers. The geography of the area is flat with semi-arid scrub. Early history: 1834–1868 Although the population has always been small, the site is located at the intersection of the Oregon Trail and the Overland Stage Trail and it was chosen for a stage coach station. The station, which was built of stone and adobe in 1856, was in operation when Mark Twain passed through, and still stands today. The Pony Express used this station as a stopover in 1861-62. Later, in 1868, it became a stop on the railroad, which was when it started to be called Granger. The area of what is present-day Granger had significance to the mountain men who trapped in the early years of the American West. It was chosen as the site of their annual rendezvous in 1834 (the rendezvous was still somewhat spread out, as each supplier set up camp at different location along the river). The American Fur Company, among other suppliers, were present, and American Indians and trappers traded furs for goods. Several weeks were spent recounting events from the previous year and reveling in assorted amusements, while lubricated with liquor. The records show that the event occurred at the junction of the Hams Fork and Blacks Fork rivers. Geography Granger is located at (41.594036, -109.966607). According to the United States Census Bureau, the town has a total area of , all land. Demographics 2010 census As of the census of 2010, there were 139 people, 57 households, and 38 families living in the town. The population density was . There were 72 housing units at an average density of . The racial makeup of the town was 88.5% White, 0.7% African American, 9.4% from other races, and 1.4% from two or more races. Hispanic or Latino of any race were 15.1% of the population. There were 57 households, of which 24.6% had children under the age of 18 living with them, 54.4% were married couples living together, 3.5% had a female householder with no husband present, 8.8% had a male householder with no wife present, and 33.3% were non-families. 21.1% of all households were made up of individuals, and 5.3% had someone living alone who was 65 years of age or older. The average household size was 2.44 and the average family size was 2.82. The median age in the town was 39.5 years. 25.2% of residents were under the age of 18; 5.7% were between the ages of 18 and 24; 23.8% were from 25 to 44; 38.1% were from 45 to 64; and 7.2% were 65 years of age or older. The gender makeup of the town was 54.7% male and 45.3% female. 2000 census As of the census of 2000, there were 146 people, 54 households, and 40 families living in the town. The population density was 59.0 people per square mile (22.8/km2). There were 76 housing units at an average density of 30.7 per square mile (11.9/km2). The racial makeup of the town was 82.19% White, 8.22% from other races, and 9.59% from two or more races. Hispanic or Latino of any race were 22.60% of the population. There were 54 households, out of which 35.2% had children under the age of 18 living with them, 68.5% were married couples living together, 5.6% had a female householder with no husband present, and 25.9% were non-families. 24.1% of all households were made up of individuals, and 5.6% had someone living alone who was 65 years of age or older. The average household size was 2.70 and the average family size was 3.18. In the town, the population was spread out, with 28.8% under the age of 18, 10.3% from 18 to 24, 18.5% from 25 to 44, 33.6% from 45 to 64, and 8.9% who were 65 years of age or older. The median age was 38 years. For every 100 females, there were 100.0 males. For every 100 females age 18 and over, there were 116.7 males. The median income for a household in the town was $46,563, and the median income for a family was $52,083. Males had a median income of $45,750 versus $19,375 for females. The per capita income for the town was $17,764. There were 10.5% of families and 12.3% of the population living below the poverty line, including 5.7% of under eighteens and 21.1% of those over 64. Education Public education in the town of Granger is provided by Sweetwater County School District #2. Granger has a public library, a branch of the Sweetwater County Library System. See also List of municipalities in Wyoming References External links Towns in Sweetwater County, Wyoming Towns in Wyoming Stagecoach stops in the United States Overland Trail
```smalltalk " Abstract superclass for file infos for a FreeType font " Class { #name : 'AbstractFreeTypeFileInfo', #superclass : 'Object', #instVars : [ 'index', 'familyName', 'styleName', 'postscriptName', 'bold', 'italic', 'fixedWidth', 'numFaces', 'familyGroupName', 'slant', 'slantValue', 'weight', 'stretch', 'weightValue', 'stretchValue', 'styleNameExtracted', 'upright' ], #category : 'FreeType-FontManager', #package : 'FreeType', #tag : 'FontManager' } { #category : 'testing' } AbstractFreeTypeFileInfo class >> isAbstract [ ^ self == AbstractFreeTypeFileInfo ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> bold [ "Answer the value of bold" ^ bold ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> bold: anObject [ "Set the value of bold" bold := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> extractAttributesFromNames [ "derive values for the receiver's style(italic), weight, and stretch inst vars. Also set the familyGroupName and styleNameExtracted" | p | p := FreeTypeNameParser new familyNameIn: self validFamilyName; styleNameIn: self validStyleName; italicFlag: italic; boldFlag: bold; parse. familyGroupName := p familyName. slant := p extractedSlant. slantValue := p extractedSlantValue. weight := p extractedWeight. weightValue := p extractedWeightValue. stretch := p extractedStretch. stretchValue := p extractedStretchValue. upright := p extractedUpright. styleNameExtracted := ''. stretch ifNotNil: [ styleNameExtracted := styleNameExtracted , stretch ]. weight ifNotNil: [ styleNameExtracted := styleNameExtracted , ' ' , weight ]. "and:[weight asLowercase ~= 'medium']" slant ifNotNil: [ styleNameExtracted := styleNameExtracted , ' ' , slant ]. styleNameExtracted := styleNameExtracted trimBoth. styleNameExtracted ifEmpty: [ styleNameExtracted := upright ifNil: [ 'Regular' ] ] ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> familyGroupName [ "Answer the value of familyGroupName" ^ familyGroupName ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> familyName [ "Answer the value of familyName" ^ familyName ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> familyName: anObject [ "Set the value of familyName" familyName := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> fixedWidth [ "Answer the value of fixedWidth" ^ fixedWidth ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> fixedWidth: anObject [ "Set the value of fixedWidth" fixedWidth := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> index [ "Answer the value of index" ^ index ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> index: anObject [ "Set the value of index" index := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> isBolderThan: val [ ^self weightValue >= val ] { #category : 'testing' } AbstractFreeTypeFileInfo >> isEmbedded [ ^false ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> isItalicOrOblique [ ^self slantValue > 0 ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> italic [ "Answer the value of italic" ^ italic ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> italic: anObject [ "Set the value of italic" italic := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> numFaces [ "Answer the value of numFaces" ^ numFaces ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> numFaces: anObject [ "Set the value of numFaces" numFaces := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> postscriptName [ "Answer the value of postscriptName" ^ postscriptName ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> postscriptName: anObject [ "Set the value of postscriptName" postscriptName := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> slant [ "Answer the value of slant" ^ slant ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> slantValue [ ^slantValue ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> stretch [ "Answer the value of stretch" ^ stretch ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> stretchValue [ "Answer the value of stretchValue" ^ stretchValue ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> stretchValue: anObject [ "Set the value of stretchValue" stretchValue := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> style [ "Answer the value of slant" ^ slant ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> styleName [ "Answer the value of styleName" ^ styleName ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> styleName: anObject [ "Set the value of styleName" styleName := anObject ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> styleNameExtracted [ ^styleNameExtracted ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> styleNameWithItalicForcedToBe: aString [ | answer | answer := ''. stretch ifNotNil: [ answer := answer , stretch ]. weight ifNotNil: [ answer := answer , ' ' , weight ]. "and:[weight asLowercase ~= 'medium']" answer := answer , ' ' , aString. answer := answer trimBoth. ^ answer ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> styleNameWithWeightForcedToBe: aString [ | answer | answer := ''. stretch ifNotNil:[ answer := answer ,stretch]. answer := answer , ' ', aString. slant ifNotNil:[ answer := answer , ' ', slant]. answer := answer trimBoth. ^answer ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> styleNameWithWeightForcedToBe: aString italicForcedToBe: aString2 [ | answer | answer := ''. stretch ifNotNil:[ answer := answer ,stretch]. answer := answer , ' ', aString. answer := answer , ' ', aString2. answer := answer trimBoth. ^answer ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> validFamilyName [ "answer the receiver's familyName, or an alternative name to use if the familyName is invalid for some reason" (familyName copyWithout: $? ) ifEmpty:[ "workaround problem with FreeType 2.2.1 and MS Gothic, MS Mincho where familyName is not read correctly. This may be fixed in later versions of FreeType" self baseName asUppercase = 'MSGOTHIC' ifTrue:[ index = 0 ifTrue:[^'MS Gothic']. index = 1 ifTrue:[^'MS PGothic']. index = 2 ifTrue:[^'MS UI Gothic']]. self baseName asUppercase = 'MSMINCHO' ifTrue:[ index = 0 ifTrue:[^'MS Mincho']. index = 1 ifTrue:[^'MS PMincho']. ^self baseName asUppercase, ' ', index asString]]. ^familyName ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> validStyleName [ "answer the receiver's styleName, or an alternative name to use if the styleName is invalid for some reason" (styleName copyWithout: $? ) ifEmpty:[ | answer | "workaround problem with FreeType 2.2.1 and MS Gothic, MS Mincho where familyName is not read correctly. This may be fixed in later versions of FreeType" answer := ''. italic ifTrue:[answer := answer , 'Italic ']. bold ifTrue:[answer := answer, 'Bold ']. (italic or:[bold]) not ifTrue:[answer := answer, 'Regular ']. ^answer trimBoth]. ^styleName ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> weight [ "Answer the value of weight" ^ weight ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> weightValue [ "Answer the value of weightValue" ^ weightValue ] { #category : 'accessing' } AbstractFreeTypeFileInfo >> weightValue: anObject [ "Set the value of weightValue" weightValue := anObject ] ```
Young Patriots (in Basque: Gazte Abertzaleak (GA)) is since 1988 the youth wing of the Basque political party Eusko Alkartasuna (EA). Gazte Abertzaleak is a founding member of the EFAY (Youth branch of the European Free Alliance). Gazte Abertzaleak has an ideology in common with Eusko Alkartasuna, but assuming their own position on several issues due to the political autonomy they enjoy. GA is represented in the executive board of every local organization of EA, in regional organizations and its secretary general is full member of the national executive of the mother party Eusko Alkartasuna. Their current secretary general is Andoni Iriondo, elected in 2019 Secretaries general 1988–1990 – Sabin Arana 1990–1992 – Fernando Velasco 1992–1994 – Yon Goikoetxea 1994–1996 – Jon Ander Arrieta 1996–1998 – Peio Urizar 1998–2002 – Martín Arámburu 2002–2004 – Andoni Iturzaeta 2004–2007 – Ibon Usandizaga 2007–2008 – Harkaitz Millan 2008–2009 – Alain Zamorano 2009–2012 – Maider Carrere 2012–2014 – Haritz Perez 2014–2016 – Ibon Garcia 2016–2019 – Asier Gomez 2019–present – Andoni Iriondo Former members Alex Alba Martin Aranburu Ikerne Badiola Mikel Irujo Onintza Lasa Maiorga Ramirez Elisa Sainz de Murieta Pello Urizar Fernando Velasco Maider Carrere Haritz Perez References External links Youth wings of political parties in Spain Basque nationalism
```shell map_version_from_commit() { local commitid=$1 local tag="$(git describe --abbrev=0 --tags ${commitid})" local date="$(git show --pretty=%cd --date=format:%Y%m%d ${commitid} | head -1)" local short_commit="$(git rev-parse --short ${commitid})" printf "${tag}+${date}.git${short_commit}" } libdispatch_version=5.1.5 libobjc2_version=2.1 gnustep_make_version=2.7.0 gnustep_base_version=1.27.0 gnustep_gui_version=0.28.0+nextspace gnustep_back_version=0.28.0+nextspace gorm_version=1.2.26 projectcenter_version=0.6.2 nextspace_version=68055da986c9d4259dbf244e2f77933c9598dd5b ```
```php <?php namespace App\Http\Controllers; use App\Http\Requests; use Goutte\Client; class WebScrapingController extends Controller { protected $crawler; const NEWS_URL = 'path_to_url /** * Initialize controller */ public function __construct() { $this->client = new Client(); } /** * Return all data to the Stripe API dashboard * @return mixed */ public function getPage() { $links = $this->getData(self::NEWS_URL); return view('api.scraping')->withLinks($links); } /** * Scrape the Links * @param $siteToCrawl * @return array */ public function getData($siteToCrawl) { $crawler = $this->client->request('GET', $siteToCrawl); $arr = $crawler->filter('.title a[href^="http"], a[href^="https"]')->each(function($element) { $links = []; array_push($links, $element->text()); return $links; }); return $arr; } } ```
The PEN Translation Prize (formerly known as the PEN/Book-of-the-Month Club Translation Prize through 2008) is an annual award given by PEN America (formerly PEN American Center) to outstanding translations into the English language. It has been presented annually by PEN America and the Book of the Month Club since 1963. It was the first award in the United States expressly for literary translators. A 1999 New York Times article called it "the Academy Award of Translation" and that the award is thus usually not given to younger translators. The distinction comes with a cash prize of USD $3,000. Any book-length English translation published in the United States during the year in question is eligible, irrespective of the residence or nationality of either the translator or the original author. The award is separate from the similar PEN Award for Poetry in Translation. The PEN Translation Prize was called one of "the most prominent translation awards." The award is one of many PEN awards sponsored by International PEN affiliates in over 145 PEN centres around the world. The PEN American Center awards have been characterized as being among the "major" American literary prizes. Winners See also PEN/Heim Translation Fund Grants References External links PEN Translation Prize Translation awards PEN America awards Awards established in 1963 1963 establishments in the United States
Wall rock is the rock that constitutes the wall of an area undergoing geologic activity. Examples are the rock along the neck of a volcano, on the edge of a pluton that is being emplaced, along a fault plane, enclosing a mineral deposit, or where a vein or dike is being emplaced. In volcanoes, wall rock can often become broken off the wall and incorporated into the erupted volcanic rock as xenoliths. These xenoliths are important to geologists because they can come from rock units that are otherwise not exposed at the Earth's surface. See also Country rock (geology) References WordNet Rock formations
```yaml comment: Shows the Rubrik Radar amount of Files Added. commonfields: id: RubrikCDMClusterConnectionState version: -1 dockerimage: demisto/python3:3.10.14.95956 enabled: true name: RubrikCDMClusterConnectionState runas: DBotWeakRole script: '' scripttarget: 0 subtype: python3 tags: - dynamic-section - field-change-triggered type: python fromversion: 6.0.0 tests: - No tests (auto formatted) ```
```go /* path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package fs import ( "fmt" "io/ioutil" "log" "os" "path/filepath" ) var _ FileSystem = realFS{} // realFS implements FileSystem using the local filesystem. type realFS struct{} // MakeRealFS makes an instance of realFS. func MakeRealFS() FileSystem { return realFS{} } // Create delegates to os.Create. func (realFS) Create(name string) (File, error) { return os.Create(name) } // Mkdir delegates to os.Mkdir. func (realFS) Mkdir(name string) error { return os.Mkdir(name, 0777|os.ModeDir) } // MkdirAll delegates to os.MkdirAll. func (realFS) MkdirAll(name string) error { return os.MkdirAll(name, 0777|os.ModeDir) } // RemoveAll delegates to os.RemoveAll. func (realFS) RemoveAll(name string) error { return os.RemoveAll(name) } // Open delegates to os.Open. func (realFS) Open(name string) (File, error) { return os.Open(name) } // CleanedAbs returns a cleaned, absolute path // with no symbolic links split into directory // and file components. If the entire path is // a directory, the file component is an empty // string. func (x realFS) CleanedAbs( path string) (ConfirmedDir, string, error) { absRoot, err := filepath.Abs(path) if err != nil { return "", "", fmt.Errorf( "abs path error on '%s' : %v", path, err) } deLinked, err := filepath.EvalSymlinks(absRoot) if err != nil { return "", "", fmt.Errorf( "evalsymlink failure on '%s' : %v", path, err) } if x.IsDir(deLinked) { return ConfirmedDir(deLinked), "", nil } d := filepath.Dir(deLinked) if !x.IsDir(d) { // Programmer/assumption error. log.Fatalf("first part of '%s' not a directory", deLinked) } if d == deLinked { // Programmer/assumption error. log.Fatalf("d '%s' should be a subset of deLinked", d) } f := filepath.Base(deLinked) if filepath.Join(d, f) != deLinked { // Programmer/assumption error. log.Fatalf("these should be equal: '%s', '%s'", filepath.Join(d, f), deLinked) } return ConfirmedDir(d), f, nil } // Exists returns true if os.Stat succeeds. func (realFS) Exists(name string) bool { _, err := os.Stat(name) return err == nil } // Glob returns the list of matching files func (realFS) Glob(pattern string) ([]string, error) { return filepath.Glob(pattern) } // IsDir delegates to os.Stat and FileInfo.IsDir func (realFS) IsDir(name string) bool { info, err := os.Stat(name) if err != nil { return false } return info.IsDir() } // ReadFile delegates to ioutil.ReadFile. func (realFS) ReadFile(name string) ([]byte, error) { return ioutil.ReadFile(name) } // WriteFile delegates to ioutil.WriteFile with read/write permissions. func (realFS) WriteFile(name string, c []byte) error { return ioutil.WriteFile(name, c, 0666) } ```
```java /* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * * Project Info: path_to_url * * This library is free software; you can redistribute it and/or modify it * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * * You should have received a copy of the GNU Lesser General Public * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * NumberAxisTest.java * ------------------- * * Original Author: David Gilbert; * Contributor(s): -; * */ package org.jfree.chart.axis; import java.awt.geom.Rectangle2D; import java.text.DecimalFormat; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.TestUtils; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.api.RectangleEdge; import org.jfree.chart.internal.CloneUtils; import org.jfree.data.RangeType; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Tests for the {@link NumberAxis} class. */ public class NumberAxisTest { /** * Confirm that cloning works. * * @throws java.lang.CloneNotSupportedException */ @Test public void testCloning() throws CloneNotSupportedException { NumberAxis a1 = new NumberAxis("Test"); NumberAxis a2 = CloneUtils.clone(a1); assertNotSame(a1, a2); assertSame(a1.getClass(), a2.getClass()); assertEquals(a1, a2); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { NumberAxis a1 = new NumberAxis("Test"); NumberAxis a2 = new NumberAxis("Test"); assertEquals(a1, a2); //private boolean autoRangeIncludesZero; a1.setAutoRangeIncludesZero(false); assertNotEquals(a1, a2); a2.setAutoRangeIncludesZero(false); assertEquals(a1, a2); //private boolean autoRangeStickyZero; a1.setAutoRangeStickyZero(false); assertNotEquals(a1, a2); a2.setAutoRangeStickyZero(false); assertEquals(a1, a2); //private NumberTickUnit tickUnit; a1.setTickUnit(new NumberTickUnit(25.0)); assertNotEquals(a1, a2); a2.setTickUnit(new NumberTickUnit(25.0)); assertEquals(a1, a2); //private NumberFormat numberFormatOverride; a1.setNumberFormatOverride(new DecimalFormat("0.00")); assertNotEquals(a1, a2); a2.setNumberFormatOverride(new DecimalFormat("0.00")); assertEquals(a1, a2); a1.setRangeType(RangeType.POSITIVE); assertNotEquals(a1, a2); a2.setRangeType(RangeType.POSITIVE); assertEquals(a1, a2); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashCode() { NumberAxis a1 = new NumberAxis("Test"); NumberAxis a2 = new NumberAxis("Test"); assertEquals(a1, a2); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } private static final double EPSILON = 0.0000001; /** * Test the translation of Java2D values to data values. */ @Test public void testTranslateJava2DToValue() { NumberAxis axis = new NumberAxis(); axis.setRange(50.0, 100.0); Rectangle2D dataArea = new Rectangle2D.Double(10.0, 50.0, 400.0, 300.0); double y1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT); assertEquals(y1, 95.8333333, EPSILON); double y2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertEquals(y2, 95.8333333, EPSILON); double x1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertEquals(x1, 58.125, EPSILON); double x2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertEquals(x2, 58.125, EPSILON); axis.setInverted(true); double y3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT); assertEquals(y3, 54.1666667, EPSILON); double y4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertEquals(y4, 54.1666667, EPSILON); double x3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertEquals(x3, 91.875, EPSILON); double x4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertEquals(x4, 91.875, EPSILON); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { NumberAxis a1 = new NumberAxis("Test Axis"); NumberAxis a2 = TestUtils.serialised(a1); assertEquals(a1, a2); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. */ @Test public void testAutoRange1() { DefaultCategoryDataset<String, String> dataset = new DefaultCategoryDataset<>(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset); CategoryPlot<?, ?> plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); assertEquals(axis.getLowerBound(), 0.0, EPSILON); assertEquals(axis.getUpperBound(), 210.0, EPSILON); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. In this * case, the 'autoRangeIncludesZero' flag is set to false. */ @Test public void testAutoRange2() { DefaultCategoryDataset<String,String> dataset = new DefaultCategoryDataset<>(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createLineChart("Test", "Categories", "Value", dataset, PlotOrientation.VERTICAL, false, false, false); CategoryPlot<?, ?> plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(axis.getLowerBound(), 95.0, EPSILON); assertEquals(axis.getUpperBound(), 205.0, EPSILON); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. In this * case, the 'autoRangeIncludesZero' flag is set to false AND the * original dataset is replaced with a new dataset. */ @Test public void testAutoRange3() { DefaultCategoryDataset<String,String> dataset = new DefaultCategoryDataset<>(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createLineChart("Test", "Categories", "Value", dataset, PlotOrientation.VERTICAL, false, false, false); @SuppressWarnings("unchecked") CategoryPlot<String, String> plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(axis.getLowerBound(), 95.0, EPSILON); assertEquals(axis.getUpperBound(), 205.0, EPSILON); // now replacing the dataset should update the axis range... DefaultCategoryDataset<String,String> dataset2 = new DefaultCategoryDataset<>(); dataset2.setValue(900.0, "Row 1", "Column 1"); dataset2.setValue(1000.0, "Row 1", "Column 2"); plot.setDataset(dataset2); assertEquals(axis.getLowerBound(), 895.0, EPSILON); assertEquals(axis.getUpperBound(), 1005.0, EPSILON); } /** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */ @Test public void testAutoRange4() { DefaultCategoryDataset<String,String> dataset = new DefaultCategoryDataset<>(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset, PlotOrientation.VERTICAL, false, false, false); @SuppressWarnings("unchecked") CategoryPlot<String, String> plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); BarRenderer br = (BarRenderer) plot.getRenderer(); br.setIncludeBaseInRange(false); assertEquals(95.0, axis.getLowerBound(), EPSILON); assertEquals(205.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); axis.setAutoRangeIncludesZero(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); // now replacing the dataset should update the axis range... DefaultCategoryDataset<String,String> dataset2 = new DefaultCategoryDataset<>(); dataset2.setValue(900.0, "Row 1", "Column 1"); dataset2.setValue(1000.0, "Row 1", "Column 2"); plot.setDataset(dataset2); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(1050.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(false); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(1050.0, axis.getUpperBound(), EPSILON); axis.setAutoRangeIncludesZero(false); assertEquals(895.0, axis.getLowerBound(), EPSILON); assertEquals(1005.0, axis.getUpperBound(), EPSILON); } /** * Checks that the auto-range for the domain axis on an XYPlot is * working as expected. */ @Test public void testXYAutoRange1() { XYSeries<String> series = new XYSeries<>("Series 1"); series.add(1.0, 1.0); series.add(2.0, 2.0); series.add(3.0, 3.0); XYSeriesCollection<String> dataset = new XYSeriesCollection<>(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y", dataset); XYPlot<?> plot = (XYPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(0.9, axis.getLowerBound(), EPSILON); assertEquals(3.1, axis.getUpperBound(), EPSILON); } /** * Checks that the auto-range for the range axis on an XYPlot is * working as expected. */ @Test public void testXYAutoRange2() { XYSeries<String> series = new XYSeries<>("Series 1"); series.add(1.0, 1.0); series.add(2.0, 2.0); series.add(3.0, 3.0); XYSeriesCollection<String> dataset = new XYSeriesCollection<>(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y", dataset); XYPlot<?> plot = (XYPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(0.9, axis.getLowerBound(), EPSILON); assertEquals(3.1, axis.getUpperBound(), EPSILON); } // /** // * Some checks for the setRangeType() method. // */ // public void testSetRangeType() { // // NumberAxis axis = new NumberAxis("X"); // axis.setRangeType(RangeType.POSITIVE); // assertEquals(RangeType.POSITIVE, axis.getRangeType()); // // // test a change to RangeType.POSITIVE // axis.setRangeType(RangeType.FULL); // axis.setRange(-5.0, 5.0); // axis.setRangeType(RangeType.POSITIVE); // assertEquals(new Range(0.0, 5.0), axis.getRange()); // // axis.setRangeType(RangeType.FULL); // axis.setRange(-10.0, -5.0); // axis.setRangeType(RangeType.POSITIVE); // assertEquals(new Range(0.0, axis.getAutoRangeMinimumSize()), // axis.getRange()); // // // test a change to RangeType.NEGATIVE // axis.setRangeType(RangeType.FULL); // axis.setRange(-5.0, 5.0); // axis.setRangeType(RangeType.NEGATIVE); // assertEquals(new Range(-5.0, 0.0), axis.getRange()); // // axis.setRangeType(RangeType.FULL); // axis.setRange(5.0, 10.0); // axis.setRangeType(RangeType.NEGATIVE); // assertEquals(new Range(-axis.getAutoRangeMinimumSize(), 0.0), // axis.getRange()); // // // try null // boolean pass = false; // try { // axis.setRangeType(null); // } // catch (IllegalArgumentException e) { // pass = true; // } // assertTrue(pass); // } /** * Some checks for the setLowerBound() method. */ @Test public void testSetLowerBound() { NumberAxis axis = new NumberAxis("X"); axis.setRange(0.0, 10.0); axis.setLowerBound(5.0); assertEquals(5.0, axis.getLowerBound(), EPSILON); axis.setLowerBound(10.0); assertEquals(10.0, axis.getLowerBound(), EPSILON); assertEquals(11.0, axis.getUpperBound(), EPSILON); //axis.setRangeType(RangeType.POSITIVE); //axis.setLowerBound(-5.0); //assertEquals(0.0, axis.getLowerBound(), EPSILON); } } ```
The Beauty of the Rain is the fifth studio album by Dar Williams. Track listing All songs written by Dar Williams, except where noted. "Mercy of the Fallen" – 4:11 "Farewell to the Old Me" – 2:45 "I Saw a Bird Fly Away" – 2:51 "The Beauty of the Rain" – 3:00 "The World's Not Falling Apart" – 4:24 "The One Who Knows" – 3:47 "Closer to Me" (Williams, Rob Hyman) – 3:42 "Fishing in the Morning" – 2:38 "Whispering Pines" (Richard Manuel, Robbie Robertson) – 4:00 "Your Fire Your Soul" – 3:04 "I Have Lost My Dreams" – 3:05 Personnel Dar Williams – guitar, vocals Eric Bazilian – guitar, mandolin Chris Botti – trumpet Cliff Eberhardt – vocals Béla Fleck – banjo Steve Holley – drums Rob Hyman – piano, Hammond organ, production, Wurlitzer, melodica, keyboards, Reed organ Stewart Lerman – bass guitar, guitar, keyboards, engineering, production Michael Kang – violin Alison Krauss – vocals Stefan Lessard – bass guitar David Mansfield – violin John Medeski – piano, clavinet, Hammond organ Sammy Merendino – drums John Popper – harmonica, vocals Steuart Smith – guitar, 12-string guitar, e-bow, piano, Hammond organ, harmonica Paul Sokolow – bass guitar Carol Steele – percussion William Wittman – bass guitar, engineering, mixing 2003 albums Dar Williams albums Razor & Tie albums Albums produced by Rob Hyman Albums produced by Stewart Lerman
```scala /* */ package akka.stream.alpakka.jakartajms import java.util.concurrent.atomic.AtomicBoolean import akka.stream.alpakka.jakartajms.impl.{JmsAckSession, JmsSession} import jakarta.jms import scala.concurrent.{Future, Promise} case class AckEnvelope private[jakartajms] (message: jms.Message, private val jmsSession: JmsAckSession) { val processed = new AtomicBoolean(false) def acknowledge(): Unit = if (processed.compareAndSet(false, true)) jmsSession.ack(message) } case class TxEnvelope private[jakartajms] (message: jms.Message, private val jmsSession: JmsSession) { private[this] val commitPromise = Promise[() => Unit]() private[jakartajms] val commitFuture: Future[() => Unit] = commitPromise.future def commit(): Unit = commitPromise.success(jmsSession.session.commit _) def rollback(): Unit = commitPromise.success(jmsSession.session.rollback _) } ```
```c++ //your_sha256_hash--------------------------------------- //your_sha256_hash--------------------------------------- #include "RuntimeBasePch.h" #include "ThreadServiceWrapper.h" #include "Types/TypePropertyCache.h" #ifdef ENABLE_SCRIPT_DEBUGGING #include "Debug/DebuggingFlags.h" #include "Debug/DiagProbe.h" #include "Debug/DebugManager.h" #endif #include "Chars.h" #include "CaseInsensitive.h" #include "CharSet.h" #include "CharMap.h" #include "StandardChars.h" #include "Base/ThreadContextTlsEntry.h" #include "Base/ThreadBoundThreadContextManager.h" #include "Language/SourceDynamicProfileManager.h" #include "Language/CodeGenRecyclableData.h" #include "Language/InterpreterStackFrame.h" #include "Language/JavascriptStackWalker.h" #include "Base/ScriptMemoryDumper.h" #if DBG #include "Memory/StressTest.h" #endif #ifdef DYNAMIC_PROFILE_MUTATOR #include "Language/DynamicProfileMutator.h" #endif #ifdef ENABLE_BASIC_TELEMETRY #include "Telemetry.h" #include "Recycler/RecyclerTelemetryTransmitter.h" #endif // ENABLE_BASIC_TELEMETRY const int TotalNumberOfBuiltInProperties = Js::PropertyIds::_countJSOnlyProperty; /* * When we aren't adding any additional properties */ void DefaultInitializeAdditionalProperties(ThreadContext *threadContext) { } /* * */ void (*InitializeAdditionalProperties)(ThreadContext *threadContext) = DefaultInitializeAdditionalProperties; CriticalSection ThreadContext::s_csThreadContext; size_t ThreadContext::processNativeCodeSize = 0; ThreadContext * ThreadContext::globalListFirst = nullptr; ThreadContext * ThreadContext::globalListLast = nullptr; THREAD_LOCAL uint ThreadContext::activeScriptSiteCount = 0; const Js::PropertyRecord * const ThreadContext::builtInPropertyRecords[] = { Js::BuiltInPropertyRecords::EMPTY, #define ENTRY_INTERNAL_SYMBOL(n) Js::BuiltInPropertyRecords::n, #define ENTRY_SYMBOL(n, d) Js::BuiltInPropertyRecords::n, #define ENTRY(n) Js::BuiltInPropertyRecords::n, #define ENTRY2(n, s) ENTRY(n) #include "Base/JnDirectFields.h" }; ThreadContext::RecyclableData::RecyclableData(Recycler *const recycler) : pendingFinallyException(nullptr), soErrorObject(nullptr, nullptr, nullptr, true), oomErrorObject(nullptr, nullptr, nullptr, true), terminatedErrorObject(nullptr, nullptr, nullptr), typesWithProtoPropertyCache(recycler), #if ENABLE_NATIVE_CODEGEN propertyGuards(recycler, 128), #endif oldEntryPointInfo(nullptr), #ifdef ENABLE_SCRIPT_DEBUGGING returnedValueList(nullptr), #endif constructorCacheInvalidationCount(0) { } ThreadContext::ThreadContext(AllocationPolicyManager * allocationPolicyManager, JsUtil::ThreadService::ThreadServiceCallback threadServiceCallback, bool enableExperimentalFeatures) : currentThreadId(::GetCurrentThreadId()), stackLimitForCurrentThread(0), stackProber(nullptr), isThreadBound(false), hasThrownPendingException(false), hasBailedOutBitPtr(nullptr), noScriptScope(false), heapEnum(nullptr), threadContextFlags(ThreadContextFlagNoFlag), JsUtil::DoublyLinkedListElement<ThreadContext>(), allocationPolicyManager(allocationPolicyManager), threadService(threadServiceCallback), isOptimizedForManyInstances(Js::Configuration::Global.flags.OptimizeForManyInstances), bgJit(Js::Configuration::Global.flags.BgJit), pageAllocator(allocationPolicyManager, PageAllocatorType_Thread, Js::Configuration::Global.flags, 0, RecyclerHeuristic::Instance.DefaultMaxFreePageCount, false #if ENABLE_BACKGROUND_PAGE_FREEING , &backgroundPageQueue #endif ), recycler(nullptr), hasCollectionCallBack(false), callDispose(true), #if ENABLE_NATIVE_CODEGEN jobProcessor(nullptr), #endif interruptPoller(nullptr), expirableCollectModeGcCount(-1), expirableObjectList(nullptr), expirableObjectDisposeList(nullptr), numExpirableObjects(0), disableExpiration(false), callRootLevel(0), nextTypeId((Js::TypeId)Js::Constants::ReservedTypeIds), entryExitRecord(nullptr), leafInterpreterFrame(nullptr), threadServiceWrapper(nullptr), tryHandlerAddrOfReturnAddr(nullptr), temporaryArenaAllocatorCount(0), temporaryGuestArenaAllocatorCount(0), crefSContextForDiag(0), m_prereservedRegionAddr(0), scriptContextList(nullptr), scriptContextEverRegistered(false), #if DBG_DUMP || defined(PROFILE_EXEC) topLevelScriptSite(nullptr), #endif polymorphicCacheState(0), stackProbeCount(0), #ifdef BAILOUT_INJECTION bailOutByteCodeLocationCount(0), #endif sourceCodeSize(0), nativeCodeSize(0), threadAlloc(_u("TC"), GetPageAllocator(), Js::Throw::OutOfMemory), inlineCacheThreadInfoAllocator(_u("TC-InlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory), isInstInlineCacheThreadInfoAllocator(_u("TC-IsInstInlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory), equivalentTypeCacheInfoAllocator(_u("TC-EquivalentTypeCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory), protoInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 521), storeFieldInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 293), isInstInlineCacheByFunction(&isInstInlineCacheThreadInfoAllocator, 131), registeredInlineCacheCount(0), unregisteredInlineCacheCount(0), noSpecialPropertyRegistry(this->GetPageAllocator()), onlyWritablePropertyRegistry(this->GetPageAllocator()), standardUTF8Chars(0), standardUnicodeChars(0), hasUnhandledException(FALSE), hasCatchHandler(FALSE), disableImplicitFlags(DisableImplicitNoFlag), hasCatchHandlerToUserCode(false), caseInvariantPropertySet(nullptr), entryPointToBuiltInOperationIdCache(&threadAlloc, 0), #if ENABLE_NATIVE_CODEGEN preReservedVirtualAllocator(), #if !FLOATVAR codeGenNumberThreadAllocator(nullptr), xProcNumberPageSegmentManager(nullptr), #endif m_jitNumericProperties(nullptr), m_jitNeedsPropertyUpdate(false), #if DYNAMIC_INTERPRETER_THUNK || defined(ASMJS_PLAT) thunkPageAllocators(allocationPolicyManager, /* allocXData */ false, /* virtualAllocator */ nullptr, GetCurrentProcess()), #endif codePageAllocators(allocationPolicyManager, ALLOC_XDATA, GetPreReservedVirtualAllocator(), GetCurrentProcess()), #if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM) jitThunkEmitter(this, &VirtualAllocWrapper::Instance , GetCurrentProcess()), #endif #endif dynamicObjectEnumeratorCacheMap(&HeapAllocator::Instance, 16), //threadContextFlags(ThreadContextFlagNoFlag), #ifdef NTBUILD telemetryBlock(&localTelemetryBlock), #endif configuration(enableExperimentalFeatures), jsrtRuntime(nullptr), propertyMap(nullptr), rootPendingClose(nullptr), exceptionCode(0), isProfilingUserCode(true), loopDepth(0), redeferralState(InitialRedeferralState), gcSinceLastRedeferral(0), gcSinceCallCountsCollected(0), tridentLoadAddress(nullptr), m_remoteThreadContextInfo(nullptr) #ifdef ENABLE_SCRIPT_DEBUGGING , debugManager(nullptr) #endif #if ENABLE_TTD , TTDContext(nullptr) , TTDExecutionInfo(nullptr) , TTDLog(nullptr) , TTDRootNestingCount(0) #endif #ifdef ENABLE_DIRECTCALL_TELEMETRY , directCallTelemetry(this) #endif #if ENABLE_JS_REENTRANCY_CHECK , noJsReentrancy(false) #endif , emptyStringPropertyRecord(nullptr) , recyclerTelemetryHostInterface(this) , reentrancySafeOrHandled(false) , isInReentrancySafeRegion(false) , closedScriptContextCount(0) , visibilityState(VisibilityState::Undefined) { hostScriptContextStack = Anew(GetThreadAlloc(), JsUtil::Stack<HostScriptContext*>, GetThreadAlloc()); functionCount = 0; sourceInfoCount = 0; #if DBG || defined(RUNTIME_DATA_COLLECTION) scriptContextCount = 0; #endif isScriptActive = false; #ifdef ENABLE_CUSTOM_ENTROPY entropy.Initialize(); #endif #if ENABLE_NATIVE_CODEGEN this->bailOutRegisterSaveSpace = AnewArrayZ(this->GetThreadAlloc(), Js::Var, GetBailOutRegisterSaveSlotCount()); #endif #if DBG_DUMP scriptSiteCount = 0; pageAllocator.debugName = _u("Thread"); #endif #ifdef DYNAMIC_PROFILE_MUTATOR this->dynamicProfileMutator = DynamicProfileMutator::GetMutator(); #endif PERF_COUNTER_INC(Basic, ThreadContext); #ifdef LEAK_REPORT this->rootTrackerScriptContext = nullptr; this->threadId = ::GetCurrentThreadId(); #endif #ifdef NTBUILD memset(&localTelemetryBlock, 0, sizeof(localTelemetryBlock)); #endif AutoCriticalSection autocs(ThreadContext::GetCriticalSection()); ThreadContext::LinkToBeginning(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast); #if DBG // Since we created our page allocator while we were constructing this thread context // it will pick up the thread context id that is current on the thread. We need to update // that now. pageAllocator.UpdateThreadContextHandle((ThreadContextId)this); #endif #if DBG arrayMutationSeed = (Js::Configuration::Global.flags.ArrayMutationTestSeed != 0) ? (uint)Js::Configuration::Global.flags.ArrayMutationTestSeed : (uint)time(NULL); srand(arrayMutationSeed); #endif this->InitAvailableCommit(); } void ThreadContext::InitAvailableCommit() { // Once per process: get the available commit for the process from the OS and push it to the AutoSystemInfo. // (This must be done lazily, outside DllMain. And it must be done from the Runtime, since the common lib // doesn't have access to the DelayLoadLibrary stuff.) ULONG64 commit; BOOL success = AutoSystemInfo::Data.GetAvailableCommit(&commit); if (!success) { commit = (ULONG64)-1; #ifdef NTBUILD APP_MEMORY_INFORMATION AppMemInfo; success = GetWinCoreProcessThreads()->GetProcessInformation( GetCurrentProcess(), ProcessAppMemoryInfo, &AppMemInfo, sizeof(AppMemInfo)); if (success) { commit = AppMemInfo.AvailableCommit; } #endif AutoSystemInfo::Data.SetAvailableCommit(commit); } } void ThreadContext::SetStackProber(StackProber * stackProber) { this->stackProber = stackProber; if (stackProber != NULL && this->stackLimitForCurrentThread != Js::Constants::StackLimitForScriptInterrupt) { this->stackLimitForCurrentThread = stackProber->GetScriptStackLimit(); } } size_t ThreadContext::GetScriptStackLimit() const { return stackProber->GetScriptStackLimit(); } HANDLE ThreadContext::GetProcessHandle() const { return GetCurrentProcess(); } intptr_t ThreadContext::GetThreadStackLimitAddr() const { return (intptr_t)GetAddressOfStackLimitForCurrentThread(); } #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_WASM_SIMD) intptr_t ThreadContext::GetSimdTempAreaAddr(uint8 tempIndex) const { return (intptr_t)&X86_TEMP_SIMD[tempIndex]; } #endif intptr_t ThreadContext::GetDisableImplicitFlagsAddr() const { return (intptr_t)&disableImplicitFlags; } intptr_t ThreadContext::GetImplicitCallFlagsAddr() const { return (intptr_t)&implicitCallFlags; } ptrdiff_t ThreadContext::GetChakraBaseAddressDifference() const { return 0; } ptrdiff_t ThreadContext::GetCRTBaseAddressDifference() const { return 0; } IActiveScriptProfilerHeapEnum* ThreadContext::GetHeapEnum() { return heapEnum; } void ThreadContext::SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum) { Assert((newHeapEnum != nullptr && heapEnum == nullptr) || (newHeapEnum == nullptr && heapEnum != nullptr)); heapEnum = newHeapEnum; } void ThreadContext::ClearHeapEnum() { Assert(heapEnum != nullptr); heapEnum = nullptr; } void ThreadContext::GlobalInitialize() { for (int i = 0; i < _countof(builtInPropertyRecords); i++) { builtInPropertyRecords[i]->SetHash(JsUtil::CharacterBuffer<WCHAR>::StaticGetHashCode(builtInPropertyRecords[i]->GetBuffer(), builtInPropertyRecords[i]->GetLength())); } } ThreadContext::~ThreadContext() { { AutoCriticalSection autocs(ThreadContext::GetCriticalSection()); ThreadContext::Unlink(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast); } #if ENABLE_TTD if(this->TTDContext != nullptr) { TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDContext); this->TTDContext = nullptr; } if(this->TTDExecutionInfo != nullptr) { TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDExecutionInfo); this->TTDExecutionInfo = nullptr; } if(this->TTDLog != nullptr) { TT_HEAP_DELETE(TTD::EventLog, this->TTDLog); this->TTDLog = nullptr; } #endif #ifdef LEAK_REPORT if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag)) { AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): %s (TID: %d)"), this, this->GetRecycler()->IsInDllCanUnloadNow()? _u("DllCanUnloadNow") : this->GetRecycler()->IsInDetachProcess()? _u("DetachProcess") : _u("Destructor"), this->threadId); LeakReport::DumpUrl(this->threadId); } #endif if (interruptPoller) { HeapDelete(interruptPoller); interruptPoller = nullptr; } #if DBG // ThreadContext dtor may be running on a different thread. // Recycler may call finalizer that free temp Arenas, which will free pages back to // the page Allocator, which will try to suspend idle on a different thread. // So we need to disable idle decommit asserts. pageAllocator.ShutdownIdleDecommit(); #endif // Allocating memory during the shutdown codepath is not preferred // so we'll close the page allocator before we release the GC // If any dispose is allocating memory during shutdown, that is a bug pageAllocator.Close(); // The recycler need to delete before the background code gen thread // because that might run finalizer which need access to the background code gen thread. if (recycler != nullptr) { for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next) { if (!scriptContext->IsActuallyClosed()) { // We close ScriptContext here because anyhow HeapDelete(recycler) when disposing the // JavaScriptLibrary will close ScriptContext. Explicit close gives us chance to clear // other things to which ScriptContext holds reference to AssertMsg(!IsInScript(), "Can we be in script here?"); scriptContext->MarkForClose(); } } // If all scriptContext's have been closed, then the sourceProfileManagersByUrl // should have been released AssertMsg(this->recyclableData->sourceProfileManagersByUrl == nullptr || this->recyclableData->sourceProfileManagersByUrl->Count() == 0, "There seems to have been a refcounting imbalance."); this->recyclableData->sourceProfileManagersByUrl = nullptr; this->recyclableData->oldEntryPointInfo = nullptr; if (this->recyclableData->symbolRegistrationMap != nullptr) { this->recyclableData->symbolRegistrationMap->Clear(); this->recyclableData->symbolRegistrationMap = nullptr; } #ifdef ENABLE_SCRIPT_DEBUGGING if (this->recyclableData->returnedValueList != nullptr) { this->recyclableData->returnedValueList->Clear(); this->recyclableData->returnedValueList = nullptr; } #endif if (this->propertyMap != nullptr) { HeapDelete(this->propertyMap); this->propertyMap = nullptr; } #if ENABLE_NATIVE_CODEGEN if (this->m_jitNumericProperties != nullptr) { HeapDelete(this->m_jitNumericProperties); this->m_jitNumericProperties = nullptr; } #endif // Unpin the memory for leak report so we don't report this as a leak. recyclableData.Unroot(recycler); #if defined(LEAK_REPORT) || defined(CHECK_MEMORY_LEAK) for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next) { scriptContext->ClearSourceContextInfoMaps(); scriptContext->ShutdownClearSourceLists(); } #ifdef LEAK_REPORT // heuristically figure out which one is the root tracker script engine // and force close on it if (this->rootTrackerScriptContext != nullptr) { this->rootTrackerScriptContext->Close(false); } #endif #endif #if ENABLE_NATIVE_CODEGEN #if !FLOATVAR if (this->codeGenNumberThreadAllocator) { HeapDelete(this->codeGenNumberThreadAllocator); this->codeGenNumberThreadAllocator = nullptr; } if (this->xProcNumberPageSegmentManager) { HeapDelete(this->xProcNumberPageSegmentManager); this->xProcNumberPageSegmentManager = nullptr; } #endif #endif #ifdef ENABLE_SCRIPT_DEBUGGING Assert(this->debugManager == nullptr); #endif #if ENABLE_CONCURRENT_GC && defined(_WIN32) AssertOrFailFastMsg(recycler->concurrentThread == NULL, "Recycler background thread should have been shutdown before destroying Recycler."); AssertOrFailFastMsg((recycler->parallelThread1.concurrentThread == NULL) && (recycler->parallelThread2.concurrentThread == NULL), "Recycler parallelThread(s) should have been shutdown before destroying Recycler."); #endif HeapDelete(recycler); } #if ENABLE_NATIVE_CODEGEN if(jobProcessor) { if(this->bgJit) { HeapDelete(static_cast<JsUtil::BackgroundJobProcessor *>(jobProcessor)); } else { HeapDelete(static_cast<JsUtil::ForegroundJobProcessor *>(jobProcessor)); } jobProcessor = nullptr; } #endif // Do not require all GC callbacks to be revoked, because Trident may not revoke if there // is a leak, and we don't want the leak to be masked by an assert this->collectCallBackList.Clear(&HeapAllocator::Instance); this->protoInlineCacheByPropId.Reset(); this->storeFieldInlineCacheByPropId.Reset(); this->isInstInlineCacheByFunction.Reset(); this->equivalentTypeCacheEntryPoints.Reset(); this->noSpecialPropertyRegistry.Reset(); this->onlyWritablePropertyRegistry.Reset(); this->registeredInlineCacheCount = 0; this->unregisteredInlineCacheCount = 0; AssertMsg(this->GetHeapEnum() == nullptr, "Heap enumeration should have been cleared/closed by the ScriptSite."); if (this->GetHeapEnum() != nullptr) { this->ClearHeapEnum(); } #ifdef BAILOUT_INJECTION if (Js::Configuration::Global.flags.IsEnabled(Js::BailOutByteCodeFlag) && Js::Configuration::Global.flags.BailOutByteCode.Empty()) { Output::Print(_u("Bail out byte code location count: %d"), this->bailOutByteCodeLocationCount); } #endif Assert(processNativeCodeSize >= nativeCodeSize); ::InterlockedExchangeSubtract(&processNativeCodeSize, nativeCodeSize); PERF_COUNTER_DEC(Basic, ThreadContext); #ifdef DYNAMIC_PROFILE_MUTATOR if (this->dynamicProfileMutator != nullptr) { this->dynamicProfileMutator->Delete(); } #endif } void ThreadContext::SetJSRTRuntime(void* runtime) { Assert(jsrtRuntime == nullptr); jsrtRuntime = runtime; #ifdef ENABLE_BASIC_TELEMETRY Telemetry::EnsureInitializeForJSRT(); #endif } void ThreadContext::CloseForJSRT() { // This is used for JSRT APIs only. Assert(this->jsrtRuntime); #ifdef ENABLE_BASIC_TELEMETRY // log any relevant telemetry before disposing the current thread for cases which are properly shutdown Telemetry::OnJSRTThreadContextClose(); #endif ShutdownThreads(); } ThreadContext* ThreadContext::GetContextForCurrentThread() { ThreadContextTLSEntry * tlsEntry = ThreadContextTLSEntry::GetEntryForCurrentThread(); if (tlsEntry != nullptr) { return static_cast<ThreadContext *>(tlsEntry->GetThreadContext()); } return nullptr; } void ThreadContext::ValidateThreadContext() { #if DBG // verify the runtime pointer is valid. { BOOL found = FALSE; AutoCriticalSection autocs(ThreadContext::GetCriticalSection()); ThreadContext* currentThreadContext = GetThreadContextList(); while (currentThreadContext) { if (currentThreadContext == this) { return; } currentThreadContext = currentThreadContext->Next(); } AssertMsg(found, "invalid thread context"); } #endif } class AutoRecyclerPtr : public AutoPtr<Recycler> { public: AutoRecyclerPtr(Recycler * ptr) : AutoPtr<Recycler>(ptr) {} ~AutoRecyclerPtr() { #if ENABLE_CONCURRENT_GC if (ptr != nullptr) { ptr->ShutdownThread(); } #endif } }; LPFILETIME ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetLastScriptExecutionEndTime() const { #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD) return &(tc->telemetryBlock->lastScriptEndTime); #else return nullptr; #endif } bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitGCTelemetryStats(RecyclerTelemetryInfo& rti) { #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD) return Js::TransmitRecyclerTelemetryStats(rti); #else return false; #endif } bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitHeapUsage(size_t totalHeapBytes, size_t usedHeapBytes, double heapUsedRatio) { #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD) return Js::TransmitRecyclerHeapUsage(totalHeapBytes, usedHeapBytes, heapUsedRatio); #else return false; #endif } bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::IsTelemetryProviderEnabled() const { #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD) return Js::IsTelemetryProviderEnabled(); #else return false; #endif } bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitTelemetryError(const RecyclerTelemetryInfo& rti, const char * msg) { #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD) return Js::TransmitRecyclerTelemetryError(rti, msg); #else return false; #endif } bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::IsThreadBound() const { return this->tc->IsThreadBound(); } DWORD ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetCurrentScriptThreadID() const { return this->tc->GetCurrentThreadId(); } uint ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetClosedContextCount() const { return this->tc->closedScriptContextCount; } Recycler* ThreadContext::EnsureRecycler() { if (recycler == NULL) { AutoRecyclerPtr newRecycler(HeapNew(Recycler, GetAllocationPolicyManager(), &pageAllocator, Js::Throw::OutOfMemory, Js::Configuration::Global.flags, &recyclerTelemetryHostInterface)); newRecycler->Initialize(isOptimizedForManyInstances, &threadService); // use in-thread GC when optimizing for many instances newRecycler->SetCollectionWrapper(this); #if ENABLE_NATIVE_CODEGEN // This may throw, so it needs to be after the recycler is initialized, // otherwise, the recycler dtor may encounter problems #if !FLOATVAR // TODO: we only need one of the following, one for OOP jit and one for in-proc BG JIT AutoPtr<CodeGenNumberThreadAllocator> localCodeGenNumberThreadAllocator( HeapNew(CodeGenNumberThreadAllocator, newRecycler)); AutoPtr<XProcNumberPageSegmentManager> localXProcNumberPageSegmentManager( HeapNew(XProcNumberPageSegmentManager, newRecycler)); #endif #endif this->recyclableData.Root(RecyclerNewZ(newRecycler, RecyclableData, newRecycler), newRecycler); if (this->IsThreadBound()) { newRecycler->SetIsThreadBound(); } // Assign the recycler to the ThreadContext after everything is initialized, because an OOM during initialization would // result in only partial initialization, so the 'recycler' member variable should remain null to cause full // reinitialization when requested later. Anything that happens after the Detach must have special cleanup code. this->recycler = newRecycler.Detach(); try { #ifdef RECYCLER_WRITE_BARRIER #ifdef TARGET_64 if (!RecyclerWriteBarrierManager::OnThreadInit()) { Js::Throw::OutOfMemory(); } #endif #endif this->expirableObjectList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc); this->expirableObjectDisposeList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc); InitializePropertyMaps(); // has many dependencies on the recycler and other members of the thread context #if ENABLE_NATIVE_CODEGEN #if !FLOATVAR this->codeGenNumberThreadAllocator = localCodeGenNumberThreadAllocator.Detach(); this->xProcNumberPageSegmentManager = localXProcNumberPageSegmentManager.Detach(); #endif #endif } catch(...) { // Initialization failed, undo what was done above. Callees that throw must clean up after themselves. if (this->recyclableData != nullptr) { this->recyclableData.Unroot(this->recycler); } { // AutoRecyclerPtr's destructor takes care of shutting down the background thread and deleting the recycler AutoRecyclerPtr recyclerToDelete(this->recycler); this->recycler = nullptr; } throw; } JS_ETW(EventWriteJSCRIPT_GC_INIT(this->recycler, this->GetHiResTimer()->Now())); } #if DBG if (CONFIG_FLAG(RecyclerTest)) { StressTester test(recycler); test.Run(); } #endif return recycler; } Js::PropertyRecord const * ThreadContext::GetPropertyName(Js::PropertyId propertyId) { // This API should only be use on the main thread Assert(GetCurrentThreadContextId() == (ThreadContextId)this); return this->GetPropertyNameImpl<false>(propertyId); } Js::PropertyRecord const * ThreadContext::GetPropertyNameLocked(Js::PropertyId propertyId) { return GetPropertyNameImpl<true>(propertyId); } template <bool locked> Js::PropertyRecord const * ThreadContext::GetPropertyNameImpl(Js::PropertyId propertyId) { //TODO: Remove this when completely transformed to use PropertyRecord*. Currently this is only partially done, // and there are calls to GetPropertyName with InternalPropertyId. if (propertyId >= 0 && Js::IsInternalPropertyId(propertyId)) { return Js::InternalPropertyRecords::GetInternalPropertyName(propertyId); } int propertyIndex = propertyId - Js::PropertyIds::_none; if (propertyIndex < 0 || propertyIndex > propertyMap->GetLastIndex()) { propertyIndex = 0; } const Js::PropertyRecord * propertyRecord = nullptr; if (locked) { propertyMap->LockResize(); } bool found = propertyMap->TryGetValueAt(propertyIndex, &propertyRecord); if (locked) { propertyMap->UnlockResize(); } AssertMsg(found && propertyRecord != nullptr, "using invalid propertyid"); return propertyRecord; } void ThreadContext::FindPropertyRecord(Js::JavascriptString *pstName, Js::PropertyRecord const ** propertyRecord) { pstName->GetPropertyRecord(propertyRecord, true); if (*propertyRecord != nullptr) { return; } // GetString is not guaranteed to be null-terminated, but we explicitly pass length to the next step LPCWCH propertyName = pstName->GetString(); FindPropertyRecord(propertyName, pstName->GetLength(), propertyRecord); if (*propertyRecord) { pstName->CachePropertyRecord(*propertyRecord); } } void ThreadContext::FindPropertyRecord(__in LPCWCH propertyName, __in int propertyNameLength, Js::PropertyRecord const ** propertyRecord) { EnterPinnedScope((volatile void **)propertyRecord); *propertyRecord = FindPropertyRecord(propertyName, propertyNameLength); LeavePinnedScope(); } Js::PropertyRecord const * ThreadContext::GetPropertyRecord(Js::PropertyId propertyId) { return GetPropertyNameLocked(propertyId); } bool ThreadContext::IsNumericProperty(Js::PropertyId propertyId) { return GetPropertyRecord(propertyId)->IsNumeric(); } const Js::PropertyRecord * ThreadContext::FindPropertyRecord(const char16 * propertyName, int propertyNameLength) { // IsDirectPropertyName == 1 char properties && GetEmptyStringPropertyRecord == 0 length if (propertyNameLength < 2) { if (propertyNameLength == 0) { return this->GetEmptyStringPropertyRecord(); } if (IsDirectPropertyName(propertyName, propertyNameLength)) { Js::PropertyRecord const * propertyRecord = propertyNamesDirect[propertyName[0]]; Assert(propertyRecord == propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength))); return propertyRecord; } } return propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength)); } Js::PropertyRecord const * ThreadContext::UncheckedAddPropertyId(__in LPCWSTR propertyName, __in int propertyNameLength, bool bind, bool isSymbol) { return UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), bind, isSymbol); } void ThreadContext::InitializePropertyMaps() { Assert(this->recycler != nullptr); Assert(this->recyclableData != nullptr); Assert(this->propertyMap == nullptr); Assert(this->caseInvariantPropertySet == nullptr); try { this->propertyMap = HeapNew(PropertyMap, &HeapAllocator::Instance, TotalNumberOfBuiltInProperties + 700); this->recyclableData->boundPropertyStrings = RecyclerNew(this->recycler, JsUtil::List<Js::PropertyRecord const*>, this->recycler); memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *)); Js::JavascriptLibrary::InitializeProperties(this); InitializeAdditionalProperties(this); //Js::JavascriptLibrary::InitializeDOMProperties(this); } catch(...) { // Initialization failed, undo what was done above. Callees that throw must clean up after themselves. The recycler will // be trashed, so clear members that point to recyclable memory. Stuff in 'recyclableData' will be taken care of by the // recycler, and the 'recyclableData' instance will be trashed as well. if (this->propertyMap != nullptr) { HeapDelete(this->propertyMap); } this->propertyMap = nullptr; this->caseInvariantPropertySet = nullptr; memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *)); throw; } } void ThreadContext::UncheckedAddBuiltInPropertyId() { for (int i = 0; i < _countof(builtInPropertyRecords); i++) { AddPropertyRecordInternal(builtInPropertyRecords[i]); } } bool ThreadContext::IsDirectPropertyName(const char16 * propertyName, int propertyNameLength) { return ((propertyNameLength == 1) && ((propertyName[0] & 0xFF80) == 0)); } RecyclerWeakReference<const Js::PropertyRecord> * ThreadContext::CreatePropertyRecordWeakRef(const Js::PropertyRecord * propertyRecord) { RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef; if (propertyRecord->IsBound()) { // Create a fake weak ref propertyRecordWeakRef = RecyclerNewLeaf(this->recycler, StaticPropertyRecordReference, propertyRecord); } else { propertyRecordWeakRef = recycler->CreateWeakReferenceHandle(propertyRecord); } return propertyRecordWeakRef; } Js::PropertyRecord const * ThreadContext::UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR> const& propertyName, bool bind, bool isSymbol) { #if ENABLE_TTD if(isSymbol & this->IsRuntimeInTTDMode()) { if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformReplayAction()) { //We reload all properties that occur in the trace so they only way we get here in TTD mode is: //(1) if the program is creating a new symbol (which always gets a fresh id) and we should recreate it or //(2) if it is forcing arguments in debug parse mode (instead of regular which we recorded in) Js::PropertyId propertyId = Js::Constants::NoProperty; this->TTDLog->ReplaySymbolCreationEvent(&propertyId); //Don't recreate the symbol below, instead return the known symbol by looking up on the pid const Js::PropertyRecord* res = this->GetPropertyName(propertyId); AssertMsg(res != nullptr, "This should never happen!!!"); return res; } } #endif this->propertyMap->EnsureCapacity(); // Automatically bind direct (single-character) property names, so that they can be // stored in the direct property table if (IsDirectPropertyName(propertyName.GetBuffer(), propertyName.GetLength())) { bind = true; } // Create the PropertyRecord int length = propertyName.GetLength(); uint bytelength = sizeof(char16) * length; size_t allocLength = bytelength + sizeof(char16) + ( (!isSymbol && length <= 10 && length > 0) ? sizeof(uint32) : 0); // If it's bound, create it in the thread arena, along with a fake weak ref Js::PropertyRecord * propertyRecord; if (bind) { propertyRecord = AnewPlus(GetThreadAlloc(), allocLength, Js::PropertyRecord, propertyName.GetBuffer(), length, bytelength, isSymbol); propertyRecord->isBound = true; } else { propertyRecord = RecyclerNewFinalizedLeafPlus(recycler, allocLength, Js::PropertyRecord, propertyName.GetBuffer(), length, bytelength, isSymbol); } Js::PropertyId propertyId = this->GetNextPropertyId(); #if ENABLE_TTD if(isSymbol & this->IsRuntimeInTTDMode()) { if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformRecordAction()) { this->TTDLog->RecordSymbolCreationEvent(propertyId); } } #endif propertyRecord->pid = propertyId; AddPropertyRecordInternal(propertyRecord); return propertyRecord; } void ThreadContext::AddPropertyRecordInternal(const Js::PropertyRecord * propertyRecord) { // At this point the PropertyRecord is constructed but not added to the map. const char16 * propertyName = propertyRecord->GetBuffer(); int propertyNameLength = propertyRecord->GetLength(); Js::PropertyId propertyId = propertyRecord->GetPropertyId(); Assert(propertyId == GetNextPropertyId()); Assert(!IsActivePropertyId(propertyId)); #if DBG // Only Assert we can't find the property if we are not adding a symbol. // For a symbol, the propertyName is not used and may collide with something in the map already. if (propertyNameLength > 0 && !propertyRecord->IsSymbol()) { Assert(FindPropertyRecord(propertyName, propertyNameLength) == nullptr); } #endif #if ENABLE_TTD if(this->IsRuntimeInTTDMode()) { this->TTDLog->AddPropertyRecord(propertyRecord); } #endif // Add to the map propertyMap->Add(propertyRecord); #if ENABLE_NATIVE_CODEGEN if (m_jitNumericProperties) { if (propertyRecord->IsNumeric()) { m_jitNumericProperties->Set(propertyRecord->GetPropertyId()); m_jitNeedsPropertyUpdate = true; } } #endif PropertyRecordTrace(_u("Added property '%s' at 0x%08x, pid = %d\n"), propertyName, propertyRecord, propertyId); // Do not store the pid for symbols in the direct property name table. // We don't want property ids for symbols to be searchable anyway. if (!propertyRecord->IsSymbol() && IsDirectPropertyName(propertyName, propertyNameLength)) { // Store the pids for single character properties in the propertyNamesDirect array. // This property record should have been created as bound by the caller. Assert(propertyRecord->IsBound()); Assert(propertyNamesDirect[propertyName[0]] == nullptr); propertyNamesDirect[propertyName[0]] = propertyRecord; } if (caseInvariantPropertySet) { AddCaseInvariantPropertyRecord(propertyRecord); } // Check that everything was added correctly #if DBG // Only Assert we can find the property if we are not adding a symbol. // For a symbol, the propertyName is not used and we won't be able to look the pid up via name. if (propertyNameLength && !propertyRecord->IsSymbol()) { Assert(FindPropertyRecord(propertyName, propertyNameLength) == propertyRecord); } // We will still be able to lookup the symbol property by the property id, so go ahead and check that. Assert(GetPropertyName(propertyRecord->GetPropertyId()) == propertyRecord); #endif JS_ETW_INTERNAL(EventWriteJSCRIPT_HOSTING_PROPERTYID_LIST(propertyRecord, propertyRecord->GetBuffer())); } void ThreadContext::AddCaseInvariantPropertyRecord(const Js::PropertyRecord * propertyRecord) { Assert(this->caseInvariantPropertySet != nullptr); // Create a weak reference to the property record here (since we no longer use weak refs in the property map) RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef = CreatePropertyRecordWeakRef(propertyRecord); JsUtil::CharacterBuffer<WCHAR> newPropertyName(propertyRecord->GetBuffer(), propertyRecord->GetLength()); Js::CaseInvariantPropertyListWithHashCode* list; if (!FindExistingPropertyRecord(newPropertyName, &list)) { // This binds all the property string that is key in this map with no hope of reclaiming them // TODO: do better list = RecyclerNew(recycler, Js::CaseInvariantPropertyListWithHashCode, recycler, 1); // Do the add first so that the list is non-empty and we can calculate its hashcode correctly list->Add(propertyRecordWeakRef); // This will calculate the hashcode caseInvariantPropertySet->Add(list); } else { list->Add(propertyRecordWeakRef); } } void ThreadContext::BindPropertyRecord(const Js::PropertyRecord * propertyRecord) { if (!propertyRecord->IsBound()) { Assert(!this->recyclableData->boundPropertyStrings->Contains(propertyRecord)); this->recyclableData->boundPropertyStrings->Add(propertyRecord); // Cast around constness to set propertyRecord as bound const_cast<Js::PropertyRecord *>(propertyRecord)->isBound = true; } } void ThreadContext::GetOrAddPropertyId(_In_ LPCWSTR propertyName, _In_ int propertyNameLength, _Out_ Js::PropertyRecord const ** propertyRecord) { GetOrAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), propertyRecord); } void ThreadContext::GetOrAddPropertyId(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, _Out_ Js::PropertyRecord const ** propRecord) { EnterPinnedScope((volatile void **)propRecord); *propRecord = GetOrAddPropertyRecord(propertyName); LeavePinnedScope(); } const Js::PropertyRecord * ThreadContext::GetOrAddPropertyRecordImpl(JsUtil::CharacterBuffer<char16> propertyName, bool bind) { // Make sure the recycler is around so that we can take weak references to the property strings EnsureRecycler(); const Js::PropertyRecord * propertyRecord; FindPropertyRecord(propertyName.GetBuffer(), propertyName.GetLength(), &propertyRecord); if (propertyRecord == nullptr) { propertyRecord = UncheckedAddPropertyId(propertyName, bind); } else { // PropertyRecord exists, but may not be bound. Bind now if requested. if (bind) { BindPropertyRecord(propertyRecord); } } Assert(propertyRecord != nullptr); Assert(!bind || propertyRecord->IsBound()); return propertyRecord; } void ThreadContext::AddBuiltInPropertyRecord(const Js::PropertyRecord *propertyRecord) { this->AddPropertyRecordInternal(propertyRecord); } BOOL ThreadContext::IsNumericPropertyId(Js::PropertyId propertyId, uint32* value) { if (Js::IsInternalPropertyId(propertyId)) { return false; } Js::PropertyRecord const * propertyRecord = this->GetPropertyName(propertyId); Assert(propertyRecord != nullptr); if (propertyRecord == nullptr || !propertyRecord->IsNumeric()) { return false; } *value = propertyRecord->GetNumericValue(); return true; } bool ThreadContext::IsActivePropertyId(Js::PropertyId pid) { Assert(pid != Js::Constants::NoProperty); if (Js::IsInternalPropertyId(pid)) { return true; } int propertyIndex = pid - Js::PropertyIds::_none; const Js::PropertyRecord * propertyRecord; if (propertyMap->TryGetValueAt(propertyIndex, &propertyRecord) && propertyRecord != nullptr) { return true; } return false; } void ThreadContext::InvalidatePropertyRecord(const Js::PropertyRecord * propertyRecord) { InternalInvalidateProtoTypePropertyCaches(propertyRecord->GetPropertyId()); // use the internal version so we don't check for active property id #if ENABLE_NATIVE_CODEGEN if (propertyRecord->IsNumeric() && m_jitNumericProperties) { m_jitNumericProperties->Clear(propertyRecord->GetPropertyId()); m_jitNeedsPropertyUpdate = true; } #endif this->propertyMap->Remove(propertyRecord); PropertyRecordTrace(_u("Reclaimed property '%s' at 0x%08x, pid = %d\n"), propertyRecord->GetBuffer(), propertyRecord, propertyRecord->GetPropertyId()); } Js::PropertyId ThreadContext::GetNextPropertyId() { return this->propertyMap->GetNextIndex() + Js::PropertyIds::_none; } Js::PropertyId ThreadContext::GetMaxPropertyId() { auto maxPropertyId = this->propertyMap->Count() + Js::InternalPropertyIds::Count; return maxPropertyId; } void ThreadContext::CreateNoCasePropertyMap() { Assert(caseInvariantPropertySet == nullptr); caseInvariantPropertySet = RecyclerNew(recycler, PropertyNoCaseSetType, recycler, 173); // Prevent the set from being reclaimed // Individual items in the set can be reclaimed though since they're lists of weak references // The lists themselves can be reclaimed when all the weak references in them are cleared this->recyclableData->caseInvariantPropertySet = caseInvariantPropertySet; // Note that we are allocating from the recycler below, so we may cause a GC at any time, which // could cause PropertyRecords to be collected and removed from the propertyMap. // Thus, don't use BaseDictionary::Map here, as it cannot tolerate changes while mapping. // Instead, walk the PropertyRecord entries in index order. This will work even if a GC occurs. for (int propertyIndex = 0; propertyIndex <= this->propertyMap->GetLastIndex(); propertyIndex++) { const Js::PropertyRecord * propertyRecord; if (this->propertyMap->TryGetValueAt(propertyIndex, &propertyRecord) && propertyRecord != nullptr) { AddCaseInvariantPropertyRecord(propertyRecord); } } } JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* ThreadContext::FindPropertyIdNoCase(Js::ScriptContext * scriptContext, LPCWSTR propertyName, int propertyNameLength) { return ThreadContext::FindPropertyIdNoCase(scriptContext, JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength)); } JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* ThreadContext::FindPropertyIdNoCase(Js::ScriptContext * scriptContext, JsUtil::CharacterBuffer<WCHAR> const& propertyName) { if (caseInvariantPropertySet == nullptr) { this->CreateNoCasePropertyMap(); } Js::CaseInvariantPropertyListWithHashCode* list; if (FindExistingPropertyRecord(propertyName, &list)) { return list; } return nullptr; } bool ThreadContext::FindExistingPropertyRecord(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, Js::CaseInvariantPropertyListWithHashCode** list) { Js::CaseInvariantPropertyListWithHashCode* l = this->caseInvariantPropertySet->LookupWithKey(propertyName); (*list) = l; return (l != nullptr); } void ThreadContext::CleanNoCasePropertyMap() { if (this->caseInvariantPropertySet != nullptr) { this->caseInvariantPropertySet->MapAndRemoveIf([](Js::CaseInvariantPropertyListWithHashCode* value) -> bool { if (value && value->Count() == 0) { // Remove entry return true; } // Keep entry return false; }); } } void ThreadContext::ForceCleanPropertyMap() { // No-op now that we no longer use weak refs } #if ENABLE_NATIVE_CODEGEN JsUtil::JobProcessor * ThreadContext::GetJobProcessor() { if(bgJit && isOptimizedForManyInstances) { return ThreadBoundThreadContextManager::GetSharedJobProcessor(); } if (!jobProcessor) { if(bgJit && !isOptimizedForManyInstances) { jobProcessor = HeapNew(JsUtil::BackgroundJobProcessor, GetAllocationPolicyManager(), &threadService, false /*disableParallelThreads*/); } else { jobProcessor = HeapNew(JsUtil::ForegroundJobProcessor); } } return jobProcessor; } #endif void ThreadContext::RegisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData) { Assert(codeGenRecyclableData); Assert(recyclableData); // Linking must not be done concurrently with unlinking (caller must use lock) recyclableData->codeGenRecyclableDatas.LinkToEnd(codeGenRecyclableData); } void ThreadContext::UnregisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData) { Assert(codeGenRecyclableData); if(!recyclableData) { // The thread context's recyclable data may have already been released to the recycler if we're shutting down return; } // Unlinking may be done from a background thread, but not concurrently with linking (caller must use lock). Partial unlink // does not zero the previous and next links for the unlinked node so that the recycler can scan through the node from the // main thread. recyclableData->codeGenRecyclableDatas.UnlinkPartial(codeGenRecyclableData); } uint ThreadContext::EnterScriptStart(Js::ScriptEntryExitRecord * record, bool doCleanup) { Recycler * recycler = this->GetRecycler(); Assert(recycler->IsReentrantState()); JS_ETW_INTERNAL(EventWriteJSCRIPT_RUN_START(this,0)); // Increment the callRootLevel early so that Dispose ran during FinishConcurrent will not close the current scriptContext uint oldCallRootLevel = this->callRootLevel++; if (oldCallRootLevel == 0) { Assert(!this->hasThrownPendingException); RECORD_TIMESTAMP(lastScriptStartTime); InterruptPoller *poller = this->interruptPoller; if (poller) { poller->StartScript(); } recycler->SetIsInScript(true); if (doCleanup) { recycler->EnterIdleDecommit(); #if ENABLE_CONCURRENT_GC recycler->FinishConcurrent<FinishConcurrentOnEnterScript>(); #endif if (threadServiceWrapper == NULL) { // Reschedule the next collection at the start of the script. recycler->ScheduleNextCollection(); } } } this->PushEntryExitRecord(record); AssertMsg(!this->IsScriptActive(), "Missing EnterScriptEnd or LeaveScriptStart"); this->isScriptActive = true; recycler->SetIsScriptActive(true); #if DBG_DUMP if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase)) { Output::Trace(Js::RunPhase, _u("%p> EnterScriptStart(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel); Output::Flush(); } #endif return oldCallRootLevel; } void ThreadContext::EnterScriptEnd(Js::ScriptEntryExitRecord * record, bool doCleanup) { #if DBG_DUMP if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase)) { Output::Trace(Js::RunPhase, _u("%p> EnterScriptEnd (%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel); Output::Flush(); } #endif this->PopEntryExitRecord(record); AssertMsg(this->IsScriptActive(), "Missing EnterScriptStart or LeaveScriptEnd"); this->isScriptActive = false; this->GetRecycler()->SetIsScriptActive(false); this->callRootLevel--; #ifdef EXCEPTION_CHECK ExceptionCheck::SetHandledExceptionType(record->handledExceptionType); #endif #ifdef RECYCLER_MEMORY_VERIFY recycler->Verify(Js::RunPhase); #endif if (this->callRootLevel == 0) { RECORD_TIMESTAMP(lastScriptEndTime); this->GetRecycler()->SetIsInScript(false); InterruptPoller *poller = this->interruptPoller; if (poller) { poller->EndScript(); } ClosePendingScriptContexts(); Assert(rootPendingClose == nullptr); if (this->hasThrownPendingException) { // We have some cases where the thread instant of JavascriptExceptionObject // are ignored and not clear. To avoid leaks, clear it here when // we are not in script, where no one should be using these JavascriptExceptionObject this->ClearPendingOOMError(); this->ClearPendingSOError(); this->hasThrownPendingException = false; } delayFreeCallback.ClearAll(); #ifdef ENABLE_DEBUG_CONFIG_OPTIONS if (Js::Configuration::Global.flags.FreeRejittedCode) #endif { // Since we're no longer in script, old entry points can now be collected Js::FunctionEntryPointInfo* current = this->recyclableData->oldEntryPointInfo; this->recyclableData->oldEntryPointInfo = nullptr; // Clear out the next pointers so older entry points wont be held on // as a false positive while (current != nullptr) { Js::FunctionEntryPointInfo* next = current->nextEntryPoint; current->nextEntryPoint = nullptr; current = next; } } if (doCleanup) { ThreadServiceWrapper* threadServiceWrapper = GetThreadServiceWrapper(); if (!threadServiceWrapper || !threadServiceWrapper->ScheduleNextCollectOnExit()) { // Do the idle GC now if we fail schedule one. recycler->CollectNow<CollectOnScriptExit>(); } recycler->LeaveIdleDecommit(); } } if (doCleanup) { PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in EnterScriptEnd: %d\n"), this->recycler->NeedDispose()); this->recycler->FinishDisposeObjectsNow<FinishDispose>(); } JS_ETW_INTERNAL(EventWriteJSCRIPT_RUN_STOP(this,0)); } void ThreadContext::SetForceOneIdleCollection() { ThreadServiceWrapper* threadServiceWrapper = GetThreadServiceWrapper(); if (threadServiceWrapper) { threadServiceWrapper->SetForceOneIdleCollection(); } } bool ThreadContext::IsOnStack(void const *ptr) { if (IS_ASAN_FAKE_STACK_ADDR(ptr)) { return true; } #if defined(_M_IX86) && defined(_MSC_VER) return ptr < (void*)__readfsdword(0x4) && ptr >= (void*)__readfsdword(0xE0C); #elif defined(_M_AMD64) && defined(_MSC_VER) return ptr < (void*)__readgsqword(0x8) && ptr >= (void*)__readgsqword(0x1478); #elif defined(_M_ARM) ULONG lowLimit, highLimit; ::GetCurrentThreadStackLimits(&lowLimit, &highLimit); bool isOnStack = (void*)lowLimit <= ptr && ptr < (void*)highLimit; return isOnStack; #elif defined(_M_ARM64) ULONG64 lowLimit, highLimit; ::GetCurrentThreadStackLimits(&lowLimit, &highLimit); bool isOnStack = (void*)lowLimit <= ptr && ptr < (void*)highLimit; return isOnStack; #elif !defined(_MSC_VER) return ::IsAddressOnStack((ULONG_PTR) ptr); #else AssertMsg(FALSE, "IsOnStack -- not implemented yet case"); Js::Throw::NotImplemented(); return false; #endif } size_t ThreadContext::GetStackLimitForCurrentThread() const { FAULTINJECT_SCRIPT_TERMINATION; size_t limit = this->stackLimitForCurrentThread; Assert(limit == Js::Constants::StackLimitForScriptInterrupt || !this->GetStackProber() || limit == this->GetStackProber()->GetScriptStackLimit()); return limit; } void ThreadContext::SetStackLimitForCurrentThread(size_t limit) { this->stackLimitForCurrentThread = limit; } _NOINLINE //Win8 947081: might use wrong _AddressOfReturnAddress() if this and caller are inlined bool ThreadContext::IsStackAvailable(size_t size, bool* isInterrupt) { size_t sp = (size_t)_AddressOfReturnAddress(); size_t stackLimit = this->GetStackLimitForCurrentThread(); bool stackAvailable = (sp > size && (sp - size) > stackLimit); // Verify that JIT'd frames didn't mess up the ABI stack alignment Assert(((uintptr_t)sp & (AutoSystemInfo::StackAlign - 1)) == (sizeof(void*) & (AutoSystemInfo::StackAlign - 1))); #if DBG this->GetStackProber()->AdjustKnownStackLimit(sp, size); #endif FAULTINJECT_STACK_PROBE if (stackAvailable) { return true; } if (sp <= stackLimit) { if (stackLimit == Js::Constants::StackLimitForScriptInterrupt) { if (sp <= this->GetStackProber()->GetScriptStackLimit()) { // Take down the process if we cant recover from the stack overflow Js::Throw::FatalInternalError(); } if (isInterrupt) { *isInterrupt = true; // when stack not available, indicate if due to script interrupt } } } return false; } _NOINLINE //Win8 947081: might use wrong _AddressOfReturnAddress() if this and caller are inlined bool ThreadContext::IsStackAvailableNoThrow(size_t size) { size_t sp = (size_t)_AddressOfReturnAddress(); size_t stackLimit = this->GetStackLimitForCurrentThread(); bool stackAvailable = (sp > stackLimit) && (sp > size) && ((sp - size) > stackLimit); FAULTINJECT_STACK_PROBE return stackAvailable; } /* static */ bool ThreadContext::IsCurrentStackAvailable(size_t size) { ThreadContext *currentContext = GetContextForCurrentThread(); Assert(currentContext); return currentContext->IsStackAvailable(size); } /* returnAddress will be passed in the stackprobe call at the beginning of interpreter frame. We need to probe the stack before we link up the InterpreterFrame structure in threadcontext, and if we throw there, the stack walker might get confused when trying to identify a frame is interpreter frame by comparing the current ebp in ebp chain with return address specified in the last InterpreterFrame linked in threadcontext. We need to pass in the return address of the probing frame to skip the right one (we need to skip first match in a->a->a recursion, but not in a->b->a recursion). */ void ThreadContext::ProbeStackNoDispose(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress) { AssertCanHandleStackOverflow(); if (!this->IsStackAvailable(size)) { if (this->IsExecutionDisabled()) { // The probe failed because we hammered the stack limit to trigger script interrupt. Assert(this->DoInterruptProbe()); throw Js::ScriptAbortException(); } Js::Throw::StackOverflow(scriptContext, returnAddress); } #if defined(NTBUILD) || defined(__IOS__) || defined(__ANDROID__) // Use every Nth stack probe as a QC trigger. if (AutoSystemInfo::ShouldQCMoreFrequently() && this->HasInterruptPoller() && this->IsScriptActive()) { ++(this->stackProbeCount); if (this->stackProbeCount > ThreadContext::StackProbePollThreshold) { this->stackProbeCount = 0; this->CheckInterruptPoll(); } } #endif } void ThreadContext::ProbeStack(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress) { this->ProbeStackNoDispose(size, scriptContext, returnAddress); #if PERFMAP_TRACE_ENABLED if (PlatformAgnostic::PerfTrace::mapsRequested) { PlatformAgnostic::PerfTrace::WritePerfMap(); } #endif // BACKGROUND-GC TODO: If we're stuck purely in JITted code, we should have the // background GC thread modify the threads stack limit to trigger the runtime stack probe if (this->callDispose) { PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in ProbeStack: %d\n"), this->recycler->NeedDispose()); this->recycler->FinishDisposeObjectsNow<FinishDisposeTimed>(); } } void ThreadContext::ProbeStack(size_t size, Js::RecyclableObject * obj, Js::ScriptContext *scriptContext) { AssertCanHandleStackOverflowCall(obj->IsExternal() || (Js::JavascriptOperators::GetTypeId(obj) == Js::TypeIds_Function && Js::VarTo<Js::JavascriptFunction>(obj)->IsExternalFunction())); if (!this->IsStackAvailable(size)) { if (this->IsExecutionDisabled()) { // The probe failed because we hammered the stack limit to trigger script interrupt. Assert(this->DoInterruptProbe()); throw Js::ScriptAbortException(); } if (obj->IsExternal() || (Js::JavascriptOperators::GetTypeId(obj) == Js::TypeIds_Function && Js::VarTo<Js::JavascriptFunction>(obj)->IsExternalFunction())) { Js::JavascriptError::ThrowStackOverflowError(scriptContext); } Js::Throw::StackOverflow(scriptContext, NULL); } } void ThreadContext::ProbeStack(size_t size) { Assert(this->IsScriptActive()); Js::ScriptEntryExitRecord *entryExitRecord = this->GetScriptEntryExit(); Assert(entryExitRecord); Js::ScriptContext *scriptContext = entryExitRecord->scriptContext; Assert(scriptContext); this->ProbeStack(size, scriptContext); } /* static */ void ThreadContext::ProbeCurrentStack(size_t size, Js::ScriptContext *scriptContext) { Assert(scriptContext != nullptr); Assert(scriptContext->GetThreadContext() == GetContextForCurrentThread()); scriptContext->GetThreadContext()->ProbeStack(size, scriptContext); } /* static */ void ThreadContext::ProbeCurrentStackNoDispose(size_t size, Js::ScriptContext *scriptContext) { Assert(scriptContext != nullptr); Assert(scriptContext->GetThreadContext() == GetContextForCurrentThread()); scriptContext->GetThreadContext()->ProbeStackNoDispose(size, scriptContext); } template <bool leaveForHost> void ThreadContext::LeaveScriptStart(void * frameAddress) { Assert(this->IsScriptActive()); #if DBG_DUMP if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase)) { Output::Trace(Js::RunPhase, _u("%p> LeaveScriptStart(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel); Output::Flush(); } #endif Js::ScriptEntryExitRecord * entryExitRecord = this->GetScriptEntryExit(); AssertMsg(entryExitRecord && entryExitRecord->frameIdOfScriptExitFunction == nullptr, "Missing LeaveScriptEnd or EnterScriptStart"); entryExitRecord->frameIdOfScriptExitFunction = frameAddress; this->isScriptActive = false; this->GetRecycler()->SetIsScriptActive(false); AssertMsg(!(leaveForHost && this->IsDisableImplicitCall()), "Disable implicit call should have been caught before leaving script for host"); // Save the implicit call flags entryExitRecord->savedImplicitCallFlags = this->GetImplicitCallFlags(); // clear the hasReentered to detect if we have reentered into script entryExitRecord->hasReentered = false; #if DBG || defined(PROFILE_EXEC) entryExitRecord->leaveForHost = leaveForHost; #endif #if DBG entryExitRecord->leaveForAsyncHostOperation = false; #endif #ifdef PROFILE_EXEC if (leaveForHost) { entryExitRecord->scriptContext->ProfileEnd(Js::RunPhase); } #endif } void ThreadContext::DisposeOnLeaveScript() { PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in LeaveScriptStart: %d\n"), this->recycler->NeedDispose()); if (this->callDispose && !recycler->IsCollectionDisabled()) { this->recycler->FinishDisposeObjectsNow<FinishDispose>(); } } template <bool leaveForHost> void ThreadContext::LeaveScriptEnd(void * frameAddress) { Assert(!this->IsScriptActive()); #if DBG_DUMP if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase)) { Output::Trace(Js::RunPhase, _u("%p> LeaveScriptEnd(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel); Output::Flush(); } #endif Js::ScriptEntryExitRecord * entryExitRecord = this->GetScriptEntryExit(); AssertMsg(entryExitRecord && entryExitRecord->frameIdOfScriptExitFunction, "LeaveScriptEnd without LeaveScriptStart"); AssertMsg(frameAddress == nullptr || frameAddress == entryExitRecord->frameIdOfScriptExitFunction, "Mismatched script exit frames"); Assert(!!entryExitRecord->leaveForHost == leaveForHost); entryExitRecord->frameIdOfScriptExitFunction = nullptr; AssertMsg(!this->IsScriptActive(), "Missing LeaveScriptStart or LeaveScriptStart"); this->isScriptActive = true; this->GetRecycler()->SetIsScriptActive(true); Js::ImplicitCallFlags savedImplicitCallFlags = entryExitRecord->savedImplicitCallFlags; if (leaveForHost) { savedImplicitCallFlags = (Js::ImplicitCallFlags)(savedImplicitCallFlags | Js::ImplicitCall_External); } else if (entryExitRecord->hasReentered) { savedImplicitCallFlags = (Js::ImplicitCallFlags)(savedImplicitCallFlags | Js::ImplicitCall_AsyncHostOperation); } // Restore the implicit call flags this->SetImplicitCallFlags(savedImplicitCallFlags); #ifdef PROFILE_EXEC if (leaveForHost) { entryExitRecord->scriptContext->ProfileBegin(Js::RunPhase); } #endif } // explicit instantiations template void ThreadContext::LeaveScriptStart<true>(void * frameAddress); template void ThreadContext::LeaveScriptStart<false>(void * frameAddress); template void ThreadContext::LeaveScriptEnd<true>(void * frameAddress); template void ThreadContext::LeaveScriptEnd<false>(void * frameAddress); void ThreadContext::PushInterpreterFrame(Js::InterpreterStackFrame *interpreterFrame) { interpreterFrame->SetPreviousFrame(this->leafInterpreterFrame); this->leafInterpreterFrame = interpreterFrame; } Js::InterpreterStackFrame * ThreadContext::PopInterpreterFrame() { Js::InterpreterStackFrame *interpreterFrame = this->leafInterpreterFrame; Assert(interpreterFrame); this->leafInterpreterFrame = interpreterFrame->GetPreviousFrame(); return interpreterFrame; } BOOL ThreadContext::ExecuteRecyclerCollectionFunctionCommon(Recycler * recycler, CollectionFunction function, CollectionFlags flags) { return __super::ExecuteRecyclerCollectionFunction(recycler, function, flags); } #if DBG bool ThreadContext::IsInAsyncHostOperation() const { if (!this->IsScriptActive()) { Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord; if (lastRecord != NULL) { return !!lastRecord->leaveForAsyncHostOperation; } } return false; } #endif #if ENABLE_NATIVE_CODEGEN void ThreadContext::SetJITConnectionInfo(HANDLE processHandle, void* serverSecurityDescriptor, UUID connectionId) { Assert(JITManager::GetJITManager()->IsOOPJITEnabled()); if (!JITManager::GetJITManager()->IsConnected()) { // TODO: return HRESULT JITManager::GetJITManager()->ConnectRpcServer(processHandle, serverSecurityDescriptor, connectionId); } } bool ThreadContext::EnsureJITThreadContext(bool allowPrereserveAlloc) { #if ENABLE_OOP_NATIVE_CODEGEN Assert(JITManager::GetJITManager()->IsOOPJITEnabled()); if (!JITManager::GetJITManager()->IsConnected()) { return false; } if (m_remoteThreadContextInfo) { return true; } ThreadContextDataIDL contextData; contextData.threadStackLimitAddr = reinterpret_cast<intptr_t>(GetAddressOfStackLimitForCurrentThread()); contextData.bailOutRegisterSaveSpaceAddr = (intptr_t)bailOutRegisterSaveSpace; contextData.disableImplicitFlagsAddr = (intptr_t)GetAddressOfDisableImplicitFlags(); contextData.implicitCallFlagsAddr = (intptr_t)GetAddressOfImplicitCallFlags(); contextData.scriptStackLimit = GetScriptStackLimit(); contextData.isThreadBound = IsThreadBound(); contextData.allowPrereserveAlloc = allowPrereserveAlloc; #if defined(ENABLE_WASM_SIMD) && (_M_IX86 || _M_AMD64) contextData.simdTempAreaBaseAddr = (intptr_t)GetSimdTempArea(); #endif m_jitNumericProperties = HeapNew(BVSparse<HeapAllocator>, &HeapAllocator::Instance); for (auto iter = propertyMap->GetIterator(); iter.IsValid(); iter.MoveNext()) { if (iter.CurrentKey()->IsNumeric()) { m_jitNumericProperties->Set(iter.CurrentKey()->GetPropertyId()); m_jitNeedsPropertyUpdate = true; } } HRESULT hr = JITManager::GetJITManager()->InitializeThreadContext( &contextData, &m_remoteThreadContextInfo, &m_prereservedRegionAddr, &m_jitThunkStartAddr); JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate); // Initialize mutable ThreadContext state if needed Js::TypeId wellKnownType = this->wellKnownHostTypeIds[WellKnownHostType_HTMLAllCollection]; if (m_remoteThreadContextInfo && wellKnownType != Js::TypeIds_Undefined) { hr = JITManager::GetJITManager()->SetWellKnownHostTypeId(m_remoteThreadContextInfo, wellKnownType); JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate); } return m_remoteThreadContextInfo != nullptr; #endif } #endif #if ENABLE_TTD void ThreadContext::InitTimeTravel(ThreadContext* threadContext, void* runtimeHandle, uint32 snapInterval, uint32 snapHistoryLength) { TTDAssert(!this->IsRuntimeInTTDMode(), "We should only init once."); this->TTDContext = HeapNew(TTD::ThreadContextTTD, this, runtimeHandle, snapInterval, snapHistoryLength); this->TTDLog = HeapNew(TTD::EventLog, this); } void ThreadContext::InitHostFunctionsAndTTData(bool record, bool replay, bool debug, size_t optTTUriLength, const char* optTTUri, TTD::TTDOpenResourceStreamCallback openResourceStreamfp, TTD::TTDReadBytesFromStreamCallback readBytesFromStreamfp, TTD::TTDWriteBytesToStreamCallback writeBytesToStreamfp, TTD::TTDFlushAndCloseStreamCallback flushAndCloseStreamfp, TTD::TTDCreateExternalObjectCallback createExternalObjectfp, TTD::TTDCreateJsRTContextCallback createJsRTContextCallbackfp, TTD::TTDReleaseJsRTContextCallback releaseJsRTContextCallbackfp, TTD::TTDSetActiveJsRTContext setActiveJsRTContextfp) { AssertMsg(this->IsRuntimeInTTDMode(), "Need to call init first."); this->TTDContext->TTDataIOInfo = { openResourceStreamfp, readBytesFromStreamfp, writeBytesToStreamfp, flushAndCloseStreamfp, 0, nullptr }; this->TTDContext->TTDExternalObjectFunctions = { createExternalObjectfp, createJsRTContextCallbackfp, releaseJsRTContextCallbackfp, setActiveJsRTContextfp }; if(record) { TTDAssert(optTTUri == nullptr, "No URI is needed in record mode (the host explicitly provides it when writing."); this->TTDLog->InitForTTDRecord(debug); } else { TTDAssert(optTTUri != nullptr, "We need a URI in replay mode so we can initialize the log from it"); this->TTDLog->InitForTTDReplay(this->TTDContext->TTDataIOInfo, optTTUri, optTTUriLength, debug); this->sourceInfoCount = this->TTDLog->GetSourceInfoCount(); } #if !ENABLE_TTD_DIAGNOSTICS_TRACING if(debug) { #endif TTD::TTInnerLoopLastStatementInfo lsi; TTD::TTDebuggerSourceLocation dsl; this->TTDLog->LoadLastSourceLineInfo(lsi, dsl); this->TTDExecutionInfo = HeapNew(TTD::ExecutionInfoManager, lsi); if(dsl.HasValue()) { this->TTDExecutionInfo->SetPendingTTDToTarget(dsl); } #if !ENABLE_TTD_DIAGNOSTICS_TRACING } #endif } #endif BOOL ThreadContext::ExecuteRecyclerCollectionFunction(Recycler * recycler, CollectionFunction function, CollectionFlags flags) { // If the thread context doesn't have an associated Recycler set, don't do anything if (this->recycler == nullptr) { return FALSE; } // Take etw rundown lock on this thread context. We can't collect entryPoints if we are in etw rundown. AutoCriticalSection autocs(this->GetFunctionBodyLock()); // Disable calling dispose from leave script or the stack probe // while we're executing the recycler wrapper AutoRestoreValue<bool> callDispose(&this->callDispose, false); BOOL ret = FALSE; #if ENABLE_TTD // //TODO: We lose any events that happen in the callbacks (such as JsRelease) which may be a problem in the future. // It may be possible to defer the collection of these objects to an explicit collection at the yield loop (same for weak set/map). // We already indirectly do this for ScriptContext collection (but that is buggy so needs to be fixed too). // if(this->IsRuntimeInTTDMode()) { this->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionTTAction); } #endif if (!this->IsScriptActive()) { Assert(!this->IsDisableImplicitCall() || this->IsInAsyncHostOperation()); ret = this->ExecuteRecyclerCollectionFunctionCommon(recycler, function, flags); // Make sure that we finish a collect that is activated outside of script, since // we won't have exit script to schedule it if (!this->IsInScript() && recycler->CollectionInProgress() && ((flags & CollectOverride_DisableIdleFinish) == 0) && threadServiceWrapper) { threadServiceWrapper->ScheduleFinishConcurrent(); } } else { void * frameAddr = nullptr; GET_CURRENT_FRAME_ID(frameAddr); // We may need stack to call out from Dispose or QC if (!this->IsDisableImplicitCall()) // otherwise Dispose/QC disabled { // If we don't have stack space to call out from Dispose or QC, // don't throw, simply return false. This gives SnailAlloc a better // chance of allocating in low stack-space situations (like allocating // a StackOverflowException object) if (!this->IsStackAvailableNoThrow(Js::Constants::MinStackCallout)) { return false; } } this->LeaveScriptStart<false>(frameAddr); ret = this->ExecuteRecyclerCollectionFunctionCommon(recycler, function, flags); this->LeaveScriptEnd<false>(frameAddr); // After OOM changed to fatal error, this throw still exists on allocation path if (this->callRootLevel != 0) { this->CheckScriptInterrupt(); } } #if ENABLE_TTD if(this->IsRuntimeInTTDMode()) { this->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionTTAction); } #endif return ret; } void ThreadContext::DisposeObjects(Recycler * recycler) { if (this->IsDisableImplicitCall()) { // Don't dispose objects when implicit calls are disabled, since disposing may cause implicit calls. Objects will remain // in the dispose queue and will be disposed later when implicit calls are not disabled. return; } // We shouldn't DisposeObjects in NoScriptScope as this might lead to script execution. // Callers of DisposeObjects should ensure !IsNoScriptScope() before calling DisposeObjects. if (this->IsNoScriptScope()) { FromDOM_NoScriptScope_unrecoverable_error(); } if (!this->IsScriptActive()) { __super::DisposeObjects(recycler); } else { void * frameAddr = nullptr; GET_CURRENT_FRAME_ID(frameAddr); // We may need stack to call out from Dispose // This code path is not in GC on allocation code path any more, it's OK to throw here this->ProbeStack(Js::Constants::MinStackCallout); this->LeaveScriptStart<false>(frameAddr); __super::DisposeObjects(recycler); this->LeaveScriptEnd<false>(frameAddr); } } void ThreadContext::PushEntryExitRecord(Js::ScriptEntryExitRecord * record) { AssertMsg(record, "Didn't provide a script entry record to push"); Assert(record->next == nullptr); Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord; if (lastRecord != nullptr) { // If we enter script again, we should have leave with leaveForHost or leave for dispose. Assert(lastRecord->leaveForHost || lastRecord->leaveForAsyncHostOperation); lastRecord->hasReentered = true; record->next = lastRecord; // these are on stack, which grows down. if this condition doesn't hold, // then the list somehow got messed up if ( #if defined(JSRT_VERIFY_RUNTIME_STATE) || defined(DEBUG) !IsOnStack(lastRecord) || #endif ((uintptr_t)record >= (uintptr_t)lastRecord && !IS_ASAN_FAKE_STACK_ADDR(record) && !IS_ASAN_FAKE_STACK_ADDR(lastRecord))) { EntryExitRecord_Corrupted_unrecoverable_error(); } } this->entryExitRecord = record; } void ThreadContext::PopEntryExitRecord(Js::ScriptEntryExitRecord * record) { AssertMsg(record && record == this->entryExitRecord, "Mismatch script entry/exit"); // these are on stack, which grows down. if this condition doesn't hold, // then the list somehow got messed up Js::ScriptEntryExitRecord * next = this->entryExitRecord->next; if (next && ( #if defined(JSRT_VERIFY_RUNTIME_STATE) || defined(DEBUG) !IsOnStack(next) || #endif ((uintptr_t)this->entryExitRecord >= (uintptr_t)next && !IS_ASAN_FAKE_STACK_ADDR(this->entryExitRecord) && !IS_ASAN_FAKE_STACK_ADDR(next)))) { EntryExitRecord_Corrupted_unrecoverable_error(); } this->entryExitRecord = next; } BOOL ThreadContext::ReserveStaticTypeIds(__in int first, __in int last) { if ( nextTypeId <= first ) { nextTypeId = (Js::TypeId) last; return TRUE; } else { return FALSE; } } Js::TypeId ThreadContext::ReserveTypeIds(int count) { Js::TypeId firstTypeId = nextTypeId; nextTypeId = (Js::TypeId)(nextTypeId + count); return firstTypeId; } Js::TypeId ThreadContext::CreateTypeId() { return nextTypeId = (Js::TypeId)(nextTypeId + 1); } void ThreadContext::SetWellKnownHostTypeId(WellKnownHostType wellKnownType, Js::TypeId typeId) { AssertMsg(wellKnownType <= WellKnownHostType_Last, "ThreadContext::SetWellKnownHostTypeId called on unknown type"); if (wellKnownType >= 0 && wellKnownType <= WellKnownHostType_Last) { this->wellKnownHostTypeIds[wellKnownType] = typeId; #if ENABLE_NATIVE_CODEGEN // The jit server really only needs to know about WellKnownHostType_HTMLAllCollection if (this->m_remoteThreadContextInfo && wellKnownType == WellKnownHostType_HTMLAllCollection) { HRESULT hr = JITManager::GetJITManager()->SetWellKnownHostTypeId(this->m_remoteThreadContextInfo, (int)typeId); JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate); } #endif } } #ifdef ENABLE_SCRIPT_DEBUGGING void ThreadContext::EnsureDebugManager() { if (this->debugManager == nullptr) { this->debugManager = HeapNew(Js::DebugManager, this, this->GetAllocationPolicyManager()); } InterlockedIncrement(&crefSContextForDiag); Assert(this->debugManager != nullptr); } void ThreadContext::ReleaseDebugManager() { Assert(crefSContextForDiag > 0); Assert(this->debugManager != nullptr); LONG lref = InterlockedDecrement(&crefSContextForDiag); if (lref == 0) { if (this->recyclableData != nullptr) { this->recyclableData->returnedValueList = nullptr; } if (this->debugManager != nullptr) { this->debugManager->Close(); HeapDelete(this->debugManager); this->debugManager = nullptr; } } } #endif Js::TempArenaAllocatorObject * ThreadContext::GetTemporaryAllocator(LPCWSTR name) { AssertCanHandleOutOfMemory(); if (temporaryArenaAllocatorCount != 0) { temporaryArenaAllocatorCount--; Js::TempArenaAllocatorObject * allocator = recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount]; recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount] = nullptr; return allocator; } return Js::TempArenaAllocatorObject::Create(this); } void ThreadContext::ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject * tempAllocator) { if (temporaryArenaAllocatorCount < MaxTemporaryArenaAllocators) { tempAllocator->GetAllocator()->Reset(); recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount] = tempAllocator; temporaryArenaAllocatorCount++; return; } tempAllocator->Dispose(false); } Js::TempGuestArenaAllocatorObject * ThreadContext::GetTemporaryGuestAllocator(LPCWSTR name) { AssertCanHandleOutOfMemory(); if (temporaryGuestArenaAllocatorCount != 0) { temporaryGuestArenaAllocatorCount--; Js::TempGuestArenaAllocatorObject * allocator = recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount]; allocator->AdviseInUse(); recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount] = nullptr; return allocator; } return Js::TempGuestArenaAllocatorObject::Create(this); } void ThreadContext::ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject * tempGuestAllocator) { if (temporaryGuestArenaAllocatorCount < MaxTemporaryArenaAllocators) { tempGuestAllocator->AdviseNotInUse(); recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount] = tempGuestAllocator; temporaryGuestArenaAllocatorCount++; return; } tempGuestAllocator->Dispose(false); } void ThreadContext::AddToPendingScriptContextCloseList(Js::ScriptContext * scriptContext) { Assert(scriptContext != nullptr); if (rootPendingClose == nullptr) { rootPendingClose = scriptContext; return; } // Prepend to the list. scriptContext->SetNextPendingClose(rootPendingClose); rootPendingClose = scriptContext; } void ThreadContext::RemoveFromPendingClose(Js::ScriptContext * scriptContext) { Assert(scriptContext != nullptr); if (rootPendingClose == nullptr) { // We already sent a close message, ignore the notification. return; } // Base case: The root is being removed. Move the root along. if (scriptContext == rootPendingClose) { rootPendingClose = rootPendingClose->GetNextPendingClose(); return; } Js::ScriptContext * currScriptContext = rootPendingClose; Js::ScriptContext * nextScriptContext = nullptr; while (currScriptContext) { nextScriptContext = currScriptContext->GetNextPendingClose(); if (!nextScriptContext) { break; } if (nextScriptContext == scriptContext) { // The next pending close ScriptContext is the one to be removed - set prev->next to next->next currScriptContext->SetNextPendingClose(nextScriptContext->GetNextPendingClose()); return; } currScriptContext = nextScriptContext; } // We expect to find scriptContext in the pending close list. Assert(false); } void ThreadContext::ClosePendingScriptContexts() { Js::ScriptContext * scriptContext = rootPendingClose; if (scriptContext == nullptr) { return; } Js::ScriptContext * nextScriptContext; do { nextScriptContext = scriptContext->GetNextPendingClose(); scriptContext->Close(false); scriptContext = nextScriptContext; } while (scriptContext); rootPendingClose = nullptr; } void ThreadContext::RegisterScriptContext(Js::ScriptContext *scriptContext) { // NOTE: ETW rundown thread may be reading the scriptContextList concurrently. We don't need to // lock access because we only insert to the front here. scriptContext->next = this->scriptContextList; if (this->scriptContextList) { Assert(this->scriptContextList->prev == NULL); this->scriptContextList->prev = scriptContext; } scriptContext->prev = NULL; this->scriptContextList = scriptContext; if(NoJIT()) { scriptContext->ForceNoNative(); } if (NoDynamicThunks()) { scriptContext->ForceNoDynamicThunks(); } #if DBG || defined(RUNTIME_DATA_COLLECTION) scriptContextCount++; #endif scriptContextEverRegistered = true; } void ThreadContext::UnregisterScriptContext(Js::ScriptContext *scriptContext) { // NOTE: ETW rundown thread may be reading the scriptContextList concurrently. Since this function // is only called by ~ScriptContext() which already synchronized to ETW rundown, we are safe here. if (scriptContext == this->scriptContextList) { Assert(scriptContext->prev == NULL); this->scriptContextList = scriptContext->next; } else { scriptContext->prev->next = scriptContext->next; } if (scriptContext->next) { scriptContext->next->prev = scriptContext->prev; } scriptContext->prev = nullptr; scriptContext->next = nullptr; #if DBG || defined(RUNTIME_DATA_COLLECTION) scriptContextCount--; #endif } ThreadContext::CollectCallBack * ThreadContext::AddRecyclerCollectCallBack(RecyclerCollectCallBackFunction callback, void * context) { AutoCriticalSection autocs(&csCollectionCallBack); CollectCallBack * collectCallBack = this->collectCallBackList.PrependNode(&HeapAllocator::Instance); collectCallBack->callback = callback; collectCallBack->context = context; this->hasCollectionCallBack = true; return collectCallBack; } void ThreadContext::RemoveRecyclerCollectCallBack(ThreadContext::CollectCallBack * collectCallBack) { AutoCriticalSection autocs(&csCollectionCallBack); this->collectCallBackList.RemoveElement(&HeapAllocator::Instance, collectCallBack); this->hasCollectionCallBack = !this->collectCallBackList.Empty(); } void ThreadContext::PreCollectionCallBack(CollectionFlags flags) { #ifdef PERF_COUNTERS PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: deferparse - # of func: %d # deferparsed: %d\n"), PerfCounter::CodeCounterSet::GetTotalFunctionCounter().GetValue(), PerfCounter::CodeCounterSet::GetDeferredFunctionCounter().GetValue()); #endif // This needs to be done before ClearInlineCaches since that method can empty the list of // script contexts with inline caches this->ClearScriptContextCaches(); // Clear up references to types to avoid keeping them alive this->noSpecialPropertyRegistry.Clear(); this->onlyWritablePropertyRegistry.Clear(); // Clean up unused memory before we start collecting this->CleanNoCasePropertyMap(); this->TryEnterExpirableCollectMode(); const BOOL concurrent = flags & CollectMode_Concurrent; const BOOL partial = flags & CollectMode_Partial; if (!partial) { // Integrate allocated pages from background JIT threads #if ENABLE_NATIVE_CODEGEN #if !FLOATVAR if (codeGenNumberThreadAllocator) { codeGenNumberThreadAllocator->Integrate(); } if (this->xProcNumberPageSegmentManager) { this->xProcNumberPageSegmentManager->Integrate(); } #endif #endif } RecyclerCollectCallBackFlags callBackFlags = (RecyclerCollectCallBackFlags) ((concurrent ? Collect_Begin_Concurrent : Collect_Begin) | (partial? Collect_Begin_Partial : Collect_Begin)); CollectionCallBack(callBackFlags); } void ThreadContext::PreSweepCallback() { CollectionCallBack(Collect_Begin_Sweep); #ifdef PERSISTENT_INLINE_CACHES ClearInlineCachesWithDeadWeakRefs(); #else ClearInlineCaches(); #endif ClearIsInstInlineCaches(); ClearEquivalentTypeCaches(); ClearEnumeratorCaches(); this->dynamicObjectEnumeratorCacheMap.Clear(); } void ThreadContext::PreRescanMarkCallback() { // If this feature is turned off or if we're already in profile collection mode, do nothing // We also do nothing if expiration is explicitly disabled by someone lower down the stack if (!PHASE_OFF1(Js::ExpirableCollectPhase) && InExpirableCollectMode() && !this->disableExpiration) { this->DoExpirableCollectModeStackWalk(); } } void ThreadContext::DoExpirableCollectModeStackWalk() { if (this->entryExitRecord != nullptr) { // If we're in script, we will do a stack walk, find the JavascriptFunction's on the stack // and mark their entry points as being used so that we don't prematurely expire them Js::ScriptContext* topScriptContext = this->entryExitRecord->scriptContext; Js::JavascriptStackWalker walker(topScriptContext, TRUE); Js::JavascriptFunction* javascriptFunction = nullptr; while (walker.GetCallerWithoutInlinedFrames(&javascriptFunction)) { if (javascriptFunction != nullptr && Js::ScriptFunction::Test(javascriptFunction)) { Js::ScriptFunction* scriptFunction = (Js::ScriptFunction*) javascriptFunction; scriptFunction->GetFunctionBody()->MapEntryPoints([](int index, Js::FunctionEntryPointInfo* entryPoint){ entryPoint->SetIsObjectUsed(); }); // Make sure we marked the current one when iterating all entry points Js::ProxyEntryPointInfo* entryPointInfo = scriptFunction->GetEntryPointInfo(); Assert(entryPointInfo == nullptr || !entryPointInfo->IsFunctionEntryPointInfo() || ((Js::FunctionEntryPointInfo*)entryPointInfo)->IsObjectUsed()); } } } } void ThreadContext::CollectionCallBack(RecyclerCollectCallBackFlags flags) { DListBase<CollectCallBack>::Iterator i(&this->collectCallBackList); while (i.Next()) { i.Data().callback(i.Data().context, flags); } } void ThreadContext::WaitCollectionCallBack() { // Avoid taking the lock if there are no call back if (hasCollectionCallBack) { AutoCriticalSection autocs(&csCollectionCallBack); CollectionCallBack(Collect_Wait); } } void ThreadContext::PostCollectionCallBack() { CollectionCallBack(Collect_End); TryExitExpirableCollectMode(); // Recycler is null in the case where the ThreadContext is in the process of creating the recycler and // we have a GC triggered (say because the -recyclerStress flag is passed in) if (this->recycler != NULL) { if (this->recycler->InCacheCleanupCollection()) { this->recycler->ClearCacheCleanupCollection(); for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next) { scriptContext->CleanupWeakReferenceDictionaries(); } } } } void ThreadContext::PostSweepRedeferralCallBack() { if (this->DoTryRedeferral()) { HRESULT hr = S_OK; BEGIN_TRANSLATE_OOM_TO_HRESULT { this->TryRedeferral(); } END_TRANSLATE_OOM_TO_HRESULT(hr); } this->UpdateRedeferralState(); } bool ThreadContext::DoTryRedeferral() const { if (PHASE_FORCE1(Js::RedeferralPhase) || PHASE_STRESS1(Js::RedeferralPhase)) { return true; } if (PHASE_OFF1(Js::RedeferralPhase)) { return false; } switch (this->redeferralState) { case InitialRedeferralState: return false; case StartupRedeferralState: return gcSinceCallCountsCollected >= StartupRedeferralInactiveThreshold; case MainRedeferralState: return gcSinceCallCountsCollected >= MainRedeferralInactiveThreshold; default: Assert(0); return false; }; } void ThreadContext::OnScanStackCallback(void ** stackTop, size_t byteCount, void ** registers, size_t registersByteCount) { // Scan the stack to match with current list of delayed free buffer. For those which are not found on the stack // will be released (ref-count decremented) if (!this->delayFreeCallback.HasAnyItem()) { return; } this->delayFreeCallback.ScanStack(stackTop, byteCount, registers, registersByteCount); } bool ThreadContext::DoRedeferFunctionBodies() const { #if ENABLE_TTD if (this->IsRuntimeInTTDMode()) { return false; } #endif if (PHASE_FORCE1(Js::RedeferralPhase) || PHASE_STRESS1(Js::RedeferralPhase)) { return true; } if (PHASE_OFF1(Js::RedeferralPhase)) { return false; } switch (this->redeferralState) { case InitialRedeferralState: return false; case StartupRedeferralState: return gcSinceLastRedeferral >= StartupRedeferralCheckInterval; case MainRedeferralState: return gcSinceLastRedeferral >= MainRedeferralCheckInterval; default: Assert(0); return false; }; } uint ThreadContext::GetRedeferralCollectionInterval() const { switch(this->redeferralState) { case InitialRedeferralState: return InitialRedeferralDelay; case StartupRedeferralState: return StartupRedeferralCheckInterval; case MainRedeferralState: return MainRedeferralCheckInterval; default: Assert(0); return (uint)-1; } } uint ThreadContext::GetRedeferralInactiveThreshold() const { switch(this->redeferralState) { case InitialRedeferralState: return InitialRedeferralDelay; case StartupRedeferralState: return StartupRedeferralInactiveThreshold; case MainRedeferralState: return MainRedeferralInactiveThreshold; default: Assert(0); return (uint)-1; } } void ThreadContext::TryRedeferral() { bool doRedefer = this->DoRedeferFunctionBodies(); // Collect the set of active functions. ActiveFunctionSet *pActiveFuncs = nullptr; if (doRedefer) { pActiveFuncs = Anew(this->GetThreadAlloc(), ActiveFunctionSet, this->GetThreadAlloc()); this->GetActiveFunctions(pActiveFuncs); #if DBG this->redeferredFunctions = 0; this->recoveredBytes = 0; #endif } uint inactiveThreshold = this->GetRedeferralInactiveThreshold(); Js::ScriptContext *scriptContext; for (scriptContext = GetScriptContextList(); scriptContext; scriptContext = scriptContext->next) { if (scriptContext->IsClosed()) { continue; } scriptContext->RedeferFunctionBodies(pActiveFuncs, inactiveThreshold); } if (pActiveFuncs) { Adelete(this->GetThreadAlloc(), pActiveFuncs); #if DBG if (PHASE_STATS1(Js::RedeferralPhase) && this->redeferredFunctions) { Output::Print(_u("Redeferred: %d, Bytes: 0x%x\n"), this->redeferredFunctions, this->recoveredBytes); } #endif } } void ThreadContext::GetActiveFunctions(ActiveFunctionSet * pActiveFuncs) { if (!this->IsInScript() || this->entryExitRecord == nullptr) { return; } Js::JavascriptStackWalker walker(GetScriptContextList(), TRUE, NULL, true); Js::JavascriptFunction *function = nullptr; while (walker.GetCallerWithoutInlinedFrames(&function)) { if (function->GetFunctionInfo()->HasBody()) { Js::FunctionBody *body = function->GetFunctionInfo()->GetFunctionBody(); body->UpdateActiveFunctionSet(pActiveFuncs, nullptr); } } } void ThreadContext::UpdateRedeferralState() { uint inactiveThreshold = this->GetRedeferralInactiveThreshold(); uint collectInterval = this->GetRedeferralCollectionInterval(); if (this->gcSinceCallCountsCollected >= inactiveThreshold) { this->gcSinceCallCountsCollected = 0; if (this->gcSinceLastRedeferral >= collectInterval) { // Advance state switch (this->redeferralState) { case InitialRedeferralState: this->redeferralState = StartupRedeferralState; break; case StartupRedeferralState: this->redeferralState = MainRedeferralState; break; case MainRedeferralState: break; default: Assert(0); break; } this->gcSinceLastRedeferral = 0; } } else { this->gcSinceCallCountsCollected++; this->gcSinceLastRedeferral++; } } void ThreadContext::PreDisposeObjectsCallBack() { this->expirableObjectDisposeList->Clear(); } #ifdef FAULT_INJECTION void ThreadContext::DisposeScriptContextByFaultInjectionCallBack() { if (FAULTINJECT_SCRIPT_TERMINATION_ON_DISPOSE) { int scriptContextToClose = -1; /* inject only if we have more than 1 script context*/ uint totalScriptCount = GetScriptContextCount(); if (totalScriptCount > 1) { if (Js::Configuration::Global.flags.FaultInjectionScriptContextToTerminateCount > 0) { scriptContextToClose = Js::Configuration::Global.flags.FaultInjectionScriptContextToTerminateCount % totalScriptCount; for (Js::ScriptContext *scriptContext = GetScriptContextList(); scriptContext; scriptContext = scriptContext->next) { if (scriptContextToClose-- == 0) { scriptContext->DisposeScriptContextByFaultInjection(); break; } } } else { fwprintf(stderr, _u("***FI: FaultInjectionScriptContextToTerminateCount Failed, Value should be > 0. \n")); } } } } #endif #pragma region "Expirable Object Methods" void ThreadContext::TryExitExpirableCollectMode() { // If this feature is turned off or if we're already in profile collection mode, do nothing // We also do nothing if expiration is explicitly disabled by someone lower down the stack if (PHASE_OFF1(Js::ExpirableCollectPhase) || !InExpirableCollectMode() || this->disableExpiration) { return; } if (InExpirableCollectMode()) { OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Checking to see whether to complete Expirable Object Collection: GC Count is %d\n"), this->expirableCollectModeGcCount); if (this->expirableCollectModeGcCount > 0) { this->expirableCollectModeGcCount--; } if (this->expirableCollectModeGcCount == 0 && (this->recycler->InCacheCleanupCollection() || CONFIG_FLAG(ForceExpireOnNonCacheCollect))) { OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Completing Expirable Object Collection\n")); ExpirableObjectList::Iterator expirableObjectIterator(this->expirableObjectList); while (expirableObjectIterator.Next()) { ExpirableObject* object = expirableObjectIterator.Data(); Assert(object); if (!object->IsObjectUsed()) { object->Expire(); } } // Leave expirable collection mode expirableCollectModeGcCount = -1; } } } bool ThreadContext::InExpirableCollectMode() { // We're in expirable collect if we have expirable objects registered, // and expirableCollectModeGcCount is not negative // and when debugger is attaching, it might have set the function to deferredParse. return (expirableObjectList != nullptr && numExpirableObjects > 0 && expirableCollectModeGcCount >= 0 #ifdef ENABLE_SCRIPT_DEBUGGING && (this->GetDebugManager() != nullptr && !this->GetDebugManager()->IsDebuggerAttaching()) #endif ); } void ThreadContext::TryEnterExpirableCollectMode() { // If this feature is turned off or if we're already in profile collection mode, do nothing if (PHASE_OFF1(Js::ExpirableCollectPhase) || InExpirableCollectMode()) { OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Not running Expirable Object Collection\n")); return; } double entryPointCollectionThreshold = Js::Configuration::Global.flags.ExpirableCollectionTriggerThreshold / 100.0; double currentThreadNativeCodeRatio = ((double) GetCodeSize()) / Js::Constants::MaxThreadJITCodeHeapSize; OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Current native code ratio: %f\n"), currentThreadNativeCodeRatio); if (currentThreadNativeCodeRatio > entryPointCollectionThreshold) { OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Setting up Expirable Object Collection\n")); this->expirableCollectModeGcCount = Js::Configuration::Global.flags.ExpirableCollectionGCCount; ExpirableObjectList::Iterator expirableObjectIterator(this->expirableObjectList); while (expirableObjectIterator.Next()) { ExpirableObject* object = expirableObjectIterator.Data(); Assert(object); object->EnterExpirableCollectMode(); } } } void ThreadContext::RegisterExpirableObject(ExpirableObject* object) { Assert(this->expirableObjectList); Assert(object->GetRegistrationHandle() == nullptr); ExpirableObject** registrationData = this->expirableObjectList->PrependNode(); (*registrationData) = object; object->SetRegistrationHandle((void*) registrationData); OUTPUT_VERBOSE_TRACE(Js::ExpirableCollectPhase, _u("Registered 0x%p\n"), object); numExpirableObjects++; } void ThreadContext::UnregisterExpirableObject(ExpirableObject* object) { Assert(this->expirableObjectList); Assert(object->GetRegistrationHandle() != nullptr); ExpirableObject** registrationData = (ExpirableObject**)PointerValue(object->GetRegistrationHandle()); Assert(*registrationData == object); this->expirableObjectList->MoveElementTo(registrationData, this->expirableObjectDisposeList); object->ClearRegistrationHandle(); OUTPUT_VERBOSE_TRACE(Js::ExpirableCollectPhase, _u("Unregistered 0x%p\n"), object); numExpirableObjects--; } #pragma endregion void ThreadContext::ClearScriptContextCaches() { for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext != nullptr; scriptContext = scriptContext->next) { scriptContext->ClearScriptContextCaches(); } } #ifdef PERSISTENT_INLINE_CACHES void ThreadContext::ClearInlineCachesWithDeadWeakRefs() { #if ENABLE_DEBUG_CONFIG_OPTIONS || defined(ENABLE_JS_ETW) size_t allocatedSize = 0; size_t preClearFreeListSize = 0; size_t freeListSize = 0; size_t polyInlineCacheSize = 0; uint scriptContextCount = 0; // Note: this event is not meaningful for MemGC, only Chakra JS_ETW(EventWriteJSCRIPT_GC_CLEAR_INLINECACHE_START()); #endif for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext != nullptr; scriptContext = scriptContext->next) { #if ENABLE_DEBUG_CONFIG_OPTIONS || defined(ENABLE_JS_ETW) scriptContextCount++; allocatedSize += scriptContext->GetInlineCacheAllocator()->AllocatedSize(); preClearFreeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize(); #endif scriptContext->ClearInlineCachesWithDeadWeakRefs(); #if ENABLE_DEBUG_CONFIG_OPTIONS || defined(ENABLE_JS_ETW) freeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize();; polyInlineCacheSize += scriptContext->GetInlineCacheAllocator()->GetPolyInlineCacheSize(); #endif } JS_ETW(EventWriteJSCRIPT_GC_CLEAR_INLINECACHE_STOP(this, scriptContextCount, (uint) allocatedSize, (uint) preClearFreeListSize, (uint) freeListSize, (uint) polyInlineCacheSize)); #if ENABLE_DEBUG_CONFIG_OPTIONS if (PHASE_TRACE1(Js::InlineCachePhase)) { Output::Print(_u("Inline cache arena: total = %5I64u KB, free list = %5I64u KB, poly caches = %5I64u KB, script contexts = %u\n"), static_cast<uint64>(allocatedSize / 1024), static_cast<uint64>(freeListSize / 1024), static_cast<uint64>(polyInlineCacheSize / 1024), scriptContextCount); } #endif } #if ENABLE_NATIVE_CODEGEN void ThreadContext::ClearInvalidatedUniqueGuards() { // If a propertyGuard was invalidated, make sure to remove it's entry from unique property guard table of other property records. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards; guards.Map([this](Js::PropertyRecord const * propertyRecord, PropertyGuardEntry* entry, const RecyclerWeakReference<const Js::PropertyRecord>* weakRef) { entry->uniqueGuards.MapAndRemoveIf([=](RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef) { Js::PropertyGuard* guard = guardWeakRef->Get(); bool shouldRemove = guard != nullptr && !guard->IsValid(); if (shouldRemove) { if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"), propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue()); Output::Flush(); } if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"), propertyRecord->GetBuffer(), guard->GetValue()); Output::Flush(); } } return shouldRemove; }); }); } #endif void ThreadContext::ClearInlineCaches() { if (PHASE_TRACE1(Js::InlineCachePhase)) { size_t size = 0; size_t freeListSize = 0; size_t polyInlineCacheSize = 0; uint scriptContextCount = 0; for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next) { scriptContextCount++; size += scriptContext->GetInlineCacheAllocator()->AllocatedSize(); freeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize(); #ifdef POLY_INLINE_CACHE_SIZE_STATS polyInlineCacheSize += scriptContext->GetInlineCacheAllocator()->GetPolyInlineCacheSize(); #endif }; Output::Print(_u("Inline cache arena: total = %5I64u KB, free list = %5I64u KB, poly caches = %5I64u KB, script contexts = %u\n"), static_cast<uint64>(size / 1024), static_cast<uint64>(freeListSize / 1024), static_cast<uint64>(polyInlineCacheSize / 1024), scriptContextCount); } Js::ScriptContext *scriptContext = this->scriptContextList; while (scriptContext != nullptr) { scriptContext->ClearInlineCaches(); scriptContext = scriptContext->next; } inlineCacheThreadInfoAllocator.Reset(); protoInlineCacheByPropId.ResetNoDelete(); storeFieldInlineCacheByPropId.ResetNoDelete(); registeredInlineCacheCount = 0; unregisteredInlineCacheCount = 0; } #endif //PERSISTENT_INLINE_CACHES void ThreadContext::ClearIsInstInlineCaches() { Js::ScriptContext *scriptContext = this->scriptContextList; while (scriptContext != nullptr) { scriptContext->ClearIsInstInlineCaches(); scriptContext = scriptContext->next; } isInstInlineCacheThreadInfoAllocator.Reset(); isInstInlineCacheByFunction.ResetNoDelete(); } void ThreadContext::ClearEnumeratorCaches() { Js::ScriptContext *scriptContext = this->scriptContextList; while (scriptContext != nullptr) { scriptContext->ClearEnumeratorCaches(); scriptContext = scriptContext->next; } } void ThreadContext::ClearEquivalentTypeCaches() { #if ENABLE_NATIVE_CODEGEN // Called from PreSweepCallback to clear pointers to types that have no live object references left. // The EquivalentTypeCache used to keep these types alive, but this caused memory growth in cases where // entry points stayed around for a long time. // In future we may want to pin the reference/guard type to the entry point, but that choice will depend // on a use case where pinning the type helps us optimize. Lacking that, clearing the guard type is a // simpler short-term solution. // Note that clearing unmarked types from the cache and guard is needed for correctness if the cache doesn't keep // the types alive. FOREACH_DLISTBASE_ENTRY_EDITING(Js::EntryPointInfo *, entryPoint, &equivalentTypeCacheEntryPoints, iter) { bool isLive = entryPoint->ClearEquivalentTypeCaches(); if (!isLive) { iter.RemoveCurrent(&equivalentTypeCacheInfoAllocator); } } NEXT_DLISTBASE_ENTRY_EDITING; // Note: Don't reset the list, because we're only clearing the dead types from these caches. // There may still be type references we need to keep an eye on. #endif } Js::EntryPointInfo ** ThreadContext::RegisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo * entryPoint) { return equivalentTypeCacheEntryPoints.PrependNode(&equivalentTypeCacheInfoAllocator, entryPoint); } void ThreadContext::UnregisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo ** entryPoint) { equivalentTypeCacheEntryPoints.RemoveElement(&equivalentTypeCacheInfoAllocator, entryPoint); } void ThreadContext::RegisterProtoInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId) { if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase)) { Output::Print(_u("InlineCacheInvalidation: registering proto cache 0x%p for property %s(%u)\n"), inlineCache, GetPropertyName(propertyId)->GetBuffer(), propertyId); Output::Flush(); } RegisterInlineCache(protoInlineCacheByPropId, inlineCache, propertyId); } void ThreadContext::RegisterStoreFieldInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId) { if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase)) { Output::Print(_u("InlineCacheInvalidation: registering store field cache 0x%p for property %s(%u)\n"), inlineCache, GetPropertyName(propertyId)->GetBuffer(), propertyId); Output::Flush(); } RegisterInlineCache(storeFieldInlineCacheByPropId, inlineCache, propertyId); } void ThreadContext::RegisterInlineCache(InlineCacheListMapByPropertyId& inlineCacheMap, Js::InlineCache * inlineCache, Js::PropertyId propertyId) { InlineCacheList* inlineCacheList; if (!inlineCacheMap.TryGetValue(propertyId, &inlineCacheList)) { inlineCacheList = Anew(&this->inlineCacheThreadInfoAllocator, InlineCacheList, &this->inlineCacheThreadInfoAllocator); inlineCacheMap.AddNew(propertyId, inlineCacheList); } Js::InlineCache** inlineCacheRef = inlineCacheList->PrependNode(); Assert(inlineCacheRef != nullptr); *inlineCacheRef = inlineCache; inlineCache->invalidationListSlotPtr = inlineCacheRef; this->registeredInlineCacheCount++; } void ThreadContext::NotifyInlineCacheBatchUnregistered(uint count) { this->unregisteredInlineCacheCount += count; // Negative or 0 InlineCacheInvalidationListCompactionThreshold forces compaction all the time. if (CONFIG_FLAG(InlineCacheInvalidationListCompactionThreshold) <= 0 || this->registeredInlineCacheCount / this->unregisteredInlineCacheCount < (uint)CONFIG_FLAG(InlineCacheInvalidationListCompactionThreshold)) { CompactInlineCacheInvalidationLists(); } } void ThreadContext::InvalidateProtoInlineCaches(Js::PropertyId propertyId) { InlineCacheList* inlineCacheList; if (protoInlineCacheByPropId.TryGetValueAndRemove(propertyId, &inlineCacheList)) { if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase)) { Output::Print(_u("InlineCacheInvalidation: invalidating proto caches for property %s(%u)\n"), GetPropertyName(propertyId)->GetBuffer(), propertyId); Output::Flush(); } InvalidateAndDeleteInlineCacheList(inlineCacheList); } } void ThreadContext::InvalidateStoreFieldInlineCaches(Js::PropertyId propertyId) { InlineCacheList* inlineCacheList; if (storeFieldInlineCacheByPropId.TryGetValueAndRemove(propertyId, &inlineCacheList)) { if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase)) { Output::Print(_u("InlineCacheInvalidation: invalidating store field caches for property %s(%u)\n"), GetPropertyName(propertyId)->GetBuffer(), propertyId); Output::Flush(); } InvalidateAndDeleteInlineCacheList(inlineCacheList); } } void ThreadContext::InvalidateAndDeleteInlineCacheList(InlineCacheList* inlineCacheList) { Assert(inlineCacheList != nullptr); uint cacheCount = 0; uint nullCacheCount = 0; FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList) { cacheCount++; if (inlineCache != nullptr) { if (PHASE_VERBOSE_TRACE1(Js::TraceInlineCacheInvalidationPhase)) { Output::Print(_u("InlineCacheInvalidation: invalidating cache 0x%p\n"), inlineCache); Output::Flush(); } memset(inlineCache, 0, sizeof(Js::InlineCache)); } else { nullCacheCount++; } } NEXT_SLISTBASE_ENTRY; Adelete(&this->inlineCacheThreadInfoAllocator, inlineCacheList); this->registeredInlineCacheCount = this->registeredInlineCacheCount > cacheCount ? this->registeredInlineCacheCount - cacheCount : 0; this->unregisteredInlineCacheCount = this->unregisteredInlineCacheCount > nullCacheCount ? this->unregisteredInlineCacheCount - nullCacheCount : 0; } void ThreadContext::CompactInlineCacheInvalidationLists() { #if DBG uint countOfNodesToCompact = this->unregisteredInlineCacheCount; this->totalUnregisteredCacheCount = 0; #endif Assert(this->unregisteredInlineCacheCount > 0); CompactProtoInlineCaches(); if (this->unregisteredInlineCacheCount > 0) { CompactStoreFieldInlineCaches(); } Assert(countOfNodesToCompact == this->totalUnregisteredCacheCount); } void ThreadContext::CompactProtoInlineCaches() { protoInlineCacheByPropId.MapUntil([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList) { CompactInlineCacheList(inlineCacheList); return this->unregisteredInlineCacheCount == 0; }); } void ThreadContext::CompactStoreFieldInlineCaches() { storeFieldInlineCacheByPropId.MapUntil([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList) { CompactInlineCacheList(inlineCacheList); return this->unregisteredInlineCacheCount == 0; }); } void ThreadContext::CompactInlineCacheList(InlineCacheList* inlineCacheList) { Assert(inlineCacheList != nullptr); uint cacheCount = 0; FOREACH_SLISTBASE_ENTRY_EDITING(Js::InlineCache*, inlineCache, inlineCacheList, iterator) { if (inlineCache == nullptr) { iterator.RemoveCurrent(); cacheCount++; } } NEXT_SLISTBASE_ENTRY_EDITING; #if DBG this->totalUnregisteredCacheCount += cacheCount; #endif if (cacheCount > 0) { AssertMsg(this->unregisteredInlineCacheCount >= cacheCount, "Some codepaths didn't unregistered the inlineCaches which might leak memory."); this->unregisteredInlineCacheCount = this->unregisteredInlineCacheCount > cacheCount ? this->unregisteredInlineCacheCount - cacheCount : 0; AssertMsg(this->registeredInlineCacheCount >= cacheCount, "Some codepaths didn't registered the inlineCaches which might leak memory."); this->registeredInlineCacheCount = this->registeredInlineCacheCount > cacheCount ? this->registeredInlineCacheCount - cacheCount : 0; } } #if DBG bool ThreadContext::IsProtoInlineCacheRegistered(const Js::InlineCache* inlineCache, Js::PropertyId propertyId) { return IsInlineCacheRegistered(protoInlineCacheByPropId, inlineCache, propertyId); } bool ThreadContext::IsStoreFieldInlineCacheRegistered(const Js::InlineCache* inlineCache, Js::PropertyId propertyId) { return IsInlineCacheRegistered(storeFieldInlineCacheByPropId, inlineCache, propertyId); } bool ThreadContext::IsInlineCacheRegistered(InlineCacheListMapByPropertyId& inlineCacheMap, const Js::InlineCache* inlineCache, Js::PropertyId propertyId) { InlineCacheList* inlineCacheList; if (inlineCacheMap.TryGetValue(propertyId, &inlineCacheList)) { return IsInlineCacheInList(inlineCache, inlineCacheList); } else { return false; } } bool ThreadContext::IsInlineCacheInList(const Js::InlineCache* inlineCache, const InlineCacheList* inlineCacheList) { Assert(inlineCache != nullptr); Assert(inlineCacheList != nullptr); FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, curInlineCache, inlineCacheList) { if (curInlineCache == inlineCache) { return true; } } NEXT_SLISTBASE_ENTRY; return false; } #endif #if ENABLE_NATIVE_CODEGEN ThreadContext::PropertyGuardEntry* ThreadContext::EnsurePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, bool& foundExistingEntry) { PropertyGuardDictionary &guards = this->recyclableData->propertyGuards; PropertyGuardEntry* entry = nullptr; foundExistingEntry = guards.TryGetValue(propertyRecord, &entry); if (!foundExistingEntry) { entry = RecyclerNew(GetRecycler(), PropertyGuardEntry, GetRecycler()); guards.UncheckedAdd(CreatePropertyRecordWeakRef(propertyRecord), entry); } return entry; } Js::PropertyGuard* ThreadContext::RegisterSharedPropertyGuard(Js::PropertyId propertyId) { Assert(IsActivePropertyId(propertyId)); const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId); bool foundExistingGuard; PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard); if (entry->sharedGuard == nullptr) { entry->sharedGuard = Js::PropertyGuard::New(GetRecycler()); } Js::PropertyGuard* guard = entry->sharedGuard; PHASE_PRINT_VERBOSE_TRACE1(Js::FixedMethodsPhase, _u("FixedFields: registered shared guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p, %s\n"), propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue(), foundExistingGuard ? _u("existing") : _u("new")); PHASE_PRINT_TESTTRACE1(Js::FixedMethodsPhase, _u("FixedFields: registered shared guard: name: %s, value: 0x%p, %s\n"), propertyRecord->GetBuffer(), guard->GetValue(), foundExistingGuard ? _u("existing") : _u("new")); return guard; } void ThreadContext::RegisterLazyBailout(Js::PropertyId propertyId, Js::EntryPointInfo* entryPoint) { const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId); bool foundExistingGuard; PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard); if (!entry->entryPoints) { entry->entryPoints = RecyclerNew(recycler, PropertyGuardEntry::EntryPointDictionary, recycler, /*capacity*/ 3); } entry->entryPoints->UncheckedAdd(entryPoint, NULL); } void ThreadContext::RegisterUniquePropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard* guard) { Assert(IsActivePropertyId(propertyId)); Assert(guard != nullptr); RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef = this->recycler->CreateWeakReferenceHandle(guard); RegisterUniquePropertyGuard(propertyId, guardWeakRef); } void ThreadContext::RegisterUniquePropertyGuard(Js::PropertyId propertyId, RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef) { Assert(IsActivePropertyId(propertyId)); Assert(guardWeakRef != nullptr); Js::PropertyGuard* guard = guardWeakRef->Get(); Assert(guard != nullptr); const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId); bool foundExistingGuard; PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard); entry->uniqueGuards.Item(guardWeakRef); if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: registered unique guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p, %s entry\n"), propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue(), foundExistingGuard ? _u("existing") : _u("new")); Output::Flush(); } if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: registered unique guard: name: %s, value: 0x%p, %s entry\n"), propertyRecord->GetBuffer(), guard->GetValue(), foundExistingGuard ? _u("existing") : _u("new")); Output::Flush(); } } void ThreadContext::RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache) { Assert(Js::ConstructorCache::GetOffsetOfGuardValue() == Js::PropertyGuard::GetOffsetOfValue()); Assert(Js::ConstructorCache::GetSizeOfGuardValue() == Js::PropertyGuard::GetSizeOfValue()); RegisterUniquePropertyGuard(propertyId, reinterpret_cast<Js::PropertyGuard*>(cache)); } void ThreadContext::InvalidatePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, PropertyGuardEntry* entry, bool isAllPropertyGuardsInvalidation) { Assert(entry != nullptr); if (entry->sharedGuard != nullptr) { Js::PropertyGuard* guard = entry->sharedGuard; if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"), propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue()); Output::Flush(); } if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"), propertyRecord->GetBuffer(), guard->GetValue()); Output::Flush(); } guard->Invalidate(); } uint count = 0; entry->uniqueGuards.Map([&count, propertyRecord](RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef) { Js::PropertyGuard* guard = guardWeakRef->Get(); if (guard != nullptr) { if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"), propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue()); Output::Flush(); } if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase)) { Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"), propertyRecord->GetBuffer(), guard->GetValue()); Output::Flush(); } guard->Invalidate(); count++; } }); entry->uniqueGuards.Clear(); // Count no. of invalidations done so far. Exclude if this is all property guards invalidation in which case // the unique Guards will be cleared anyway. if (!isAllPropertyGuardsInvalidation) { this->recyclableData->constructorCacheInvalidationCount += count; if (this->recyclableData->constructorCacheInvalidationCount > (uint)CONFIG_FLAG(ConstructorCacheInvalidationThreshold)) { // TODO: In future, we should compact the uniqueGuards dictionary so this function can be called from PreCollectionCallback // instead this->ClearInvalidatedUniqueGuards(); this->recyclableData->constructorCacheInvalidationCount = 0; } } if (entry->entryPoints && entry->entryPoints->Count() > 0) { Js::JavascriptStackWalker stackWalker(this->GetScriptContextList()); Js::JavascriptFunction* caller = nullptr; while (stackWalker.GetCaller(&caller, /*includeInlineFrames*/ false)) { // If the current frame is already from a bailout - we do not need to do on stack invalidation if (caller != nullptr && Js::ScriptFunction::Test(caller) && !stackWalker.GetCurrentFrameFromBailout()) { BYTE dummy; Js::FunctionEntryPointInfo* functionEntryPoint = caller->GetFunctionBody()->GetDefaultFunctionEntryPointInfo(); if (functionEntryPoint->IsInNativeAddressRange((DWORD_PTR)stackWalker.GetInstructionPointer())) { if (entry->entryPoints->TryGetValue(functionEntryPoint, &dummy)) { functionEntryPoint->DoLazyBailout( stackWalker.GetCurrentAddressOfInstructionPointer(), static_cast<BYTE*>(stackWalker.GetFramePointer()) #if DBG , caller->GetFunctionBody() , propertyRecord #endif ); } } } } entry->entryPoints->Map([=](Js::EntryPointInfo* info, BYTE& dummy, const RecyclerWeakReference<Js::EntryPointInfo>* infoWeakRef) { OUTPUT_TRACE2(Js::LazyBailoutPhase, info->GetFunctionBody(), _u("Lazy bailout - Invalidation due to property: %s \n"), propertyRecord->GetBuffer()); info->Invalidate(true); }); entry->entryPoints->Clear(); } } void ThreadContext::InvalidatePropertyGuards(Js::PropertyId propertyId) { const Js::PropertyRecord* propertyRecord = GetPropertyName(propertyId); PropertyGuardDictionary &guards = this->recyclableData->propertyGuards; PropertyGuardEntry* entry = nullptr; if (guards.TryGetValueAndRemove(propertyRecord, &entry)) { InvalidatePropertyGuardEntry(propertyRecord, entry, false); } } void ThreadContext::InvalidateAllPropertyGuards() { PropertyGuardDictionary &guards = this->recyclableData->propertyGuards; if (guards.Count() > 0) { guards.Map([this](Js::PropertyRecord const * propertyRecord, PropertyGuardEntry* entry, const RecyclerWeakReference<const Js::PropertyRecord>* weakRef) { InvalidatePropertyGuardEntry(propertyRecord, entry, true); }); guards.Clear(); } } #endif void ThreadContext::InvalidateAllProtoInlineCaches() { protoInlineCacheByPropId.Map([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList) { InvalidateAndDeleteInlineCacheList(inlineCacheList); }); protoInlineCacheByPropId.Reset(); } #if DBG // Verifies if object is registered in any proto InlineCache bool ThreadContext::IsObjectRegisteredInProtoInlineCaches(Js::DynamicObject * object) { return protoInlineCacheByPropId.MapUntil([object](Js::PropertyId propertyId, InlineCacheList* inlineCacheList) { FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList) { if (inlineCache != nullptr && !inlineCache->IsEmpty()) { // Verify this object is not present in prototype chain of inlineCache's type bool isObjectPresentOnPrototypeChain = Js::JavascriptOperators::MapObjectAndPrototypesUntil<true>(inlineCache->GetType()->GetPrototype(), [=](Js::RecyclableObject* prototype) { return prototype == object; }); if (isObjectPresentOnPrototypeChain) { return true; } } } NEXT_SLISTBASE_ENTRY; return false; }); } // Verifies if object is registered in any storeField InlineCache bool ThreadContext::IsObjectRegisteredInStoreFieldInlineCaches(Js::DynamicObject * object) { return storeFieldInlineCacheByPropId.MapUntil([object](Js::PropertyId propertyId, InlineCacheList* inlineCacheList) { FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList) { if (inlineCache != nullptr && !inlineCache->IsEmpty()) { // Verify this object is not present in prototype chain of inlineCache's type bool isObjectPresentOnPrototypeChain = Js::JavascriptOperators::MapObjectAndPrototypesUntil<true>(inlineCache->GetType()->GetPrototype(), [=](Js::RecyclableObject* prototype) { return prototype == object; }); if (isObjectPresentOnPrototypeChain) { return true; } } } NEXT_SLISTBASE_ENTRY; return false; }); } #endif bool ThreadContext::AreAllProtoInlineCachesInvalidated() { return protoInlineCacheByPropId.Count() == 0; } void ThreadContext::InvalidateAllStoreFieldInlineCaches() { storeFieldInlineCacheByPropId.Map([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList) { InvalidateAndDeleteInlineCacheList(inlineCacheList); }); storeFieldInlineCacheByPropId.Reset(); } bool ThreadContext::AreAllStoreFieldInlineCachesInvalidated() { return storeFieldInlineCacheByPropId.Count() == 0; } #if DBG bool ThreadContext::IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * inlineCache, Js::Var function) { Assert(inlineCache != nullptr); Assert(function != nullptr); Js::IsInstInlineCache* firstInlineCache; if (this->isInstInlineCacheByFunction.TryGetValue(function, &firstInlineCache)) { return IsIsInstInlineCacheInList(inlineCache, firstInlineCache); } else { return false; } } #endif void ThreadContext::RegisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function) { Assert(function != nullptr); Assert(inlineCache != nullptr); // We should never cross-register or re-register a cache that is already on some invalidation list (for its function or some other function). // Every cache must be first cleared and unregistered before being registered again. AssertMsg(inlineCache->function == nullptr, "We should only register instance-of caches that have not yet been populated."); Js::IsInstInlineCache** inlineCacheRef = nullptr; if (this->isInstInlineCacheByFunction.TryGetReference(function, &inlineCacheRef)) { AssertMsg(!IsIsInstInlineCacheInList(inlineCache, *inlineCacheRef), "Why are we registering a cache that is already registered?"); inlineCache->next = *inlineCacheRef; *inlineCacheRef = inlineCache; } else { inlineCache->next = nullptr; this->isInstInlineCacheByFunction.Add(function, inlineCache); } } void ThreadContext::UnregisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function) { Assert(inlineCache != nullptr); Js::IsInstInlineCache** inlineCacheRef = nullptr; if (this->isInstInlineCacheByFunction.TryGetReference(function, &inlineCacheRef)) { Assert(*inlineCacheRef != nullptr); if (inlineCache == *inlineCacheRef) { *inlineCacheRef = (*inlineCacheRef)->next; if (*inlineCacheRef == nullptr) { this->isInstInlineCacheByFunction.Remove(function); } } else { Js::IsInstInlineCache * prevInlineCache; Js::IsInstInlineCache * curInlineCache; for (prevInlineCache = *inlineCacheRef, curInlineCache = (*inlineCacheRef)->next; curInlineCache != nullptr; prevInlineCache = curInlineCache, curInlineCache = curInlineCache->next) { if (curInlineCache == inlineCache) { prevInlineCache->next = curInlineCache->next; return; } } AssertMsg(false, "Why are we unregistering a cache that is not registered?"); } } } void ThreadContext::InvalidateIsInstInlineCacheList(Js::IsInstInlineCache* inlineCacheList) { Assert(inlineCacheList != nullptr); Js::IsInstInlineCache* curInlineCache; Js::IsInstInlineCache* nextInlineCache; for (curInlineCache = inlineCacheList; curInlineCache != nullptr; curInlineCache = nextInlineCache) { if (PHASE_VERBOSE_TRACE1(Js::TraceInlineCacheInvalidationPhase)) { Output::Print(_u("InlineCacheInvalidation: invalidating instanceof cache 0x%p\n"), curInlineCache); Output::Flush(); } // Stash away the next cache before we zero out the current one (including its next pointer). nextInlineCache = curInlineCache->next; // Clear the current cache to invalidate it. memset(curInlineCache, 0, sizeof(Js::IsInstInlineCache)); } } void ThreadContext::InvalidateIsInstInlineCachesForFunction(Js::Var function) { Js::IsInstInlineCache* inlineCacheList; if (this->isInstInlineCacheByFunction.TryGetValueAndRemove(function, &inlineCacheList)) { InvalidateIsInstInlineCacheList(inlineCacheList); } } void ThreadContext::InvalidateAllIsInstInlineCaches() { isInstInlineCacheByFunction.Map([this](const Js::Var function, Js::IsInstInlineCache* inlineCacheList) { InvalidateIsInstInlineCacheList(inlineCacheList); }); isInstInlineCacheByFunction.Clear(); } bool ThreadContext::AreAllIsInstInlineCachesInvalidated() const { return isInstInlineCacheByFunction.Count() == 0; } #if DBG bool ThreadContext::IsIsInstInlineCacheInList(const Js::IsInstInlineCache* inlineCache, const Js::IsInstInlineCache* inlineCacheList) { Assert(inlineCache != nullptr); Assert(inlineCacheList != nullptr); for (const Js::IsInstInlineCache* curInlineCache = inlineCacheList; curInlineCache != nullptr; curInlineCache = curInlineCache->next) { if (curInlineCache == inlineCache) { return true; } } return false; } #endif void ThreadContext::RegisterTypeWithProtoPropertyCache(const Js::PropertyId propertyId, Js::Type *const type) { Assert(propertyId != Js::Constants::NoProperty); Assert(IsActivePropertyId(propertyId)); Assert(type); PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache; TypeHashSet *typeHashSet = nullptr; if(!typesWithProtoPropertyCache.TryGetValue(propertyId, &typeHashSet)) { typeHashSet = RecyclerNew(recycler, TypeHashSet, recycler); typesWithProtoPropertyCache.Add(propertyId, typeHashSet); } typeHashSet->Item(type, false); } void ThreadContext::InvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId) { Assert(propertyId != Js::Constants::NoProperty); Assert(IsActivePropertyId(propertyId)); InternalInvalidateProtoTypePropertyCaches(propertyId); } void ThreadContext::InternalInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId) { // Get the hash set of registered types associated with the property ID, invalidate each type in the hash set, and // remove the property ID and its hash set from the map PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache; TypeHashSet *typeHashSet = nullptr; if(typesWithProtoPropertyCache.Count() != 0 && typesWithProtoPropertyCache.TryGetValueAndRemove(propertyId, &typeHashSet)) { DoInvalidateProtoTypePropertyCaches(propertyId, typeHashSet); } } void ThreadContext::InvalidateAllProtoTypePropertyCaches() { PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache; if (typesWithProtoPropertyCache.Count() > 0) { typesWithProtoPropertyCache.Map([this](Js::PropertyId propertyId, TypeHashSet * typeHashSet) { DoInvalidateProtoTypePropertyCaches(propertyId, typeHashSet); }); typesWithProtoPropertyCache.Clear(); } } void ThreadContext::DoInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId, TypeHashSet *const typeHashSet) { Assert(propertyId != Js::Constants::NoProperty); Assert(typeHashSet); typeHashSet->Map( [propertyId](Js::Type *const type, const bool unused, const RecyclerWeakReference<Js::Type>*) { type->GetPropertyCache()->ClearIfPropertyIsOnAPrototype(propertyId); }); } BOOL ThreadContext::HasPreviousHostScriptContext() { return hostScriptContextStack->Count() != 0; } HostScriptContext* ThreadContext::GetPreviousHostScriptContext() { return hostScriptContextStack->Peek(); } void ThreadContext::PushHostScriptContext(HostScriptContext* topProvider) { // script engine can be created coming from GetDispID, so push/pop can be // happening after the first round of enterscript as well. we might need to // revisit the whole callRootLevel but probably not now. // Assert(HasPreviousHostScriptContext() || callRootLevel == 0); hostScriptContextStack->Push(topProvider); } HostScriptContext* ThreadContext::PopHostScriptContext() { return hostScriptContextStack->Pop(); // script engine can be created coming from GetDispID, so push/pop can be // happening after the first round of enterscript as well. we might need to // revisit the whole callRootLevel but probably not now. // Assert(HasPreviousHostScriptContext() || callRootLevel == 0); } #if DBG || defined(PROFILE_EXEC) bool ThreadContext::AsyncHostOperationStart(void * suspendRecord) { bool wasInAsync = false; Assert(!this->IsScriptActive()); Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord; if (lastRecord != NULL) { if (!lastRecord->leaveForHost) { #if DBG wasInAsync = !!lastRecord->leaveForAsyncHostOperation; lastRecord->leaveForAsyncHostOperation = true; #endif #ifdef PROFILE_EXEC lastRecord->scriptContext->ProfileSuspend(Js::RunPhase, (Js::Profiler::SuspendRecord *)suspendRecord); #endif } else { Assert(!lastRecord->leaveForAsyncHostOperation); } } return wasInAsync; } void ThreadContext::AsyncHostOperationEnd(bool wasInAsync, void * suspendRecord) { Assert(!this->IsScriptActive()); Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord; if (lastRecord != NULL) { if (!lastRecord->leaveForHost) { Assert(lastRecord->leaveForAsyncHostOperation); #if DBG lastRecord->leaveForAsyncHostOperation = wasInAsync; #endif #ifdef PROFILE_EXEC lastRecord->scriptContext->ProfileResume((Js::Profiler::SuspendRecord *)suspendRecord); #endif } else { Assert(!lastRecord->leaveForAsyncHostOperation); Assert(!wasInAsync); } } } #endif #if DBG void ThreadContext::CheckJsReentrancyOnDispose() { if (!this->IsDisableImplicitCall()) { AssertJsReentrancy(); } } #endif #ifdef RECYCLER_DUMP_OBJECT_GRAPH void DumpRecyclerObjectGraph() { ThreadContext * threadContext = ThreadContext::GetContextForCurrentThread(); if (threadContext == nullptr) { Output::Print(_u("No thread context")); } threadContext->GetRecycler()->DumpObjectGraph(); } #endif #if ENABLE_NATIVE_CODEGEN bool ThreadContext::IsNativeAddressHelper(void * pCodeAddr, Js::ScriptContext* currentScriptContext) { bool isNativeAddr = false; if (currentScriptContext && currentScriptContext->GetJitFuncRangeCache() != nullptr) { isNativeAddr = currentScriptContext->GetJitFuncRangeCache()->IsNativeAddr(pCodeAddr); } for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext && !isNativeAddr; scriptContext = scriptContext->next) { if (scriptContext == currentScriptContext || scriptContext->GetJitFuncRangeCache() == nullptr) { continue; } isNativeAddr = scriptContext->GetJitFuncRangeCache()->IsNativeAddr(pCodeAddr); } return isNativeAddr; } BOOL ThreadContext::IsNativeAddress(void * pCodeAddr, Js::ScriptContext* currentScriptContext) { #if ENABLE_OOP_NATIVE_CODEGEN if (JITManager::GetJITManager()->IsOOPJITEnabled()) { if (PreReservedVirtualAllocWrapper::IsInRange((void*)m_prereservedRegionAddr, pCodeAddr)) { return true; } if (IsAllJITCodeInPreReservedRegion()) { return false; } if (AutoSystemInfo::IsJscriptModulePointer(pCodeAddr)) { return false; } #if DBG boolean result; HRESULT hr = JITManager::GetJITManager()->IsNativeAddr(this->m_remoteThreadContextInfo, (intptr_t)pCodeAddr, &result); #endif bool isNativeAddr = IsNativeAddressHelper(pCodeAddr, currentScriptContext); #if DBG Assert(FAILED(hr) || result == (isNativeAddr? TRUE:FALSE)); #endif return isNativeAddr; } else #endif { PreReservedVirtualAllocWrapper *preReservedVirtualAllocWrapper = this->GetPreReservedVirtualAllocator(); if (preReservedVirtualAllocWrapper->IsInRange(pCodeAddr)) { return TRUE; } if (!this->IsAllJITCodeInPreReservedRegion()) { #if DBG AutoCriticalSection autoLock(&this->codePageAllocators.cs); #endif bool isNativeAddr = IsNativeAddressHelper(pCodeAddr, currentScriptContext); #if DBG Assert(this->codePageAllocators.IsInNonPreReservedPageAllocator(pCodeAddr) == isNativeAddr); #endif return isNativeAddr; } return FALSE; } } #endif #if ENABLE_PROFILE_INFO void ThreadContext::EnsureSourceProfileManagersByUrlMap() { if(this->recyclableData->sourceProfileManagersByUrl == nullptr) { this->EnsureRecycler(); this->recyclableData->sourceProfileManagersByUrl = RecyclerNew(GetRecycler(), SourceProfileManagersByUrlMap, GetRecycler()); } } // // Returns the cache profile manager for the URL and hash combination for a particular dynamic script. There is a ref count added for every script context // that references the shared profile manager info. // Js::SourceDynamicProfileManager* ThreadContext::GetSourceDynamicProfileManager(_In_z_ const WCHAR* url, _In_ uint hash, _Inout_ bool* addRef) { EnsureSourceProfileManagersByUrlMap(); Js::SourceDynamicProfileManager* profileManager = nullptr; SourceDynamicProfileManagerCache* managerCache = nullptr; bool newCache = false; if(!this->recyclableData->sourceProfileManagersByUrl->TryGetValue(url, &managerCache)) { if(this->recyclableData->sourceProfileManagersByUrl->Count() >= INMEMORY_CACHE_MAX_URL) { return nullptr; } managerCache = RecyclerNewZ(this->GetRecycler(), SourceDynamicProfileManagerCache); newCache = true; } bool createProfileManager = false; if(!managerCache->sourceProfileManagerMap) { managerCache->sourceProfileManagerMap = RecyclerNew(this->GetRecycler(), SourceDynamicProfileManagerMap, this->GetRecycler()); createProfileManager = true; } else { createProfileManager = !managerCache->sourceProfileManagerMap->TryGetValue(hash, &profileManager); } if(createProfileManager) { if(managerCache->sourceProfileManagerMap->Count() < INMEMORY_CACHE_MAX_PROFILE_MANAGER) { profileManager = RecyclerNewZ(this->GetRecycler(), Js::SourceDynamicProfileManager, this->GetRecycler()); managerCache->sourceProfileManagerMap->Add(hash, profileManager); } } else { profileManager->Reuse(); } if(!*addRef) { managerCache->AddRef(); *addRef = true; OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, _u("Addref dynamic source profile manger - Url: %s\n"), url); } if (newCache) { // Let's make a copy of the URL because there is no guarantee this URL will remain alive in the future. size_t lengthInChars = wcslen(url) + 1; WCHAR* urlCopy = RecyclerNewArrayLeaf(GetRecycler(), WCHAR, lengthInChars); js_memcpy_s(urlCopy, lengthInChars * sizeof(WCHAR), url, lengthInChars * sizeof(WCHAR)); this->recyclableData->sourceProfileManagersByUrl->Add(urlCopy, managerCache); } return profileManager; } // // Decrement the ref count for this URL and cleanup the corresponding record if there are no other references to it. // uint ThreadContext::ReleaseSourceDynamicProfileManagers(const WCHAR* url) { // If we've already freed the recyclable data, we're shutting down the thread context so skip clean up if (this->recyclableData == nullptr) return 0; SourceDynamicProfileManagerCache* managerCache = this->recyclableData->sourceProfileManagersByUrl->Lookup(url, nullptr); uint refCount = 0; if(managerCache) // manager cache may be null we exceeded -INMEMORY_CACHE_MAX_URL { refCount = managerCache->Release(); OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, _u("Release dynamic source profile manger %d Url: %s\n"), refCount, url); Output::Flush(); if(refCount == 0) { this->recyclableData->sourceProfileManagersByUrl->Remove(url); } } return refCount; } #endif void ThreadContext::EnsureSymbolRegistrationMap() { if (this->recyclableData->symbolRegistrationMap == nullptr) { this->EnsureRecycler(); this->recyclableData->symbolRegistrationMap = RecyclerNew(GetRecycler(), SymbolRegistrationMap, GetRecycler()); } } const Js::PropertyRecord* ThreadContext::GetSymbolFromRegistrationMap(const char16* stringKey, charcount_t stringLength) { this->EnsureSymbolRegistrationMap(); Js::HashedCharacterBuffer<char16> propertyName = Js::HashedCharacterBuffer<char16>(stringKey, stringLength); return this->recyclableData->symbolRegistrationMap->LookupWithKey(&propertyName, nullptr); } const Js::PropertyRecord* ThreadContext::AddSymbolToRegistrationMap(const char16* stringKey, charcount_t stringLength) { this->EnsureSymbolRegistrationMap(); const Js::PropertyRecord* propertyRecord = this->UncheckedAddPropertyId(stringKey, stringLength, /*bind*/false, /*isSymbol*/true); Assert(propertyRecord); // We need to support null characters in the Symbol names. For e.g. "A\0Z" is a valid symbol name and is different than "A\0Y". // However, as the key contains a null character we need to hash the symbol name past the null character. The default implementation terminates // at the null character, so we use the Js::HashedCharacterBuffer as key. We allocate the key in the recycler memory as it needs to be around // for the lifetime of the map. Js::HashedCharacterBuffer<char16> * propertyName = RecyclerNew(GetRecycler(), Js::HashedCharacterBuffer<char16>, propertyRecord->GetBuffer(), propertyRecord->GetLength()); this->recyclableData->symbolRegistrationMap->Add(propertyName, propertyRecord); return propertyRecord; } #if ENABLE_TTD JsUtil::BaseDictionary<Js::HashedCharacterBuffer<char16>*, const Js::PropertyRecord*, Recycler, PowerOf2SizePolicy, Js::PropertyRecordStringHashComparer>* ThreadContext::GetSymbolRegistrationMap_TTD() { //This adds a little memory but makes simplifies other logic -- maybe revise later this->EnsureSymbolRegistrationMap(); return this->recyclableData->symbolRegistrationMap; } #endif void ThreadContext::ClearImplicitCallFlags() { SetImplicitCallFlags(Js::ImplicitCall_None); } void ThreadContext::ClearImplicitCallFlags(Js::ImplicitCallFlags flags) { Assert((flags & Js::ImplicitCall_None) == 0); SetImplicitCallFlags((Js::ImplicitCallFlags)(implicitCallFlags & ~flags)); } void ThreadContext::CheckAndResetImplicitCallAccessorFlag() { Js::ImplicitCallFlags accessorCallFlag = (Js::ImplicitCallFlags)(Js::ImplicitCall_Accessor & ~Js::ImplicitCall_None); if ((GetImplicitCallFlags() & accessorCallFlag) != 0) { ClearImplicitCallFlags(accessorCallFlag); AddImplicitCallFlags(Js::ImplicitCall_NonProfiledAccessor); } } bool ThreadContext::HasNoSideEffect(Js::RecyclableObject * function) const { Js::FunctionInfo::Attributes attributes = Js::FunctionInfo::GetAttributes(function); return this->HasNoSideEffect(function, attributes); } bool ThreadContext::HasNoSideEffect(Js::RecyclableObject * function, Js::FunctionInfo::Attributes attributes) const { if (((attributes & Js::FunctionInfo::CanBeHoisted) != 0) || ((attributes & Js::FunctionInfo::HasNoSideEffect) != 0 && !IsDisableImplicitException())) { Assert((attributes & Js::FunctionInfo::HasNoSideEffect) != 0); return true; } return false; } bool ThreadContext::RecordImplicitException() { // Record the exception in the implicit call flag AddImplicitCallFlags(Js::ImplicitCall_Exception); if (IsDisableImplicitException()) { // Indicate that we shouldn't throw if ImplicitExceptions have been disabled return false; } // Disabling implicit exception when disabling implicit calls can result in valid exceptions not being thrown. // Instead we tell not to throw only if an implicit call happened and they are disabled. This is to cover the case // of an exception being thrown because an implicit call not executed left the execution in a bad state. // Since there is an implicit call, we expect to bailout and handle this operation in the interpreter instead. bool hasImplicitCallHappened = IsDisableImplicitCall() && (GetImplicitCallFlags() & ~Js::ImplicitCall_Exception); return !hasImplicitCallHappened; } void ThreadContext::SetThreadServiceWrapper(ThreadServiceWrapper* inThreadServiceWrapper) { AssertMsg(threadServiceWrapper == NULL || inThreadServiceWrapper == NULL, "double set ThreadServiceWrapper"); threadServiceWrapper = inThreadServiceWrapper; } ThreadServiceWrapper* ThreadContext::GetThreadServiceWrapper() { return threadServiceWrapper; } uint ThreadContext::GetRandomNumber() { #ifdef ENABLE_CUSTOM_ENTROPY return (uint)GetEntropy().GetRand(); #else uint randomNumber = 0; errno_t e = rand_s(&randomNumber); Assert(e == 0); return randomNumber; #endif } #if defined(ENABLE_JS_ETW) && defined(NTBUILD) void ThreadContext::EtwLogPropertyIdList() { propertyMap->Map([&](const Js::PropertyRecord* propertyRecord){ EventWriteJSCRIPT_HOSTING_PROPERTYID_LIST(propertyRecord, propertyRecord->GetBuffer()); }); } #endif #ifdef ENABLE_DEBUG_CONFIG_OPTIONS Js::Var ThreadContext::GetMemoryStat(Js::ScriptContext* scriptContext) { ScriptMemoryDumper dumper(scriptContext); return dumper.Dump(); } void ThreadContext::SetAutoProxyName(LPCWSTR objectName) { recyclableData->autoProxyName = objectName; } #endif // // Regex helpers // UnifiedRegex::StandardChars<uint8>* ThreadContext::GetStandardChars(__inout_opt uint8* dummy) { if (standardUTF8Chars == 0) { ArenaAllocator* allocator = GetThreadAlloc(); standardUTF8Chars = Anew(allocator, UnifiedRegex::UTF8StandardChars, allocator); } return standardUTF8Chars; } UnifiedRegex::StandardChars<char16>* ThreadContext::GetStandardChars(__inout_opt char16* dummy) { if (standardUnicodeChars == 0) { ArenaAllocator* allocator = GetThreadAlloc(); standardUnicodeChars = Anew(allocator, UnifiedRegex::UnicodeStandardChars, allocator); } return standardUnicodeChars; } void ThreadContext::CheckScriptInterrupt() { if (TestThreadContextFlag(ThreadContextFlagCanDisableExecution)) { if (this->IsExecutionDisabled()) { Assert(this->DoInterruptProbe()); throw Js::ScriptAbortException(); } } else { this->CheckInterruptPoll(); } } void ThreadContext::CheckInterruptPoll() { // Disable QC when implicit calls are disabled since the host can do anything before returning back, like servicing the // message loop, which may in turn cause script code to be executed and implicit calls to be made if (!IsDisableImplicitCall()) { InterruptPoller *poller = this->interruptPoller; if (poller) { poller->CheckInterruptPoll(); } } } void * ThreadContext::GetDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType) { void * data = nullptr; return this->dynamicObjectEnumeratorCacheMap.TryGetValue(dynamicType, &data)? data : nullptr; } void ThreadContext::AddDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType, void * cache) { this->dynamicObjectEnumeratorCacheMap.Item(dynamicType, cache); } InterruptPoller::InterruptPoller(ThreadContext *tc) : threadContext(tc), lastPollTick(0), lastResetTick(0), isDisabled(FALSE) { tc->SetInterruptPoller(this); } void InterruptPoller::CheckInterruptPoll() { if (!isDisabled) { Js::ScriptEntryExitRecord *entryExitRecord = this->threadContext->GetScriptEntryExit(); if (entryExitRecord) { Js::ScriptContext *scriptContext = entryExitRecord->scriptContext; if (scriptContext) { this->TryInterruptPoll(scriptContext); } } } } void InterruptPoller::GetStatementCount(ULONG *pluHi, ULONG *pluLo) { DWORD resetTick = this->lastResetTick; DWORD pollTick = this->lastPollTick; DWORD elapsed; elapsed = pollTick - resetTick; ULONGLONG statements = (ULONGLONG)elapsed * InterruptPoller::TicksToStatements; *pluLo = (ULONG)statements; *pluHi = (ULONG)(statements >> 32); } void ThreadContext::DisableExecution() { Assert(TestThreadContextFlag(ThreadContextFlagCanDisableExecution)); // Hammer the stack limit with a value that will cause script abort on the next stack probe. this->SetStackLimitForCurrentThread(Js::Constants::StackLimitForScriptInterrupt); return; } void ThreadContext::EnableExecution() { Assert(this->GetStackProber()); // Restore the normal stack limit. this->SetStackLimitForCurrentThread(this->GetStackProber()->GetScriptStackLimit()); // It's possible that the host disabled execution after the script threw an exception // of it's own, so we shouldn't clear that. Only exceptions for script termination // should be cleared. if (GetRecordedException() == GetPendingTerminatedErrorObject()) { SetRecordedException(NULL); } } bool ThreadContext::TestThreadContextFlag(ThreadContextFlags contextFlag) const { return (this->threadContextFlags & contextFlag) != 0; } void ThreadContext::SetThreadContextFlag(ThreadContextFlags contextFlag) { this->threadContextFlags = (ThreadContextFlags)(this->threadContextFlags | contextFlag); } void ThreadContext::ClearThreadContextFlag(ThreadContextFlags contextFlag) { this->threadContextFlags = (ThreadContextFlags)(this->threadContextFlags & ~contextFlag); } #ifdef ENABLE_GLOBALIZATION Js::DelayLoadWinRtString * ThreadContext::GetWinRTStringLibrary() { delayLoadWinRtString.EnsureFromSystemDirOnly(); return &delayLoadWinRtString; } #if defined(ENABLE_INTL_OBJECT) || defined(ENABLE_ES6_CHAR_CLASSIFIER) #ifdef INTL_WINGLOB Js::WindowsGlobalizationAdapter* ThreadContext::GetWindowsGlobalizationAdapter() { return &windowsGlobalizationAdapter; } Js::DelayLoadWindowsGlobalization* ThreadContext::GetWindowsGlobalizationLibrary() { delayLoadWindowsGlobalizationLibrary.Ensure(this->GetWinRTStringLibrary()); return &delayLoadWindowsGlobalizationLibrary; } #endif // INTL_WINGLOB #endif #ifdef ENABLE_FOUNDATION_OBJECT Js::WindowsFoundationAdapter* ThreadContext::GetWindowsFoundationAdapter() { return &windowsFoundationAdapter; } Js::DelayLoadWinRtFoundation* ThreadContext::GetWinRtFoundationLibrary() { delayLoadWinRtFoundationLibrary.EnsureFromSystemDirOnly(); return &delayLoadWinRtFoundationLibrary; } #endif #endif // ENABLE_GLOBALIZATION // Despite the name, callers expect this to return the highest propid + 1. uint ThreadContext::GetHighestPropertyNameIndex() const { return propertyMap->GetLastIndex() + 1 + Js::InternalPropertyIds::Count; } #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT) void ThreadContext::ReportAndCheckLeaksOnProcessDetach() { bool needReportOrCheck = false; #ifdef LEAK_REPORT needReportOrCheck = needReportOrCheck || Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag); #endif #ifdef CHECK_MEMORY_LEAK needReportOrCheck = needReportOrCheck || (Js::Configuration::Global.flags.CheckMemoryLeak && MemoryLeakCheck::IsEnableOutput()); #endif if (!needReportOrCheck) { return; } // Report leaks even if this is a force termination and we have not clean up the thread // This is call during process detach. No one should be creating new thread context. // So don't need to take the lock ThreadContext * current = GetThreadContextList(); while (current) { #if DBG current->pageAllocator.ClearConcurrentThreadId(); #endif Recycler * recycler = current->GetRecycler(); #ifdef LEAK_REPORT if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag)) { AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): Process Termination (TID: %d)"), current, current->threadId); LeakReport::DumpUrl(current->threadId); // Heuristically figure out which one is the root tracker script engine // and force close on it if (current->rootTrackerScriptContext != nullptr) { current->rootTrackerScriptContext->Close(false); } recycler->ReportLeaksOnProcessDetach(); } #endif #ifdef CHECK_MEMORY_LEAK recycler->CheckLeaksOnProcessDetach(_u("Process Termination")); #endif current = current->Next(); } } #endif #ifdef LEAK_REPORT void ThreadContext::SetRootTrackerScriptContext(Js::ScriptContext * scriptContext) { Assert(this->rootTrackerScriptContext == nullptr); this->rootTrackerScriptContext = scriptContext; scriptContext->isRootTrackerScriptContext = true; } void ThreadContext::ClearRootTrackerScriptContext(Js::ScriptContext * scriptContext) { Assert(this->rootTrackerScriptContext == scriptContext); this->rootTrackerScriptContext->isRootTrackerScriptContext = false; this->rootTrackerScriptContext = nullptr; } #endif AutoTagNativeLibraryEntry::AutoTagNativeLibraryEntry(Js::RecyclableObject* function, Js::CallInfo callInfo, PCWSTR name, void* addr) { // Save function/callInfo values (for StackWalker). Compiler may stackpack/optimize them for built-in native functions. entry.function = function; entry.callInfo = callInfo; entry.name = name; entry.addr = addr; ThreadContext* threadContext = function->GetScriptContext()->GetThreadContext(); threadContext->PushNativeLibraryEntry(&entry); } AutoTagNativeLibraryEntry::~AutoTagNativeLibraryEntry() { ThreadContext* threadContext = entry.function->GetScriptContext()->GetThreadContext(); Assert(threadContext->PeekNativeLibraryEntry() == &entry); threadContext->PopNativeLibraryEntry(); } #if ENABLE_JS_REENTRANCY_CHECK #if DBG void JsReentLock::setObjectForMutation(Js::Var object) { m_arrayObject = nullptr; if (object != nullptr && Js::DynamicObject::IsAnyArray(object)) { m_arrayObject = object; } // Don't care about any other objects for now } void JsReentLock::setSecondObjectForMutation(Js::Var object) { m_arrayObject2 = nullptr; if (object != nullptr && Js::DynamicObject::IsAnyArray(object)) { m_arrayObject2 = object; } // Don't care about any other objects for now } void JsReentLock::MutateArrayObject(Js::Var arrayObject) { if (arrayObject) { Js::JavascriptArray *arr = Js::JavascriptArray::FromAnyArray(arrayObject); uint32 random = static_cast<unsigned int>(rand()); if (random % 20 == 0) { arr->DoTypeMutation(); } else if (random % 20 == 1) { // TODO : modify the length of the current array // Or other opportunities } } } void JsReentLock::MutateArrayObject() { if (CONFIG_FLAG(EnableArrayTypeMutation)) { JsReentLock::MutateArrayObject(m_arrayObject); JsReentLock::MutateArrayObject(m_arrayObject2); } } #endif #endif ```
```smalltalk namespace Asp.Versioning.Routing; using System.Web.Http.Routing; /// <summary> /// Represents an API version aware <see cref="UrlHelper">URL helper</see>. /// </summary> public class ApiVersionUrlHelper : UrlHelper { /// <summary> /// Initializes a new instance of the <see cref="ApiVersionUrlHelper"/> class. /// </summary> /// <param name="url">The inner <see cref="UrlHelper">URL helper</see>.</param> public ApiVersionUrlHelper( UrlHelper url ) { Url = url ?? throw new System.ArgumentNullException( nameof( url ) ); if ( url.Request != null ) { Request = url.Request; } } /// <summary> /// Gets the inner URL helper. /// </summary> /// <value>The inner <see cref="UrlHelper">URL helper</see>.</value> protected UrlHelper Url { get; } /// <inheritdoc /> public override string Content( string path ) => Url.Content( path ); /// <inheritdoc /> public override string Link( string routeName, object routeValues ) => Url.Link( routeName, AddApiVersionRouteValueIfNecessary( new HttpRouteValueDictionary( routeValues ) ) ); /// <inheritdoc /> public override string Link( string routeName, IDictionary<string, object> routeValues ) => Url.Link( routeName, AddApiVersionRouteValueIfNecessary( routeValues ) ); /// <inheritdoc /> public override string Route( string routeName, object routeValues ) => Url.Route( routeName, AddApiVersionRouteValueIfNecessary( new HttpRouteValueDictionary( routeValues ) ) ); /// <inheritdoc /> public override string Route( string routeName, IDictionary<string, object> routeValues ) => Url.Route( routeName, AddApiVersionRouteValueIfNecessary( routeValues ) ); private IDictionary<string, object>? AddApiVersionRouteValueIfNecessary( IDictionary<string, object>? routeValues ) { if ( Request == null ) { return routeValues; } var properties = Request.ApiVersionProperties(); var key = properties.RouteParameter; if ( string.IsNullOrEmpty( key ) ) { return routeValues; } var value = properties.RawRequestedApiVersion; if ( string.IsNullOrEmpty( value ) ) { return routeValues; } if ( routeValues == null ) { return new HttpRouteValueDictionary() { [key!] = value! }; } if ( !routeValues.ContainsKey( key! ) ) { routeValues.Add( key!, value! ); } return routeValues; } } ```
```php <?php /** */ namespace Test; use OC\Files\Mount; /** * Test moveable mount for mocking */ class TestMoveableMountPoint extends Mount\MountPoint implements Mount\MoveableMount { /** * Move the mount point to $target * * @param string $target the target mount point * @return bool */ public function moveMount($target) { $this->setMountPoint($target); } /** * Remove the mount points * * @return mixed * @return bool */ public function removeMount() { } } ```
The thin sand rat or lesser sand rat (Psammomys vexillaris) is a species of rodent in the family Muridae. It has also been previously named the pale sand rat based on work published by Oldfield Thomas in 1925. It is found in Algeria, Libya, and Tunisia, and its natural habitats are subtropical or tropical dry shrubland and intermittent salt lakes. The thin sand rat was previously classified as a subspecies of the fat sand rat. However, morphological differences in size and coat color between the two animals, along with recent molecular evidence suggest that they are different species. The thin sand rat may be a natural reservoir for the disease leishmaniasis. References Psammomys Mammals described in 1925 Taxa named by Oldfield Thomas Taxonomy articles created by Polbot
```smalltalk Package { #name : 'BaselineOfDrTests' } ```
Bigfoot Discovery Museum is a museum in Felton, California devoted to Bigfoot (Sasquatch). The founder, Michael Rugg, graduated from Stanford University in 1968, worked in Silicon Valley until the dot-com bust, then opened the museum in 2004 or 2005. Paula Yarr is listed as a co-founder. The museum features tchotchkes from the 1970s Bigfoot boom, and the 1980s resurrection with Harry and the Hendersons memorabilia. References Sources 2005 establishments in California Bigfoot museums Museums established in 2005 Museums in Santa Cruz County, California
```smalltalk using YoutubeExplode.Common; namespace YoutubeExplode.Search; /// <summary> /// <p> /// Abstract result returned by a search query. /// Use pattern matching to handle specific instances of this type. /// </p> /// <p> /// Can be either one of the following: /// <list type="bullet"> /// <item><see cref="VideoSearchResult" /></item> /// <item><see cref="PlaylistSearchResult" /></item> /// <item><see cref="ChannelSearchResult" /></item> /// </list> /// </p> /// </summary> public interface ISearchResult : IBatchItem { /// <summary> /// Result URL. /// </summary> string Url { get; } /// <summary> /// Result title. /// </summary> string Title { get; } } ```
Magenta Skycode was an indie rock band from Turku, Finland, formed in 2005 by . The band's members were Tomi Mäkilä on keyboard and synthesizer, percussionist Niko Kivikangas, guitarist Henry Ojala, bassist Kalle Taivainen and singer and songwriter Jori Sjöroos, previously known as . Sjöroos also formed This Empty Flow and produced another Finnish pop rock band PMMP. Magenta Skycode is the name of This Empty Flow's debut album. Albums IIIII (2006) Relief (2010) EPs Compassion (2005) We Will Be Warm (2013) References External links Finnish dream pop musical groups Finnish indie rock groups Finnish post-punk music groups Musical groups established in 2005 Musical groups disestablished in 2014 Musical groups from Turku
```go package langserver import ( "context" lsp "github.com/sourcegraph/go-lsp" "github.com/sourcegraph/jsonrpc2" ) func initialize(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) { return lsp.InitializeResult{ Capabilities: lsp.ServerCapabilities{ TextDocumentSync: &lsp.TextDocumentSyncOptionsOrKind{ Options: &lsp.TextDocumentSyncOptions{ OpenClose: true, Change: lsp.TDSKFull, }, }, }, }, nil } ```
```php <?php /** * Multisite administration functions. * * @package WordPress * @subpackage Multisite * @since 3.0.0 */ /** * Determine if uploaded file exceeds space quota. * * @since 3.0.0 * * @param array $file $_FILES array for a given file. * @return array $_FILES array with 'error' key set if file exceeds quota. 'error' is empty otherwise. */ function check_upload_size( $file ) { if ( get_site_option( 'upload_space_check_disabled' ) ) return $file; if ( $file['error'] != '0' ) // there's already an error return $file; if ( defined( 'WP_IMPORTING' ) ) return $file; $space_left = get_upload_space_available(); $file_size = filesize( $file['tmp_name'] ); if ( $space_left < $file_size ) { $file['error'] = sprintf( __( 'Not enough space to upload. %1$s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ); } if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) { $file['error'] = sprintf( __( 'This file is too big. Files must be less than %1$s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ); } if ( upload_is_user_over_quota( false ) ) { $file['error'] = __( 'You have used your space quota. Please delete files before uploading.' ); } if ( $file['error'] != '0' && ! isset( $_POST['html-upload'] ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) { wp_die( $file['error'] . ' <a href="javascript:history.go(-1)">' . __( 'Back' ) . '</a>' ); } return $file; } /** * Delete a site. * * @since 3.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $blog_id Site ID. * @param bool $drop True if site's database tables should be dropped. Default is false. */ function wpmu_delete_blog( $blog_id, $drop = false ) { global $wpdb; $switch = false; if ( get_current_blog_id() != $blog_id ) { $switch = true; switch_to_blog( $blog_id ); } $blog = get_blog_details( $blog_id ); /** * Fires before a site is deleted. * * @since MU * * @param int $blog_id The site ID. * @param bool $drop True if site's table should be dropped. Default is false. */ do_action( 'delete_blog', $blog_id, $drop ); $users = get_users( array( 'blog_id' => $blog_id, 'fields' => 'ids' ) ); // Remove users from this blog. if ( ! empty( $users ) ) { foreach ( $users as $user_id ) { remove_user_from_blog( $user_id, $blog_id ); } } update_blog_status( $blog_id, 'deleted', 1 ); $current_site = get_current_site(); // If a full blog object is not available, do not destroy anything. if ( $drop && ! $blog ) { $drop = false; } // Don't destroy the initial, main, or root blog. if ( $drop && ( 1 == $blog_id || is_main_site( $blog_id ) || ( $blog->path == $current_site->path && $blog->domain == $current_site->domain ) ) ) { $drop = false; } $upload_path = trim( get_option( 'upload_path' ) ); // If ms_files_rewriting is enabled and upload_path is empty, wp_upload_dir is not reliable. if ( $drop && get_site_option( 'ms_files_rewriting' ) && empty( $upload_path ) ) { $drop = false; } if ( $drop ) { $uploads = wp_get_upload_dir(); $tables = $wpdb->tables( 'blog' ); /** * Filter the tables to drop when the site is deleted. * * @since MU * * @param array $tables The site tables to be dropped. * @param int $blog_id The ID of the site to drop tables for. */ $drop_tables = apply_filters( 'wpmu_drop_tables', $tables, $blog_id ); foreach ( (array) $drop_tables as $table ) { $wpdb->query( "DROP TABLE IF EXISTS `$table`" ); } $wpdb->delete( $wpdb->blogs, array( 'blog_id' => $blog_id ) ); /** * Filter the upload base directory to delete when the site is deleted. * * @since MU * * @param string $uploads['basedir'] Uploads path without subdirectory. @see wp_upload_dir() * @param int $blog_id The site ID. */ $dir = apply_filters( 'wpmu_delete_blog_upload_dir', $uploads['basedir'], $blog_id ); $dir = rtrim( $dir, DIRECTORY_SEPARATOR ); $top_dir = $dir; $stack = array($dir); $index = 0; while ( $index < count( $stack ) ) { // Get indexed directory from stack $dir = $stack[$index]; $dh = @opendir( $dir ); if ( $dh ) { while ( ( $file = @readdir( $dh ) ) !== false ) { if ( $file == '.' || $file == '..' ) continue; if ( @is_dir( $dir . DIRECTORY_SEPARATOR . $file ) ) { $stack[] = $dir . DIRECTORY_SEPARATOR . $file; } elseif ( @is_file( $dir . DIRECTORY_SEPARATOR . $file ) ) { @unlink( $dir . DIRECTORY_SEPARATOR . $file ); } } @closedir( $dh ); } $index++; } $stack = array_reverse( $stack ); // Last added dirs are deepest foreach ( (array) $stack as $dir ) { if ( $dir != $top_dir) @rmdir( $dir ); } clean_blog_cache( $blog ); } if ( $switch ) restore_current_blog(); } /** * Delete a user from the network and remove from all sites. * * @since 3.0.0 * * @todo Merge with wp_delete_user() ? * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $id The user ID. * @return bool True if the user was deleted, otherwise false. */ function wpmu_delete_user( $id ) { global $wpdb; if ( ! is_numeric( $id ) ) { return false; } $id = (int) $id; $user = new WP_User( $id ); if ( !$user->exists() ) return false; // Global super-administrators are protected, and cannot be deleted. $_super_admins = get_super_admins(); if ( in_array( $user->user_login, $_super_admins, true ) ) { return false; } /** * Fires before a user is deleted from the network. * * @since MU * * @param int $id ID of the user about to be deleted from the network. */ do_action( 'wpmu_delete_user', $id ); $blogs = get_blogs_of_user( $id ); if ( ! empty( $blogs ) ) { foreach ( $blogs as $blog ) { switch_to_blog( $blog->userblog_id ); remove_user_from_blog( $id, $blog->userblog_id ); $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) ); foreach ( (array) $post_ids as $post_id ) { wp_delete_post( $post_id ); } // Clean links $link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) ); if ( $link_ids ) { foreach ( $link_ids as $link_id ) wp_delete_link( $link_id ); } restore_current_blog(); } } $meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) ); foreach ( $meta as $mid ) delete_metadata_by_mid( 'user', $mid ); $wpdb->delete( $wpdb->users, array( 'ID' => $id ) ); clean_user_cache( $user ); /** This action is documented in wp-admin/includes/user.php */ do_action( 'deleted_user', $id ); return true; } /** * Sends an email when a site administrator email address is changed. * * @since 3.0.0 * * @param string $old_value The old email address. Not currently used. * @param string $value The new email address. */ function update_option_new_admin_email( $old_value, $value ) { if ( $value == get_option( 'admin_email' ) || !is_email( $value ) ) return; $hash = md5( $value. time() .mt_rand() ); $new_admin_email = array( 'hash' => $hash, 'newemail' => $value ); update_option( 'adminhash', $new_admin_email ); /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */ $email_text = __( 'Howdy ###USERNAME###, You recently requested to have the administration email address on your site changed. If this is correct, please click on the following link to change it: ###ADMIN_URL### You can safely ignore and delete this email if you do not want to take this action. This email has been sent to ###EMAIL### Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filter the email text sent when the site admin email is changed. * * The following strings have a special meaning and will get replaced dynamically: * ###USERNAME### The current user's username. * ###ADMIN_URL### The link to click on to confirm the email change. * ###EMAIL### The new email. * ###SITENAME### The name of the site. * ###SITEURL### The URL to the site. * * @since MU * * @param string $email_text Text in the email. * @param string $new_admin_email New admin email that the current administration email was changed to. */ $content = apply_filters( 'new_admin_email_content', $email_text, $new_admin_email ); $current_user = wp_get_current_user(); $content = str_replace( '###USERNAME###', $current_user->user_login, $content ); $content = str_replace( '###ADMIN_URL###', esc_url( self_admin_url( 'options.php?adminhash='.$hash ) ), $content ); $content = str_replace( '###EMAIL###', $value, $content ); $content = str_replace( '###SITENAME###', get_site_option( 'site_name' ), $content ); $content = str_replace( '###SITEURL###', network_home_url(), $content ); wp_mail( $value, sprintf( __( '[%s] New Admin Email Address' ), wp_specialchars_decode( get_option( 'blogname' ) ) ), $content ); } /** * Sends an email when an email address change is requested. * * @since 3.0.0 * * @global WP_Error $errors WP_Error object. * @global wpdb $wpdb WordPress database object. */ function send_confirmation_on_profile_email() { global $errors, $wpdb; $current_user = wp_get_current_user(); if ( ! is_object($errors) ) $errors = new WP_Error(); if ( $current_user->ID != $_POST['user_id'] ) return false; if ( $current_user->user_email != $_POST['email'] ) { if ( !is_email( $_POST['email'] ) ) { $errors->add( 'user_email', __( "<strong>ERROR</strong>: The email address isn&#8217;t correct." ), array( 'form-field' => 'email' ) ); return; } if ( $wpdb->get_var( $wpdb->prepare( "SELECT user_email FROM {$wpdb->users} WHERE user_email=%s", $_POST['email'] ) ) ) { $errors->add( 'user_email', __( "<strong>ERROR</strong>: The email address is already used." ), array( 'form-field' => 'email' ) ); delete_user_meta( $current_user->ID, '_new_email' ); return; } $hash = md5( $_POST['email'] . time() . mt_rand() ); $new_user_email = array( 'hash' => $hash, 'newemail' => $_POST['email'] ); update_user_meta( $current_user->ID, '_new_email', $new_user_email ); /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */ $email_text = __( 'Howdy ###USERNAME###, You recently requested to have the email address on your account changed. If this is correct, please click on the following link to change it: ###ADMIN_URL### You can safely ignore and delete this email if you do not want to take this action. This email has been sent to ###EMAIL### Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filter the email text sent when a user changes emails. * * The following strings have a special meaning and will get replaced dynamically: * ###USERNAME### The current user's username. * ###ADMIN_URL### The link to click on to confirm the email change. * ###EMAIL### The new email. * ###SITENAME### The name of the site. * ###SITEURL### The URL to the site. * * @since MU * * @param string $email_text Text in the email. * @param string $new_user_email New user email that the current user has changed to. */ $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email ); $content = str_replace( '###USERNAME###', $current_user->user_login, $content ); $content = str_replace( '###ADMIN_URL###', esc_url( admin_url( 'profile.php?newuseremail='.$hash ) ), $content ); $content = str_replace( '###EMAIL###', $_POST['email'], $content); $content = str_replace( '###SITENAME###', get_site_option( 'site_name' ), $content ); $content = str_replace( '###SITEURL###', network_home_url(), $content ); wp_mail( $_POST['email'], sprintf( __( '[%s] New Email Address' ), wp_specialchars_decode( get_option( 'blogname' ) ) ), $content ); $_POST['email'] = $current_user->user_email; } } /** * Adds an admin notice alerting the user to check for confirmation email * after email address change. * * @since 3.0.0 * * @global string $pagenow */ function new_user_email_admin_notice() { global $pagenow; if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) && $email = get_user_meta( get_current_user_id(), '_new_email', true ) ) { /* translators: %s: New email address */ echo '<div class="notice notice-info"><p>' . sprintf( __( 'Your email address has not been updated yet. Please check your inbox at %s for a confirmation email.' ), '<code>' . esc_html( $email['newemail'] ) . '</code>' ) . '</p></div>'; } } /** * Check whether a site has used its allotted upload space. * * @since MU * * @param bool $echo Optional. If $echo is set and the quota is exceeded, a warning message is echoed. Default is true. * @return bool True if user is over upload space quota, otherwise false. */ function upload_is_user_over_quota( $echo = true ) { if ( get_site_option( 'upload_space_check_disabled' ) ) return false; $space_allowed = get_space_allowed(); if ( ! is_numeric( $space_allowed ) ) { $space_allowed = 10; // Default space allowed is 10 MB } $space_used = get_space_used(); if ( ( $space_allowed - $space_used ) < 0 ) { if ( $echo ) _e( 'Sorry, you have used your space allocation. Please delete some files to upload more files.' ); return true; } else { return false; } } /** * Displays the amount of disk space used by the current site. Not used in core. * * @since MU */ function display_space_usage() { $space_allowed = get_space_allowed(); $space_used = get_space_used(); $percent_used = ( $space_used / $space_allowed ) * 100; if ( $space_allowed > 1000 ) { $space = number_format( $space_allowed / KB_IN_BYTES ); /* translators: Gigabytes */ $space .= __( 'GB' ); } else { $space = number_format( $space_allowed ); /* translators: Megabytes */ $space .= __( 'MB' ); } ?> <strong><?php printf( __( 'Used: %1$s%% of %2$s' ), number_format( $percent_used ), $space ); ?></strong> <?php } /** * Get the remaining upload space for this site. * * @since MU * * @param int $size Current max size in bytes * @return int Max size in bytes */ function fix_import_form_size( $size ) { if ( upload_is_user_over_quota( false ) ) { return 0; } $available = get_upload_space_available(); return min( $size, $available ); } /** * Displays the site upload space quota setting form on the Edit Site Settings screen. * * @since 3.0.0 * * @param int $id The ID of the site to display the setting for. */ function upload_space_setting( $id ) { switch_to_blog( $id ); $quota = get_option( 'blog_upload_space' ); restore_current_blog(); if ( !$quota ) $quota = ''; ?> <tr> <th><label for="blog-upload-space-number"><?php _e( 'Site Upload Space Quota' ); ?></label></th> <td> <input type="number" step="1" min="0" style="width: 100px" name="option[blog_upload_space]" id="blog-upload-space-number" aria-describedby="blog-upload-space-desc" value="<?php echo $quota; ?>" /> <span id="blog-upload-space-desc"><span class="screen-reader-text"><?php _e( 'Size in megabytes' ); ?></span> <?php _e( 'MB (Leave blank for network default)' ); ?></span> </td> </tr> <?php } /** * Update the status of a user in the database. * * Used in core to mark a user as spam or "ham" (not spam) in Multisite. * * @since 3.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $id The user ID. * @param string $pref The column in the wp_users table to update the user's status * in (presumably user_status, spam, or deleted). * @param int $value The new status for the user. * @param null $deprecated Deprecated as of 3.0.2 and should not be used. * @return int The initially passed $value. */ function update_user_status( $id, $pref, $value, $deprecated = null ) { global $wpdb; if ( null !== $deprecated ) _deprecated_argument( __FUNCTION__, '3.1' ); $wpdb->update( $wpdb->users, array( sanitize_key( $pref ) => $value ), array( 'ID' => $id ) ); $user = new WP_User( $id ); clean_user_cache( $user ); if ( $pref == 'spam' ) { if ( $value == 1 ) { /** * Fires after the user is marked as a SPAM user. * * @since 3.0.0 * * @param int $id ID of the user marked as SPAM. */ do_action( 'make_spam_user', $id ); } else { /** * Fires after the user is marked as a HAM user. Opposite of SPAM. * * @since 3.0.0 * * @param int $id ID of the user marked as HAM. */ do_action( 'make_ham_user', $id ); } } return $value; } /** * Cleans the user cache for a specific user. * * @since 3.0.0 * * @param int $id The user ID. * @return bool|int The ID of the refreshed user or false if the user does not exist. */ function refresh_user_details( $id ) { $id = (int) $id; if ( !$user = get_userdata( $id ) ) return false; clean_user_cache( $user ); return $id; } /** * Returns the language for a language code. * * @since 3.0.0 * * @param string $code Optional. The two-letter language code. Default empty. * @return string The language corresponding to $code if it exists. If it does not exist, * then the first two letters of $code is returned. */ function format_code_lang( $code = '' ) { $code = strtolower( substr( $code, 0, 2 ) ); $lang_codes = array( 'aa' => 'Afar', 'ab' => 'Abkhazian', 'af' => 'Afrikaans', 'ak' => 'Akan', 'sq' => 'Albanian', 'am' => 'Amharic', 'ar' => 'Arabic', 'an' => 'Aragonese', 'hy' => 'Armenian', 'as' => 'Assamese', 'av' => 'Avaric', 'ae' => 'Avestan', 'ay' => 'Aymara', 'az' => 'Azerbaijani', 'ba' => 'Bashkir', 'bm' => 'Bambara', 'eu' => 'Basque', 'be' => 'Belarusian', 'bn' => 'Bengali', 'bh' => 'Bihari', 'bi' => 'Bislama', 'bs' => 'Bosnian', 'br' => 'Breton', 'bg' => 'Bulgarian', 'my' => 'Burmese', 'ca' => 'Catalan; Valencian', 'ch' => 'Chamorro', 'ce' => 'Chechen', 'zh' => 'Chinese', 'cu' => 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic', 'cv' => 'Chuvash', 'kw' => 'Cornish', 'co' => 'Corsican', 'cr' => 'Cree', 'cs' => 'Czech', 'da' => 'Danish', 'dv' => 'Divehi; Dhivehi; Maldivian', 'nl' => 'Dutch; Flemish', 'dz' => 'Dzongkha', 'en' => 'English', 'eo' => 'Esperanto', 'et' => 'Estonian', 'ee' => 'Ewe', 'fo' => 'Faroese', 'fj' => 'Fijjian', 'fi' => 'Finnish', 'fr' => 'French', 'fy' => 'Western Frisian', 'ff' => 'Fulah', 'ka' => 'Georgian', 'de' => 'German', 'gd' => 'Gaelic; Scottish Gaelic', 'ga' => 'Irish', 'gl' => 'Galician', 'gv' => 'Manx', 'el' => 'Greek, Modern', 'gn' => 'Guarani', 'gu' => 'Gujarati', 'ht' => 'Haitian; Haitian Creole', 'ha' => 'Hausa', 'he' => 'Hebrew', 'hz' => 'Herero', 'hi' => 'Hindi', 'ho' => 'Hiri Motu', 'hu' => 'Hungarian', 'ig' => 'Igbo', 'is' => 'Icelandic', 'io' => 'Ido', 'ii' => 'Sichuan Yi', 'iu' => 'Inuktitut', 'ie' => 'Interlingue', 'ia' => 'Interlingua (International Auxiliary Language Association)', 'id' => 'Indonesian', 'ik' => 'Inupiaq', 'it' => 'Italian', 'jv' => 'Javanese', 'ja' => 'Japanese', 'kl' => 'Kalaallisut; Greenlandic', 'kn' => 'Kannada', 'ks' => 'Kashmiri', 'kr' => 'Kanuri', 'kk' => 'Kazakh', 'km' => 'Central Khmer', 'ki' => 'Kikuyu; Gikuyu', 'rw' => 'Kinyarwanda', 'ky' => 'Kirghiz; Kyrgyz', 'kv' => 'Komi', 'kg' => 'Kongo', 'ko' => 'Korean', 'kj' => 'Kuanyama; Kwanyama', 'ku' => 'Kurdish', 'lo' => 'Lao', 'la' => 'Latin', 'lv' => 'Latvian', 'li' => 'Limburgan; Limburger; Limburgish', 'ln' => 'Lingala', 'lt' => 'Lithuanian', 'lb' => 'Luxembourgish; Letzeburgesch', 'lu' => 'Luba-Katanga', 'lg' => 'Ganda', 'mk' => 'Macedonian', 'mh' => 'Marshallese', 'ml' => 'Malayalam', 'mi' => 'Maori', 'mr' => 'Marathi', 'ms' => 'Malay', 'mg' => 'Malagasy', 'mt' => 'Maltese', 'mo' => 'Moldavian', 'mn' => 'Mongolian', 'na' => 'Nauru', 'nv' => 'Navajo; Navaho', 'nr' => 'Ndebele, South; South Ndebele', 'nd' => 'Ndebele, North; North Ndebele', 'ng' => 'Ndonga', 'ne' => 'Nepali', 'nn' => 'Norwegian Nynorsk; Nynorsk, Norwegian', 'nb' => 'Bokml, Norwegian, Norwegian Bokml', 'no' => 'Norwegian', 'ny' => 'Chichewa; Chewa; Nyanja', 'oc' => 'Occitan, Provenal', 'oj' => 'Ojibwa', 'or' => 'Oriya', 'om' => 'Oromo', 'os' => 'Ossetian; Ossetic', 'pa' => 'Panjabi; Punjabi', 'fa' => 'Persian', 'pi' => 'Pali', 'pl' => 'Polish', 'pt' => 'Portuguese', 'ps' => 'Pushto', 'qu' => 'Quechua', 'rm' => 'Romansh', 'ro' => 'Romanian', 'rn' => 'Rundi', 'ru' => 'Russian', 'sg' => 'Sango', 'sa' => 'Sanskrit', 'sr' => 'Serbian', 'hr' => 'Croatian', 'si' => 'Sinhala; Sinhalese', 'sk' => 'Slovak', 'sl' => 'Slovenian', 'se' => 'Northern Sami', 'sm' => 'Samoan', 'sn' => 'Shona', 'sd' => 'Sindhi', 'so' => 'Somali', 'st' => 'Sotho, Southern', 'es' => 'Spanish; Castilian', 'sc' => 'Sardinian', 'ss' => 'Swati', 'su' => 'Sundanese', 'sw' => 'Swahili', 'sv' => 'Swedish', 'ty' => 'Tahitian', 'ta' => 'Tamil', 'tt' => 'Tatar', 'te' => 'Telugu', 'tg' => 'Tajik', 'tl' => 'Tagalog', 'th' => 'Thai', 'bo' => 'Tibetan', 'ti' => 'Tigrinya', 'to' => 'Tonga (Tonga Islands)', 'tn' => 'Tswana', 'ts' => 'Tsonga', 'tk' => 'Turkmen', 'tr' => 'Turkish', 'tw' => 'Twi', 'ug' => 'Uighur; Uyghur', 'uk' => 'Ukrainian', 'ur' => 'Urdu', 'uz' => 'Uzbek', 've' => 'Venda', 'vi' => 'Vietnamese', 'vo' => 'Volapk', 'cy' => 'Welsh','wa' => 'Walloon','wo' => 'Wolof', 'xh' => 'Xhosa', 'yi' => 'Yiddish', 'yo' => 'Yoruba', 'za' => 'Zhuang; Chuang', 'zu' => 'Zulu' ); /** * Filter the language codes. * * @since MU * * @param array $lang_codes Key/value pair of language codes where key is the short version. * @param string $code A two-letter designation of the language. */ $lang_codes = apply_filters( 'lang_codes', $lang_codes, $code ); return strtr( $code, $lang_codes ); } /** * Synchronize category and post tag slugs when global terms are enabled. * * @since 3.0.0 * * @param object $term The term. * @param string $taxonomy The taxonomy for $term. Should be 'category' or 'post_tag', as these are * the only taxonomies which are processed by this function; anything else * will be returned untouched. * @return object|array Returns `$term`, after filtering the 'slug' field with {@see sanitize_title()} * if $taxonomy is 'category' or 'post_tag'. */ function sync_category_tag_slugs( $term, $taxonomy ) { if ( global_terms_enabled() && ( $taxonomy == 'category' || $taxonomy == 'post_tag' ) ) { if ( is_object( $term ) ) { $term->slug = sanitize_title( $term->name ); } else { $term['slug'] = sanitize_title( $term['name'] ); } } return $term; } /** * Displays an access denied message when a user tries to view a site's dashboard they * do not have access to. * * @since 3.2.0 * @access private */ function _access_denied_splash() { if ( ! is_user_logged_in() || is_network_admin() ) return; $blogs = get_blogs_of_user( get_current_user_id() ); if ( wp_list_filter( $blogs, array( 'userblog_id' => get_current_blog_id() ) ) ) return; $blog_name = get_bloginfo( 'name' ); if ( empty( $blogs ) ) wp_die( sprintf( __( 'You attempted to access the "%1$s" dashboard, but you do not currently have privileges on this site. If you believe you should be able to access the "%1$s" dashboard, please contact your network administrator.' ), $blog_name ), 403 ); $output = '<p>' . sprintf( __( 'You attempted to access the "%1$s" dashboard, but you do not currently have privileges on this site. If you believe you should be able to access the "%1$s" dashboard, please contact your network administrator.' ), $blog_name ) . '</p>'; $output .= '<p>' . __( 'If you reached this screen by accident and meant to visit one of your own sites, here are some shortcuts to help you find your way.' ) . '</p>'; $output .= '<h3>' . __('Your Sites') . '</h3>'; $output .= '<table>'; foreach ( $blogs as $blog ) { $output .= '<tr>'; $output .= "<td>{$blog->blogname}</td>"; $output .= '<td><a href="' . esc_url( get_admin_url( $blog->userblog_id ) ) . '">' . __( 'Visit Dashboard' ) . '</a> | ' . '<a href="' . esc_url( get_home_url( $blog->userblog_id ) ). '">' . __( 'View Site' ) . '</a></td>'; $output .= '</tr>'; } $output .= '</table>'; wp_die( $output, 403 ); } /** * Checks if the current user has permissions to import new users. * * @since 3.0.0 * * @param string $permission A permission to be checked. Currently not used. * @return bool True if the user has proper permissions, false if they do not. */ function check_import_new_users( $permission ) { if ( !is_super_admin() ) return false; return true; } // See "import_allow_fetch_attachments" and "import_attachment_size_limit" filters too. /** * Generates and displays a drop-down of available languages. * * @since 3.0.0 * * @param array $lang_files Optional. An array of the language files. Default empty array. * @param string $current Optional. The current language code. Default empty. */ function mu_dropdown_languages( $lang_files = array(), $current = '' ) { $flag = false; $output = array(); foreach ( (array) $lang_files as $val ) { $code_lang = basename( $val, '.mo' ); if ( $code_lang == 'en_US' ) { // American English $flag = true; $ae = __( 'American English' ); $output[$ae] = '<option value="' . esc_attr( $code_lang ) . '"' . selected( $current, $code_lang, false ) . '> ' . $ae . '</option>'; } elseif ( $code_lang == 'en_GB' ) { // British English $flag = true; $be = __( 'British English' ); $output[$be] = '<option value="' . esc_attr( $code_lang ) . '"' . selected( $current, $code_lang, false ) . '> ' . $be . '</option>'; } else { $translated = format_code_lang( $code_lang ); $output[$translated] = '<option value="' . esc_attr( $code_lang ) . '"' . selected( $current, $code_lang, false ) . '> ' . esc_html ( $translated ) . '</option>'; } } if ( $flag === false ) // WordPress english $output[] = '<option value=""' . selected( $current, '', false ) . '>' . __( 'English' ) . "</option>"; // Order by name uksort( $output, 'strnatcasecmp' ); /** * Filter the languages available in the dropdown. * * @since MU * * @param array $output HTML output of the dropdown. * @param array $lang_files Available language files. * @param string $current The current language code. */ $output = apply_filters( 'mu_dropdown_languages', $output, $lang_files, $current ); echo implode( "\n\t", $output ); } /** * Displays an admin notice to upgrade all sites after a core upgrade. * * @since 3.0.0 * * @global int $wp_db_version The version number of the database. * @global string $pagenow * * @return false False if the current user is not a super admin. */ function site_admin_notice() { global $wp_db_version, $pagenow; if ( ! is_super_admin() ) { return false; } if ( 'upgrade.php' == $pagenow ) { return; } if ( get_site_option( 'wpmu_upgrade_site' ) != $wp_db_version ) { echo "<div class='update-nag'>" . sprintf( __( 'Thank you for Updating! Please visit the <a href="%s">Upgrade Network</a> page to update all your sites.' ), esc_url( network_admin_url( 'upgrade.php' ) ) ) . "</div>"; } } /** * Avoids a collision between a site slug and a permalink slug. * * In a subdirectory install this will make sure that a site and a post do not use the * same subdirectory by checking for a site with the same name as a new post. * * @since 3.0.0 * * @param array $data An array of post data. * @param array $postarr An array of posts. Not currently used. * @return array The new array of post data after checking for collisions. */ function avoid_blog_page_permalink_collision( $data, $postarr ) { if ( is_subdomain_install() ) return $data; if ( $data['post_type'] != 'page' ) return $data; if ( !isset( $data['post_name'] ) || $data['post_name'] == '' ) return $data; if ( !is_main_site() ) return $data; $post_name = $data['post_name']; $c = 0; while( $c < 10 && get_id_from_blogname( $post_name ) ) { $post_name .= mt_rand( 1, 10 ); $c ++; } if ( $post_name != $data['post_name'] ) { $data['post_name'] = $post_name; } return $data; } /** * Handles the display of choosing a user's primary site. * * This displays the user's primary site and allows the user to choose * which site is primary. * * @since 3.0.0 */ function choose_primary_blog() { ?> <table class="form-table"> <tr> <?php /* translators: My sites label */ ?> <th scope="row"><label for="primary_blog"><?php _e( 'Primary Site' ); ?></label></th> <td> <?php $all_blogs = get_blogs_of_user( get_current_user_id() ); $primary_blog = get_user_meta( get_current_user_id(), 'primary_blog', true ); if ( count( $all_blogs ) > 1 ) { $found = false; ?> <select name="primary_blog" id="primary_blog"> <?php foreach ( (array) $all_blogs as $blog ) { if ( $primary_blog == $blog->userblog_id ) $found = true; ?><option value="<?php echo $blog->userblog_id ?>"<?php selected( $primary_blog, $blog->userblog_id ); ?>><?php echo esc_url( get_home_url( $blog->userblog_id ) ) ?></option><?php } ?> </select> <?php if ( !$found ) { $blog = reset( $all_blogs ); update_user_meta( get_current_user_id(), 'primary_blog', $blog->userblog_id ); } } elseif ( count( $all_blogs ) == 1 ) { $blog = reset( $all_blogs ); echo esc_url( get_home_url( $blog->userblog_id ) ); if ( $primary_blog != $blog->userblog_id ) // Set the primary blog again if it's out of sync with blog list. update_user_meta( get_current_user_id(), 'primary_blog', $blog->userblog_id ); } else { echo "N/A"; } ?> </td> </tr> </table> <?php } /** * Grants Super Admin privileges. * * @since 3.0.0 * * @global array $super_admins * * @param int $user_id ID of the user to be granted Super Admin privileges. * @return bool True on success, false on failure. This can fail when the user is * already a super admin or when the `$super_admins` global is defined. */ function grant_super_admin( $user_id ) { // If global super_admins override is defined, there is nothing to do here. if ( isset( $GLOBALS['super_admins'] ) ) { return false; } /** * Fires before the user is granted Super Admin privileges. * * @since 3.0.0 * * @param int $user_id ID of the user that is about to be granted Super Admin privileges. */ do_action( 'grant_super_admin', $user_id ); // Directly fetch site_admins instead of using get_super_admins() $super_admins = get_site_option( 'site_admins', array( 'admin' ) ); $user = get_userdata( $user_id ); if ( $user && ! in_array( $user->user_login, $super_admins ) ) { $super_admins[] = $user->user_login; update_site_option( 'site_admins' , $super_admins ); /** * Fires after the user is granted Super Admin privileges. * * @since 3.0.0 * * @param int $user_id ID of the user that was granted Super Admin privileges. */ do_action( 'granted_super_admin', $user_id ); return true; } return false; } /** * Revokes Super Admin privileges. * * @since 3.0.0 * * @global array $super_admins * * @param int $user_id ID of the user Super Admin privileges to be revoked from. * @return bool True on success, false on failure. This can fail when the user's email * is the network admin email or when the `$super_admins` global is defined. */ function revoke_super_admin( $user_id ) { // If global super_admins override is defined, there is nothing to do here. if ( isset( $GLOBALS['super_admins'] ) ) { return false; } /** * Fires before the user's Super Admin privileges are revoked. * * @since 3.0.0 * * @param int $user_id ID of the user Super Admin privileges are being revoked from. */ do_action( 'revoke_super_admin', $user_id ); // Directly fetch site_admins instead of using get_super_admins() $super_admins = get_site_option( 'site_admins', array( 'admin' ) ); $user = get_userdata( $user_id ); if ( $user && 0 !== strcasecmp( $user->user_email, get_site_option( 'admin_email' ) ) ) { if ( false !== ( $key = array_search( $user->user_login, $super_admins ) ) ) { unset( $super_admins[$key] ); update_site_option( 'site_admins', $super_admins ); /** * Fires after the user's Super Admin privileges are revoked. * * @since 3.0.0 * * @param int $user_id ID of the user Super Admin privileges were revoked from. */ do_action( 'revoked_super_admin', $user_id ); return true; } } return false; } /** * Whether or not we can edit this network from this page. * * By default editing of network is restricted to the Network Admin for that `$site_id` * this allows for this to be overridden. * * @since 3.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $site_id The network/site ID to check. * @return bool True if network can be edited, otherwise false. */ function can_edit_network( $site_id ) { global $wpdb; if ( $site_id == $wpdb->siteid ) $result = true; else $result = false; /** * Filter whether this network can be edited from this page. * * @since 3.1.0 * * @param bool $result Whether the network can be edited from this page. * @param int $site_id The network/site ID to check. */ return apply_filters( 'can_edit_network', $result, $site_id ); } /** * Thickbox image paths for Network Admin. * * @since 3.1.0 * * @access private */ function _thickbox_path_admin_subfolder() { ?> <script type="text/javascript"> var tb_pathToImage = "<?php echo includes_url( 'js/thickbox/loadingAnimation.gif', 'relative' ); ?>"; </script> <?php } /** * * @param array $users */ function confirm_delete_users( $users ) { $current_user = wp_get_current_user(); if ( ! is_array( $users ) || empty( $users ) ) { return false; } ?> <h1><?php esc_html_e( 'Users' ); ?></h1> <?php if ( 1 == count( $users ) ) : ?> <p><?php _e( 'You have chosen to delete the user from all networks and sites.' ); ?></p> <?php else : ?> <p><?php _e( 'You have chosen to delete the following users from all networks and sites.' ); ?></p> <?php endif; ?> <form action="users.php?action=dodelete" method="post"> <input type="hidden" name="dodelete" /> <?php wp_nonce_field( 'ms-users-delete' ); $site_admins = get_super_admins(); $admin_out = '<option value="' . esc_attr( $current_user->ID ) . '">' . $current_user->user_login . '</option>'; ?> <table class="form-table"> <?php foreach ( ( $allusers = (array) $_POST['allusers'] ) as $user_id ) { if ( $user_id != '' && $user_id != '0' ) { $delete_user = get_userdata( $user_id ); if ( ! current_user_can( 'delete_user', $delete_user->ID ) ) { wp_die( sprintf( __( 'Warning! User %s cannot be deleted.' ), $delete_user->user_login ) ); } if ( in_array( $delete_user->user_login, $site_admins ) ) { wp_die( sprintf( __( 'Warning! User cannot be deleted. The user %s is a network administrator.' ), '<em>' . $delete_user->user_login . '</em>' ) ); } ?> <tr> <th scope="row"><?php echo $delete_user->user_login; ?> <?php echo '<input type="hidden" name="user[]" value="' . esc_attr( $user_id ) . '" />' . "\n"; ?> </th> <?php $blogs = get_blogs_of_user( $user_id, true ); if ( ! empty( $blogs ) ) { ?> <td><fieldset><p><legend><?php printf( /* translators: user login */ __( 'What should be done with content owned by %s?' ), '<em>' . $delete_user->user_login . '</em>' ); ?></legend></p> <?php foreach ( (array) $blogs as $key => $details ) { $blog_users = get_users( array( 'blog_id' => $details->userblog_id, 'fields' => array( 'ID', 'user_login' ) ) ); if ( is_array( $blog_users ) && !empty( $blog_users ) ) { $user_site = "<a href='" . esc_url( get_home_url( $details->userblog_id ) ) . "'>{$details->blogname}</a>"; $user_dropdown = '<label for="reassign_user" class="screen-reader-text">' . __( 'Select a user' ) . '</label>'; $user_dropdown .= "<select name='blog[$user_id][$key]' id='reassign_user'>"; $user_list = ''; foreach ( $blog_users as $user ) { if ( ! in_array( $user->ID, $allusers ) ) { $user_list .= "<option value='{$user->ID}'>{$user->user_login}</option>"; } } if ( '' == $user_list ) { $user_list = $admin_out; } $user_dropdown .= $user_list; $user_dropdown .= "</select>\n"; ?> <ul style="list-style:none;"> <li><?php printf( __( 'Site: %s' ), $user_site ); ?></li> <li><label><input type="radio" id="delete_option0" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID ?>]" value="delete" checked="checked" /> <?php _e( 'Delete all content.' ); ?></label></li> <li><label><input type="radio" id="delete_option1" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID ?>]" value="reassign" /> <?php _e( 'Attribute all content to:' ); ?></label> <?php echo $user_dropdown; ?></li> </ul> <?php } } echo "</fieldset></td></tr>"; } else { ?> <td><fieldset><p><legend><?php _e( 'User has no sites or content and will be deleted.' ); ?></legend></p> <?php } ?> </tr> <?php } } ?> </table> <?php /** This action is documented in wp-admin/users.php */ do_action( 'delete_user_form', $current_user, $allusers ); if ( 1 == count( $users ) ) : ?> <p><?php _e( 'Once you hit &#8220;Confirm Deletion&#8221;, the user will be permanently removed.' ); ?></p> <?php else : ?> <p><?php _e( 'Once you hit &#8220;Confirm Deletion&#8221;, these users will be permanently removed.' ); ?></p> <?php endif; submit_button( __('Confirm Deletion'), 'primary' ); ?> </form> <?php return true; } /** * Print JavaScript in the header on the Network Settings screen. * * @since 4.1.0 */ function network_settings_add_js() { ?> <script type="text/javascript"> jQuery(document).ready( function($) { var languageSelect = $( '#WPLANG' ); $( 'form' ).submit( function() { // Don't show a spinner for English and installed languages, // as there is nothing to download. if ( ! languageSelect.find( 'option:selected' ).data( 'installed' ) ) { $( '#submit', this ).after( '<span class="spinner language-install-spinner" />' ); } }); }); </script> <?php } ```
The 12931 / 12932 Mumbai Central–Ahmedabad Double Decker Express is a Double Decker Express train belonging to Indian Railways that runs between Mumbai Central (MMCT) and Ahmedabad Junction (ADI) in India. It runs 6 days in week except Sunday. It operates as train number 12931 from Mumbai Central to Ahmedabad Junction and as train number 12932 in the reverse direction. On 20 March 2017, the exteriors of the train departing Mumbai Central were covered with vinyl wrapping advertisements becoming the Indian Railway's first "branded" train. The advertisements were for soap brand Savlon, as part of its Savlon Swasth India Mission, a social awareness initiative for promoting hand hygiene. Coach composition 12931 / 12932 Mumbai Central - Ahmedabad Double Decker Express had 11 AC Chair Car and 2 EOG cars. As with most train services in India, coach composition may be amended depending on demand. Service 12931 / 12932 Mumbai Central - Ahmedabad Double Decker Express was first introduced on 19 September 2012. it runs 6 days except Sunday. It covers the distance of 491 kilometres in 6 hours 55 mins as 12931 Mumbai Central - Ahmedabad Double Decker Express and as 12932 Ahmedabad - Mumbai Central Double Decker Express (71 km/h). Gallery References External links Sister Trains Gujarat Queen Karnavati Express Mumbai Central - Ahmedabad Passenger Mumbai Central-Ahmedabad Shatabdi Express Mumbai–Ahmedabad trains Double-decker trains of India Railway services introduced in 2012 2012 establishments in India Rail transport in Maharashtra
The 1987–88 SEC Women's Basketball Season began with practices in October 1987, followed by the start of the 1987–88 NCAA Division I women's basketball season in November. Conference play started in early January 1988 and concluded in March, followed by the 1988 SEC women's basketball tournament in Albany, Georgia. Preseason Preseason All-SEC teams Coaches select 5 players Players in bold are choices for SEC Player of the Year Rankings SEC regular season Postseason SEC tournament Honors and awards All-SEC awards and teams References Southeastern Conference women's basketball seasons
Yukarıkaraören is a neighbourhood in the municipality and district of Kızılcahamam, Ankara Province, Turkey. Its population is 189 (2022). References Neighbourhoods in Kızılcahamam District
Visitor management refers to a set of practices or hardware additions that administrators can use to monitor the usage of a building or site. By gathering this information, a visitor management system can record the usage of facilities by specific visitors and provide documentation of visitor's whereabouts. Proponents of an information-rich visitor management system point to increased security, particularly in schools, as one benefit. As more parents demand action from schools that will protect children from sexual predators, some school districts are turning to modern visitor management systems that not only track a visitor's stay, but also check the visitor's information against national and local criminal databases. Visitor management technologies Computer visitor management systems Basic computer or electronic visitor management systems use a computer network to monitor and record visitor information and are commonly hosted on an iPad or a touchless kiosk. An electronic visitor management system improves upon most of the negative points of a pen and paper system. Visitor ID can be checked against national and local databases, as well as in-house databases for potential security problems. Visitor management software as a service The legacy on-site visitor management software is considered to be expensive and requires maintenance, having obstacles of the overlap of operations, facility management and IT, and difficulties in introducing a unified system to multiple company locations with different processes and requirements. SaaS visitor management software for schools allows administrators to screen visitors upon entrance, often checking for sex offender status, and restricting access to unauthorized entrants. SaaS visitor management software for the real estate industry allows landlords and managers to remotely control and monitor access rights without the need to pass physical keys and keycards to new tenants. SaaS visitor management software for commercial offices allows facilities managers to automate their building's reception area with advocates of this type of system claiming a variety of benefits, including both security and privacy. Many modern SaaS visitor management systems are tablet-based apps, and are thin client solutions operating software as a service in the cloud. Visitor management systems on smartphones Smart phone based visitor management system work similarly to a web-based system, but hosts can get real-time notifications or alerts on their device. Hosts can allow or deny visits to guests based on their interests or availability. Smartphone-based visitor management systems also enable features like automatic and touchless sign-in using technologies that include QR codes and geofencing. Integrations with other systems Cloud-based visitor management systems offer integration with other workplace management systems, such as communication apps, access control, data report, and Wi-Fi credentials. An integrated visitor management system organises, streamlines, and collects important data that facilities managers can use to understand their workplaces while offering a great experience for employees and visitors. Featuring an open API enables modern visitor management systems to integrate with any software and workflows without limitation. Types of Visitor Management Systems Pen and paper-based system On-premise software Cloud-based software Use Cases Hospitals Schools Commercial buildings Offices Convention Centers/ Manufactories for contractor management See also Access control Optical turnstile Identity document Proximity card Boom barrier Cross-device tracking References External links Access control Security
Bjørn Erik Thon (born 6 February 1964) is a Norwegian jurist and ombudsman. Career He graduated as cand.jur. in 1989. From 1999 to 2000, during the first cabinet Bondevik Thon worked as a political advisor in the Ministry of Justice and the Police. He has been a member of Grefsen-Kjelsås borough council for the Liberal Party. From 2000 to 2010, he headed the office of the Norwegian Consumer Ombudsman. His period was renewed in 2007. He succeeded Georg Apenes as director of the Norwegian Data Inspectorate in late May 2010, though his immediate predecessor was acting director Ove Skåra. Ombudsman of Gender Equality and Anti-Discrimination On 19 November 2021, he was nominated to succeed Hanne Bjurstrøm as ombudsman of the Gender Equality and Anti-Discrimination Ombud. He became the first man to hold the position. He assumes office on 28 February 2022. In July 2022, Thon argued that the incident of a Russian woman not being granted a job interview due to her nationality, was a clear example of discrimination. He also emphasised that it was important to differentiate between the Russian state and individual Russian citizens. He was supported by lawyer Henriette Willix from Advokatfirmaet Sulland. Writing In 2000, he started his career as a writer with his crime novel Svart kappe. He followed with the crime novels Den tause klienten in 2002 and Den enes død in 2004. In 2005 he wrote the consumer issues book Forbrukerjungelboka with Ola Fæhn. References 1964 births Living people Norwegian jurists Directors of government agencies of Norway Norwegian crime fiction writers Norwegian non-fiction writers Ombudsmen in Norway Liberal Party (Norway) politicians Politicians from Oslo
```yaml # # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # name: pg_description columns: objoid: caseSensitive: true dataType: -5 generated: false name: objoid primaryKey: false unsigned: false visible: true classoid: caseSensitive: true dataType: -5 generated: false name: classoid primaryKey: false unsigned: false visible: true objsubid: caseSensitive: true dataType: 4 generated: false name: objsubid primaryKey: false unsigned: false visible: true description: caseSensitive: true dataType: 12 generated: false name: description primaryKey: false unsigned: false visible: true indexes: pg_description_o_c_o_index: name: pg_description_o_c_o_index ```
```xml import * as React from 'react'; import { Divider } from '@fluentui/react-northstar'; const DividerExampleContent = () => <Divider>Some text</Divider>; export default DividerExampleContent; ```
Thrombus perviousness is an imaging biomarker which is used to estimate clot permeability from CT imaging. It reflects the ability of artery-occluding thrombi to let fluid seep into and through them. The more pervious a thrombus, the more fluid it lets through. Thrombus perviousness can be measured using radiological imaging routinely performed in the clinical management of acute ischemic stroke: CT scans without intravenous contrast (also called non-contrast CT, in short NCCT) combined with CT scans after intravenously administered contrast fluid (CT-angiography, in short CTA). Pervious thrombi may let more blood pass through to the ischemic brain tissue, and/or have a larger contact surface and histopathology more sensitive for thrombolytic medication. Thus, patients with pervious thrombi may have less brain tissue damage by stroke. The value of thrombus perviousness in acute ischemic stroke treatment is currently being researched. Etymology Emilie Santos et al. introduced the term thrombus perviousness in 2016 to estimate thrombus permeability in ischemic stroke patients. Before, Mishra et al. used ‘residual flow within the clot’, and Frölich et al. used ‘antegrade flow across incomplete vessel occlusions’ to describe an estimate of thrombus permeability. Permeability is the physical measure of the ability of a material to transmit fluids over time. To measure thrombus permeability, one needs to measure contrast flow through a clot over time and the pressure drop caused by the occlusion, which is commonly not possible in the acute management of a patient with acute ischemic stroke. Current standard diagnostic protocol for acute ischemic stroke only requires single-phase imaging, visualizing the thrombus at a snapshot in time. Therefore, thrombus perviousness was introduced as a derivative measure of permeability. Measurement The amount of contrast that seeps into a thrombus can be quantified by the density difference of thrombi between non-contrast computed tomography (NCCT) and CT angiography (CTA) images. Two measures for thrombus perviousness have been introduced: (1) the void fraction and (2) thrombus attenuation increase (TAI). Void fraction (ε) The void fraction represents the ratio of the void volume within a thrombus, filled with a volume of blood (Vblood) and the volume of thrombus material (Vthrombus):Void fraction can be estimated by measuring the attenuation increase (Δ) between NCCT and CTA in the thrombus (Δthrombus) and in the contralateral artery, filling with contrast on CTA (Δblood), and subsequently compute the ratio of these Δs: Thrombus attenuation increase To measure TAI, the mean attenuation (density, in Hounsfield Units) of a clot is measured on NCCT (ρthrombusNCCT) and subtracted from the thrombus density measured on CTA (ρthrombusCTA). CTA thrombus density increases after administration of the high-density contrast fluid used in CTA: Δthrombus = ρthrombusCTA – ρthrombusNCCT A manual (volume of interest [ROI]-based) and semi-automated (full thrombus segmentation) method have been described to measure thrombus density. Manual 3-ROI TAI assessment In the manual thrombus perviousness assessment, spherical ROIs with a diameter of 2 mm are manually placed in the thrombus, both on NCCT and CTA. To improve reflection of possible thrombus heterogeneity, three ROIs are placed per imaging modality rather than one. The average of every three ROIs is calculated and used as ρthrombusNCCT and ρthrombusCTA. Semi-automated full thrombus segmentation In automated measurements, the thrombus on CTA images is semi-automatically segmented in three steps. An observer places four seed points. The first two are placed in the vasculature ipsilateral to (on the same side as) the occlusion, one proximal and one distal to the clot. The second two are placed in the contralateral vasculature (on the opposite side), both at approximately the same height as the first two points. The automated method subsequently segments the contralateral vasculature using these seed points. The segmentation of the contralateral side is mapped to the occluded artery, using mirror symmetry, to segment the occluded artery. The thrombus is segmented using intensity based region growing. Finally, the density distribution of the entire thrombus in NCCT is compared to that in CTA to calculate thrombus attenuation increase (Δ). Comparison between 3-ROI and semi-automated full thrombus measurement It has been shown that manual measurement tends to overestimate actual entire thrombus density, especially in low-density thrombi. Measurements based on the full thrombus show a wider variety of thrombus densities and better discrimination of high- and low-density thrombi and shows a stronger correlation with outcome measures than measurements based on 3 ROIs. Influence of imaging parameters TAI measurements performed on CT scans with thicker slices will be less accurate, because volume averaging results in a reduction of thrombus density on NCCT. Therefore, it has been suggested to only use thin-slice CT images (≤2.5 mm) to measure thrombus perviousness. Additional permeability measures Alternative measures of similar thrombus permeability characteristics have been introduced and are still being introduced. Mishra et al. introduced the residual flow grade, which distinguishes no contrast penetration (grade 0); contrast permeating diffusely through thrombus (grade 1); and tiny hairline lumen or streak of well-defined contrast within the thrombus extending either through its entire length or part of the thrombus (grade 2). Clinical relevance Currently, treatment for acute ischemic stroke due to an occlusion of one of the arteries of the proximal anterior intracranial circulation consists of intravenous thrombolysis followed by endovascular thrombectomy for patients that arrive at the hospital within 4.5 hours of stroke onset. Patients that arrive later than 4.5 hours after onset, or have contra-indications for intravenous thrombolysis can still be eligible for endovascular thrombectomy only. Even with treatment, not all patients recover after their stroke; many are left with permanent brain damage. Increased thrombus perviousness may decrease brain damage during stroke by allowing more blood to reach the ischemic tissue. Furthermore, level of perviousness may reflect histopathological composition of clots or size of contact surface for thrombolytic medication, thereby influencing effectiveness of thrombolysis. Thrombus perviousness in research A number of studies has been conducted on the effects of thrombus perviousness on NCCT and CTA. In addition, dynamic imaging modalities have been used to investigate thrombus perviousness/permeability in animal and laboratory studies and in humans using digital subtraction angiography (DSA) and CT Perfusion/4D-CTA. 4D-CTA may enable more accurate measurement of TAI, since it overcomes the influence of varying scan timing and contrast arrival in single phase CTA. References Radiography Radiology
The mottle-backed elaenia (Elaenia gigas) is a species of bird in the family Tyrannidae. It is found in Bolivia, Colombia, Ecuador, and Peru. Its natural habitats are subtropical or tropical moist shrubland and heavily degraded former forest. References mottle-backed elaenia Birds of the Ecuadorian Amazon Birds of the Peruvian Amazon mottle-backed elaenia mottle-backed elaenia Taxonomy articles created by Polbot
```php <?php /** * This file was originally part of brick/math * * * 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. * * @link path_to_url brick/math at GitHub */ declare(strict_types=1); namespace Ramsey\Uuid\Math; /** * Specifies a rounding behavior for numerical operations capable of discarding * precision. * * Each rounding mode indicates how the least significant returned digit of a * rounded result is to be calculated. If fewer digits are returned than the * digits needed to represent the exact numerical result, the discarded digits * will be referred to as the discarded fraction regardless the digits' * contribution to the value of the number. In other words, considered as a * numerical value, the discarded fraction could have an absolute value greater * than one. */ final class RoundingMode { /** * Private constructor. This class is not instantiable. * * @codeCoverageIgnore */ private function __construct() { } /** * Asserts that the requested operation has an exact result, hence no * rounding is necessary. */ public const UNNECESSARY = 0; /** * Rounds away from zero. * * Always increments the digit prior to a nonzero discarded fraction. * Note that this rounding mode never decreases the magnitude of the * calculated value. */ public const UP = 1; /** * Rounds towards zero. * * Never increments the digit prior to a discarded fraction (i.e., * truncates). Note that this rounding mode never increases the magnitude of * the calculated value. */ public const DOWN = 2; /** * Rounds towards positive infinity. * * If the result is positive, behaves as for UP; if negative, behaves as for * DOWN. Note that this rounding mode never decreases the calculated value. */ public const CEILING = 3; /** * Rounds towards negative infinity. * * If the result is positive, behave as for DOWN; if negative, behave as for * UP. Note that this rounding mode never increases the calculated value. */ public const FLOOR = 4; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, * in which case round up. * * Behaves as for UP if the discarded fraction is >= 0.5; otherwise, behaves * as for DOWN. Note that this is the rounding mode commonly taught at * school. */ public const HALF_UP = 5; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, * in which case round down. * * Behaves as for UP if the discarded fraction is > 0.5; otherwise, behaves * as for DOWN. */ public const HALF_DOWN = 6; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, * in which case round towards positive infinity. * * If the result is positive, behaves as for HALF_UP; if negative, behaves * as for HALF_DOWN. */ public const HALF_CEILING = 7; /** * Rounds towards "nearest neighbor" unless both neighbors are equidistant, * in which case round towards negative infinity. * * If the result is positive, behaves as for HALF_DOWN; if negative, behaves * as for HALF_UP. */ public const HALF_FLOOR = 8; /** * Rounds towards the "nearest neighbor" unless both neighbors are * equidistant, in which case rounds towards the even neighbor. * * Behaves as for HALF_UP if the digit to the left of the discarded fraction * is odd; behaves as for HALF_DOWN if it's even. * * Note that this is the rounding mode that statistically minimizes * cumulative error when applied repeatedly over a sequence of calculations. * It is sometimes known as "Banker's rounding", and is chiefly used in the * USA. */ public const HALF_EVEN = 9; } ```
Qanj Ali Khan Afshar castle () is a historical castle located in Baft County in Kerman Province, The longevity of this fortress dates back to the Safavid dynasty. References Castles in Iran
```python from __future__ import unicode_literals import sys import inspect from collections import Mapping from future.utils import PY3, exec_ if PY3: import builtins def apply(f, *args, **kw): return f(*args, **kw) from past.builtins import str as oldstr def chr(i): """ Return a byte-string of one character with ordinal i; 0 <= i <= 256 """ return oldstr(bytes((i,))) def cmp(x, y): """ cmp(x, y) -> integer Return negative if x<y, zero if x==y, positive if x>y. """ return (x > y) - (x < y) from sys import intern def oct(number): """oct(number) -> string Return the octal representation of an integer """ return '0' + builtins.oct(number)[2:] raw_input = input from imp import reload unicode = str unichr = chr xrange = range else: import __builtin__ apply = __builtin__.apply chr = __builtin__.chr cmp = __builtin__.cmp execfile = __builtin__.execfile intern = __builtin__.intern oct = __builtin__.oct raw_input = __builtin__.raw_input reload = __builtin__.reload unicode = __builtin__.unicode unichr = __builtin__.unichr xrange = __builtin__.xrange if PY3: def execfile(filename, myglobals=None, mylocals=None): """ Read and execute a Python script from a file in the given namespaces. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. """ if myglobals is None: # There seems to be no alternative to frame hacking here. caller_frame = inspect.stack()[1] myglobals = caller_frame[0].f_globals mylocals = caller_frame[0].f_locals elif mylocals is None: # Only if myglobals is given do we set mylocals to it. mylocals = myglobals if not isinstance(myglobals, Mapping): raise TypeError('globals must be a mapping') if not isinstance(mylocals, Mapping): raise TypeError('locals must be a mapping') with open(filename, "rbU") as fin: source = fin.read() code = compile(source, filename, "exec") exec_(code, myglobals, mylocals) if PY3: __all__ = ['apply', 'chr', 'cmp', 'execfile', 'intern', 'raw_input', 'reload', 'unichr', 'unicode', 'xrange'] else: __all__ = [] ```
```c++ #include <vector> #include "hdf5.h" #include "hdf5_hl.h" #include "caffe/layers/hdf5_output_layer.hpp" #include "caffe/util/hdf5.hpp" namespace caffe { template <typename Dtype> void HDF5OutputLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { file_name_ = this->layer_param_.hdf5_output_param().file_name(); file_id_ = H5Fcreate(file_name_.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); CHECK_GE(file_id_, 0) << "Failed to open HDF5 file" << file_name_; file_opened_ = true; } template <typename Dtype> HDF5OutputLayer<Dtype>::~HDF5OutputLayer<Dtype>() { if (file_opened_) { herr_t status = H5Fclose(file_id_); CHECK_GE(status, 0) << "Failed to close HDF5 file " << file_name_; } } template <typename Dtype> void HDF5OutputLayer<Dtype>::SaveBlobs() { // TODO: no limit on the number of blobs LOG(INFO) << "Saving HDF5 file " << file_name_; CHECK_EQ(data_blob_.num(), label_blob_.num()) << "data blob and label blob must have the same batch size"; hdf5_save_nd_dataset(file_id_, HDF5_DATA_DATASET_NAME, data_blob_); hdf5_save_nd_dataset(file_id_, HDF5_DATA_LABEL_NAME, label_blob_); LOG(INFO) << "Successfully saved " << data_blob_.num() << " rows"; } template <typename Dtype> void HDF5OutputLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_GE(bottom.size(), 2); CHECK_EQ(bottom[0]->num(), bottom[1]->num()); data_blob_.Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); label_blob_.Reshape(bottom[1]->num(), bottom[1]->channels(), bottom[1]->height(), bottom[1]->width()); const int data_datum_dim = bottom[0]->count() / bottom[0]->num(); const int label_datum_dim = bottom[1]->count() / bottom[1]->num(); for (int i = 0; i < bottom[0]->num(); ++i) { caffe_copy(data_datum_dim, &bottom[0]->cpu_data()[i * data_datum_dim], &data_blob_.mutable_cpu_data()[i * data_datum_dim]); caffe_copy(label_datum_dim, &bottom[1]->cpu_data()[i * label_datum_dim], &label_blob_.mutable_cpu_data()[i * label_datum_dim]); } SaveBlobs(); } template <typename Dtype> void HDF5OutputLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { return; } #ifdef CPU_ONLY STUB_GPU(HDF5OutputLayer); #endif INSTANTIATE_CLASS(HDF5OutputLayer); REGISTER_LAYER_CLASS(HDF5Output); } // namespace caffe ```
```swift // // CollapsibleTableViewCell.swift // ios-swift-collapsible-table-section // // Created by Yong Su on 7/17/17. // import UIKit class CollapsibleTableViewCell: UITableViewCell { let nameLabel = UILabel() let detailLabel = UILabel() // MARK: Initalizers override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let marginGuide = contentView.layoutMarginsGuide // configure nameLabel contentView.addSubview(nameLabel) nameLabel.translatesAutoresizingMaskIntoConstraints = false nameLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true nameLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true nameLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true nameLabel.numberOfLines = 0 nameLabel.font = UIFont.systemFont(ofSize: 16) // configure detailLabel contentView.addSubview(detailLabel) detailLabel.lineBreakMode = .byWordWrapping detailLabel.translatesAutoresizingMaskIntoConstraints = false detailLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true detailLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true detailLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true detailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 5).isActive = true detailLabel.numberOfLines = 0 detailLabel.font = UIFont.systemFont(ofSize: 12) detailLabel.textColor = UIColor.lightGray } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ```
Sulaiman Khateeb (1922–1978) was an Urdu, Deccani poet. References External links http://www.thehindu.com/todays-paper/tp-national/tp-karnataka/sslc-toppers-to-be-feted/article125698.ece http://www.thehindu.com/todays-paper/tp-national/tp-andhrapradesh/mizahia-mushaira-sets-off-guffaws/article2829976.ece http://www.karnatakamuslims.com/portal/great-deccani-urdu-poet-sulaiman-khateeb-on-the-web/ Home page http://www.siasat.com/english/news/suleman-khateeb%E2%80%99s-dakhini-urdu-poetry-reforms-society-%E2%80%93-mr-zahid-ali-khan http://timesofindia.indiatimes.com/topic/Sulaiman-Khateeb http://www.siasat.com/english/news/sulaiman-khateeb-memorial-function http://www.caravanmagazine.in/arts/god-small-verse-dakhani-poetry-khateeb Urdu-language poets from India 1922 births 1978 deaths 20th-century Indian poets Indian male poets 20th-century Indian male writers
Hedi El Kholti (born February 24, 1967, in Rabat, Morocco) is a writer and editor based in Los Angeles. He is co-editor of Semiotext(e) alongside Chris Kraus and Sylvère Lotringer. He was partner at the now defunct Dilettante Press and currently edits Semiotext(e)’s ‘occasional intellectual journal’ Animal Shelter. He is a graduate of the Art Center College of Design. Bibliography Animal Shelter 1 (Semiotext(e), 2008) Animal Shelter 2 (Semiotext(e), 2012) Animal Shelter 3 (Semiotext(e), 2013) References External links Semiotext(e) Homepage Hedi El Kholti on WorldCat Writers from Casablanca Living people 1967 births Moroccan writers Art Center College of Design alumni Writers from Los Angeles American people of Moroccan descent
Derek Watkins (born February 13, 1974), known professionally as Fonzworth Bentley, is an American rapper, actor, television presenter, and author. He is perhaps best known for being Sean Combs' former personal valet and assistant, as first seen in Making the Band 2, and was the host of MTV's From G's to Gents. He was born in Atlanta, Georgia. Career He first appeared rapping on Da Band's 2002 album Too Hot for TV, in the track "Cheers to Me, Mr. Bentley (Interlude)". In 2003, Bentley was featured on the "Good Day, Good Sir" skit on OutKast's Speakerboxxx/The Love Below. In 2004, he made a cameo in the music video of Kanye West's "The New Workout Plan". Bentley is credited as a songwriter on multiple Yeezus tracks including “On Sight,” “Black Skinhead,” “I Am a God,” and “Hold My Liquor.” He is also credited as a producer on West's “Ultralight Beam.” His debut album, C.O.L.O.U.R.S., was released via iTunes on April 26, 2011. He was also featured, playing the violin in the "Yes We Can" music video in support of Barack Obama's 2008 presidential campaign. Other media work Bentley was an executive producer for Borrow My Crew in 2005, in which he allowed one boy, Cory Cole, to borrow the entourage of P. Diddy for two days. In 2008, he hosted the MTV reality series From G's to Gents, which ran for two seasons. In 2007, Bentley authored an etiquette book, Advance Your Swagger: How to Use Manners, Confidence and Style to Get Ahead. In May 2009, Bentley hosted one of the afterparties following the White House Correspondents' Dinner in Washington, D.C. Public service In 2007, Bentley contributed to KnowHow2GO. Bentley's involvement in the campaign has included creation of a radio public service advertisement ("Wanna Go?") and participation in the 2007 YMCA Black and Hispanic Achievers Teen Leadership Summit in Orlando, Florida. Bentley sang as a member of the chorus for "We Are The World", a remake of the original for Haiti, in February 2010. Works Television From G's to Gents (2008–09) Top Ten Gentlemen's Club (2008) Confessions of a Celebrity Assistant (2006, the E! Channel) VH1 Fashion Rocks (2006) All Shades of Fine: 25 Hottest Women of the Past 25 Years (2005) P. Diddy Presents the Bad Boys of Comedy (2005) Caleta Condor, Chile (2005) Before, During and After the Sunset (2005) Borrow My Crew (2005) Fade to Black (2004) Making the Band 2 (2002–2003, series) Films Honey (2003) – Barber Fat Albert (2004) – Salesman Idlewild (2006) – Voice of Flask We Were Once A Fairytale – cameo appearance Think Like a Man Too'' (2014) - Limo Driver References External links Living people Male actors from Atlanta American male television actors American male film actors American fashion designers African-American rappers Morehouse College alumni MTV Video Music Award winners Fashion Institute of Technology alumni 1974 births 21st-century American rappers Purple Ribbon All-Stars members 21st-century African-American musicians 20th-century African-American people
The Chumash Wilderness is a wilderness area within the southern Los Padres National Forest. It is located in the Transverse Ranges, in northern Ventura County and southwestern Kern County in California. The wilderness was created by the U.S. Congress as part of the Los Padres Condor Range and River Protection Act of 1992 (Public Law 102–301). The same legislation also established the Garcia, Machesna Mountain, Matilija, Sespe, and Silver Peak Wilderness areas. Geography The Chumash Wilderness includes most of the highest terrain in Ventura County. The nearest towns are in the Mountain Communities of the Tejon Pass region, including the unincorporated communities of Frazier Park to the east, Lockwood Valley and Cuddy Valley to the south, Pine Mountain Club to the north. The Cuyama Valley region is to the west The wilderness area extends from just west of the summit of Mount Pinos () to Cerro Noroeste (Mount Abel) to the west, and south into the badlands north of Lockwood Valley Road. Since Mount Pinos, Cerro Noroeste, and the Pine Mountain Club are developed with paved roads, they did not qualify for inclusion in the wilderness, which wraps partially around them. The highest point in the Chumash Wilderness is Sawmill Mountain, at . Major trailheads into the wilderness can be found at Mount Pinos as well as Cerro Noroeste/Mount Abel. From the Mount Pinos parking area, the wilderness trailhead is approximately 2 miles (3 km) along a dirt road with a locked gate. Vegetation within the wilderness includes chaparral at lower elevations, and conifers at higher elevations. Some of the badlands near the southern edge of the wilderness are almost barren of vegetation, and include steep slopes with knife-edge ridges. Snow is frequent from fall until late spring at the highest elevations. Rain is rare in the summer, and wildfires are natural in the fire ecology based habitats. Characteristic fauna of the wilderness include black bear, mountain lion, bobcat, as well as the endangered California condor. The wilderness is at the heart of the historic range of this large endangered species of scavengers. See also Sespe Condor Sanctuary Mountain Communities of the Tejon Pass References External links Wildernesses within the Los Padres National Forest Description at Wilderness.net U.S. Geological Survey Map at the U.S. Geological Survey Map Website. Retrieved April 17, 2023. Los Padres National Forest Mt. Pinos Ranger District, Los Padres National Forest Wilderness areas of California Protected areas of Ventura County, California Protected areas of Kern County, California Mountain Communities of the Tejon Pass Protected areas established in 1992 1992 establishments in California
The 2002 James Madison Dukes football team was an American football team that represented James Madison University during the 2002 NCAA Division I-AA football season as a member of the Atlantic 10 Conference. In their fourth year under head coach Mickey Matthews, the team compiled a 5–7 record. Schedule References James Madison James Madison Dukes football seasons James Madison Dukes football
```xml import {Prisma} from "../client/index"; declare global { namespace TsED { interface Configuration { prisma?: Prisma.PrismaClientOptions; } } } ```
This is a list of musicians from British Columbia. A Jeff Abel Tommy Alto Carolyn Arends B Ashleigh Ball Dan Bejar Doug Bennett Barney Bentall Art Bergmann Geoff Berner Kim Bingham Claire Boucher Dean Brody Chad Brownlee Michael Bublé Louise Burns C Kathryn Calder Sean Casavant Torquil Campbell Warren Cann Michelle Creber Allison Crowe D Mac DeMarco F Stephen Fearing Jon-Rae Fletcher Roy Forbes Frazey Ford David Foster Nelly Furtado G Hannah Georgas Jody Glenham Matthew Good Grimes H Tim Hecker Bill Henderson Veda Hille Jacob Hoggard Chris Hooper Tom Hooper Paul Hyde Joshua Hyslop J Ingrid Jensen Carly Rae Jepsen Vincent Jones K Kevin Kane Joey "Shithead" Keithley Geoffrey Kelly Brad Kent Diana Krall Kyprios L Tom Landa Sook-Yin Lee Alex Lifeson Suzanne Little M Brian MacLeod Madchild Dan Mangan John Mann Carolyn Mark Hugh McMillan Carey Mercer Mae Moore Scott Morgan Bob Murphy N Bif Naked Nardwuar the Human Serviette Darryl Neudorf A. C. Newman O Oh Susanna Neil Osborne P Brandon Paris Daniel Powter Prevail R Josh Ramsay Bob Rock T Kristy Thirsk Philip J. Thomas Devin Townsend U Shari Ulrich David Usher W Daniel Wesley See also List of bands from British Columbia British Columbia
```yaml id: JoeSecurityTestPlaybook version: -1 name: JoeSecurityTestPlaybook starttaskid: "0" tasks: "0": id: "0" taskid: cc28c8ab-311a-4824-8d23-835302ba4979 type: start task: id: cc28c8ab-311a-4824-8d23-835302ba4979 version: -1 name: "" iscommand: false brand: "" nexttasks: '#none#': - "1" separatecontext: false view: |- { "position": { "x": 480, "y": 50 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "1": id: "1" taskid: b709b6d5-b43e-4655-8bb8-0b5ab953670c type: regular task: id: b709b6d5-b43e-4655-8bb8-0b5ab953670c version: -1 name: Start fresh scriptName: DeleteContext type: regular iscommand: false brand: "" nexttasks: '#none#': - "2" scriptarguments: all: simple: "yes" key: {} separatecontext: false view: |- { "position": { "x": 480, "y": 195 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "2": id: "2" taskid: 96067934-a6d0-4db6-8fa1-2bbee7042f7e type: regular task: id: 96067934-a6d0-4db6-8fa1-2bbee7042f7e version: -1 name: Validate instance is working script: '|||joe-is-online' type: regular iscommand: true brand: "" nexttasks: '#none#': - "11" separatecontext: false view: |- { "position": { "x": 480, "y": 360 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "3": id: "3" taskid: b8c719f0-cdb2-4d73-874d-df30d8d7b0d1 type: regular task: id: b8c719f0-cdb2-4d73-874d-df30d8d7b0d1 version: -1 name: Analyse a file using a url without waiting script: Joe Security|||joe-analysis-submit-sample type: regular iscommand: true brand: Joe Security nexttasks: '#none#': - "4" scriptarguments: comments: {} file_id: {} internet-access: {} sample_url: simple: path_to_url should_wait: {} systems: {} separatecontext: false view: |- { "position": { "x": 50, "y": 895 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "4": id: "4" taskid: 7df24a5c-11d1-4580-8a36-4754a917ad42 type: regular task: id: 7df24a5c-11d1-4580-8a36-4754a917ad42 version: -1 name: Analyse a url without waiting script: Joe Security|||joe-analysis-submit-url type: regular iscommand: true brand: Joe Security nexttasks: '#none#': - "5" scriptarguments: comments: {} internet-access: {} should_wait: simple: "False" systems: {} url: simple: www.google.com separatecontext: false view: |- { "position": { "x": 50, "y": 1070 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "5": id: "5" taskid: 158e112c-947a-47a0-8c55-734079399005 type: regular task: id: 158e112c-947a-47a0-8c55-734079399005 version: -1 name: Get info on the file analysis script: Joe Security|||joe-analysis-info type: regular iscommand: true brand: Joe Security nexttasks: '#none#': - "6" scriptarguments: webid: simple: ${Joe.Analysis.[1].WebID} separatecontext: false view: |- { "position": { "x": 50, "y": 1245 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "6": id: "6" taskid: 27281436-1ef6-4f01-85f5-7280b83af45b type: regular task: id: 27281436-1ef6-4f01-85f5-7280b83af45b version: -1 name: Get info on the URL analysis script: Joe Security|||joe-analysis-info type: regular iscommand: true brand: Joe Security nexttasks: '#none#': - "18" scriptarguments: webid: simple: ${Joe.Analysis.[2].WebID} separatecontext: false view: |- { "position": { "x": 50, "y": 1420 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "9": id: "9" taskid: 490fc5b1-6a84-4b30-8372-a061547eb72f type: regular task: id: 490fc5b1-6a84-4b30-8372-a061547eb72f version: -1 name: Create sample file scriptName: FileCreateAndUpload type: regular iscommand: false brand: "" nexttasks: '#none#': - "19" scriptarguments: data: simple: qwerty entryId: {} filename: simple: zaq\ma.txt separatecontext: false view: |- { "position": { "x": 50, "y": 1745 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "11": id: "11" taskid: 2226ad58-a862-44a3-8c65-dc035a5c290f type: regular task: id: 2226ad58-a862-44a3-8c65-dc035a5c290f version: -1 name: Search command script: Joe Security|||joe-search type: regular iscommand: true brand: Joe Security nexttasks: '#none#': - "14" - "16" - "17" scriptarguments: query: simple: www.google.com separatecontext: false view: |- { "position": { "x": 480, "y": 545 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "14": id: "14" taskid: 91ecae03-c0c0-4891-869a-0f03d886f9e3 type: regular task: id: 91ecae03-c0c0-4891-869a-0f03d886f9e3 version: -1 name: Download url Report - XML script: Joe Security|||joe-download-report type: regular iscommand: true brand: Joe Security nexttasks: '#none#': - "3" scriptarguments: type: simple: xml webid: complex: root: ${Joe accessor: Analysis(val.Status == "finished")} transformers: - operator: atIndex args: index: value: simple: "0" - operator: getField args: field: value: simple: WebID separatecontext: false view: |- { "position": { "x": 480, "y": 720 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "16": id: "16" taskid: 838cae49-6cbb-4faa-8388-5ab8dc292ae2 type: regular task: id: 838cae49-6cbb-4faa-8388-5ab8dc292ae2 version: -1 name: Download url Report - JSON script: Joe Security|||joe-download-report type: regular iscommand: true brand: Joe Security scriptarguments: type: simple: json webid: complex: root: ${Joe accessor: Analysis(val.Status == "finished")} transformers: - operator: atIndex args: index: value: simple: "0" - operator: getField args: field: value: simple: WebID separatecontext: false view: |- { "position": { "x": 950, "y": 720 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "17": id: "17" taskid: 0bf0941a-9cbf-4039-8f6e-d31ca56f0c4a type: regular task: id: 0bf0941a-9cbf-4039-8f6e-d31ca56f0c4a version: -1 name: Download url Report - HTML script: Joe Security|||joe-download-report type: regular iscommand: true brand: Joe Security scriptarguments: type: simple: html webid: complex: root: ${Joe accessor: Analysis(val.Status == "finished")} transformers: - operator: atIndex args: index: value: simple: "0" - operator: getField args: field: value: simple: WebID separatecontext: false view: |- { "position": { "x": 60, "y": 720 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "18": id: "18" taskid: b0e413db-9656-4234-887a-3dc1106dd7bd type: condition task: id: b0e413db-9656-4234-887a-3dc1106dd7bd version: -1 name: verify output DBotScore.Indicator type: condition iscommand: false brand: "" nexttasks: "yes": - "9" separatecontext: false conditions: - label: "yes" condition: - - operator: isNotEmpty left: value: simple: DBotScore.Indicator iscontext: true view: |- { "position": { "x": 50, "y": 1590 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 "19": id: "19" taskid: 95a141e0-bed5-4076-8434-be7ae638955a type: regular task: id: 95a141e0-bed5-4076-8434-be7ae638955a version: -1 name: submit file sample with backslash in its name description: Submit a sample for analysis. script: '|||joe-analysis-submit-sample' type: regular iscommand: true brand: "" scriptarguments: comments: {} file_id: simple: ${File.EntryID} internet-access: {} sample_url: {} should_wait: {} systems: {} separatecontext: false view: |- { "position": { "x": 50, "y": 1920 } } note: false timertriggers: [] ignoreworker: false skipunavailable: false quietmode: 0 view: |- { "linkLabelsPosition": {}, "paper": { "dimensions": { "height": 1965, "width": 1280, "x": 50, "y": 50 } } } inputs: [] outputs: [] fromversion: 5.0.0 ```
```javascript 'use strict'; module.exports = { pkg: { patches: { 'lib/index.js': [ "require.resolve('socket.io-client/dist/socket.io.js.map')", "require.resolve('socket.io-client/dist/socket.io.js.map', 'must-exclude')", ], }, }, }; ```
```go // Unless explicitly stated otherwise all files in this repository are licensed // This product includes software developed at Datadog (path_to_url //go:build docker && trivy package docker import ( "context" "fmt" "reflect" "github.com/DataDog/datadog-agent/comp/core/config" workloadmeta "github.com/DataDog/datadog-agent/comp/core/workloadmeta/def" "github.com/DataDog/datadog-agent/pkg/sbom" "github.com/DataDog/datadog-agent/pkg/sbom/collectors" "github.com/DataDog/datadog-agent/pkg/util/docker" "github.com/DataDog/datadog-agent/pkg/util/optional" "github.com/DataDog/datadog-agent/pkg/util/trivy" "github.com/docker/docker/client" ) // resultChanSize defines the result channel size // 1000 is already a very large default value const resultChanSize = 1000 type scannerFunc func(ctx context.Context, imgMeta *workloadmeta.ContainerImageMetadata, client client.ImageAPIClient, scanOptions sbom.ScanOptions) (sbom.Report, error) // scanRequest defines a scan request. This struct should be // hashable to be pushed in the work queue for processing. type scanRequest struct { imageID string } // NewScanRequest creates a new scan request func NewScanRequest(imageID string) sbom.ScanRequest { return scanRequest{imageID: imageID} } // Collector returns the collector name func (r scanRequest) Collector() string { return collectors.DockerCollector } // Type returns the scan request type func (r scanRequest) Type(sbom.ScanOptions) string { return sbom.ScanDaemonType } // ID returns the scan request ID func (r scanRequest) ID() string { return r.imageID } // Collector defines a collector type Collector struct { trivyCollector *trivy.Collector resChan chan sbom.ScanResult opts sbom.ScanOptions cl client.ImageAPIClient wmeta optional.Option[workloadmeta.Component] closed bool } // CleanCache cleans the cache func (c *Collector) CleanCache() error { return c.trivyCollector.CleanCache() } // Init initializes the collector func (c *Collector) Init(cfg config.Component, wmeta optional.Option[workloadmeta.Component]) error { trivyCollector, err := trivy.GetGlobalCollector(cfg, wmeta) if err != nil { return err } c.wmeta = wmeta c.trivyCollector = trivyCollector c.opts = sbom.ScanOptionsFromConfig(cfg, true) return nil } // Scan performs a scan func (c *Collector) Scan(ctx context.Context, request sbom.ScanRequest) sbom.ScanResult { dockerScanRequest, ok := request.(scanRequest) if !ok { return sbom.ScanResult{Error: fmt.Errorf("invalid request type '%s' for collector '%s'", reflect.TypeOf(request), collectors.DockerCollector)} } if c.cl == nil { cl, err := docker.GetDockerUtil() if err != nil { return sbom.ScanResult{Error: fmt.Errorf("error creating docker client: %s", err)} } c.cl = cl.RawClient() } wmeta, ok := c.wmeta.Get() if !ok { return sbom.ScanResult{Error: fmt.Errorf("workloadmeta store is not initialized")} } imageMeta, err := wmeta.GetImage(dockerScanRequest.ID()) if err != nil { return sbom.ScanResult{Error: fmt.Errorf("image metadata not found for image id %s: %s", dockerScanRequest.ID(), err)} } var scanner scannerFunc if c.opts.OverlayFsScan { scanner = c.trivyCollector.ScanDockerImageFromGraphDriver } else { scanner = c.trivyCollector.ScanDockerImage } report, err := scanner( ctx, imageMeta, c.cl, c.opts, ) return sbom.ScanResult{ Error: err, Report: report, ImgMeta: imageMeta, } } // Type returns the container image scan type func (c *Collector) Type() collectors.ScanType { return collectors.ContainerImageScanType } // Channel returns the channel to send scan results func (c *Collector) Channel() chan sbom.ScanResult { return c.resChan } // Options returns the collector options func (c *Collector) Options() sbom.ScanOptions { return c.opts } // Shutdown shuts down the collector func (c *Collector) Shutdown() { if c.resChan != nil && !c.closed { close(c.resChan) } c.closed = true } func init() { collectors.RegisterCollector(collectors.DockerCollector, &Collector{ resChan: make(chan sbom.ScanResult, resultChanSize), }) } ```
```objective-c // // VTMenuItem.h // VTMagic // // Created by tianzhuo on 7/8/16. // #import <UIKit/UIKit.h> @interface VTMenuItem : UIButton /** * YES */ @property (nonatomic, assign) BOOL dotHidden; @end ```
Sasha Goodlett (born August 9, 1990) is an American professional basketball player who last played for the Halcones de Xalapa Femenil of the LNBPF LIGA NACIONAL DE BALONCESTO PROFESIONAL FEMENIL. Born in Bolton, Mississippi, she played at Georgia Institute of Technology and Clinton High School. Georgia Tech statistics Source References External links WNBA stats Georgia Tech Yellow Jackets bio 1990 births Living people American expatriate basketball people in China American women's basketball players Basketball players from Jackson, Mississippi Centers (basketball) Chicago Sky players Georgia Tech Yellow Jackets women's basketball players Heilongjiang Dragons players Indiana Fever draft picks Indiana Fever players
```c++ //===-- MCAsmInfoWasm.cpp - Wasm asm properties -----------------*- C++ -*-===// // // See path_to_url for license information. // //===your_sha256_hash------===// // // This file defines target asm properties related what form asm statements // should take in general on Wasm-based targets // //===your_sha256_hash------===// #include "llvm/MC/MCAsmInfoWasm.h" using namespace llvm; void MCAsmInfoWasm::anchor() {} MCAsmInfoWasm::MCAsmInfoWasm() { HasIdentDirective = true; HasNoDeadStrip = true; WeakRefDirective = "\t.weak\t"; PrivateGlobalPrefix = ".L"; PrivateLabelPrefix = ".L"; } ```
```cmake set(Z_BUILD_INFO_FILE_CONTENTS "CRTLinkage: ${VCPKG_CRT_LINKAGE}\n") string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "LibraryLinkage: ${VCPKG_LIBRARY_LINKAGE}\n") if (DEFINED VCPKG_POLICY_DLLS_WITHOUT_LIBS) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyDLLsWithoutLIBs: ${VCPKG_POLICY_DLLS_WITHOUT_LIBS}\n") endif() if (DEFINED VCPKG_POLICY_DLLS_WITHOUT_EXPORTS) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyDLLsWithoutExports: ${VCPKG_POLICY_DLLS_WITHOUT_EXPORTS}\n") endif() if (DEFINED VCPKG_POLICY_DLLS_IN_STATIC_LIBRARY) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyDLLsInStaticLibrary: ${VCPKG_POLICY_DLLS_IN_STATIC_LIBRARY}\n") endif() if (DEFINED VCPKG_POLICY_MISMATCHED_NUMBER_OF_BINARIES) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyMismatchedNumberOfBinaries: ${VCPKG_POLICY_MISMATCHED_NUMBER_OF_BINARIES}\n") endif() if (DEFINED VCPKG_POLICY_EMPTY_PACKAGE) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyEmptyPackage: ${VCPKG_POLICY_EMPTY_PACKAGE}\n") endif() if (DEFINED VCPKG_POLICY_ONLY_RELEASE_CRT) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyOnlyReleaseCRT: ${VCPKG_POLICY_ONLY_RELEASE_CRT}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_OBSOLETE_MSVCRT) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowObsoleteMsvcrt: ${VCPKG_POLICY_ALLOW_OBSOLETE_MSVCRT}\n") endif() if (DEFINED VCPKG_POLICY_EMPTY_INCLUDE_FOLDER) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyEmptyIncludeFolder: ${VCPKG_POLICY_EMPTY_INCLUDE_FOLDER}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_RESTRICTED_HEADERS) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowRestrictedHeaders: ${VCPKG_POLICY_ALLOW_RESTRICTED_HEADERS}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_DUMPBIN_CHECKS) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipDumpbinChecks: ${VCPKG_POLICY_SKIP_DUMPBIN_CHECKS}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_ARCHITECTURE_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipArchitectureCheck: ${VCPKG_POLICY_SKIP_ARCHITECTURE_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_CMAKE_HELPER_PORT) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyCmakeHelperPort: ${VCPKG_POLICY_CMAKE_HELPER_PORT}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_ABSOLUTE_PATHS_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipAbsolutePathsCheck: ${VCPKG_POLICY_SKIP_ABSOLUTE_PATHS_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_ALL_POST_BUILD_CHECKS) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipAllPostBuildChecks: ${VCPKG_POLICY_SKIP_ALL_POST_BUILD_CHECKS}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_APPCONTAINER_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipAppcontainerCheck: ${VCPKG_POLICY_SKIP_APPCONTAINER_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_CRT_LINKAGE_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipCrtLinkageCheck: ${VCPKG_POLICY_SKIP_CRT_LINKAGE_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_MISPLACED_CMAKE_FILES_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipMisplacedCMakeFilesCheck: ${VCPKG_POLICY_SKIP_MISPLACED_CMAKE_FILES_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_LIB_CMAKE_MERGE_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipLibCMakeMergeCheck: ${VCPKG_POLICY_SKIP_LIB_CMAKE_MERGE_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_DLLS_IN_LIB) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowDllsInLib: ${VCPKG_POLICY_ALLOW_DLLS_IN_LIB}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_MISPLACED_REGULAR_FILES_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipMisplacedRegularFilesCheck: ${VCPKG_POLICY_SKIP_MISPLACED_REGULAR_FILES_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_COPYRIGHT_CHECK) endif() if (DEFINED VCPKG_POLICY_ALLOW_KERNEL32_FROM_XBOX) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowKernel32FromXBox: ${VCPKG_POLICY_ALLOW_KERNEL32_FROM_XBOX}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_EXES_IN_BIN) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowExesInBin: ${VCPKG_POLICY_ALLOW_EXES_IN_BIN}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_USAGE_INSTALL_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipUsageInstallCheck: ${VCPKG_POLICY_SKIP_USAGE_INSTALL_CHECK}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_EMPTY_FOLDERS) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowEmptyFolders: ${VCPKG_POLICY_ALLOW_EMPTY_FOLDERS}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_DEBUG_INCLUDE) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowDebugInclude: ${VCPKG_POLICY_ALLOW_DEBUG_INCLUDE}\n") endif() if (DEFINED VCPKG_POLICY_ALLOW_DEBUG_SHARE) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicyAllowDebugShare: ${VCPKG_POLICY_ALLOW_DEBUG_SHARE}\n") endif() if (DEFINED VCPKG_POLICY_SKIP_PKGCONFIG_CHECK) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "PolicySkipPkgConfigCheck: ${VCPKG_POLICY_SKIP_PKGCONFIG_CHECK}\n") endif() if (DEFINED VCPKG_HEAD_VERSION) string(APPEND "Z_BUILD_INFO_FILE_CONTENTS" "Version: ${VCPKG_HEAD_VERSION}\n") endif() file(WRITE "${CURRENT_PACKAGES_DIR}/BUILD_INFO" "${Z_BUILD_INFO_FILE_CONTENTS}") ```
The Akşehir chub (Squalius recurvirostris) is a species of ray-finned fish in the family Cyprinidae. It is found in central Anatolia in Turkey. References Squalius Fish described in 2011
```python # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import unittest import paddle from paddle.distributed import fleet paddle.enable_static() class TestFleetBase(unittest.TestCase): def setUp(self): os.environ["POD_IP"] = "127.0.0.1" os.environ["PADDLE_TRAINER_ENDPOINTS"] = "127.0.0.1:36001" os.environ["PADDLE_TRAINERS_NUM"] = "2" os.environ["PADDLE_PSERVERS_IP_PORT_LIST"] = ( "127.0.0.1:36001,127.0.0.2:36001" ) def test_fleet_init(self): os.environ["TRAINING_ROLE"] = "PSERVER" os.environ["POD_IP"] = "127.0.0.1" os.environ["PADDLE_PORT"] = "36001" role = fleet.PaddleCloudRoleMaker(is_collective=False) fleet.init(role) fleet.init() fleet.init(is_collective=False) self.assertRaises(Exception, fleet.init, is_collective="F") self.assertRaises(Exception, fleet.init, role_maker="F") if __name__ == "__main__": unittest.main() ```
```ocaml module Types (F : Ctypes.TYPE) = struct end ```
```objective-c // // LFStreamPackage.h // LFLiveKit // // Created by on 16/5/2. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "LFAudioFrame.h" #import "LFVideoFrame.h" /// @protocol LFStreamPackage <NSObject> @required - (nullable instancetype)initWithVideoSize:(CGSize)videoSize; - (nullable NSData*)aaCPacket:(nullable LFAudioFrame*)audioFrame; - (nullable NSData*)h264Packet:(nullable LFVideoFrame*)videoFrame; @end ```
```smalltalk // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Toolkit.Uwp.UI.Controls.TextToolbarButtons { /// <summary> /// Specifies a Default ButtonType to Manipulate /// </summary> public enum ButtonType { /// <summary> /// Bold Button /// </summary> Bold, /// <summary> /// Italics Button /// </summary> Italics, /// <summary> /// Strikethrough Button /// </summary> Strikethrough, /// <summary> /// Code button /// </summary> Code, /// <summary> /// Quote Button /// </summary> Quote, /// <summary> /// Link Button /// </summary> Link, /// <summary> /// List Button /// </summary> List, /// <summary> /// Ordered List Button /// </summary> OrderedList, /// <summary> /// Header Selector /// </summary> Headers } } ```
```php <?php /* * * File ini bagian dari: * * OpenSID * * Sistem informasi desa sumber terbuka untuk memajukan desa * * Aplikasi dan source code ini dirilis berdasarkan lisensi GPL V3 * * Hak Cipta 2009 - 2015 Combine Resource Institution (path_to_url * Hak Cipta 2016 - 2024 Perkumpulan Desa Digital Terbuka (path_to_url * * Dengan ini diberikan izin, secara gratis, kepada siapa pun yang mendapatkan salinan * dari perangkat lunak ini dan file dokumentasi terkait ("Aplikasi Ini"), untuk diperlakukan * tanpa batasan, termasuk hak untuk menggunakan, menyalin, mengubah dan/atau mendistribusikan, * asal tunduk pada syarat berikut: * * Pemberitahuan hak cipta di atas dan pemberitahuan izin ini harus disertakan dalam * setiap salinan atau bagian penting Aplikasi Ini. Barang siapa yang menghapus atau menghilangkan * pemberitahuan ini melanggar ketentuan lisensi Aplikasi Ini. * * PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN, BAIK TERSURAT MAUPUN * TERSIRAT. PENULIS ATAU PEMEGANG HAK CIPTA SAMA SEKALI TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN ATAU * KEWAJIBAN APAPUN ATAS PENGGUNAAN ATAU LAINNYA TERKAIT APLIKASI INI. * * @package OpenSID * @author Tim Pengembang OpenDesa * @copyright Hak Cipta 2009 - 2015 Combine Resource Institution (path_to_url * @copyright Hak Cipta 2016 - 2024 Perkumpulan Desa Digital Terbuka (path_to_url * @license path_to_url GPL V3 * @link path_to_url * */ use App\Enums\StatusPengaduanEnum; use App\Models\Pengaduan; defined('BASEPATH') || exit('No direct script access allowed'); class Pengaduan_admin extends Admin_Controller { public function __construct() { parent::__construct(); $this->modul_ini = 'pengaduan'; } public function index() { $data = $this->widget(); return view('admin.pengaduan_warga.index', $data); } protected function widget(): array { return [ 'allstatus' => Pengaduan::status()->count(), 'status1' => Pengaduan::status(StatusPengaduanEnum::MENUNGGU_DIPROSES)->count(), 'status2' => Pengaduan::status(StatusPengaduanEnum::SEDANG_DIPROSES)->count(), 'status3' => Pengaduan::status(StatusPengaduanEnum::SELESAI_DIPROSES)->count(), 'm_allstatus' => Pengaduan::bulanan()->count(), 'm_status1' => Pengaduan::bulanan(StatusPengaduanEnum::MENUNGGU_DIPROSES)->count(), 'm_status2' => Pengaduan::bulanan(StatusPengaduanEnum::SEDANG_DIPROSES)->count(), 'm_status3' => Pengaduan::bulanan(StatusPengaduanEnum::SELESAI_DIPROSES)->count(), ]; } public function datatables() { if ($this->input->is_ajax_request()) { $status = $this->input->get('status'); return datatables()->of(Pengaduan::tipe()->filter($status)) ->addColumn('ceklist', static function ($row) { if (can('h')) { return '<input type="checkbox" name="id_cb[]" value="' . $row->id . '"/>'; } }) ->addIndexColumn() ->addColumn('aksi', static function ($row): string { $aksi = ''; if (can('u')) { $aksi .= '<a href="' . ci_route('pengaduan_admin.form', $row->id) . '" class="btn btn-warning btn-sm" title="Tanggapi Pengaduan"><i class="fa fa-mail-forward"></i></a> '; } if (can('u')) { $aksi .= '<a href="' . ci_route('pengaduan_admin.detail', $row->id) . '" class="btn btn-info btn-sm" title="Lihat Detail"><i class="fa fa-eye"></i></a> '; } if (can('h')) { $aksi .= '<a href="#" data-href="' . ci_route('pengaduan_admin.delete', $row->id) . '" class="btn bg-maroon btn-sm" title="Hapus Data" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash"></i></a> '; } return $aksi; }) ->editColumn('status', static fn ($row): string => '<span class="label ' . StatusPengaduanEnum::label()[$row->status] . '">' . ucwords(StatusPengaduanEnum::valueOf($row->status)) . ' </span>') ->editColumn('created_at', static fn ($row): string => tgl_indo2($row->created_at)) ->rawColumns(['ceklist', 'aksi', 'status']) ->make(); } return show_404(); } public function form($id = '') { $this->redirect_hak_akses('u'); if ($id) { $action = 'Tanggapi Pengaduan'; $form_action = ci_route('pengaduan_admin.kirim', $id); $pengaduan_warga = Pengaduan::findOrFail($id); } return view('admin.pengaduan_warga.form', ['action' => $action, 'form_action' => $form_action, 'pengaduan_warga' => $pengaduan_warga]); } public function kirim($id): void { $this->redirect_hak_akses('u'); try { $pengaduan = Pengaduan::findOrFail($id); $pengaduan->update(['status' => $this->request['status']]); Pengaduan::where('id_pengaduan', $id)->update(['status' => $this->request['status']]); Pengaduan::create([ 'config_id' => $pengaduan->config_id, 'id_pengaduan' => $id, 'nama' => $this->session->nama, 'isi' => bersihkan_xss($this->request['isi']), 'status' => $this->request['status'], 'ip_address' => $this->input->ip_address() ?? '', ]); redirect_with('success', 'Berhasil Ditanggapi'); } catch (Exception $e) { log_message('error', $e); } redirect_with('error', 'Gagal Ditanggapi'); } public function detail($id = '') { $this->redirect_hak_akses('u'); if ($id) { $action = 'Detail Pengaduan'; $pengaduan = Pengaduan::findOrFail($id); } return view('admin.pengaduan_warga.detail', ['action' => $action, 'pengaduan' => $pengaduan]); } public function delete($id = null): void { $this->redirect_hak_akses('h'); try { Pengaduan::destroy($id ?? $this->request['id_cb']); // Hapus komentar if ($id) { $this->request['id_cb'] = [$id]; } Pengaduan::whereIn('id_pengaduan', $this->request['id_cb'])->delete(); redirect_with('success', 'Berhasil Hapus Data'); } catch (Exception $e) { log_message('error', $e); } redirect_with('error', 'Gagal Hapus Data'); } } ```
Labelling or labeling is describing someone or something in a word or short phrase. Labeling may also refer to: Packaging and labeling Food labelling Labeling theory, in sociology Isotopic labeling Typography (cartography), also known as map labeling, placing text on maps Automatic label placement, the computational algorithms for automating map labeling See also Label (disambiguation) Label printer
```scala package com.prisma.deploy.connector.mongo.impl import com.prisma.deploy.connector.persistence.MigrationPersistence import com.prisma.shared.models.MigrationStatus.MigrationStatus import com.prisma.shared.models.{Migration, MigrationId, MigrationStatus} import com.prisma.utils.mongo.MongoExtensions import org.joda.time.DateTime import org.mongodb.scala.bson.BsonDateTime import org.mongodb.scala.bson.collection.immutable.Document import org.mongodb.scala.model.Sorts._ import org.mongodb.scala.model.{Filters, Updates} import org.mongodb.scala.{MongoCollection, MongoDatabase} import scala.concurrent.{ExecutionContext, Future} case class MongoMigrationPersistence(internalDatabase: MongoDatabase)(implicit ec: ExecutionContext) extends MigrationPersistence with MongoExtensions { val migrations: MongoCollection[Document] = internalDatabase.getCollection("Migration") val revision = "revision" override def byId(migrationId: MigrationId): Future[Option[Migration]] = { enrichWithPreviousMigration { migrations .find(Filters.and(projectIdFilter(migrationId.projectId), revisionFilter(migrationId.revision))) .collect .toFuture() .map(_.headOption.map(DbMapper.convertToMigrationModel)) } } override def loadAll(projectId: String): Future[Seq[Migration]] = { migrations .find(projectIdFilter(projectId)) .sort(descending(revision)) .collect .toFuture() .map(_.map(DbMapper.convertToMigrationModel)) .map(migs => enrichWithPreviousSchemas(migs.toVector)) } override def create(migration: Migration): Future[Migration] = { def lastRevision = migrations .find(projectIdFilter(migration.projectId)) .sort(descending(revision)) .collect .toFuture() .map(_.headOption.map(DbMapper.convertToMigrationModel(_).revision)) for { lastRevision <- lastRevision withRevisionBumped = migration.copy(revision = lastRevision.getOrElse(0) + 1) _ <- migrations.insertOne(DbMapper.convertToDocument(withRevisionBumped)).toFuture() withPreviousMigration <- enrichWithPreviousMigration(withRevisionBumped) } yield withPreviousMigration } private def updateColumn(id: MigrationId, field: String, value: Any) = { migrations .updateOne(Filters.and(projectIdFilter(id.projectId), revisionFilter(id.revision)), Updates.set(field, value)) .toFuture .map(_ => ()) } override def updateMigrationStatus(id: MigrationId, status: MigrationStatus): Future[Unit] = { updateColumn(id, "status", status.toString) } override def updateMigrationErrors(id: MigrationId, errors: Vector[String]): Future[Unit] = { updateColumn(id, "errors", errors) } override def updateMigrationApplied(id: MigrationId, applied: Int): Future[Unit] = { updateColumn(id, "applied", applied) } override def updateMigrationRolledBack(id: MigrationId, rolledBack: Int): Future[Unit] = { updateColumn(id, "rolledBack", rolledBack) } override def updateStartedAt(id: MigrationId, startedAt: DateTime): Future[Unit] = { updateColumn(id, "startedAt", BsonDateTime(startedAt.getMillis)) } override def updateFinishedAt(id: MigrationId, finishedAt: DateTime): Future[Unit] = { updateColumn(id, "finishedAt", BsonDateTime(finishedAt.getMillis)) } override def getLastMigration(projectId: String): Future[Option[Migration]] = { enrichWithPreviousMigration { migrations .find(Filters.and(projectIdFilter(projectId), statusFilter(MigrationStatus.Success))) .sort(descending(revision)) .collect .toFuture() .map(_.headOption.map(DbMapper.convertToMigrationModel)) } } override def getNextMigration(projectId: String): Future[Option[Migration]] = { enrichWithPreviousMigration { migrations .find( Filters.and( projectIdFilter(projectId), Filters.or(statusFilter(MigrationStatus.Pending), statusFilter(MigrationStatus.InProgress), statusFilter(MigrationStatus.RollingBack)) ) ) .sort(ascending(revision)) .collect .toFuture() .map(_.headOption.map(DbMapper.convertToMigrationModel)) } } override def loadDistinctUnmigratedProjectIds(): Future[Seq[String]] = { migrations .find(Filters.or(statusFilter(MigrationStatus.Pending), statusFilter(MigrationStatus.InProgress), statusFilter(MigrationStatus.RollingBack))) .collect .toFuture() .map(_.map(DbMapper.convertToMigrationModel(_).projectId).distinct) } private def projectIdFilter(projectId: String) = Filters.eq("projectId", projectId) private def revisionFilter(revision: Int) = Filters.eq(this.revision, revision) private def statusFilter(status: MigrationStatus) = Filters.eq("status", status.toString) private def enrichWithPreviousMigration(migration: Future[Option[Migration]]): Future[Option[Migration]] = { migration.flatMap { case Some(mig) => enrichWithPreviousMigration(mig).map(Some(_)) case None => Future.successful(None) } } private def enrichWithPreviousMigration(migration: Migration): Future[Migration] = { migrations .find( Filters.and( projectIdFilter(migration.projectId), Filters.lt(revision, migration.revision), statusFilter(MigrationStatus.Success) ) ) .sort(descending(revision)) .collect .toFuture() .map(_.headOption) .map { case Some(doc) => val previousMigration = DbMapper.convertToMigrationModel(doc) migration.copy(previousSchema = previousMigration.schema) case None => migration } } } ```
```ruby # frozen_string_literal: true class ChangeStatesOnProposals < ActiveRecord::Migration[6.1] class Proposal < ApplicationRecord self.table_name = :decidim_proposals_proposals STATES = { not_answered: 0, evaluating: 10, accepted: 20, rejected: -10, withdrawn: -20 }.freeze end def up rename_column :decidim_proposals_proposals, :state, :old_state add_column :decidim_proposals_proposals, :state, :integer, default: 0, null: false Proposal.reset_column_information Proposal::STATES.each_pair do |status, index| Proposal.where(old_state: status).update_all(state: index) # rubocop:disable Rails/SkipsModelValidations end remove_column :decidim_proposals_proposals, :old_state end def down rename_column :decidim_proposals_proposals, :state, :old_state add_column :decidim_proposals_proposals, :state, :string Proposal.reset_column_information Proposal::STATES.each_pair do |status, index| Proposal.where(old_state: index).update_all(state: status) # rubocop:disable Rails/SkipsModelValidations end remove_column :decidim_proposals_proposals, :old_state end end ```
```python import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * POPULATE_INDICATOR_FIELDS = ['indicator_type', 'value', 'id'] INDICATOR_TYPES = ['Domain', 'Email', 'File MD', 'IP', 'IPv6', 'IPv6CIDR', 'URL'] ''' STANDALONE FUNCTION ''' def execute_get_indicators_by_query(query: str, indicators_types: dict) -> list: """ Executes GetIndicatorsByQuery and returns a list of indicators. Args: query: a query from the user. indicators_types: A dict of in indicators types. Returns: A list of indicators. """ indicator_list = [] res = demisto.executeCommand('GetIndicatorsByQuery', args={'populateFields': POPULATE_INDICATOR_FIELDS, 'query': query}) indicators = res[0]['Contents'] for indicator in indicators: indicator_type = indicator.get('indicator_type') indicator_value = indicator.get('value') if indicator_type in INDICATOR_TYPES: indicator_list.append({'value': indicator_value, 'itype': indicators_types.get('ip') if indicator_type.lower() in {'ip', 'ipv6', 'ipv6cidr'} else indicators_types.get(indicator_type.lower())}) return indicator_list def validate_indicators(email_list: list, md5_list: list, ip_list: list, url_list: list, domain_list: list) -> None: """ Validates users indicators input. Args: email_list: A list of emails. md5_list: A list of md5s. ip_list: A list of IPs. url_list: A list of URLs. domain_list: A list of domains. """ invalid_indicators = [] for email in email_list: if not re.match(emailRegex, email): invalid_indicators.append(email) for md5 in md5_list: if not re.match(md5Regex, md5): invalid_indicators.append(md5) for ip in ip_list: if FeedIndicatorType.ip_to_indicator_type(ip) is None: invalid_indicators.append(ip) for url in url_list: if not re.match(urlRegex, url): invalid_indicators.append(url) for domain in domain_list: if not re.match(domainRegex, domain): invalid_indicators.append(domain) if len(invalid_indicators) > 0: raise DemistoException(f'Invalid indicators values: {", ".join(map(str,invalid_indicators))}') def get_indicators_from_user(args: dict, indicators_types: dict) -> list: """ Validate and returns a list of indicators from user args. Args: args: Arguments provided by user. indicators_types: A dict of in indicators types. Returns: A list of indicators. """ indicator_list: list[dict] = [] indicators = {'email_list': argToList(args.get('email_values', [])), 'md5_list': argToList(args.get('md5_values', [])), 'ip_list': argToList(args.get('ip_values', [])), 'url_list': argToList(args.get('url_values', [])), 'domain_list': argToList(args.get('domain_values', []))} validate_indicators(**indicators) for indicator_list_name, indicators_list in indicators.items(): indicator_type = indicator_list_name.split("_")[0] indicator_list.extend( { 'value': indicator_value, 'itype': indicators_types.get(indicator_type), } for indicator_value in indicators_list ) return indicator_list def get_indicators_and_build_json(args: dict) -> CommandResults: """ Gets a list of indicators and builds JSON. Args: args: Arguments provided by user. Returns: A CommandResults object with the relevant JSON. """ list_indicators = [] indicators_types = {'email': args.get('email_indicator_type', 'mal_email'), 'md5': args.get('md5_indicator_type', 'mal_md5'), 'ip': args.get('ip_indicator_type', 'mal_ip'), 'url': args.get('url_indicator_type', 'mal_url'), 'domain': args.get('domain_indicator_type', 'mal_domain')} if indicator_query := args.get('indicator_query'): list_indicators = execute_get_indicators_by_query(indicator_query, indicators_types) else: list_indicators = get_indicators_from_user(args, indicators_types) outputs = str({'objects': list_indicators}) return CommandResults(outputs_key_field='ThreatstreamBuildIocImportJson', outputs={'ThreatstreamBuildIocImportJson': outputs}, readable_output=outputs) ''' MAIN FUNCTION ''' def main(): try: args = demisto.args() return_results(get_indicators_and_build_json(args)) except Exception as ex: return_error(f'Failed to execute ThreatstreamBuildIocImportJson. Error: {str(ex)}') ''' ENTRY POINT ''' if __name__ in ('__main__', '__builtin__', 'builtins'): main() ```
```c /** ****************************************************************************** * @file stm32f1xx_hal_pcd.c * @author MCD Application Team * @version V1.0.4 * @date 29-April-2016 * @brief PCD HAL module driver. * This file provides firmware functions to manage the following * functionalities of the USB Peripheral Controller: * + Initialization and de-initialization functions * + IO operation functions * + Peripheral Control functions * + Peripheral State functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] The PCD HAL driver can be used as follows: (#) Declare a PCD_HandleTypeDef handle structure, for example: PCD_HandleTypeDef hpcd; (#) Fill parameters of Init structure in HCD handle (#) Call HAL_PCD_Init() API to initialize the HCD peripheral (Core, Device core, ...) (#) Initialize the PCD low level resources through the HAL_PCD_MspInit() API: (##) Enable the PCD/USB Low Level interface clock using the following macro (+++) __HAL_RCC_USB_CLK_ENABLE(); For USB Device FS peripheral available on STM32F102xx and STM32F103xx devices (+++) __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); For USB OTG FS peripheral available on STM32F105xx and STM32F107xx devices (##) Initialize the related GPIO clocks (##) Configure PCD pin-out (##) Configure PCD NVIC interrupt (#)Associate the Upper USB device stack to the HAL PCD Driver: (##) hpcd.pData = pdev; (#)Enable HCD transmission and reception: (##) HAL_PCD_Start(); @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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 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. * ****************************************************************************** */ /* Includes your_sha256_hash--*/ #include "stm32f1xx_hal.h" /** @addtogroup STM32F1xx_HAL_Driver * @{ */ #ifdef HAL_PCD_MODULE_ENABLED #if defined(STM32F102x6) || defined(STM32F102xB) || \ defined(STM32F103x6) || defined(STM32F103xB) || \ defined(STM32F103xE) || defined(STM32F103xG) || \ defined(STM32F105xC) || defined(STM32F107xC) /** @defgroup PCD PCD * @brief PCD HAL module driver * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup PCD_Private_Macros PCD Private Macros * @{ */ #define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup PCD_Private_Functions PCD Private Functions * @{ */ #if defined (USB_OTG_FS) static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum); #endif /* USB_OTG_FS */ #if defined (USB) static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd); #endif /* USB */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup PCD_Exported_Functions PCD Exported Functions * @{ */ /** @defgroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This section provides functions allowing to: @endverbatim * @{ */ /** * @brief Initializes the PCD according to the specified * parameters in the PCD_InitTypeDef and create the associated handle. * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) { uint32_t index = 0; /* Check the PCD handle allocation */ if(hpcd == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); if(hpcd->State == HAL_PCD_STATE_RESET) { /* Allocate lock resource and initialize it */ hpcd->Lock = HAL_UNLOCKED; /* Init the low level hardware : GPIO, CLOCK, NVIC... */ HAL_PCD_MspInit(hpcd); } hpcd->State = HAL_PCD_STATE_BUSY; /* Disable the Interrupts */ __HAL_PCD_DISABLE(hpcd); /*Init the Core (common init.) */ USB_CoreInit(hpcd->Instance, hpcd->Init); /* Force Device Mode*/ USB_SetCurrentMode(hpcd->Instance , USB_DEVICE_MODE); /* Init endpoints structures */ for (index = 0; index < 15 ; index++) { /* Init ep structure */ hpcd->IN_ep[index].is_in = 1; hpcd->IN_ep[index].num = index; hpcd->IN_ep[index].tx_fifo_num = index; /* Control until ep is actvated */ hpcd->IN_ep[index].type = EP_TYPE_CTRL; hpcd->IN_ep[index].maxpacket = 0; hpcd->IN_ep[index].xfer_buff = 0; hpcd->IN_ep[index].xfer_len = 0; } for (index = 0; index < 15 ; index++) { hpcd->OUT_ep[index].is_in = 0; hpcd->OUT_ep[index].num = index; hpcd->IN_ep[index].tx_fifo_num = index; /* Control until ep is activated */ hpcd->OUT_ep[index].type = EP_TYPE_CTRL; hpcd->OUT_ep[index].maxpacket = 0; hpcd->OUT_ep[index].xfer_buff = 0; hpcd->OUT_ep[index].xfer_len = 0; } /* Init Device */ USB_DevInit(hpcd->Instance, hpcd->Init); hpcd->USB_Address = 0; hpcd->State= HAL_PCD_STATE_READY; USB_DevDisconnect (hpcd->Instance); return HAL_OK; } /** * @brief DeInitializes the PCD peripheral * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd) { /* Check the PCD handle allocation */ if(hpcd == NULL) { return HAL_ERROR; } hpcd->State = HAL_PCD_STATE_BUSY; /* Stop Device */ HAL_PCD_Stop(hpcd); /* DeInit the low level hardware */ HAL_PCD_MspDeInit(hpcd); hpcd->State = HAL_PCD_STATE_RESET; return HAL_OK; } /** * @brief Initializes the PCD MSP. * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_MspInit could be implemented in the user file */ } /** * @brief DeInitializes PCD MSP. * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_MspDeInit could be implemented in the user file */ } /** * @} */ /** @defgroup PCD_Exported_Functions_Group2 IO operation functions * @brief Data transfers functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the PCD data transfers. @endverbatim * @{ */ /** * @brief Start The USB Device. * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) { __HAL_LOCK(hpcd); HAL_PCDEx_SetConnectionState (hpcd, 1); USB_DevConnect (hpcd->Instance); __HAL_PCD_ENABLE(hpcd); __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Stop The USB Device. * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) { __HAL_LOCK(hpcd); __HAL_PCD_DISABLE(hpcd); USB_StopDevice(hpcd->Instance); USB_DevDisconnect (hpcd->Instance); __HAL_UNLOCK(hpcd); return HAL_OK; } #if defined (USB_OTG_FS) /** * @brief This function handles PCD interrupt request. * @param hpcd: PCD handle * @retval HAL status */ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) { USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; uint32_t index = 0, ep_intr = 0, epint = 0, epnum = 0; uint32_t fifoemptymsk = 0, temp = 0; USB_OTG_EPTypeDef *ep = NULL; /* ensure that we are in device mode */ if (USB_GetMode(hpcd->Instance) == USB_OTG_MODE_DEVICE) { /* avoid spurious interrupt */ if(__HAL_PCD_IS_INVALID_INTERRUPT(hpcd)) { return; } if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_MMIS)) { /* incorrect mode, acknowledge the interrupt */ __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_MMIS); } if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OEPINT)) { epnum = 0; /* Read in the device interrupt bits */ ep_intr = USB_ReadDevAllOutEpInterrupt(hpcd->Instance); while ( ep_intr ) { if (ep_intr & 0x1) { epint = USB_ReadDevOutEPInterrupt(hpcd->Instance, epnum); if(( epint & USB_OTG_DOEPINT_XFRC) == USB_OTG_DOEPINT_XFRC) { CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_XFRC); HAL_PCD_DataOutStageCallback(hpcd, epnum); } if(( epint & USB_OTG_DOEPINT_STUP) == USB_OTG_DOEPINT_STUP) { /* Inform the upper layer that a setup packet is available */ HAL_PCD_SetupStageCallback(hpcd); CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STUP); } if(( epint & USB_OTG_DOEPINT_OTEPDIS) == USB_OTG_DOEPINT_OTEPDIS) { CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPDIS); } } epnum++; ep_intr >>= 1; } } if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_IEPINT)) { /* Read in the device interrupt bits */ ep_intr = USB_ReadDevAllInEpInterrupt(hpcd->Instance); epnum = 0; while ( ep_intr ) { if (ep_intr & 0x1) /* In ITR */ { epint = USB_ReadDevInEPInterrupt(hpcd->Instance, epnum); if(( epint & USB_OTG_DIEPINT_XFRC) == USB_OTG_DIEPINT_XFRC) { fifoemptymsk = 0x1 << epnum; USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_XFRC); HAL_PCD_DataInStageCallback(hpcd, epnum); } if(( epint & USB_OTG_DIEPINT_TOC) == USB_OTG_DIEPINT_TOC) { CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_TOC); } if(( epint & USB_OTG_DIEPINT_ITTXFE) == USB_OTG_DIEPINT_ITTXFE) { CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_ITTXFE); } if(( epint & USB_OTG_DIEPINT_INEPNE) == USB_OTG_DIEPINT_INEPNE) { CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_INEPNE); } if(( epint & USB_OTG_DIEPINT_EPDISD) == USB_OTG_DIEPINT_EPDISD) { CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_EPDISD); } if(( epint & USB_OTG_DIEPINT_TXFE) == USB_OTG_DIEPINT_TXFE) { PCD_WriteEmptyTxFifo(hpcd , epnum); } } epnum++; ep_intr >>= 1; } } /* Handle Resume Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT)) { /* Clear the Remote Wake-up signalling */ USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; HAL_PCD_ResumeCallback(hpcd); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT); } /* Handle Suspend Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP)) { if((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS) { HAL_PCD_SuspendCallback(hpcd); } __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP); } /* Handle Reset Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBRST)) { USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; USB_FlushTxFifo(hpcd->Instance , 0 ); for (index = 0; index < hpcd->Init.dev_endpoints ; index++) { USBx_INEP(index)->DIEPINT = 0xFF; USBx_OUTEP(index)->DOEPINT = 0xFF; } USBx_DEVICE->DAINT = 0xFFFFFFFF; USBx_DEVICE->DAINTMSK |= 0x10001; USBx_DEVICE->DOEPMSK |= (USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM | USB_OTG_DOEPMSK_EPDM); USBx_DEVICE->DIEPMSK |= (USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM); /* Set Default Address to 0 */ USBx_DEVICE->DCFG &= ~USB_OTG_DCFG_DAD; /* setup EP0 to receive SETUP packets */ USB_EP0_OutStart(hpcd->Instance, (uint8_t *)hpcd->Setup); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBRST); } /* Handle Enumeration done Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE)) { USB_ActivateSetup(hpcd->Instance); hpcd->Instance->GUSBCFG &= ~USB_OTG_GUSBCFG_TRDT; hpcd->Init.speed = USB_OTG_SPEED_FULL; hpcd->Init.ep0_mps = USB_OTG_FS_MAX_PACKET_SIZE ; hpcd->Instance->GUSBCFG |= (uint32_t)((USBD_FS_TRDT_VALUE << 10) & USB_OTG_GUSBCFG_TRDT); HAL_PCD_ResetCallback(hpcd); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE); } /* Handle RxQLevel Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_RXFLVL)) { USB_MASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); temp = USBx->GRXSTSP; ep = &hpcd->OUT_ep[temp & USB_OTG_GRXSTSP_EPNUM]; if(((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_DATA_UPDT) { if((temp & USB_OTG_GRXSTSP_BCNT) != 0) { USB_ReadPacket(USBx, ep->xfer_buff, (temp & USB_OTG_GRXSTSP_BCNT) >> 4); ep->xfer_buff += (temp & USB_OTG_GRXSTSP_BCNT) >> 4; ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4; } } else if (((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_SETUP_UPDT) { USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8); ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4; } USB_UNMASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); } /* Handle SOF Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_SOF)) { HAL_PCD_SOFCallback(hpcd); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SOF); } /* Handle Incomplete ISO IN Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR)) { HAL_PCD_ISOINIncompleteCallback(hpcd, epnum); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR); } /* Handle Incomplete ISO OUT Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT)) { HAL_PCD_ISOOUTIncompleteCallback(hpcd, epnum); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT); } /* Handle Connection event Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT)) { HAL_PCD_ConnectCallback(hpcd); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT); } /* Handle Disconnection event Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OTGINT)) { temp = hpcd->Instance->GOTGINT; if((temp & USB_OTG_GOTGINT_SEDET) == USB_OTG_GOTGINT_SEDET) { HAL_PCD_DisconnectCallback(hpcd); } hpcd->Instance->GOTGINT |= temp; } } } #endif /* USB_OTG_FS */ #if defined (USB) /** * @brief This function handles PCD interrupt request. * @param hpcd: PCD handle * @retval HAL status */ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) { uint32_t wInterrupt_Mask = 0; if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_CTR)) { /* servicing of the endpoint correct transfer interrupt */ /* clear of the CTR flag into the sub */ PCD_EP_ISR_Handler(hpcd); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_RESET)) { __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_RESET); HAL_PCD_ResetCallback(hpcd); HAL_PCD_SetAddress(hpcd, 0); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_PMAOVR)) { __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_PMAOVR); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_ERR)) { __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ERR); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP)) { hpcd->Instance->CNTR &= ~(USB_CNTR_LP_MODE); /*set wInterrupt_Mask global variable*/ wInterrupt_Mask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ | USB_CNTR_ESOFM | USB_CNTR_RESETM; /*Set interrupt mask*/ hpcd->Instance->CNTR = wInterrupt_Mask; HAL_PCD_ResumeCallback(hpcd); __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_WKUP); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SUSP)) { /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SUSP); /* Force low-power mode in the macrocell */ hpcd->Instance->CNTR |= USB_CNTR_FSUSP; hpcd->Instance->CNTR |= USB_CNTR_LP_MODE; if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP) == 0) { HAL_PCD_SuspendCallback(hpcd); } } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SOF)) { __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SOF); HAL_PCD_SOFCallback(hpcd); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_ESOF)) { /* clear ESOF flag in ISTR */ __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ESOF); } } #endif /* USB */ /** * @brief Data out stage callbacks * @param hpcd: PCD handle * @param epnum: endpoint number * @retval None */ __weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); UNUSED(epnum); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_DataOutStageCallback could be implemented in the user file */ } /** * @brief Data IN stage callbacks * @param hpcd: PCD handle * @param epnum: endpoint number * @retval None */ __weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); UNUSED(epnum); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_DataInStageCallback could be implemented in the user file */ } /** * @brief Setup stage callback * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_SetupStageCallback could be implemented in the user file */ } /** * @brief USB Start Of Frame callbacks * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_SOFCallback could be implemented in the user file */ } /** * @brief USB Reset callbacks * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_ResetCallback could be implemented in the user file */ } /** * @brief Suspend event callbacks * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_SuspendCallback could be implemented in the user file */ } /** * @brief Resume event callbacks * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_ResumeCallback could be implemented in the user file */ } /** * @brief Incomplete ISO OUT callbacks * @param hpcd: PCD handle * @param epnum: endpoint number * @retval None */ __weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); UNUSED(epnum); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file */ } /** * @brief Incomplete ISO IN callbacks * @param hpcd: PCD handle * @param epnum: endpoint number * @retval None */ __weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); UNUSED(epnum); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_ISOINIncompleteCallback could be implemented in the user file */ } /** * @brief Connection event callbacks * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_ConnectCallback could be implemented in the user file */ } /** * @brief Disconnection event callbacks * @param hpcd: PCD handle * @retval None */ __weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hpcd); /* NOTE : This function should not be modified, when the callback is needed, the HAL_PCD_DisconnectCallback could be implemented in the user file */ } /** * @} */ /** @defgroup PCD_Exported_Functions_Group3 Peripheral Control functions * @brief management functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to control the PCD data transfers. @endverbatim * @{ */ /** * @brief Connect the USB device * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) { __HAL_LOCK(hpcd); HAL_PCDEx_SetConnectionState (hpcd, 1); USB_DevConnect(hpcd->Instance); __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Disconnect the USB device * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) { __HAL_LOCK(hpcd); HAL_PCDEx_SetConnectionState (hpcd, 0); USB_DevDisconnect(hpcd->Instance); __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Set the USB Device address * @param hpcd: PCD handle * @param address: new device address * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address) { __HAL_LOCK(hpcd); hpcd->USB_Address = address; USB_SetDevAddress(hpcd->Instance, address); __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Open and configure an endpoint * @param hpcd: PCD handle * @param ep_addr: endpoint address * @param ep_mps: endpoint max packet size * @param ep_type: endpoint type * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type) { HAL_StatusTypeDef ret = HAL_OK; PCD_EPTypeDef *ep = NULL; if ((ep_addr & 0x80) == 0x80) { ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { ep = &hpcd->OUT_ep[ep_addr & 0x7F]; } ep->num = ep_addr & 0x7F; ep->is_in = (0x80 & ep_addr) != 0; ep->maxpacket = ep_mps; ep->type = ep_type; __HAL_LOCK(hpcd); USB_ActivateEndpoint(hpcd->Instance , ep); __HAL_UNLOCK(hpcd); return ret; } /** * @brief Deactivate an endpoint * @param hpcd: PCD handle * @param ep_addr: endpoint address * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { PCD_EPTypeDef *ep = NULL; if ((ep_addr & 0x80) == 0x80) { ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { ep = &hpcd->OUT_ep[ep_addr & 0x7F]; } ep->num = ep_addr & 0x7F; ep->is_in = (0x80 & ep_addr) != 0; __HAL_LOCK(hpcd); USB_DeactivateEndpoint(hpcd->Instance , ep); __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Receive an amount of data * @param hpcd: PCD handle * @param ep_addr: endpoint address * @param pBuf: pointer to the reception buffer * @param len: amount of data to be received * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) { PCD_EPTypeDef *ep = NULL; ep = &hpcd->OUT_ep[ep_addr & 0x7F]; /*setup and start the Xfer */ ep->xfer_buff = pBuf; ep->xfer_len = len; ep->xfer_count = 0; ep->is_in = 0; ep->num = ep_addr & 0x7F; __HAL_LOCK(hpcd); if ((ep_addr & 0x7F) == 0 ) { USB_EP0StartXfer(hpcd->Instance , ep); } else { USB_EPStartXfer(hpcd->Instance , ep); } __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Get Received Data Size * @param hpcd: PCD handle * @param ep_addr: endpoint address * @retval Data Size */ uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { return hpcd->OUT_ep[ep_addr & 0x7F].xfer_count; } /** * @brief Send an amount of data * @param hpcd: PCD handle * @param ep_addr: endpoint address * @param pBuf: pointer to the transmission buffer * @param len: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) { PCD_EPTypeDef *ep = NULL; ep = &hpcd->IN_ep[ep_addr & 0x7F]; /*setup and start the Xfer */ ep->xfer_buff = pBuf; ep->xfer_len = len; ep->xfer_count = 0; ep->is_in = 1; ep->num = ep_addr & 0x7F; __HAL_LOCK(hpcd); if ((ep_addr & 0x7F) == 0 ) { USB_EP0StartXfer(hpcd->Instance , ep); } else { USB_EPStartXfer(hpcd->Instance , ep); } __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Set a STALL condition over an endpoint * @param hpcd: PCD handle * @param ep_addr: endpoint address * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { PCD_EPTypeDef *ep = NULL; if ((0x80 & ep_addr) == 0x80) { ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { ep = &hpcd->OUT_ep[ep_addr]; } ep->is_stall = 1; ep->num = ep_addr & 0x7F; ep->is_in = ((ep_addr & 0x80) == 0x80); __HAL_LOCK(hpcd); USB_EPSetStall(hpcd->Instance , ep); if((ep_addr & 0x7F) == 0) { USB_EP0_OutStart(hpcd->Instance, (uint8_t *)hpcd->Setup); } __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Clear a STALL condition over in an endpoint * @param hpcd: PCD handle * @param ep_addr: endpoint address * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { PCD_EPTypeDef *ep = NULL; if ((0x80 & ep_addr) == 0x80) { ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { ep = &hpcd->OUT_ep[ep_addr]; } ep->is_stall = 0; ep->num = ep_addr & 0x7F; ep->is_in = ((ep_addr & 0x80) == 0x80); __HAL_LOCK(hpcd); USB_EPClearStall(hpcd->Instance , ep); __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief Flush an endpoint * @param hpcd: PCD handle * @param ep_addr: endpoint address * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { __HAL_LOCK(hpcd); if ((ep_addr & 0x80) == 0x80) { USB_FlushTxFifo(hpcd->Instance, ep_addr & 0x7F); } else { USB_FlushRxFifo(hpcd->Instance); } __HAL_UNLOCK(hpcd); return HAL_OK; } /** * @brief HAL_PCD_ActivateRemoteWakeup : active remote wakeup signalling * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) { return(USB_ActivateRemoteWakeup(hpcd->Instance)); } /** * @brief HAL_PCD_DeActivateRemoteWakeup : de-active remote wakeup signalling * @param hpcd: PCD handle * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) { return(USB_DeActivateRemoteWakeup(hpcd->Instance)); } /** * @} */ /** @defgroup PCD_Exported_Functions_Group4 Peripheral State functions * @brief Peripheral State functions * @verbatim =============================================================================== ##### Peripheral State functions ##### =============================================================================== [..] This subsection permits to get in run-time the status of the peripheral and the data flow. @endverbatim * @{ */ /** * @brief Return the PCD state * @param hpcd: PCD handle * @retval HAL state */ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd) { return hpcd->State; } /** * @} */ /** * @} */ /** @addtogroup PCD_Private_Functions * @{ */ #if defined (USB_OTG_FS) /** * @brief DCD_WriteEmptyTxFifo * check FIFO for the next packet to be loaded * @param hpcd: PCD handle * @param epnum : endpoint number * This parameter can be a value from 0 to 15 * @retval HAL status */ static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum) { USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; USB_OTG_EPTypeDef *ep = NULL; int32_t len = 0; uint32_t len32b = 0; uint32_t fifoemptymsk = 0; ep = &hpcd->IN_ep[epnum]; len = ep->xfer_len - ep->xfer_count; if (len > ep->maxpacket) { len = ep->maxpacket; } len32b = (len + 3) / 4; while ((USBx_INEP(epnum)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) > len32b && ep->xfer_count < ep->xfer_len && ep->xfer_len != 0) { /* Write the FIFO */ len = ep->xfer_len - ep->xfer_count; if (len > ep->maxpacket) { len = ep->maxpacket; } len32b = (len + 3) / 4; USB_WritePacket(USBx, ep->xfer_buff, epnum, len); ep->xfer_buff += len; ep->xfer_count += len; } if(len <= 0) { fifoemptymsk = 0x1 << epnum; USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; } return HAL_OK; } #endif /* USB_OTG_FS */ #if defined (USB) /** * @brief This function handles PCD Endpoint interrupt request. * @param hpcd: PCD handle * @retval HAL status */ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) { PCD_EPTypeDef *ep = NULL; uint16_t count = 0; uint8_t epindex = 0; __IO uint16_t wIstr = 0; __IO uint16_t wEPVal = 0; /* stay in loop while pending interrupts */ while (((wIstr = hpcd->Instance->ISTR) & USB_ISTR_CTR) != 0) { /* extract highest priority endpoint number */ epindex = (uint8_t)(wIstr & USB_ISTR_EP_ID); if (epindex == 0) { /* Decode and service control endpoint interrupt */ /* DIR bit = origin of the interrupt */ if ((wIstr & USB_ISTR_DIR) == 0) { /* DIR = 0 */ /* DIR = 0 => IN int */ /* DIR = 0 implies that (EP_CTR_TX = 1) always */ PCD_CLEAR_TX_EP_CTR(hpcd->Instance, PCD_ENDP0); ep = &hpcd->IN_ep[0]; ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); ep->xfer_buff += ep->xfer_count; /* TX COMPLETE */ HAL_PCD_DataInStageCallback(hpcd, 0); if((hpcd->USB_Address > 0)&& ( ep->xfer_len == 0)) { hpcd->Instance->DADDR = (hpcd->USB_Address | USB_DADDR_EF); hpcd->USB_Address = 0; } } else { /* DIR = 1 */ /* DIR = 1 & CTR_RX => SETUP or OUT int */ /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ ep = &hpcd->OUT_ep[0]; wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0); if ((wEPVal & USB_EP_SETUP) != 0) { /* Get SETUP Packet*/ ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); USB_ReadPMA(hpcd->Instance, (uint8_t*)hpcd->Setup ,ep->pmaadress , ep->xfer_count); /* SETUP bit kept frozen while CTR_RX = 1*/ PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); /* Process SETUP Packet*/ HAL_PCD_SetupStageCallback(hpcd); } else if ((wEPVal & USB_EP_CTR_RX) != 0) { PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); /* Get Control Data OUT Packet*/ ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); if (ep->xfer_count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); ep->xfer_buff+=ep->xfer_count; } /* Process Control Data OUT Packet*/ HAL_PCD_DataOutStageCallback(hpcd, 0); PCD_SET_EP_RX_CNT(hpcd->Instance, PCD_ENDP0, ep->maxpacket); PCD_SET_EP_RX_STATUS(hpcd->Instance, PCD_ENDP0, USB_EP_RX_VALID); } } } else { /* Decode and service non control endpoints interrupt */ /* process related endpoint register */ wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, epindex); if ((wEPVal & USB_EP_CTR_RX) != 0) { /* clear int flag */ PCD_CLEAR_RX_EP_CTR(hpcd->Instance, epindex); ep = &hpcd->OUT_ep[epindex]; /* OUT double Buffering*/ if (ep->doublebuffer == 0) { count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); if (count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, count); } } else { if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_RX) { /*read from endpoint BUF0Addr buffer*/ count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); if (count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count); } } else { /*read from endpoint BUF1Addr buffer*/ count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); if (count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count); } } PCD_FreeUserBuffer(hpcd->Instance, ep->num, PCD_EP_DBUF_OUT); } /*multi-packet on the NON control OUT endpoint*/ ep->xfer_count+=count; ep->xfer_buff+=count; if ((ep->xfer_len == 0) || (count < ep->maxpacket)) { /* RX COMPLETE */ HAL_PCD_DataOutStageCallback(hpcd, ep->num); } else { HAL_PCD_EP_Receive(hpcd, ep->num, ep->xfer_buff, ep->xfer_len); } } /* if((wEPVal & EP_CTR_RX) */ if ((wEPVal & USB_EP_CTR_TX) != 0) { ep = &hpcd->IN_ep[epindex]; /* clear int flag */ PCD_CLEAR_TX_EP_CTR(hpcd->Instance, epindex); /* IN double Buffering*/ if (ep->doublebuffer == 0) { ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); if (ep->xfer_count != 0) { USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); } } else { if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_TX) { /*read from endpoint BUF0Addr buffer*/ ep->xfer_count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); if (ep->xfer_count != 0) { USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, ep->xfer_count); } } else { /*read from endpoint BUF1Addr buffer*/ ep->xfer_count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); if (ep->xfer_count != 0) { USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, ep->xfer_count); } } PCD_FreeUserBuffer(hpcd->Instance, ep->num, PCD_EP_DBUF_IN); } /*multi-packet on the NON control IN endpoint*/ ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); ep->xfer_buff+=ep->xfer_count; /* Zero Length Packet? */ if (ep->xfer_len == 0) { /* TX COMPLETE */ HAL_PCD_DataInStageCallback(hpcd, ep->num); } else { HAL_PCD_EP_Transmit(hpcd, ep->num, ep->xfer_buff, ep->xfer_len); } } } } return HAL_OK; } #endif /* USB */ /** * @} */ /** * @} */ #endif /* STM32F102x6 || STM32F102xB || */ /* STM32F103x6 || STM32F103xB || */ /* STM32F103xE || STM32F103xG || */ /* STM32F105xC || STM32F107xC */ #endif /* HAL_PCD_MODULE_ENABLED */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ```