text
stringlengths
1
1.04M
language
stringclasses
25 values
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Minowani's Writings on Dhamma" > <meta name="author" content="Minowani"> <meta name="keywords" content="Buddha, Dhamma, Sutta, Nikāya, Paṭiccasamuppāda, Buddhism"> <meta name="robots" content="index,follow"> <link href="../main.css" rel="stylesheet"> <title>Opportunity</title> </head> <body> <!--- <li><a href="bits/Opportunity.html">Opportunity</a></li> --> <h1 class="maintitle">Minowani's Writings</h1> <h3 class="subtitle">On Dhamma</h3> <p> <a href="../index.html">Home</a> >> <strong>Opportunity</strong> </p> <p>In AN8.3.9 (<em>Akkhaṇasuttaṃ</em>) we find people thinking the world had a chance, an opportunity, to benefit from the Buddha, because he was then there in the world.</p> <p>But we find the Buddha stating people mistake his being then there in the world for an opportunity. Even with him there, those in hell can&#39;t benefit from his Teaching, or animals, or some certain gods, or those living to far away, or those close enough but with to strong wrong views and to confused, or those simply to dumb. For those it is a mis.</p> <p>There is also the case when a person is capable but the Dhamma is not available, then too it will be a mis. Thus with the Buddha&#39;s Teaching now available for us, don&#39;t miss out on the opportunity. Study from the sermons so now and then.</p> </body> </html>
html
<reponame>ValdrST/V_pdf_Antiantiplagio<filename>vPdfAntiAntiPlagio/infraestructura/Server.py #!/usr/bin/env python from flask import Flask, escape, request, Blueprint, jsonify, make_response from os import mkdir, path import base64 import json import tempfile import logging from .Controller import Controller server_report = Blueprint('app', __name__) class Server(): def __init__(self, name, *args, **kwargs): self.app = Flask(name) self.app.register_blueprint(server_report) @server_report.route('/ws/vPdfAntiAntiPlagio',methods=['GET']) def index(): return "<h1>vPdfAntiAntiPlagio</h1>" @server_report.route('/ws/vPdfAntiAntiPlagio/procesar_documento',methods=['POST']) def procesar_documento(): print("procesar") respuesta = {} file = request.files['files[]'] pdf = file.read() pdf_name = file.filename f = tempfile.TemporaryDirectory() file_path = f.name+"/"+pdf_name with open(file_path,"wb") as file: file.write(pdf) try: controller = Controller("ws") controller.setInputFile(file_path) controller.setOutFile(f.name+"/out.pdf") controller.setPaginas("") controller.save_output() with open(f.name+"/out.pdf","rb") as file_out: respuesta["datos"] = base64.b64encode(file_out.read()).decode('utf-8') respuesta["nombre"] = pdf_name response = make_response(json.dumps(respuesta)) response.headers['Content-Type'] = 'application/json' return response, 200 except Exception: logging.error(Exception.mro) return "error" , 400 @server_report.route('/ws/vPdfAntiAntiPlagio/procesar_documento',methods=['GET']) def procesar_documento_get(): return request.get_json() #return "<h1>procesar documento get</h1>"
python
Alliance Defending Freedom (fka Alliance Defense Fund) will likely come up in Barrett's confirmation hearing this week. I've been reporting on ADF for more than a decade. Alliance Defending Freedom (fka Alliance Defense Fund) will likely come up in Barrett's confirmation hearing this week. I've been reporting on ADF for more than a decade. In my first story, 2007, I reported on how they represented a local anti-LGBTQ coalition in Boyd County, KY, which was fighting diversity training in a public high school, stemming from local efforts to block a gay-straight alliance at the school. The piece detailed how ADF had racked up a series of victories in court, based on the claim that religious organizations were victims of "viewpoint discrimination." One of ADF's attorneys that I interviewed for that story, who was very keen on ADF's agenda of overturning SCOTUS precedent on church/state separation, was Mike Johnson, who is now a Republican Congressman from Louisiana. You can read that whole story here: A decade after that first story, I wrote another piece on ADF, post-marriage equality, seemingly a crushing loss for the group and its allies. It used those same claims of discrimination against Christians to first fight marriage equality, and then undermine it. It used those same claims of discrimination against Christians to first fight marriage equality, and then undermine it. They call it "religious freedom." I covered a 2017 press conference, where I found that same Mike Johnson (now Rep. Johnson), where GOP lawmakers announced their support for Jack Phillips, owner of Masterpiece Cakeshop, whose case was before SCOTUS. Here's what Johnson said: Here's what Johnson said:
english
The All Bodo Students’ Union (ABSU) Ramfalbil Anchalik Committee on Monday observed the 17th death anniversary of the founder of the student union and former chief of Bodoland Autonomous Council (BAC), Kanakeswar Narzary at Ramfalbil. KOKRAJHAR: The All Bodo Students' Union (ABSU) Ramfalbil Anchalik Committee on Monday observed the 17th death anniversary of the founder of the student union and former chief of Bodoland Autonomous Council (BAC), Kanakeswar Narzary at Ramfalbil. As part of the programme, the former president of Ramfalbil Anchalik Committee, ABSU, and secretary of Ramfalbil Anchalik Sports Association, Bijit Kr. Narzary paid floral tribute to Narzary at his portrait after hoisting of organizational flag at half mast by president of RAC, ABSU. Kanakeswar Narzary was the founder secretary of ABSU in 1967. He was associated with the Bodo Sahitya Sabha (BSS) and became president of Kokrajhar district BSS after which he joined politics. He was also associated with the PTCA (Plains Tribal Council of Assam), Youth PTCA, Progressive PTCA, UTNLF (United Tribal Nationalist Liberation Front) and UBNLF (United Bodo Nationalist Liberation Front). Finally, he joined the People's Democratic Front (PDF) led by Daoharu Garla Batha Basumatary and became chief of BAC on June 19, 1996. He was chief of BAC till it was scrapped to sign the BTC Accord in 2003. Born in 1943 at West Tengaigaon, Narzary was also Headmaster of Gossainichina High School and took Bodofa UN Brahma with him to his school for some time. He was one of the great nationalist Bodo leaders who fought against injustice towards indigenous people.
english
{ "$id": "https://www.gov.uk/government/organisations/hm-revenue-customs/schema/itsa/custom_benefit_schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "Ignore Benefit", "description": "This schema allows a customer to create a Custom Benefit", "type": "object", "additionalProperties": false, "required": ["benefitType", "startDate"], "properties":{ "benefitType":{ "type": "string" }, "startDate":{ "type": "string" }, "endDate":{ "type": "string" } } }
json
- Nationality: Indian national candidates who have a domicile of Orissa state can apply. - Age Criteria: Candidates applying for UG admission must have completed 17 years of age 31/12/2020. - Qualifying Exam: Candidates must have passed 10+2 with science from a recognized board or university. - Qualifying Marks: Applying candidates in 10+2 must be passed with a minimum aggregate of 50% marks (for SC/ST/PWD – 40%). - Qualifying Subjects: Candidates must have passed 10+2 with Physics, Chemistry, Mathematics, or Biology subjects. B.Tech (Agriculture Engineering) - Qualifying Exam: Candidates should have passed 10+2 level from the recognized board. - Qualifying Marks: Candidates must have obtained 50% marks (for SC/ST/PWD – 40%). - Qualifying Subjects: Candidates must have passed 10+2 with PCM subjects.
english
<gh_stars>0 import * as u from './utils'; import { ILogur, ILogurInstanceOptions, ILogurTransport, ILogurInstance, ILogurTransportOptions, ITransportMethods, ILogurInstances, ILogurTransports, ILevelMethods, ILevelMethodsDefault, ILogurOptionsTransport, IConsoleTransportOptions, ISerializers, IMetadata } from './interfaces'; import { LogurInstance } from './instance'; import { ConsoleTransport } from './transports'; export class Logur implements ILogur { static instance: Logur; // The default Logur Instance. instance: ILogurInstance<ILevelMethodsDefault> & ILevelMethodsDefault; instances: ILogurInstances = {}; transports: ILogurTransports = {}; // log: ILogurInstance<ILevelMethodsDefault> & ILevelMethodsDefault; /** * Constructs Logur */ constructor() { if (Logur.instance) return Logur.instance; Logur.instance = this; } /** * Log * Gets the default internal logger. */ get log(): ILogurInstance<ILevelMethodsDefault> & ILevelMethodsDefault { // If log exists just return it. if (this.instance) return this.instance; let instance; // Try to get the default instance. instance = this.get('default'); // If no instance create it. if (!instance) instance = this.create<ILevelMethodsDefault>('default'); this.instance = instance; return this.instance; } /** * Get * Gets a loaded Logur instance or all instances * when no name is provided. * * @param name the name of the Logur Instance to get. */ get<T extends ILevelMethods>(name?: string): ILogurInstance<T> & T { return this.instances[name]; } /** * Create * Creates and loads a Logur Instance in Logur. * * @param name the name of the Logur Instance to create. * @param options Logur Instance options. */ create<T extends ILevelMethods>(name: string, options?: ILogurInstanceOptions): ILogurInstance<T> & T { if (!name) throw new Error('Failed to create Logur Instance using name of undefined.'); this.instances[name] = new LogurInstance<T>(name, options, this); return this.instances[name]; } /** * Remove * Destroys the specified Logur Instance. * * @param name */ remove(name: string): void { if (name === 'default') throw Error('cannot remove default Logur Instance.'); delete this.instances[name]; } /** * Dispose * Iterates all instances disposing of transports. * * @param exit when NOT false exit after disposing. */ dispose(exit: boolean | Function, fn?: Function) { const funcs = []; if (u.isFunction(exit)) { fn = exit as Function; exit = undefined; } fn = fn || u.noop; u.keys(this.instances).forEach((k) => { const instance = this.instances[k]; funcs.push(instance.dispose); }); u.asyncEach(funcs, () => { // Exit if true and is Node. if (exit && u.isNode()) process.exit(0); // Otherwise call callback. else fn(); }); } } /** * Get * Gets the default Logur Instance. * * @param options the Logur Instance options. */ export function get(options?: ILogurInstanceOptions): ILogurInstance<ILevelMethodsDefault> & ILevelMethodsDefault { // Get Logur. const logur = new Logur(); // Get the default instance if exists. let instance = <ILogurInstance<ILevelMethodsDefault> & ILevelMethodsDefault>logur.get<ILevelMethodsDefault>('default'); // If no instance create it. if (!instance) { const consoleTransport = { name: 'console', transport: ConsoleTransport }; // Ensure options. options = options || { transports: [consoleTransport] }; options.transports = options.transports || []; // Check if Console Transport exists. const hasConsole = options.transports.filter((t) => { return t.name === 'console' || u.isInstance(t.transport, ConsoleTransport); })[0]; // If no Console Transport push config and create instance. if (!hasConsole) options.transports.push(consoleTransport); // Create the instance. instance = logur.create<ILevelMethodsDefault>('default', options); logur.instance = instance; } return instance; }
typescript
Vinesh Phogat’s double delight after securing an Olympic quota and a maiden World championships medal in Nur-Sultan, Kazakhstan, on Wednesday was the outcome of her sheer determination and would stand her in good stead in the 2020 Games. Because of her fabulous track record and consistent performance at elite events, Vinesh’s achievements in women’s 53kg might not surprise many. However, one could understand the essence of her success when one considers the tough draw – including Rio Olympics medallist Sofia Mattsson of Sweden, 55 kg World champion Muya Mukaida from Japan and World No.1 and Worlds silver medallist Sarah Hilderbrandt of the USA – she faced. She became not only the first Indian wrestler to claim a berth in the Tokyo Games, but also the fifth woman from the country to bag a Worlds medal. Vinesh, whose Olympics dream was shattered in 2016 when she injured her knee midway through a bout in Rio, banked on her resilience to make a strong comeback and bag her second Commonwealth Games gold and the Asian Games gold in 2018. In the early part of 2019, Vinesh seemed vulnerable in certain aspects of her game in the Pro Wrestling League. “I am going to participate in as many competitions as possible. Of course, winning is the first priority, but if I don't win then I would like to learn from my mistakes. Even the smallest change can help improve my game a lot,” Vinesh had told this reporter after PWL. Vinesh secured gold medals in Grand Prix of Spain, Yasar Dogu event in Turkey and Poland Open. In Nur-Sultan, one could witness significant improvement – quick counter-attacks and better defence – in Vinesh’s game. “I am very happy to win a quota; got this medal after trying for five years. It’s a proud moment for me as I could do this for my country. I could achieve this after switching from 50kg to 53kg in about 10 months,” said Vinesh. The 25-year-old, who joined her cousin sisters Geeta and Babita to form a unique family club of Worlds medalists, knows that she has got the potential to achieve greater heights and will rely on her grit and ambition to pursue that.
english
Mumbai: The Bombay High Court Wednesday granted bail to actress Rhea Chakraborty, arrested over drugs-related charges in actor Sushant Singh Rajput’s death case. A bench of Justice Sarang Kotwal also granted bail to Rajput’s aides Dipesh Sawant and Samuel Miranda, but rejected the bail plea of Rhea Chakraborty’s brother Showik Chakraborty, who is also an accused in the case. The court also rejected the bail plea of alleged drug peddler Abdel Basit Parihar. Rhea Chakraborty and her brother was arrested last month by the Narcotics Control Bureau (NCB) in connection with its drugs probe related to the case of Rajput’s death. The other accused were also arrested by the NCB during the course of its probe into the case. The HC, while granting bail to Rhea Chakraborty and two others, directed them to deposit their passports with the NCB and not to leave the country without permission of the special NDPS court. The HC also directed Rhea to visit the nearest police station for the first 10 days after she gets out of jail. It directed her not to leave Mumbai without the NCB’s permission and to not tamper with evidence while out on bail. Rajput, 34, was found hanging at his apartment in suburban Bandra on June 14 this year. Rhea and her brother had approached the HC after their bail pleas were rejected by a special NDPS court here last month. Following extensive hearings last week, the HC had closed all arguments and reserved its verdict on the pleas. The NCB, through Additional Solicitor General Anil Singh, had opposed the bail pleas in the HC. It said there existed ample material to show that Rhea Chakraborty, her brother and others arrested in the case represented a “chain,” and an “active syndicate” that was involved in procuring, financing, harbouring, and abetting drugs and its consumption. Singh said Rhea Chakraborty had knowingly paid for Rajputs drugs, and concealed the information regarding his drug habit. These qualified as stringent charges of financing and harbouring drug consumption, as defined under the Narcotic Drugs and Psychotropic Substances (NDPS) Act. The court had posed a query to all parties on the application of the stringent section 27-A of the NDPS Act in the case. The section deals with financing and harbouring drugs and its consumers, and entails a punishment of up to 10 years. It also carries a bar on grant of bail. All the accused had opposed the application of the above section in the present case. Rhea Chakraborty’s counsel Satish Maneshinde argued that the actress had only occasionally paid for Rajputs drugs and this did not amount to financing. All the accused had also argued that the drugs seized by the NCB in the case was in small quantity, and did not qualify ascommercial quantity that could attract stringent sections under the NDPS Act. (This story has not been edited by News18 staff and is published from a syndicated news agency feed - PTI)
english
<reponame>Tatiana37/goit-react-hw-08-phonebook .box { display: flex; align-items: center; margin-right: 150px; } .icon { border-radius: 50%; box-shadow: 0px 0px 7px 2px rgb(121, 86, 86), 0px 0px 3px 0px rgb(121, 86, 86); } .text { color: rgb(94, 93, 93); font-size: 20px; margin-right: 10px; margin-left: 10px; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.1); } .btn { display: inline-block; color: white; text-decoration: none; padding: 10px; outline: none; border-color: rgb(116, 86, 86); border-radius: 10px; background: rgb(194, 156, 156); transition: 0.2s; } .btn:hover, .btn:focus { color: rgb(194, 156, 156); background-color: rgb(121, 86, 86); box-shadow: 0 1px 4px rgba(0, 0, 0, 1), 0 0 20px -23px rgba(0, 0, 0, 0.8); }
css
<reponame>JazzPants/CLI-application-with-api import type { Plugin, Ruby } from "../../types"; import prettier from "../../prettier"; import { hasAncestor } from "../../utils"; const { breakParent, group, ifBreak, indent, join, removeLines, softline } = prettier; export const printBlockVar: Plugin.Printer<Ruby.BlockVar> = ( path, opts, print ) => { const parts = ["|", removeLines(path.call(print, "body", 0))]; // The second part of this node is a list of optional block-local variables if (path.getValue().body[1]) { parts.push("; ", join(", ", path.map(print, "body", 1))); } parts.push("| "); return parts; }; // You have to go through the main print function if you could potentially have // comments attached. So we're doing this weird reflection on the printed docs // to retroactively change the printed keyword depending on if we're using // braces or not. Ideally we wouldn't do this, we would instead do this // reflection in the child printer, but this keeps the logic to just this file // and contains it, so keeping it here for now. function printBlockBeging( path: Plugin.Path<Ruby.Lbrace | Ruby.Keyword>, print: Plugin.Print, useBraces: boolean ) { let docs = print(path); const doc = useBraces ? "{" : "do"; if (Array.isArray(docs)) { docs[1] = doc; } else { docs = doc; } return docs; } type Block = Ruby.BraceBlock | Ruby.DoBlock; function printBlock(braces: boolean): Plugin.Printer<Block> { return function printBlockWithBraces(path, opts, print) { const [variables, statements] = path.getValue().body; const stmts = statements.type === "stmts" ? statements.body : statements.body[0].body; let doBlockBody: Plugin.Doc = ""; if ( stmts.length !== 1 || stmts[0].type !== "void_stmt" || stmts[0].comments ) { doBlockBody = indent([softline, path.call(print, "body", 1)]); } // If this block is nested underneath a command or command_call node, then // we can't use `do...end` because that will get associated with the parent // node as opposed to the current node (because of the difference in // operator precedence). Instead, we still use a multi-line format but // switch to using braces instead. const useBraces = braces && hasAncestor(path, ["command", "command_call"]); const doBlock = [ " ", path.call( (begingPath) => printBlockBeging(begingPath, print, useBraces), "beging" ), variables ? [" ", path.call(print, "body", 0)] : "", doBlockBody, [softline, useBraces ? "}" : "end"] ]; // We can hit this next pattern if within the block the only statement is a // comment. if ( stmts.length === 1 && stmts[0].type === "void_stmt" && stmts[0].comments ) { return [breakParent, doBlock]; } const blockReceiver = path.getParentNode().body[0]; // If the parent node is a command node, then there are no parentheses // around the arguments to that command, so we need to break the block if (["command", "command_call"].includes(blockReceiver.type)) { return [breakParent, doBlock]; } const hasBody = stmts.some(({ type }) => type !== "void_stmt"); const braceBlock = [ " ", path.call( (begingPath) => printBlockBeging(begingPath, print, true), "beging" ), hasBody || variables ? " " : "", variables ? path.call(print, "body", 0) : "", path.call(print, "body", 1), hasBody ? " " : "", "}" ]; return group(ifBreak(doBlock, braceBlock)); }; } export const printBraceBlock = printBlock(true); export const printDoBlock = printBlock(false);
typescript
The Indian Premier League has always been a platform for aspiring and talented cricketers. The game has witnessed a lot of changes in the recent years and also the career of the players playing for it. There are presently a total eight franchises playing the game. Various players have adorned various jerseys and have represented diffrent teams in the past. They have shone in it which gave them the opportunity to represent their national side. In the Indian cricket, the number has been quite big but considering the overseas players, only countable players have used the IPL as a ladder to climb to glory and fame. Each season has a new bunch of talented rookies entering the format and making it big. Here we're going to look at three overseas players who made it big in their career by playing for the IPL. The big-hitting Kieron Pollard was born in Trinidad & Tobago. In 2005, Pollard was selected for the U-19 West Indies team which toured Pakistan. He had a good series after which he got selected for the U-19 2006 World Cup held in Sri Lanka where Pollard performed poorly. Polly's impressive performance in the 2009 Champions League Twenty20 led him to be one of the most sought after players at the 2010 IPL auction. He was in demand by the Chennai Super Kings, Kolkata Knight Riders, Mumbai Indians, and Royal Challengers Bangalore. Pollard has played a total of 144 IPL matches in a time span of 10 years. With the bat, Pollard has an aggregate score of 2705 in 133 innings, with an average of 28. 47 and 83 as his high score. The West Indies all-rounder has played the rescuer role on many occasions for the Mumbai Indians. Following his impressive performance in the IPL, he was picked up in the 2010 T20 West Indies squad. Today, Pollard is an global T20 superstar as he plays for various teams in various leagues. Pollard is one of the two players who have played more than 100 ODIs but has never played a Test match. Follow Sportskeeda for all the updates on IPL purple cap, points table, schedule, news, live scores, orange cap and fantasy tips. Sunil Narine made his debut in the first-class cricket debuting for Trinidad and Tobago in February 2009, which did not go as well as expected from him. In 2011, during the Caribbean Twenty20 competition, Narine played his first T20. Narine then shone in the Champions League T20, where he became the all-time leading wicket-taker in its short history with 39 scalps. The right arm off-break bowler made his IPL debut in the 2012 IPL season for the Kolkata Knight Riders. Narine has always remained a vital force in the KKR with both bat and ball. The West Indies all-rounder has played a total of 108 matches and has scalped 122 wickets with an elegant economy of 6. 66. With the bat, Narine has scored 771 runs with an average of 17. 52 with a high score of 75. He has carried the IPL performance for West Indies too. He has taken 50 T20 wickets for the national side. Narine also took 92 wickets in just 65 ODIs for West Indies cricket, However, he is no longer a regular member in the national side and has been omitted from the World Cup squad. Follow Sportskeeda for all the updates on IPL points table, schedule, news, live scores, orange cap, purple cap and fantasy tips. Shane Watson played in the IPL for the Rajasthan Royals in the maiden IPL season in 2008. He performed well with both bat and the ball scoring four half-centuries to guide his team to victory in three matches of the tournament and in the semi-finals. He also picked up 17 wickets, won four Man of the Match awards and also the Man of the Tournament award. On the basis of his IPL performance, Watson was selected to replace Matthew Hayden in the one-day series as part of Australia's tour to the West Indies, after Hayden was injured during the IPL season. He is also the first Australian captain to score a century in T20 international. Before the IPL he was not the regular member of the Australian side. But post his good show in 2008 season the Australian cemented his place in the ODI side. He went on to score over 5500 ODI runs for Australia, including nine centuries. The all-rounder did really well with the ball too, taking 168 ODI wickets at an average of 31. 80. He is regarded as one of the best Australian all-rounder ever played the limited overs cricket for the nation, thus IPL did play its part in spoting the overseas talents. Follow Sportskeeda for all the updates on IPL orange cap, points table, schedule, news, live scores, purple cap and fantasy tips.
english
pub use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use k8s_openapi::apimachinery::pkg::apis::meta::v1::OwnerReference; use std::{borrow::Cow, collections::BTreeMap}; /// An accessor trait for a kubernetes Resource. /// /// This is for a subset of Kubernetes type that do not end in `List`. /// These types, using [`ObjectMeta`], SHOULD all have required properties: /// - `.metadata` /// - `.metadata.name` /// /// And these optional properties: /// - `.metadata.namespace` /// - `.metadata.resource_version` /// /// This avoids a bunch of the unnecessary unwrap mechanics for apps. pub trait Resource { /// Type information for types that do not know their resource information at compile time. /// /// Types that know their metadata at compile time should select `DynamicType = ()`. /// Types that require some information at runtime should select `DynamicType` /// as type of this information. /// /// See [`DynamicObject`](crate::dynamic::DynamicObject) for a valid implementation of non-k8s-openapi resources. type DynamicType: Send + Sync + 'static; /// Returns kind of this object fn kind(dt: &Self::DynamicType) -> Cow<'_, str>; /// Returns group of this object fn group(dt: &Self::DynamicType) -> Cow<'_, str>; /// Returns version of this object fn version(dt: &Self::DynamicType) -> Cow<'_, str>; /// Returns apiVersion of this object fn api_version(dt: &Self::DynamicType) -> Cow<'_, str> { let group = Self::group(dt); if group.is_empty() { return Self::version(dt); } let mut group = group.into_owned(); group.push('/'); group.push_str(&Self::version(dt)); group.into() } /// Returns the plural name of the kind /// /// This is known as the resource in apimachinery, we rename it for disambiguation. fn plural(dt: &Self::DynamicType) -> Cow<'_, str>; /// Creates a url path for http requests for this resource fn url_path(dt: &Self::DynamicType, namespace: Option<&str>) -> String { let n = if let Some(ns) = namespace { format!("namespaces/{}/", ns) } else { "".into() }; let group = Self::group(dt); let api_version = Self::api_version(dt); let plural = Self::plural(dt); format!( "/{group}/{api_version}/{namespaces}{plural}", group = if group.is_empty() { "api" } else { "apis" }, api_version = api_version, namespaces = n, plural = plural ) } /// Metadata that all persisted resources must have fn meta(&self) -> &ObjectMeta; /// Metadata that all persisted resources must have fn meta_mut(&mut self) -> &mut ObjectMeta; } /// Implement accessor trait for any ObjectMeta-using Kubernetes Resource impl<K> Resource for K where K: k8s_openapi::Metadata<Ty = ObjectMeta>, { type DynamicType = (); fn kind(_: &()) -> Cow<'_, str> { K::KIND.into() } fn group(_: &()) -> Cow<'_, str> { K::GROUP.into() } fn version(_: &()) -> Cow<'_, str> { K::VERSION.into() } fn api_version(_: &()) -> Cow<'_, str> { K::API_VERSION.into() } fn plural(_: &()) -> Cow<'_, str> { K::URL_PATH_SEGMENT.into() } fn meta(&self) -> &ObjectMeta { self.metadata() } fn meta_mut(&mut self) -> &mut ObjectMeta { self.metadata_mut() } } /// Helper methods for resources. pub trait ResourceExt: Resource { /// Returns the name of the resource, panicking if it is /// missing. Use this function if you know that name is set, for example /// when resource was received from the apiserver. /// Because of `.metadata.generateName` field, in other contexts name /// may be missing. /// /// For non-panicking alternative, you can directly read `name` field /// on the `self.meta()`. fn name(&self) -> String; /// The namespace the resource is in fn namespace(&self) -> Option<String>; /// The resource version fn resource_version(&self) -> Option<String>; /// Unique ID (if you delete resource and then create a new /// resource with the same name, it will have different ID) fn uid(&self) -> Option<String>; /// Returns resource labels fn labels(&self) -> &BTreeMap<String, String>; /// Provides mutable access to the labels fn labels_mut(&mut self) -> &mut BTreeMap<String, String>; /// Returns resource annotations fn annotations(&self) -> &BTreeMap<String, String>; /// Provider mutable access to the annotations fn annotations_mut(&mut self) -> &mut BTreeMap<String, String>; /// Returns resource owner references fn owner_references(&self) -> &[OwnerReference]; /// Provides mutable access to the owner references fn owner_references_mut(&mut self) -> &mut Vec<OwnerReference>; /// Returns resource finalizers fn finalizers(&self) -> &[String]; /// Provides mutable access to the finalizers fn finalizers_mut(&mut self) -> &mut Vec<String>; } // TODO: replace with ordinary static when BTreeMap::new() is no longer // const-unstable. use once_cell::sync::Lazy; static EMPTY_MAP: Lazy<BTreeMap<String, String>> = Lazy::new(BTreeMap::new); impl<K: Resource> ResourceExt for K { fn name(&self) -> String { self.meta().name.clone().expect(".metadata.name missing") } fn namespace(&self) -> Option<String> { self.meta().namespace.clone() } fn resource_version(&self) -> Option<String> { self.meta().resource_version.clone() } fn uid(&self) -> Option<String> { self.meta().uid.clone() } fn labels(&self) -> &BTreeMap<String, String> { self.meta().labels.as_ref().unwrap_or_else(|| &*EMPTY_MAP) } fn labels_mut(&mut self) -> &mut BTreeMap<String, String> { self.meta_mut().labels.get_or_insert_with(BTreeMap::new) } fn annotations(&self) -> &BTreeMap<String, String> { self.meta().annotations.as_ref().unwrap_or_else(|| &*EMPTY_MAP) } fn annotations_mut(&mut self) -> &mut BTreeMap<String, String> { self.meta_mut().annotations.get_or_insert_with(BTreeMap::new) } fn owner_references(&self) -> &[OwnerReference] { self.meta().owner_references.as_deref().unwrap_or_default() } fn owner_references_mut(&mut self) -> &mut Vec<OwnerReference> { self.meta_mut().owner_references.get_or_insert_with(Vec::new) } fn finalizers(&self) -> &[String] { self.meta().finalizers.as_deref().unwrap_or_default() } fn finalizers_mut(&mut self) -> &mut Vec<String> { self.meta_mut().finalizers.get_or_insert_with(Vec::new) } }
rust
{"text":"","historical":"Legislative History of Laws\n\nFor Law 13-308, see notes following § 26-833.01.\n\nDC CODE § 26-831.18\n\nCurrent through December 11, 2012","credits":"(June 9, 2001, D.C. Law 13-308, § 318, 48 DCR 3244.)","sections":[{"prefix":"a","text":" If any of the grounds under § 26-833.12 authorizing the request for the appointment of a receiver exist or if the Commissioner determines that it is necessary to conserve the assets of a merchant bank for the benefit of the depositors, investors, or other creditors of the bank or for the benefit of the general public, the Commissioner may petition the Superior Court to appoint a conservator for a merchant bank."},{"prefix":"b","text":" The Department shall be reimbursed out of the assets of the conservatorship, for all sums expended by the Department in connection with the conservatorship."},{"prefix":"c","text":" All expenses of a conservatorship shall be paid out of the assets of the merchant bank upon the approval of the Commissioner, shall be a first charge upon the assets of the merchant bank, and shall be paid in full before a final distribution or payment of dividends to creditors or shareholders of the merchant bank."}],"division":{"identifier":"V","text":"Local Business Affairs"},"title":{"identifier":"26","text":"Banks and Other Financial Institutions. (Refs & Annos)"},"chapter":{"identifier":"8A","text":"Merchant Banks."},"subchapter":{"identifier":"V","text":"Commissioner Possession, Receivership, Conservatorship, and Liquidation of Merchant Banks."},"heading":{"title":"26","chaptersection":"831","identifier":"26-831.18","catch_text":"Conservator; appointment; bond and security; qualifications; expenses."}}
json
Popular IRL streamer JakenBake shared his experience meeting Twitch President Dan Clancy during TwitchCon 2022. Taking a direct jibe at Dan for his cold behavior towards streamers and creators, the latter revealed that he didn't feel very "confident" as a streamer with someone who was so "out of touch" and walked away feeling "depressed". TwitchCon finally returned to San Diego for the first time since 2019. The three-day event kicked off with fan meets, surprise appearances, and controversies. Many fans, followers, and even creators shared photos and videos with their favorite high-profile streamers. While social media has been flooded with many positive experiences, JakenBake shared a rather uncomfortable meeting with none other than Dan Clancy. He lamented: "I don't feel confident as a streamer. " There is no denying that Twitch has had a turbulent year so far, with some of its biggest talents such as Myth, Sykkuno, and LilyPichu making their switch to YouTube. Just a couple of weeks ago, on September 21, Twitch changed its revenue sharing program with this new program, affecting some of the biggest creators. The current Twitch model works on a 50/50 split between partnered streamers and the purple platform when it comes to paid subscriptions. Some high-profile creators get a more generous 70/30 split. This is set to change in June 2023, as all of the streamers working on the Amazon-owned platform get to keep 70% of the revenue for the first $100,000 earned and the share will revert back to the usual 50/50 cut for anything above that. As expected, the new threshold will have a major impact on Twitch's top 10% of streamers. This is precisely why the majority of prominent streamers who have millions of followers and subscribers on their channel, are not happy with the way Twitch takes care of its creators. Speaking about his meeting with Dan Clancy at TwitchCon 2022, JakenBake mushed: "I'm gonna be honest dude, the President of Twitch. I'm sure personally I have no problem personally with him but honestly I don't feel confident as a streamer on the platform with someone who is that out of touch with what the streamers need and want. Very weird. I walked away feeling like depressed. Seriously sad. " As expected, as soon as the reaction video was made public, it blew up on Twitter, eliciting a plethora of reactions from viewers worldwide. At the time of writing, the tweet has garnered over 7. 2k likes and 612 retweets. Sharing a wide spectrum of reactions, here's what fans had to say: JakenBake is one of the most formidable names in the realm of content creation, boasting over 628k followers on Twitch alone. He is majorly known for his adventurous IRL streams and has brushed with danger on various occasions and even managed to capture the thrill on live broadcasts in front of thousands of viewers. From terrifying gun pranks to spine chilling adventures, Jake has kept his audience entertained with his streams all around the globe.
english
table! { use diesel::sql_types::*; results (id) { id -> Integer, path -> Varchar, } } allow_tables_to_appear_in_same_query!( results, );
rust
An elderly Gujarati couple was found dead in a south Kolkata neighbourhood, in an incident of alleged double murder that might have links to the share market, police said. The dead were identified as Ashok Shah, 60, and his wife Reshmi Shah, 55. The woman was found with a very deep injury on her shoulder, said police. Their bodies were found lying in a pool of blood in their flat in Bhabanipore area, near West Bengal Chief Minister Mamata Banerjee's residence which is a high-security zone. Police suspect some close to the victims had killed them. "Circumstantial evidence indicates that those who came to their house were known to them and the woman might have opened the door," news agency PTI said citing the officer. Gunfire was also heard from inside the house, sources said. The shell of a bullet was recovered from the house. The officer said the police are trying to find if the couple had taken loan to invest in stock market. Meanwhile, local reports citing preliminary inquiry suggest the couple had entered into an argument with a potential buyer of their house a few days ago. The police have seized the victims' mobile phones and going through their call logs. City mayor Firhad Hakim and top officers of Kolkata Police have visited the spot. Police also used sniffer dogs to conduct searches. Further investigation is on.
english
<gh_stars>1-10 { "name": "capabilities-psp", "description": "A Pod Security Policy that controls Container Capabilities", "homepage": "https://github.com/kubewarden/capabilities-psp-policy", "author": { "name": "<NAME>", "homepage": "https://github.com/kubewarden" }, "download": { "registry": "ghcr.io/kubewarden/policies/capabilities-psp:v0.1.8", "url": "https://github.com/kubewarden/capabilities-psp-policy/releases/download/v0.1.8/policy.wasm" }, "keywords": [ "PSP", "Container", "Capability", "Capabilities" ], "resources": [ "Pod" ], "mutation": true, "contextAware": false }
json
'use strict'; var yeoman = require('yeoman-generator'); var _ = require('lodash'); var path = require('path'); var filters = require(path.join(__dirname, '../../utils/filters.js')); var convert = require(path.join(__dirname, '../../utils/convert.js')); var context = require(path.join(__dirname, '../../utils/context.js')); var updater = require(path.join(__dirname, '../../utils/updater.js')); module.exports = yeoman.generators.Base.extend({ constructor: function() { yeoman.Base.apply(this, arguments); this.argument('path', { required: false }); if (this.path) { this.module = convert.pathToModule(this.path); this.name = path.basename(this.path); } }, initializing: function() { this.sourceRoot(path.join(__dirname, '../../templates')); }, prompting: function() { var done = this.async(); var prompts = [{ type: 'input', name: 'name', message: 'Enter the directive name:', default: 'sys-default', when: !this.module }, { type: 'input', name: 'module', message: 'Enter the module name:', default: getDefaultModule, when: !this.module }]; this.prompt(prompts, function(props) { this.props = props; this.props.module = this.props.module || this.module; this.props.name = this.props.name || this.name; this.props.module = filters.moduleNameFilter(this.props.module); done(); }.bind(this)); }, writing: function() { var directiveContext = context.getDefaults(this.props.name, this.props.module); var styleExt = this.config.get('style') || 'scss'; var destinationFolder; if (this.path) { destinationFolder = path.resolve(this.path) + '/'; } else { destinationFolder = 'src/' + convert.moduleToFolder(this.props.module); } var fileName = _.kebabCase(this.props.name).replace(/v-24/g, 'v24'); this.fs.copyTpl( this.templatePath('module.js'), this.destinationPath(destinationFolder + fileName + '.module.js'), directiveContext ); this.fs.copyTpl( this.templatePath('directive.js'), this.destinationPath(destinationFolder + fileName + '.directive.js'), directiveContext ); this.fs.copyTpl( this.templatePath('directive.jade'), this.destinationPath(destinationFolder + fileName + '.directive.jade') ); this.fs.copyTpl( this.templatePath('directive.css'), this.destinationPath(destinationFolder + fileName + '.directive.' + styleExt), directiveContext ); updater.updateParentModule(this.props.module, this.destinationPath(destinationFolder)); } }); function getDefaultModule(props) { return 'app.directives.' + _.camelCase(props.name); }
javascript
package fight import ( iniconf "code.google.com/p/goconf/conf" "errors" "fmt" "github.com/gamelost/bot3server/server" "math/rand" "strings" "time" ) type FightService struct { server.BotHandlerService RandomNG *rand.Rand FightMethods []string FightArenas []string } func (svc *FightService) NewService(config *iniconf.ConfigFile, publishToIRCChan chan *server.BotResponse) server.BotHandler { var newSvc = &FightService{} newSvc.Config = config newSvc.PublishToIRCChan = publishToIRCChan newSvc.RandomNG = rand.New(rand.NewSource(time.Now().UnixNano())) newSvc.FightMethods = []string{"tickles to death", "pummels", "quarters", "garrotes", "butchers", "obliterates", "tears apart limb by limb", "annihilates", "rampages past", "dismembers", "kneecaps", "uses force lightning to crispy-critter", "gets blown out of the sky by", "executes a well-timed Harai goshi on", "smothers"} newSvc.FightArenas = []string{"in a gentlemanly game of chess", "in a fight to the pain", "on the dark side of the moon", "in the mens restroom", "in the ladies restroom", "in a barroom brawl", "in a slapfest", "with dull flaming scimitars", "on the planet Hoth", "with elephant foreskins filled with brie"} return newSvc } func (svc *FightService) DispatchRequest(botRequest *server.BotRequest) { botResponse := svc.CreateBotResponse(botRequest) fighterOne, fighterTwo, err := svc.ParseInput(botRequest.Text()) if err != nil { botResponse.SetSingleLineResponse("Unable to parse fight command. Please use 'vs' or 'vs.'") } else { botResponse.SetSingleLineResponse(svc.Fight(fighterOne, fighterTwo)) } svc.PublishBotResponse(botResponse) } func (svc *FightService) Fight(fighterOne string, fighterTwo string) string { randVal := svc.RandomNG.Intn(2) if randVal == 0 { return fmt.Sprintf("%s %s %s %s.", fighterOne, svc.RandomFightVerb(), fighterTwo, svc.RandomFightArena()) } else { return fmt.Sprintf("%s %s %s %s.", fighterTwo, svc.RandomFightVerb(), fighterOne, svc.RandomFightArena()) } } func (svc *FightService) RandomFightVerb() string { randVal := svc.RandomNG.Intn(len(svc.FightMethods)) method := svc.FightMethods[randVal] return method } func (svc *FightService) RandomFightArena() string { randVal := svc.RandomNG.Intn(len(svc.FightArenas)) method := svc.FightArenas[randVal] return method } func (svc *FightService) ParseInput(input string) (fighterOne string, fighterTwo string, err error) { input = strings.TrimPrefix(input, "!fight ") fighters := strings.SplitAfterN(input, "vs", 2) if len(fighters) == 2 { fighterOne = strings.TrimSuffix(fighters[0], "vs") fighterTwo = strings.TrimPrefix(fighters[1], ".") fighterOne = strings.TrimSpace(fighterOne) fighterTwo = strings.TrimSpace(fighterTwo) } else { err := errors.New("number of fighters is not two") return "", "", err } return }
go
Colombo: India's plans looked futile on the Saturday morning, but when it started working, the second Test turned on its head putting the visitors in a position from where they can drive home the advantage on the fourth day. After wickets failed to come India's way in the first two hours, an inspired spell by Ishant Sharma broke the 127-run stand between Lahiru Thirimanne and Angelo Mathews, which opened the floodgates and swept the last seven Lankan wickets for just 65 - from 241 for 3 to 306 all out. The start to India's second innings was the least inspiring. Dhammika Prasad breached KL Rahul's (2) defence to deliver the early blow Sri Lanka so desperately needed. And like Galle, Mathews asked Herath to begin with the new ball from the other end to test the Indians. Murali Vijay and No. 3 Ajinkya Rahane saw the left-arm spinnner out and settled in nicely, without bothering about the scoring rate. The strategy worked, with a few LBW shouts in between, and took India to 70/1 at close - leading by 157 runs, Vijay 39* and Rahane 28*. The day ran for well over an hour from the scheduled close of play and ended only when the umpires' light metre showed light not good enough to continue. For the hosts, the afternoon belonged to Mathews (102), who once again highlighted himself as the most underrated batsman by striking his sixth Test hundred, fifth as captain. But Thirimanne's (62) departure seemed to have caused a lapse in the home skipper's concentration, which allowed Stuart Binny to claim his maiden Test wicket. Amit Mishra then pounced on the opportunity to savour a Sri Lankan meal and added three more wickets to his one from yesterday to end with 4 for 43. Ishant's figures read 2 for 68. Ashwin too bagged a brace in his 29 overs, with a wicket apiece for Binny and Umesh Yadav.
english
package org.jeecg.modules.nuoze.nz.controller; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.baomidou.mybatisplus.core.conditions.Wrapper; import org.jeecg.common.api.vo.Result; import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.util.oConvertUtils; import org.jeecg.modules.nuoze.nz.entity.NzSourceInventory; import org.jeecg.modules.nuoze.nz.entity.NzSrcWarehouseIn; import org.jeecg.modules.nuoze.nz.service.INzSourceInventoryService; import org.jeecg.modules.nuoze.nz.service.INzSrcWarehouseInService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.def.NormalExcelConstants; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.poi.excel.view.JeecgEntityExcelView; import org.jeecg.common.system.base.controller.JeecgController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSON; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.jeecg.common.aspect.annotation.AutoLog; /** * @Description: 原药材出入库记录 * @Author: jeecg-boot * @Date: 2020-12-02 * @Version: V1.0 */ @Api(tags="原药材出入库记录") @RestController @RequestMapping("/nz/nzSrcWarehouseIn") @Slf4j public class NzSrcWarehouseInController extends JeecgController<NzSrcWarehouseIn, INzSrcWarehouseInService> { @Autowired private INzSrcWarehouseInService nzSrcWarehouseInService; @Autowired private INzSourceInventoryService srcInvuetoryService; /** * 分页列表查询 * * @param nzSrcWarehouseIn * @param pageNo * @param pageSize * @param req * @return */ @AutoLog(value = "原药材出入库记录-分页列表查询") @ApiOperation(value="原药材出入库记录-分页列表查询", notes="原药材出入库记录-分页列表查询") @GetMapping(value = "/list") public Result<?> queryPageList(NzSrcWarehouseIn nzSrcWarehouseIn, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) { QueryWrapper<NzSrcWarehouseIn> queryWrapper = QueryGenerator.initQueryWrapper(nzSrcWarehouseIn, req.getParameterMap()); Page<NzSrcWarehouseIn> page = new Page<NzSrcWarehouseIn>(pageNo, pageSize); IPage<NzSrcWarehouseIn> pageList = nzSrcWarehouseInService.page(page, queryWrapper); return Result.OK(pageList); } /** * 添加 * * @param nzSrcWarehouseIn * @return */ @AutoLog(value = "原药材出入库记录-添加") @ApiOperation(value="原药材出入库记录-添加", notes="原药材出入库记录-添加") @PostMapping(value = "/add") public Result<?> add(@RequestBody NzSrcWarehouseIn nzSrcWarehouseIn) { //异步处理库存信息 NzSourceInventory inventory = nzSrcWarehouseIn.wareHouseToInventory(); //库存有无此原药材库存信息 QueryWrapper<NzSourceInventory> wrapper = new QueryWrapper<>(); wrapper.eq("source_id",nzSrcWarehouseIn.getSourceIds()); List<NzSourceInventory> list = srcInvuetoryService.list(wrapper); //有此库存 if(list != null && list.size() > 0){ NzSourceInventory inventory1 = list.get(0); //0为出库,减少库存 if(0 == nzSrcWarehouseIn.getType()) { //出库数量大于库存 if(inventory1.getAmount() < nzSrcWarehouseIn.getAmount()){ return Result.error("库存不足!"); } inventory.setAmount(-inventory.getAmount()); } srcInvuetoryService.updateAmount(inventory); //无库存,且为入库 }else if(1 == nzSrcWarehouseIn.getType()){ srcInvuetoryService.save(inventory); //无库存时强行出库提示错误 }else { return Result.error("库存不足!"); } System.out.println("原药材入库数==="+nzSrcWarehouseIn.getAmount()); nzSrcWarehouseInService.save(nzSrcWarehouseIn); return Result.OK("添加成功!"); } /** * 编辑 * * @param nzSrcWarehouseIn * @return */ @AutoLog(value = "原药材出入库记录-编辑") @ApiOperation(value="原药材出入库记录-编辑", notes="原药材出入库记录-编辑") @PutMapping(value = "/edit") public Result<?> edit(@RequestBody NzSrcWarehouseIn nzSrcWarehouseIn) { nzSrcWarehouseInService.updateById(nzSrcWarehouseIn); return Result.OK("编辑成功!"); } /** * 通过id删除 * * @param id * @return */ @AutoLog(value = "原药材出入库记录-通过id删除") @ApiOperation(value="原药材出入库记录-通过id删除", notes="原药材出入库记录-通过id删除") @DeleteMapping(value = "/delete") public Result<?> delete(@RequestParam(name="id",required=true) String id) { nzSrcWarehouseInService.removeById(id); return Result.OK("删除成功!"); } /** * 批量删除 * * @param ids * @return */ @AutoLog(value = "原药材出入库记录-批量删除") @ApiOperation(value="原药材出入库记录-批量删除", notes="原药材出入库记录-批量删除") @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) { this.nzSrcWarehouseInService.removeByIds(Arrays.asList(ids.split(","))); return Result.OK("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ @AutoLog(value = "原药材出入库记录-通过id查询") @ApiOperation(value="原药材出入库记录-通过id查询", notes="原药材出入库记录-通过id查询") @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name="id",required=true) String id) { NzSrcWarehouseIn nzSrcWarehouseIn = nzSrcWarehouseInService.getById(id); if(nzSrcWarehouseIn==null) { return Result.error("未找到对应数据"); } return Result.OK(nzSrcWarehouseIn); } /** * 导出excel * * @param request * @param nzSrcWarehouseIn */ @RequestMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, NzSrcWarehouseIn nzSrcWarehouseIn) { return super.exportXls(request, nzSrcWarehouseIn, NzSrcWarehouseIn.class, "原药材出入库记录"); } /** * 通过excel导入数据 * * @param request * @param response * @return */ @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, NzSrcWarehouseIn.class); } }
java
--- layout: post title: Raspi date: '2021-07-02 00:00:00 +00:00' tags: - raspberry-pi excerpt: Non-interactive mode for raspi-config notion_id: af64b57408cb4f2a93bd92a1076e92cd --- <main class="notion light-mode notion-page"> <div class="notion-viewport"></div> <div class="notion-text"><b>Non-interactive mode for </b><b><code class="notion-inline-code">raspi-config</code></b></div> <pre class="notion-code"><code class="language-Bash"># set timezone and localization raspi-config nonint do_change_timezone Asia/Jakarta raspi-config nonint do_change_locale en_US.UTF-8 # enable vnc raspi-config nonint do_vnc 0 # change resolution # DMT Mode 16 1024x768 60Hz 4:3 raspi-config nonint do_resolution 2 16</code></pre> <div class="notion-blank"> </div> <div class="notion-text">For the complete &quot;documentation&quot;, we have to dig in <a target="_blank" rel="noopener noreferrer" class="notion-link" href="https://github.com/RPi-Distro/raspi-config/blob/master/raspi-config">its source code</a>.</div> <div class="notion-blank"> </div> <div class="notion-text">This enables <a target="_blank" rel="noopener noreferrer" class="notion-link" href="https://gist.github.com/azaky/a1c65aea1f6eac5271f093bcdc36ec3a">completely automated first time setup</a>.</div> <div class="notion-blank"> </div> <div class="notion-text"><b>Remove welcome message</b></div> <pre class="notion-code"><code class="language-Bash">sudo rm /etc/xdg/autostart/piwiz.desktop</code></pre> <div class="notion-blank"> </div> <div class="notion-text"><b>Remove default password warning</b></div> <pre class="notion-code"><code class="language-Bash">sudo rm /etc/xdg/lxsession/LXDE-pi/sshpwd.sh sudo rm /etc/profile.d/sshpwd.sh</code></pre> <div class="notion-blank"> </div> <div class="notion-text"><b>Monitoring temperature</b></div> <pre class="notion-code"><code class="language-Bash">vcgencmd measure_temp</code></pre> <div class="notion-blank"> </div> </main>
html
extern crate libc; use crate::bindings; pub fn button(name: &str) -> bool { unsafe { let c_string = std::ffi::CString::new(name).unwrap(); return bindings::c_generate_imgui_button(c_string.as_ptr()); } } pub fn slider_int(name: &str, val: *mut i32, min: i32, max: i32) { unsafe { let c_string = std::ffi::CString::new(name).unwrap(); bindings::c_generate_imgui_slider_int( c_string.as_ptr(), val as *mut libc::c_int, min as libc::c_int, max as libc::c_int, ); } }
rust
<gh_stars>0 { "author": { "id": "t2_b5c4den", "name": "7Legionarmy" }, "date": { "day": 1547596800, "full": 1547676263, "month": 1546300800, "week": 1547337600 }, "id": "t3_agqg2v", "misc": { "postHint": "image" }, "picture": { "filesize": 70508, "fullUrl": "https://preview.redd.it/02dooz6lyua21.jpg?auto=webp&s=5394e2a6557799c87b3066607f45f092e9d5cb56", "hash": "1f8bb07935", "height": 480, "lqip": "data:image/jpg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAMABADASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAABwMF/8QAJBAAAQMDBAEFAAAAAAAAAAAAAQIDBAAFEQYSEyEiMTNBUXH/xAAUAQEAAAAAAAAAAAAAAAAAAAAE/8QAGREAAgMBAAAAAAAAAAAAAAAAAAECERIx/9oADAMBAAIRAxEAPwA0eu8yXZYkVMpLjDR6QqKlBb+kpcHZ6/Kk4209BbbLGzaTzPbirlyfVKPggVv2e6vzLtG0tIbjLtSC6r2UhwlKTjKwM0kRND2Z/SkaUpt4PLg8hKXMeRGc0JPQiVrh/9k=", "thumbnailUrl": "https://a.thumbs.redditmedia.com/vcLvgGUzgGiKLRabYsoTgyS58xLfYBZOQwhSJ4kcmu4.jpg", "url": "https://preview.redd.it/02dooz6lyua21.jpg?width=640&crop=smart&auto=webp&s=2825b44d3715c5ebf5ee6317889e3a8ec7f329e0", "width": 640 }, "score": { "comments": 17, "downs": 0, "isCurated": false, "ratio": 0.98, "ups": 170, "value": 170 }, "subreddit": { "id": "t5_3isai", "name": "dndmaps" }, "tags": [], "title": "How the Mighty Have Fallen", "url": "https://www.reddit.com/r/dndmaps/comments/agqg2v/how_the_mighty_have_fallen/" }
json
NEET 2019: The National Eligibility-cum-Entrance Test (NEET-UG) 2019 is scheduled to be held on Sunday, May 5, 2019, the online application process of which has been extended till December 7. The registration process was scheduled to be closed on November 30, but it has been extended following the Supreme Court’s order. All the candidates who want to apply can do so through the official website, ntaneet. nic. in. The last date of fee submission is December 8. 7. s-Block Elements (Alkali and Alkaline Earth Metals) 10. Ecology and environment. The NEET is a three-hour long exam which includes three sections – physics, chemistry and biology. Of the total 180 questions, 90 would be from biology and 45 each from physics and chemistry. Preparation syllabus includes the whole of Class 11 and 12 standard NCERT textbooks in the respective subjects. Every correct answer would fetch you plus four marks and every incorrect answer results in a negative mark. Questions that are not attempted do not have any penalty marks. So, choose your battles wisely, if you do not know a question for sure, do not mark it.
english
<reponame>Julboteroc/cannabis {"featureCount":1,"formatVersion":1,"histograms":{"meta":[{"arrayParams":{"chunkSize":10000,"length":1,"urlTemplate":"hist-20000-{Chunk}.json"},"basesPerBin":"20000"}],"stats":[{"basesPerBin":"20000","max":1,"mean":1}]},"intervals":{"classes":[{"attributes":["Start","End","Strand","Id","Name","Seq_id","Source","Subfeatures","Type"],"isArrayAttr":{"Subfeatures":1}},{"attributes":["Start","End","Strand","Coverage","Id","Identity","Indels","Matches","Mismatches","Name","Seq_id","Source","Subfeatures","Type","Unknowns"],"isArrayAttr":{"Subfeatures":1}},{"attributes":["Start","End","Strand","Id","Name","Score","Seq_id","Source","Target","Type"],"isArrayAttr":{}},{"attributes":["Start","End","Strand","Id","Name","Phase","Score","Seq_id","Source","Target","Type"],"isArrayAttr":{}},{"attributes":["Start","End","Strand","Seq_id"],"isArrayAttr":{}},{"attributes":["Start","End","Strand","Id","Name","Score","Seq_id","Source","Type"],"isArrayAttr":{}},{"attributes":["Start","End","Chunk"],"isArrayAttr":{"Sublist":1}}],"count":1,"lazyClass":6,"maxEnd":4564,"minStart":4077,"nclist":[[0,4077,4564,-1,"tig00011785.g114.t1.path1","tig00011785.g114.t1","tig00011785_overlapping_hits_sub_region","cannabis_loc_scaffold",[[1,4077,4564,-1,"100.0","tig00011785.g114.t1.mrna1","100.0","0","366","0","tig00011785.g114.t1","tig00011785_overlapping_hits_sub_region","cannabis_loc_scaffold",[[2,4485,4564,-1,"tig00011785.g114.t1.mrna1.exon1","tig00011785.g114.t1",100,"tig00011785_overlapping_hits_sub_region","cannabis_loc_scaffold","tig00011785.g114.t1 1 79 +","exon"],[2,4077,4364,-1,"tig00011785.g114.t1.mrna1.exon2","tig00011785.g114.t1",100,"tig00011785_overlapping_hits_sub_region","cannabis_loc_scaffold","tig00011785.g114.t1 80 366 +","exon"],[3,4485,4564,-1,"tig00011785.g114.t1.mrna1.cds1","tig00011785.g114.t1",0,100,"tig00011785_overlapping_hits_sub_region","cannabis_loc_scaffold","tig00011785.g114.t1 1 79 +","CDS"],[3,4077,4364,-1,"tig00011785.g114.t1.mrna1.cds2","tig00011785.g114.t1",1,100,"tig00011785_overlapping_hits_sub_region","cannabis_loc_scaffold","tig00011785.g114.t1 80 366 +","CDS"]],"mRNA","0"]],"gene"]],"urlTemplate":"lf-{Chunk}.json"}}
json
{ "command_queue": { "title": "", "attack": "Atak", "support": "Wsparcie", "relocate": "przenieś", "sent": "wysłany/e", "activated": "włączony", "deactivated": "wyłączony", "expired": "przedawniony/e", "removed": "usunięty/e", "added": "dodany/e", "general_clear": "", "general_next_command": "Następny rozkaz", "add_basics": "Podstawowe informacje", "add_origin": "Źródło", "add_selected": "Aktywna wioska", "add_target": "Cel", "add_map_selected": "Wybrana wioska na mapie", "date_type_arrive": "", "date_type_out": "", "add_current_date": "Obecny czas", "add_current_date_plus": "Zwiększ czas o 100 milisekund.", "add_current_date_minus": "Zmniejsz czas o 100 milisekund.", "add_travel_times": "Czas podróży jednostek", "add_date": "Czas/Data", "add_no_village": "Wybierz wioskę...", "add_village_search": "Znajdź wioskę...", "add_clear": "wyczyść", "add_insert_preset": "Wybierz szablon", "queue_waiting": "Rozkazy", "queue_none_added": "Brak dodanych rozkazów.", "queue_sent": "Rozkazy wysłane", "queue_none_sent": "Brak wysłanych rozkazów.", "queue_expired": "Przedawnione rozkazy", "queue_none_expired": "Brak przedawnionych rozkazów.", "queue_remove": "Usuń rozkaz z listy", "queue_filters": "Filtruj rozkazy", "filters_selected_village": "Pokaż tylko rozkazy z aktywnej wioski", "filters_barbarian_target": "Pokaż tylko rozkazy na wioski barbarzyńskie", "filters_attack": "Pokaż ataki", "filters_support": "Pokaż wsparcia", "filters_relocate": "Pokaż przeniesienia", "filters_text_match": "Filtruj za pomocą tekstu...", "command_out": "Czas wyjścia", "command_time_left": "Pozostały czas", "command_arrive": "Czas dotarcia", "error_no_units_enough": "", "error_not_own_village": "Wioska źródłowa nie należy do ciebie!", "error_origin": "Nieprawidłowa wioska źródłowa!", "error_target": "Nieprawidłowa wioska cel!", "error_no_units": "Nie wybrano jednostek!", "error_invalid_date": "Nieprawidłowy Czas", "error_already_sent_attack": "", "error_already_sent_support": "", "error_already_sent_relocate": "", "error_relocate_disabled": "", "error_no_map_selected_village": "Nie zaznaczono wioski na mapie.", "error_remove_error": "Błąd usuwania rozkazu.", "tab_add": "Dodaj rozkaz", "tab_waiting": "Oczekujące", "tab_logs": "Logi" } }
json
<filename>public/static/js/table.js function tableRender(config) { //第一个实例 layui.use('table', function () { let table = layui.table table.render({ height: 600 , page: true //开启分页 ,limits:[10,25,50,100,1000] , parseData: function (res) { //res 即为原始返回的数据 res = res.data return { "code": 0, //解析接口状态 "msg": res.msg, //解析提示文本 "count": res.total, //解析数据长度 "data": res.data //解析数据列表 }; }, ...config }); }) }
javascript
Naseem Shah to Gurbaz, SIX, oh my word! Gurbaz advances and smashes this out of the stadium! A length ball around middle from Naseem and it's treated with absolute disdain as Gurbaz swings powerfully down the ground. Wow! Naseem Shah to Gurbaz, no run, back of a length delivery just outside off, Gurbaz looks to punch it away but there's late movement for Naseem and it beats the outside edge!
english
<gh_stars>1-10 {"2010":"","2016":"","Department":"Апеляційний суд Дніпропетровської області","Region":"Дніпропетровська область","Position":"Суддя Апеляційного суду Дніпропетровської області м. Дніпропетровськ","Name":"<NAME>","Link":"http://dpa.court.gov.ua/sud0490/lkdfgjdljfghidgr/declar2014/declar2014_chernenkova/","Note":"","AdditionalNote":"","декларації 2015":"","Youtube":"","ПІБ2":"","Кількість справ":"","Оскаржені":"","Кількість скарг":"5","Кількість дисциплінарних стягнень":"","Клейма":"3","Фото":"http://picua.org/img/2016-09/23/lnyxc8l084f9pdkcbelkuz8t0.jpg","Як живе":"","Декларація доброчесності судді подано у 2016 році (вперше)":"","Декларація родинних зв’язків судді подано у 2016 році":"","key":"chernenkova_lyudmila_andriyivna","field8":"","Link 2015":"","field9":"","Декларації 2013":"","Декларації 2014":"","Декларації 2015":"","Декларації 2016":"","type":"judge","analytics":[{"y":2013,"i":265271,"k":10,"ka":1},{"y":2014,"i":282390,"k":10,"ka":1},{"y":2015,"i":250201,"ff":30,"ffa":1,"j":5},{"y":2016,"i":297776},{"y":2017,"i":303978}],"declarationsLinks":[{"id":"vulyk_71_156","year":2013,"url":"http://static.declarations.com.ua/declarations/chosen_ones/judges_batch/446_chernenkova_liudmyla_andriivna.pdf","provider":"declarations.com.ua.opendata"},{"id":"vulyk_41_170","year":2014,"url":"http://static.declarations.com.ua/declarations/chosen_ones/mega_batch/chernenkova_liudmyla_andriivna.pdf","provider":"declarations.com.ua.opendata"},{"id":"nacp_ed71365f-9ba9-4022-8ff9-c6d5bdd8ca4b","year":2015,"provider":"declarations.com.ua.opendata"},{"id":"nacp_4a8b209a-b297-4ad4-b955-9b91a2ed5cd4","year":2016,"provider":"declarations.com.ua.opendata"},{"id":"nacp_a8aed75b-5dc0-4b06-9904-b7d35f37dd90","year":2017,"provider":"declarations.com.ua.opendata"}]}
json
<gh_stars>1-10 { "parent": "block/cube_all", "textures": { "all": "glimmering:block/andesite_capstone_active" } }
json
, Created solutions with brand price. We attend seriously to produce and behave with integrity, and because of the favor of clients in your own home and overseas in the xxx industry. FXO8 LED screen – Radiant Detail: 1.High-definition, high-brightness, bright colors, clear subject, novel design, vivid image, simple and bright, can complete the simultaneous broadcast of graphic images. 3.Small screen, strong penetration of transmission, wide coverage of network, direct access to consumer terminals, low investment and quick results, good publicity effect. 4.Homemade programs, instant playback, rich content; Product detail pictures: Related Product Guide: , During in 11 years, We've participated in more than 20 exhibitions, obtains the highest praise from each customer. Our company has been devoting that "customer first" and committed to helping customers expand their business, so that they become the Big Boss !
english
<filename>aim/web/ui/src/utils/app/onDensityTypeChange.ts import { DensityOptions } from 'config/enums/densityEnum'; import * as analytics from 'services/analytics'; import { IModel, State } from 'types/services/models/model'; export default async function onDensityTypeChange<M extends State>({ type, model, appName, getMetricsData, }: { type: DensityOptions; model: IModel<M>; appName: string; getMetricsData: (shouldUrlUpdate?: boolean) => { call: () => Promise<void>; abort: () => void; }; }): Promise<void> { const modelState = model.getState(); let configData = modelState?.config; if (configData?.chart) { configData = { ...configData, chart: { ...configData.chart, densityType: type, }, }; model.setState({ config: configData }); } getMetricsData(true).call(); analytics.trackEvent( `[${appName}Explorer][Chart] Set point density to "${DensityOptions[ type ].toLowerCase()}"`, ); }
typescript
A corruption case hanging over her could be a disincentive for BSP chief Mayawati to take a clear-cut political position against the BJP at this point in time. Lalu Prasad’s ambition of cobbling together a fresh coalition of Opposition parties to take on the BJP appears to be faltering, with Bahujan Samaj Party (BSP) chief Mayawati ambivalent on participating at the Rashtriya Janata Dal’s (RJD) rally in Patna on August 27. Struck by the blow of the collapse of the “Mahagathbandhan” (Grand Alliance) government in Bihar, Prasad had been looking ahead to Patna rally as an opportunity to stitch together an alternative alliance by bringing together Uttar Pradesh’s arch political rivals – Samajwadi Party’s Akhilesh Yadav and BSP chief Mayawati – on the same platform. If Mayawati indeed skips the Patna rally, it will take the sting out of the Opposition moves to rustle up an effective political front against the BJP. “At this juncture, when the 2019 general elections are far away, the BSP gains nothing by attending such rallies. However, it is up our party chief to decide whether or not to attend – or whether to send an emissary,” a senior BSP leader told HT. Some sections in the BSP feel that party’s interests would be better served through a strategy aimed at consolidating the traditional vote banks in UP, while it is not time yet party to get into the election mode. The BSP chief – who has done business with both the BJP and the SP in the past – is known to keep her cards close to her chest. Also, a pending Central Bureau of Investigation (CBI) case against her being seen as a disincentive for her to take a clear-cut political position at this point in time. While Prasad is himself on the “wait and watch” list of the Opposition camp on account of the uncertainties concerning his political future, regional party leaders – the Mayawati camp in particular – appear guarded about the outcome of the Patna conclave.
english
The Season 3 Reloaded Patch of Warzone 2 has quite a few overpowered loadouts to offer. There are a few weapons in the armory that boast a substantially faster TTK than the others in its category. Guns like the Cronen Squall, RAAL MG, Lachmann Sub, and STB 556 can quickly mow down the opposition with their exceptional damage output. However, alongside them, there is another gun platform in Warzone 2 Season 3 Reloaded, which possesses a very fast TTK. The latest patch has left this gun untouched and it still has the potential to two-shot its opponents, even if they are fully plated. The EBR-14 Marksman Rifle in Warzone 2 is based on the real-life Mk14 Enhanced Battle Rifle of the American Armed Forces and is one of the weapons in the Ordinance platform of the title's new gunsmith system. The Season 2 patch introduced some interesting changes to this powerful weapon platform. Although the long-range damage received a small nerf, it was balanced with a buffed damage registration on the upper torso. In Season 3 Reloaded this gun registers a 126-point damage against every hit on the head, and skilled players with good aim and trigger discipline will be able to knock or eliminate their opponents in just two quick headshots. Being a semi-auto rifle, veteran players will have a lot of fun two-tapping their opponents with the EBR-14 on Ashika Island. The only downside of the weapon is the usage of sniper bullets as ammunition. As such, players need to keep a lookout for this low-spawn-rate bullet or at least keep a munition box handy in case of emergencies. In order to get the best loadout of this firearm in Season 3 Reloaded, players will have to equip it with the following attachments: The Polarfire-S suppressor plays an important role in this loadout as it improves upon the damage range, bullet velocity, and recoil smoothness of the weapon. Alongside that, it also muzzles the sound produced when this gun is fired, keeping the operators from being pinged on the tacmap and compass. The VLK 4. 0 Optic is an excellent mid-to-long-range scope for this marksman rifle. Not only does it have very minimal scope glint, it also provides players with a very clean, magnified view of the downrange. The FTAC Ripper 56 underbarrel boosts both the aiming idle stability and recoil stabilization of the firearm. This attachment will ensure that the gun remains stable while both aiming and firing the weapon. Alongside that, it also brings in some added hip-fire accuracy, which will help in situations where the enemies get close and the operator doesn't have the chance to swap to the secondary gun. The 7. 62 High-Velocity bullets buff the already high muzzle velocity by a significant margin. This attachment will ease long-range gunfights for the players as they won't have to take too much of a lead while aiming for mobile targets at far-off ranges. The default configuration of the gun only comes with 10 bullets, which gets used up quite quickly due to the semi-auto nature of the gun. As such, the 20 Round Mag is necessary to avoid having to reload multiple times in a high-octane gunfight. This is the best loadout for the EBR-14 Markman Rifle in Season 2 of Warzone 2.
english
<filename>DishDash/pages/text_photo_parser.py # Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State # Imports from this application from app import app # 2 column layout. 1st column width = 4/12 # https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout column1 = dbc.Col( [ dcc.Markdown( """ ## Feed us a photo of a recipe, handwritten or screenshot! > Upload a picture of the ingredients and/or the instructions of a recipe you like (from a cookbook or even handwritten notes) and the content will be saved automatically to your cookbook. This works for several languages. Especially well for Spanish, French and English.\n """ ), dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select a File') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'text-align': 'center', 'margin': '10px' } ), dcc.Markdown( """ [Try This Sample Photo!](/assets/ingredients2.png) """ ), html.Hr(), html.Div(id='output-data-upload'), dcc.Link(dbc.Button('Go To Name A Dish!', color='primary'), href='/ingred_parser') ], style={ 'text-align': 'center' }, md=12, ) column2 = dbc.Col( [ ] ) layout = dbc.Row([column1, column2])
python
<gh_stars>1-10 from matplotlib import pyplot as plt import random from solver import Solver import json import time def visualize(point_locations, sensor_locations, sensor_radius): plt.grid() for i in sensor_locations: circle1 = plt.Circle((i[0], i[1]), sensor_radius, color='y') plt.gcf().gca().add_artist(circle1) for i in point_locations: plt.plot(i[0], i[1], marker='s',color='b') plt.show() def plot_coverage_comparison(num_points, bip_coverage, heuristic_coverage): plt.plot(bip_coverage, marker="o") plt.plot(heuristic_coverage, marker="o") plt.xticks(range(len(num_points)), num_points) plt.xlabel("Number of Points") plt.ylabel("Coverage") plt.legend(['BIP', 'Greedy'], loc='best') plt.grid() plt.show() def plot_runtime_comparison(num_points, bip_runtime, heuristic_runtime): plt.plot(bip_runtime, marker="o") plt.plot(heuristic_runtime, marker="o") plt.xticks(range(len(num_points)), num_points) plt.xlabel("Number of Points") plt.ylabel("Runtime (seconds)") plt.legend(['BIP', 'Greedy'], loc='best') plt.grid() plt.show() def write_test_files(filename, M, budget, sensor_cost, sensor_radius, locations): test_data = {} test_data['M'] = M test_data['budget'] = budget test_data['sensor_cost'] = sensor_cost test_data['sensor_radius'] = sensor_radius test_data['locations'] = [] for i in range(len(locations)): loc = [locations[i][0], locations[i][1]] test_data['locations'].append(loc) with open("tests/" + filename + ".json", 'w+') as f: json.dump(test_data, f) def create_test_folder(): import os if not os.path.exists('tests'): os.makedirs('tests') def generate_tests(): create_test_folder() sensor_radius = 8 sensor_cost = 8 num_instances = 25 M = 100 for i in range(num_instances): num_points = 150 * (i + 1) budget = random.randint(M, M * 5) locations = [] for k in range(num_points): x = random.randint(0, M - 1) y = random.randint(0, M - 1) locations.append((x, y)) write_test_files("test_" + str(i), M, budget, sensor_cost, sensor_radius, locations) def run_all_tests(): len_locs = [] bip_coverages = [] heuristic_coverages = [] # ratio bip_runtimes = [] # seconds heuristic_runtimes = [] # seconds for i in range(24): filepath = "tests/test_" + str(i) + ".json" with open(filepath) as f: test_data = json.load(f) M = test_data['M'] budget = test_data['budget'] sensor_cost = test_data['sensor_cost'] sensor_radius = test_data['sensor_radius'] locations = [] for loc in test_data['locations']: locations.append( (loc[0], loc[1] )) s = Solver(M, sensor_radius, sensor_cost, budget, locations) start_time = time.time() BIP_solution, BIP_covered = s.solve() end_time = time.time() bip_runtimes.append(end_time - start_time) start_time = time.time() heuristic_solution, heuristic_covered = s.heuristic_solve() end_time = time.time() heuristic_runtimes.append(end_time - start_time) print("----------------------------") print("BIP coverage: {}, number of sensors used: {}".format(BIP_covered/len(locations), len(BIP_solution))) print("Heuristic coverage: {}, number of sensors used: {}".format(heuristic_covered/len(locations), len(heuristic_solution))) print("----------------------------") len_locs.append(len(locations)) bip_coverages.append(BIP_covered / len(locations)) heuristic_coverages.append(heuristic_covered/ len(locations)) #visualize(locations, BIP_solution, sensor_radius) #visualize(locations, heuristic_solution, sensor_radius) """ print(len_locs) print(bip_coverages) print(heuristic_coverages) print(bip_runtimes) print(heuristic_runtimes) """ plot_coverage_comparison(len_locs, bip_coverages, heuristic_coverages) plot_runtime_comparison(len_locs, bip_runtimes, heuristic_runtimes)
python
<reponame>kangjunseo/GraphQL<filename>tutorial/client.py from gql import Client from gql.transport.requests import RequestsHTTPTransport transport = RequestsHTTPTransport(url='http://localhost:8080/v1/graphql') client = Client(transport=transport, fetch_schema_from_transport=True)
python
<filename>remote-content-api/unused-for-now/sample-http-api/src/main/resources/SLING-INF/initial-content/content/articles/travel/zackery-von-on-the-sensor-of-mobile-dolores-et-aka-sas.json {"source":"Apache Sling's fake-content-generator","section":"Travel","folder":"travel","filename":"zackery-von-on-the-sensor-of-mobile-dolores-et-aka-sas","title":"Travel - Zackery Von on the sensor of mobile 'dolores et' (aka SAS)","tags":["array"],"seeAlso":["solon-davis-on-the-card-of-primary-reiciendis-omnis-aka-sql","fermin-bernhard-on-the-capacitor-of-mobile-rerum-aliquid-aka-adp","belle-jacobi-on-the-feed-of-online-vel-aut-aka-ai","ryder-kemmer-on-the-bandwidth-of-virtual-blanditiis-qui-aka-xml","alicia-yundt-on-the-feed-of-digital-culpa-ipsa-aka-usb"],"text":"As Zackery Von often says, Quia fugiat quo minus nisi. Non magnam quibusdam. Tempora nam velit voluptatem impedit laboriosam beatae adipisci. Fugit tempore veniam velit distinctio. Non accusantium provident voluptates quia repellendus.<br/>\nSit adipisci amet vero consectetur delectus ducimus laborum. Atque rerum non id. Eos voluptas omnis et dolorem non perferendis non incidunt est.<br/>\nSunt sed magnam dolores qui facere enim. Nobis consequatur dolorem autem aut vitae. Qui doloribus aut commodi aut facere. Fugit quia accusamus ab est illum nulla magnam nemo quae. At expedita odio aut molestias consequatur vero laborum. Consequatur rerum nihil corporis consequatur dicta dicta architecto temporibus eum.<br/>\nVoluptas nulla ut. Dicta labore error fuga voluptas quibusdam perferendis et provident adipisci. Culpa recusandae aut sed. Omnis et et et consequuntur voluptate et qui sit. Repellendus et aut repudiandae. Consequatur officiis omnis ut natus sit quod.<br/>\nMolestiae molestiae fuga velit pariatur. Veniam harum aut distinctio sed iure optio velit quasi quis. In dicta aspernatur omnis doloribus in quaerat cupiditate. Autem ut tenetur accusantium doloribus eum praesentium hic praesentium quo. Rerum nesciunt possimus vel fugit repellat quis voluptates.","jcr:primaryType":"nt:unstructured","sling:resourceType":"samples/article/travel","sling:resourceSuperType":"samples/article"}
json
<reponame>omajid/cssparser /* reset - blueprint mod */ * {padding: 0; margin: 0;} html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {margin: 0;padding: 0;border: 0;font-weight: inherit;font-style: inherit;font-size: 100%;font-family: inherit;vertical-align: baseline;} body {line-height: 1.5;} /* Tables still need 'cellspacing="0"' in the markup. */ table { border-collapse: separate; border-spacing: 0; } caption, th, td { text-align: left; font-weight: normal; } table, td, th { vertical-align:top; } /* Remove possible quote marks (") from <q>, <blockquote>. */ blockquote:before, blockquote:after, q:before, q:after { content: ""; } blockquote, q { quotes: "" ""; } /* Remove annoying border on linked images. */ a img { border: none; } /* utility */ /* lists */ /*.red-bullet li{list-style: none; background: transparent url(../resources/irb/red_bull.gif) no-repeat 0 7px; padding-left: 8px;}*/ .vanilla-inline li{display: inline; list-style: none;} .block-inline li{display: block; float: left;} .assignments li, .vanilla-rows li{font-size: 12px; font-weight: bold; list-style: none; border-top:1px solid #e4e4e4; padding: 10px 0;} /* floats */ .util-left{float: left; display: inline;} .util-right{float: right; display: inline;} .util-clear{clear: both;} /* no's*/ .no-border{border: 0 !important;} .no-margin{margin: 0 !important;} .no-bg{background: none !important;} .no-pad-left{padding-left: 0 !important;} .no-pad-right{padding-right: 0 !important;} /* clearfix */ /* hr*/ hr {margin: 0; padding: 0; height: 0px; width: 100%; clear: both; border-top: 1px solid #e4e4e4; overflow: hidden;} div.hr{overflow: hidden; width: 100%; height:0; margin: 0; padding: 0; border-top: 1px solid #e4e4e4; clear: both;} /* general typography */ body{font-family: Arial, Helvetica, Utkal, sans-serif; font-size: 12px; color: #000; background: #fafafa; } h1,h2,h3,h4,h5, h6{margin:0px;padding:0px;} a{text-decoration: none;} a:link, a:visited{color: #004276; outline: none;} a:hover{color: #ca0002;} a:focus{outline:none;} /*body { background-color:#FAFAFA;margin:0px;font:normal 12px/15px arial; } form { margin:0px; } h1, h2, h3, h4, h5, h6 { margin:0px;padding:0px; }*/ .cnn_clear { height:1px;overflow:hidden;clear:both; } .cnn_pad1top { padding:1px 0 0 0; } .cnn_pad2top { padding:2px 0 0 0; } .cnn_pad3top { padding:3px 0 0 0; } .cnn_pad5top { padding:5px 0 0 0; } .cnn_pad6top { padding:6px 0 0 0; } .cnn_pad7top { padding:7px 0 0 0; } .cnn_pad8top { padding:8px 0 0 0; } .cnn_pad9top { padding:9px 0 0 0; } .cnn_pad10top { padding:10px 0 0 0; } .cnn_pad11top { padding:11px 0 0 0; } .cnn_pad12top { padding:12px 0 0 0; } .cnn_pad15top { padding:15px 0 0 0; } .cnn_pad18top { padding:18px 0 0 0; } .cnn_pad20top { padding:20px 0 0 0; } .cnn_shdspc { background-color:#FAFAFA; } /* hdr ftr */ #cnn_hdr, #cnn_ftr, #cnn_hdr-main{margin: 0 auto; width: auto; text-align:center;min-width: 1002px; line-height: 12px;} #cnn_hdr{background: #ca0002;} /* gen purpose width constriction */ .hdr-wrap{margin: 0 auto; width: 980px; position: relative;} #cnn_hdr h1 span{display: block; _display: none; text-indent: -9999px; height: 0; width: 0;} #cnn_hdr-prompt{background: #091c3b; font-size: 10px; line-height: 12px; font-weight: bold; height: 30px; padding: 0 10px;} #cnn_hdr-prompt a{color: #fff;} #hdr-prompt-text{position:absolute; top: 7px; left: 0;} #hdr-prompt-text #hdr-arrow-us, #hdr-prompt-text #hdr-arrow-intl{position: absolute; top: 14px; right: 93px;} #hdr-prompt-text #hdr-arrow-intl{right: -1px;} #hdr-prompt-close{position:absolute; top: 7px; right: 0;} #cnn_hdr-main{height: 84px; background: #ca0002; _padding: 0 10px;} #hdr-editions{position: absolute; top: 0; left: 0;} #hdr-auth{position: absolute; top: 0; right: 0;} #hdr-editions li, #hdr-auth li{font-size: 10px; font-weight: bold; display: block; float: left; height: 20px; border-right: 1px solid #f99; padding: 0 9px; color: #f99;} #hdr-editions a, #hdr-auth a, #hdr-prompt a{color: #fff;} #hdr-editions a, #hdr-auth a, #hdr-editions span, #hdr-auth span{position: relative; top: 7px;} #hdr-search{position: absolute; right:0; top: 31px;} #ftr-search{float: right; margin-top:14px; } .cnn_ftrggle { text-align:right;padding:1px 0 0 0; } #hdr-search #hdr-search-box, #ftr-search #ftr-search-box{font-weight: bold; font-size: 10px !important; color: #666; border: 0; border-top: 2px solid #ccc; border-left: 1px solid #ccc; width: 187px; height: 16px; padding: 2px 20px 1px 7px;} #hdr-search form{background: url(http://i.cdn.turner.com/cnn/.element/img/3.0/global/header/hdr-search-google.gif) bottom right no-repeat; padding-bottom: 21px;} #ftr-search form{ width: 216px;} #hdr-search-mag, #ftr-search-mag{outline: none; border: 0; position: absolute; top: 6px; right: 3px; width: 13px; height: 12px;} #ftr-search-mag{top: 22px; right: 4px;} #hdr-search .hdr-search-on, #ftr-search .ftr-search-on{color: #000 !important;} #cnn_hdr #cnn_hdr-nav{border-bottom: 6px solid #dfdfdf; display: block; height: 35px; background: #b60002 url(http://i.cdn.turner.com/cnn/.element/img/3.0/global/header/bg-nav.gif) center; padding: 0 10px;} #cnn_hdr #us-menu, #cnn_hdr #intl-menu{display:block; margin:0 auto; width: 980px; height: 35px; border-left: 1px solid #b60002;} #us-menu li, #intl-menu li{display: block; float: left; height: 35px; background: #900; border-right: 1px solid #ca0002;} #us-menu li a, #intl-menu li a{overflow: hidden; background: #b60002 url(http://i.cdn.turner.com/cnn/.element/img/3.0/global/header/bg-nav.gif) center; line-height: 35px; border-right: 1px solid #900; color: #fff; font-weight: bold; display: block; _display: inline-block; text-decoration: none !important; height: 35px;} #us-menu li a:hover, #intl-menu li a:hover{background: #900;} #us-menu .nav-media, #intl-menu .nav-media{background: #b60002 url(http://i.cdn.turner.com/cnn/.element/img/3.0/global/header/bg-nav.gif) bottom left;} #us-menu .nav-on, #us-menu .nav-on:hover, #intl-menu .nav-on, #intl-menu .nav-on:hover{background: #fff url(http://i.cdn.turner.com/cnn/.element/img/3.0/global/header/bg-nav.gif) top; color: #ca0002;} #us-menu #nav-newspulse, #us-menu #nav-money, #us-menu #nav-sports{position: relative;} #us-menu #nav-money span, #us-menu #nav-sports span{position: relative; left: -3px;} #us-menu #nav-home{width: 55px;} #us-menu #nav-video{width:67px;} #us-menu #nav-newspulse{width:98px;} #us-menu #nav-newspulse img{position: absolute; top: 0; right: 5px;} #us-menu #nav-us{width: 37px;} #us-menu #nav-world{width: 50px;} #us-menu #nav-politics{width: 58px;} #us-menu #nav-justice{width: 58px;} #us-menu #nav-entertainment{width: 97px;} #us-menu #nav-tech{width: 42px;} #us-menu #nav-health{width: 53px;} #us-menu #nav-living{width: 50px;} #us-menu #nav-travel{width: 50px;} #us-menu #nav-opinion{width: 61px;} #us-menu #nav-ireport{width: 58px;} #us-menu #nav-money{width: 59px;} #us-menu #nav-money img{position: absolute; top: 16px; right: 8px;} #us-menu #nav-sports{width: 60px;} #us-menu #nav-sports img{position: absolute; top: 16px; right: 7px;} #intl-menu #nav-home{width: 52px;} #intl-menu #nav-video{width: 50px;} #intl-menu #nav-world{width: 54px;} #intl-menu #nav-africa{width: 54px;} #intl-menu #nav-asia{width: 43px;} #intl-menu #nav-europe{width: 58px;} #intl-menu #nav-latin-america{width: 96px;} #intl-menu #nav-middle-east{width: 84px;} #intl-menu #nav-us{width: 40px;} #intl-menu #nav-business{width: 73px;} #intl-menu #nav-world-sport{width: 89px;} #intl-menu #nav-entertainment{width: 100px;} #intl-menu #nav-tech{width: 45px;} #intl-menu #nav-travel{width: 53px;} #intl-menu #nav-ireport{width: 60px;} #cnn_ftrcntnt #cnnLWPWeather{display:inline; float: left;} #cnn_ftrcntnt #cnnLWPWeather #cnnLWPPersonalize{position: relative; top: 14px;} #cnn_maincntnr, .cnn_maincntnr { width:1000px; } .cnn_contentarea { width:990px;text-align:left; } .cnn_sdbx { background:#fff url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/Left_shadow.gif') 0px 0px repeat-y; } .cnn_sdbx1 { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/Right_shadow.gif') 100% 0px repeat-y; } .cnn_sdbx2 { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/TR_shadow_1000x6.gif') 100% 0px no-repeat; } .cnn_sdbx3 { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/TL_shadow_7x6.gif') 0px 0px no-repeat; } .cnn_sdbx4 { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/BR_shadow_1000x6.gif') 100% 100% no-repeat; } .cnn_sdbx5 { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/BL_shadow_7x6.gif') 0px 100% no-repeat; } .cnn_sdbxcntnt { padding:4px 5px; } .cnn_shdheader { height:5px;overflow:hidden;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/top.right.gif') 100% 0px no-repeat; } .cnn_shdheader div { height:5px;width:5px;overflow:hidden;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/top.right.gif') 0px 0px no-repeat; } .cnn_shdfooter { height:5px;overflow:hidden;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/bot.right.gif') 100% 0px no-repeat; } .cnn_shdfooter div { height:5px;width:5px;overflow:hidden;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/bot.right.gif') 0px 0px no-repeat; } .cnn_shdlft { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/left.5px.gif') 0px 0px repeat-y; } .cnn_shdrgt { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/right.5px.gif') 100% 0px repeat-y;padding:0px 5px; } .cnn_shdcontent { margin:0 5px; } .cnn_shdbox .cnn_shdlft { background-color:#fff; } .cnn_divline { height:1px;background-color:#E5E5E5;overflow:hidden; } .cnn_divdotted { height:1px;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/misc/dotted.line.1px.gif') top left repeat-x;overflow:hidden; } .cnn_sectbincntnt2 ul { margin:0px;padding:0px;list-style:none; } .cnn_sectbincntnt2 ul li { padding:0px 0px 2px 7px;margin:0px;font:bold 11px/14px arial, Helvetica, Utkal, sans-serif;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/red_bull.gif') 0px 5px no-repeat;color:#9a9a9a; } .cnn_sectbincntnt2 ul li h2 { font:bold 11px/14px arial, Helvetica, Utkal, sans-serif; } .cnn_sectbincntnt2 li .cnn_vidicon { margin:0 0 0 4px;vertical-align:-1px; } /* for arabic bbin */ #arabicbin ul { direction:rtl;text-align:right;margin:0px;padding:0px;list-style-type:none;list-style-position:outside; } #arabicbin ul li { padding:0px 7px 2px 0px;margin:0px;font:bold 11px/14px arial, Helvetica, Utkal, sans-serif;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/red_bull.gif') right 5px no-repeat;color:#9a9a9a; } ul.cnn_bulletbin { margin:0px;padding:0px;list-style:none; } ul.cnn_bulletbin li { padding:0px 0px 2px 7px;margin:0px;font:bold 11px/14px arial, Helvetica, Utkal, sans-serif;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/red_bull.gif') 0px 5px no-repeat;color:#9a9a9a; } ul.cnn_bulletbin li h2 { font:bold 11px/14px arial, Helvetica, Utkal, sans-serif; } ul.cnn_bulletbin li .cnn_vidicon { margin:0 0 0 4px;vertical-align:-1px; } * html ul.cnn_bulletbin li .cnn_vidicon { vertical-align:middle; } *+html ul.cnn_bulletbin li .cnn_vidicon { vertical-align:middle; } .cnn_relpostn { position:relative; } /* QUICKVOTE */ .cnn_shdsectbin .cnn_quickvotebin h4 { background-image:none; } .cnn_quickvotebin h5 { font:bold 14px/16px arial, Helvetica, Utkal, sans-serif;margin:0px;padding:0px 0px 8px 0px; } .cnn_qvbvote { color:#9a9a9a;margin:12px 0 0 0; } .cnn_qvbv1, .cnn_qvbv2 { float:left;display:inline;margin:0px; } .cnn_qvbv2 { margin:2px 0 0 4px; } .cnn_qvb336 .cnn_qvbv2 { font-size:11px;line-height:14px; } .cnn_qvbvactv { background-color:#efefef; } .cnn_qvbv9 div { margin:4px 0 0 0;height:8px;overflow:hidden;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/misc/qv.bar.bg.gif') top left repeat-x; } .cnn_qvbv4 ul { margin:0px;padding:0px;list-style:none; } .cnn_qvbv4 ul li { padding:0px 0px 4px 0px;margin:0px;width:100px;float:left;display:inline; } .cnn_qvbv4 ul li input { display:block;float:left;margin:0px 5px 0 0; } * html .cnn_qvbv4 ul li input { margin-top:-3px; } *+html .cnn_qvbv4 ul li input { margin-top:-3px; } .cnn_qvb336 .cnn_qvbv4 ul li { width:150px; } .cnn_qvbv5 { font:normal 11px/14px arial, Helvetica, Utkal, sans-serif;padding:0 0 6px 0; } .cnn_qvbv6 { font:normal 11px/14px arial, Helvetica, Utkal, sans-serif;width:210px; } .cnn_qvbv7 div { float:left;display:inline; } .cnn_qvbv7 div.cnn_clear { float:none;display:block; } .cnn_qvbv8 { width:54px;margin:1px 0 0 5px; } .cnn_qvbv9 { width:78px;overflow:hidden; } .cnn_qvbv10 { width:30px;margin:1px 0 0 0; } .cnn_qvbv11 { font:bold 10px/12px arial, Helvetica, Utkal, sans-serif;color:#828282;width:43px;margin:2px 0 0 0; } .cnn_qvbv12 { margin:4px 0 0px 0;font:bold 10px/12px arial, Helvetica, Utkal, sans-serif;color:#828282; } .cnn_qvbv13 { margin:0px 0 4px 0;color:#828282;font:normal 10px/12px arial, Helvetica, Utkal, sans-serif; } .cnn_qvbv15 { display:none; } .cnn_qvbwide { height:179px;overflow:hidden; } .cnn_qvbwide .cnn_qvbv1, .cnn_qvbwide .cnn_qvbv2 { float:none;margin:0px 0px 5px 0px;display:block;font-size:11px;line-height:14px; } .cnn_qvbwide .cnn_qvbv2 span { display:none; } .cnn_qvbwide .cnn_qvbv3 { padding:0 10px 20px 10px;font:normal 11px/14px arial; } .cnn_qvbwide .cnn_qvbv3 h5 { font:bold 16px/19px arial;color:#000;margin:0px;padding:0px 0px 1px 0px; } .cnn_qvbwide .cnn_qvbv4 { float:left;margin:2px 0px 0px 10px;display:inline;width:632px; } .cnn_qvbwide .cnn_qvbvote { float:left;display:inline;margin:3px 0px 0px 0px; } .cnn_qvbwide .cnn_qvbv4 ul { margin:0px;padding:0px;list-style:none; } .cnn_qvbwide .cnn_qvbv4 ul li { padding:0px 0px 4px 0px;width:200px;margin:0px;float:left;display:inline; } .cnn_qvbwide .cnn_tsbnav { float:right;display:inline;margin:8px 0px 0px 0px; } .cnn_qvb336 h5 { font:bold 18px/21px arial;padding:7px 0 11px 0; } .cnn_qvb336 .cnn_qvbv5 { font:normal 11px/14px arial;padding:0 0 12px 0; } .cnn_qvb336 .cnn_qvbv6 { font:normal 11px/14px arial;width:316px; } .cnn_qvb336 .cnn_qvbv7 div, .cnn_qvbwide .cnn_qvbv7 div { float:left;display:inline; } .cnn_qvb336 .cnn_qvbv7 div.cnn_clear, .cnn_qvbwide .cnn_qvbv7 div.cnn_clear { float:none;display:block; } .cnn_qvb336 .cnn_qvbv8, .cnn_qvbwide .cnn_qvbv8 { width:54px;margin:1px 0 0 5px; } .cnn_qvb336 .cnn_qvbv9, .cnn_qvbwide .cnn_qvbv9 { width:172px; } .cnn_qvb336 .cnn_qvbv10, .cnn_qvbwide .cnn_qvbv10 { width:43px;margin:1px 0 0 0; } .cnn_qvb336 .cnn_qvbv11, .cnn_qvbwide .cnn_qvbv11 { font:bold 10px/12px arial;color:#828282;width:42px;margin:2px 0 0 0; } .cnn_qvb336 .cnn_qvbv12, .cnn_qvbwide .cnn_qvbv12 { float:right;margin:9px 0 8px 0;display:inline;font:bold 10px/12px arial;color:#828282; } .cnn_qvb336 .cnn_qvbv13 { float:left;margin:9px 0 8px 0;display:inline;color:#828282;font:normal 10px/12px arial; } .cnn_qvbwide .cnn_qvbv13 { display:none; } .cnn_qvbwide .cnn_qvbv16 { height:109px;overflow:hidden; } .cnn_qvbwide .cnn_qvbv15 { display:block;color:#828282;font:normal 10px/12px arial; } .cnn_qvbwide h5 { font:bold 18px/21px arial;padding:0px 80px 4px 0; } .cnn_qvbwide .cnn_qvbv14 { float:left;display:inline;width:404px;margin:0 0 0 10px; } .cnn_qvbwide .cnn_qvbv6 { font:normal 11px/14px arial;width:316px;float:left;display:inline;margin:3px 0 0 0; } /* COMMON BUTTONS */ .cnn_mtpmorebtn, .cnn_mtpmoregbtn, .cnn_frmsrchbtn, .cnn_frmqvtbtn, .cnn_frmqvtbbtn, .cnn_frmgobtn, .cnn_frmsrchlgbtn, .cnn_mtpvmsbtn, .cnn_mtpvatbtn, .cnn_irprtrsltsbtn, .cnn_mtpmorevbtn, .cnn_fabcntrldot, .cnn_mtpvatpbtn { background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/buttons/Sprite_BT_master.gif') 0px -352px no-repeat; } .cnn_mtpmorebtn { display:block;height:17px;width:55px; } .cnn_mtpmorebtn img { height:17px;width:55px; } .cnn_mtpmorebtn:hover { background-position:0px -389px; } .cnn_mtpmoregbtn { display:block;height:17px;width:55px;background-position:0px -1758px; } .cnn_mtpmoregbtn img { height:17px;width:55px; } .cnn_mtpmoregbtn:hover { background-position:0px -1795px; } .cnn_frmsrchbtn { display:block;height:20px;width:56px;background-position:0px -500px; } .cnn_frmsrchbtn img { height:20px;width:56px; } .cnn_frmsrchbtn:hover { background-position:0px -540px; } .cnn_frmsrchlgbtn { display:block;height:27px;width:86px;background-position:0px -1459px; } .cnn_frmsrchlgbtn img { height:27px;width:86px; } .cnn_frmsrchlgbtn:hover { background-position:0px -1506px; } .cnn_frmqvtbtn { display:block;height:20px;width:55px;background-position:0px -580px; } .cnn_frmqvtbtn img { height:20px;width:55px; } .cnn_frmqvtbtn:hover { background-position:0px -620px; } .cnn_frmqvtbbtn { display:block;height:21px;width:55px;background-position:0px -1553px; } .cnn_frmqvtbbtn img { height:21px;width:55px; } .cnn_frmqvtbbtn:hover { background-position:0px -1594px; } .cnn_mtpvmsbtn { display:block;height:17px;width:115px;background-position:0px -1385px; } .cnn_mtpvmsbtn img { height:17px;width:115px; } .cnn_mtpvmsbtn:hover { background-position:0px -1422px; } .cnn_mtpvatbtn { display:block;height:17px;width:109px;background-position:0px -3929px; } .cnn_mtpvatbtn img { height:17px;width:109px; } .cnn_mtpvatbtn:hover { background-position:0px -3966px; } .cnn_mtpvatpbtn { display:block;height:17px;width:109px;background-position:0px -3285px; } .cnn_mtpvatpbtn img { height:17px;width:109px; } .cnn_mtpvatpbtn:hover { background-position:0px -3322px; } .cnn_frmgobtn { display:block;height:21px;width:47px;background-position:0px -1676px; } .cnn_frmgobtn img { height:21px;width:47px; } .cnn_frmgobtn:hover { background-position:0px -1717px; } .cnn_frmgobtn_on, .cnn_frmgobtn_on:hover { background-position:0px -1635px; } .cnn_irprtrsltsbtn { display:block;height:17px;width:146px;background-position:0px -1311px; } .cnn_irprtrsltsbtn img { height:17px;width:146px; } .cnn_irprtrsltsbtn:hover { background-position:0px -1348px; } .cnn_mtpmorevbtn { display:block;height:17px;width:92px;background-position:0px -3211px; } .cnn_mtpmorevbtn img { height:17px;width:92px; } .cnn_mtpmorevbtn:hover { background-position:0px -3248px; } .cnn_fabcntrldot { display:block;height:5px;width:5px;background-position:0px -3161px; } .cnn_fabcntrldot img { height:5px;width:5px; } .cnn_fabcntrldot:hover { background-position:0px -3186px; } .cnn_fabcntrldot_off .cnn_fabcntrldot:hover { background-position:0px -3161px;cursor:default; } .cnn_containerwht, .cnn_containerwht .cnn_contentarea { background-color:#fff;} .cnn_containerblk, .cnn_containerblk .cnn_contentarea { background-color:#000;} .cnn_containerblk .cnn_ftrwthr4 strong { color:#fff; } .cnn_fabtabbtn { background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/buttons/sprite_tabbed.gif') 100% -23px no-repeat;display:block;float:left;height:18px;font-size:11px;line-height:14px;overflow:hidden;margin-right:2px; } .cnn_fabtabbtn span { display:inline-block;background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/buttons/sprite_tabbed.gif') 0 -23px no-repeat;margin:0 10px 0 0px;height:18px;float:left; } .cnn_fabtabbtn b { display:block;padding:1px 0 0 10px; } .cnn_fabtabbtn:link, .cnn_fabtabbtn:visited, .cnn_fabtabbtn:hover { color:#fff;cursor:pointer; } .cnn_fabtabbtn:hover { background-position:100% -61px; } .cnn_fabtabbtn:hover span { background-position:0px -61px; } .cnn_fabtabbtnon, .cnn_fabtabbtnon:hover { background-position:100% -99px;cursor:default; } .cnn_fabtabbtnon span, .cnn_fabtabbtnon:hover span { background-position:0 -99px;} /* SECTION SHADING SPRITE CSS */ .cnn_shdsectbin .cnn_shdcaheader, .cnn_shdsectbin .cnn_shdcafooter, .cnn_shdmnfooter, .cnn_shd755pxfooter, .cnn_shd755pxheader, .cnn_shd755px2footer, .cnn_shd755px2header, .cnn_shd235pxheader, .cnn_shd235pxfooter { height:6px;overflow:hidden;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/shade/sprite_shades.gif') 0px -81px no-repeat; } .cnn_shdsectbin .cnn_shdcafooter { background-position:0px -124px; } .cnn_shdmnfooter { background-position:0px -174px;clear:both; } .cnn_shd755pxheader { background-position:0px -252px;height:7px; } .cnn_shd755pxfooter { background-position:0px -214px;height:7px; } .cnn_shd755px2header { background-position:0px -342px;height:7px; } .cnn_shd755px2footer { background-position:0px -299px;height:7px; } .cnn_shd235pxheader { background-position:0px -424px;height:7px; } .cnn_shd235pxfooter { background-position:0px -383px;height:7px; } /* FLIPPER CSS */ .cnn_flpprcntr { height:346px;overflow:hidden;width:637px; } .cnn_flpprt1cntr, .cnn_flpprt1pnl { position:relative;height:280px;overflow:hidden; } .cnn_flpprt1arrnv { position:absolute;top:250px;width:100%; } .cnn_flpprt1txt { position:absolute;bottom:40px;left:0px;width:250px;overflow:hidden; } .cnn_flpprt1an1, .cnn_flpprt1an2 { float:left;display:block;margin:0px;width:31px;height:31px;cursor:pointer;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/flipper/31x31_black_left_arrow.gif') 0px 0px no-repeat; } .cnn_flpprt1an2 { float:right;background:transparent url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/flipper/31x31_black_right_arrow.gif') 0px 0px no-repeat; } .cnn_flpprt1txt h1 { font:bold 27px/29px arial, Helvetica, Utkal, sans-serif; } .cnn_flpprt1txt p { margin:0px;padding:0px;font:normal 11px/14px arial, Helvetica, Utkal, sans-serif;clear:left;display:block;width:250px; } .cnn_flpprt1txt .cnn_mtpmore { margin:10px 0 0 0; } .cnn_flpprt1txt ul.cnn_bulletbin { clear:left;background-color:#000;width:250px;padding-bottom:5px; } .cnn_flpprt1txt ul.cnn_bulletbin li { margin:0px 0px 0px 10px;background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/red_bull_blk.gif');color:#999; } .cnn_flpprt1txt ul.cnn_bulletbin li a:link, .cnn_flpprt1txt ul.cnn_bulletbin li a:visited { color:#fff; } .cnn_flpprt1txt ul.cnn_bulletbin li a:hover { color:#6AB9D3; } .cnn_flpprt1nav { background-color:#E6E6E6;height:65px;width:644px; } .cnn_flpprt1nvbx { height:65px;overflow:hidden;width:160px;float:left;margin:0px;display:inline;font:normal 11px/14px arial, Helvetica, Utkal, sans-serif; } .cnn_flpprt1nvbx a:link, .cnn_flpprt1nvbx a:visited { color:#666; } .cnn_flpprt1nvbx a:hover { color:#ca0002; } .cnn_flpprt1nvbx .cnn_flpprt1nb2 a span { color:#ca0002; } .cnn_flpprt1nb4 .cnn_flpprt1nb3 a:link, .cnn_flpprt1nb4 .cnn_flpprt1nb3 a:visited { color:#004173; } .cnn_flpprt1nb4 .cnn_flpprt1nb3 a:hover { color:#ca0002; } .cnn_flpprt1nb1 { border-right:1px solid #DADADA;height:65px; } .cnn_flpprt1nb2 { height:10px;overflow:hidden; } .cnn_flpprt1nb2 div { padding:11px 10px 0 12px; } .cnn_flpprt1nb3 { font-weight:bold;padding:0 12px; } .cnn_flpprt1nvbx_active, .cnn_flpprt1nb4 { background:#fff url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/flipper/nav_blackbg.gif') 0px 0px repeat-x; } .cnn_flpprt1txt h1 span { padding:6px 10px;background-color:#000;display:block;font-weight:normal;margin-bottom:4px; } .cnn_flpprt1txt h1 span a:link, .cnn_flpprt1txt h1 span a:visited { color:#fff; } .cnn_flpprt1txt h1 span a:hover { color:#6AB9D3; } .cnn_flpprt1txt p span { padding:7px 10px;background-color:#000;display:block;color:#fff;font-weight:bold; } .cnn_flpprt1txt p span a:link, .cnn_flpprt1txt p span a:visited { color:#6bb8d4; } .cnn_flpprt1txt p span a:hover { color:#ca0002; } .cnn_flpprt1pnl { display: none; } .cnn_flpprt1pnl_active { display: block; } .cnn_flpprt1img { position: absolute; top: 0px; left: 0px; width: 637px; height: 280px; cursor: pointer; } .cnn_flpprt1rlign .cnn_flpprt1txt { left:387px; } br.cnn_clear { clear: both; margin: 0; border: 0; padding: 0; height: 0; font-size: 1px; line-height: 0px; } /* GOOGLE ADS */ .cnnWireAdLtgBox .cnnHtAdvertHead { font-weight:bold;margin:0px;padding:16px 0px 0px 0px; } .cnnWireAdLtgBox { font-size:11px;line-height:14px; } .cnnWireAdLtgBox .cnnHtAdvertLnks { padding:12px 0 0 0; } .cnnWireAdLtgBox .cnnHtAdvertTitle { font-weight:bold; } /* VIDEO BUTTONS */ #cnn_maintt2bul .cnn_mtt1img .cnn_vidplyb38x38 { position:absolute;top:34px;left:88px;z-index:20;cursor:pointer; } .cnn_sectbin1 .cnn_mtt1img .cnn_vidplyb38x38, .cnn_sectbin2 .cnn_mtt1img .cnn_vidplyb38x38, .cnn_sectbin3 .cnn_mtt1img .cnn_vidplyb38x38 { position:absolute;top:12px;left:91px;z-index:20;cursor:pointer; } .cnn_vtzimg120x68 .cnn_vidplyb38x38, .cnn_mtlplnimg .cnn_vidplyb38x38, .cnn_fabcatz .cnn_vidplyb38x38 { position:absolute;z-index:2;top:17px;left:41px;cursor:pointer; cursor:pointer; } .cnn_fabcatz .cnn_vidplyb38x38 { top: 12px; } .cnn_mtlplnimg .cnn_vidplyb38x38 { top: 15px; } .cnn_vidplyb38x38 a { display:inline-block;background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/video/thumbnail_play.png');background-position:0px 0px;cursor:pointer;height:38px;width:38px; } .cnn_vidplyb38x38 a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/video/thumbnail_play_hover.png'); } .cnn_vidplyb38x38 a img { height:38px;width:38px; } /* FOOTER CSS */ #cnn_ftrcntnt{padding-bottom: 5px;} #cnn_ftrcntnt, #cnn_ftrcntntinner{width:980px;text-align:left;padding-top:30px;position: relative;} #cnn_ftrcntntinner{border-top:2px solid #dadada;padding-top:3px;} .cnn_ftrwthr1 { float:left;width:60px;margin:0 12px 0 8px;display:inline; } .cnn_ftrwthr2 { float:left;width:684px;margin:13px 0 0 0;display:inline;font:bold 10px/14px arial, Helvetica, Utkal, sans-serif;color:#666; } .cnn_ftrwthr3 { width:50px;float:left;margin:0px;display:inline;font:bold 27px/30px arial, Helvetica, Utkal, sans-serif; } .cnn_ftrwthr4 { width:300px;float:left;margin:0px;display:inline;line-height:14px; } .cnn_ftrwthr4 strong {color:#000; } .cnn_ftrwthr4 a { font-weight:normal; } .cnn_ftrsrchcntr { float:left;width:216px;margin:16px 0 0 0;display:inline; } .cnn_ftrsrch1 { float:left;width:199px;height:21px;background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/searchBar2.1.jpg') no-repeat;overflow:hidden; } .cnn_ftrsrch2 { float:left;width:17px;margin:0px; } .cnn_ftrsrch3 { background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/PoweredByGoogle.jpg') 100% 0px no-repeat;height:14px;overflow:hidden; } .cnn_ftrsrch1 div { padding:3px 0 0 5px; } .cnn_ftrsrch1 input { border:0px;margin:0px;padding:0px;width:188px;font:bold 11px/14px arial, Helvetica, Utkal, sans-serif;color:#666; } .cnn_ftrnvlnks { padding:7px 0 8px 0;font:normal 10px/14px arial, Helvetica, Utkal, sans-serif;text-align:center;color:#999; } .cnn_ftrnvlnks div { padding:0 0 4px 0; } .cnn_ftrnvlnks div a{padding: 0 3px;} .cnn_ftrlgcpy { margin:10px 0 0 0;font:normal 10px/14px arial, Helvetica, Utkal, sans-serif;color:#666;float:left;display:inline;width:505px; } .cnn_ftrlgcpy img { vertical-align:-2px;margin:0 5px 0 0; } * html .cnn_ftrlgcpy img { vertical-align:middle; } *+html .cnn_ftrlgcpy img { vertical-align:middle; } .cnn_ftrlnggcntr img { vertical-align:-2px; } * html .cnn_ftrlnggcntr img { vertical-align:middle; } *+html .cnn_ftrlnggcntr img { vertical-align:middle; } .cnn_ftrlgcpy1 { padding:4px 0 0 0;color:#b5b5b5; } .cnn_ftrdivl2 { height:11px;background-color:#ca0002;overflow:hidden; } .cnn_ftrlnggcntr { float:right;display:inline;margin:10px 0 0 0;width:396px;font:normal 10px/14px arial, Helvetica, Utkal, sans-serif;color:#b5b5b5;text-align:right; } .cnn_ftrlnggcntr div { padding-bottom:4px; } #cnnLWPWeather #weather-def-link{display: block; padding-top: 15px;} /* BREAKING NEWS */ .cnn_dynone { display:none; } #cnn_bnbcntr { height:52px;position:relative; } #cnn_bnblft { height:52px;width:156px;position:absolute;top:0px;left:0px; } #cnn_bnbrgt1 { height:52px;width:824px;position:absolute;top:0px;left:156px;color:#fff;font:bold 17px/19px arial;overflow:hidden;z-index:5; } #cnn_bnbrgt1 div { padding:7px 313px 0 27px; } #cnn_bnbrgt3 { filter:alpha(opacity=0);-moz-opacity:.0;opacity:.0;display:inline-block; } #cnn_bnbrgt3:link, #cnn_bnbrgt3:visited { color:#64bbff;font-size:12px;line-height:15px; } #cnn_bnbrgt3:hover { color:#ca0002; } #cnn_bnbrgt2 { background:#fff url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/misc/bn_right.gif') 0px 0px no-repeat;height:52px;width:824px;position:absolute;top:0px;left:156px;z-index:3;filter:alpha(opacity=0);-moz-opacity:.0;opacity:.0; } #cnn_bnbrgt4 { position:absolute;top:3px;left:964px;z-index:5;height:15px;width:15px; } #cnn_bnbrgt4 a img { height:15px;width:15px; } /* AD CSS */ /*.cnn_adcntrt728x90 { padding:10px 0; }*/ .cnn_adcntrt728x90 .cnn_adspc728x90 .cnn_adspctimg { text-align:right;padding:5px 0 0 0; } .cnn_adspc336cntr { background-color:#F2F2F2;width:336px;height:280px; } .cnn_adspc336cntr td { vertical-align:middle;text-align:center; } .cnn_stry336adcntr { background-color:#F2F2F2; } .cnn_stry336adcntr td { vertical-align:middle;text-align:center; } .cnn_stry336adcntr table { width:336px; } .adunit_970x66 {margin:10px auto;} .adunit_728x90 {margin:10px auto;} /* SKINNY NAV */ .cnn_hdrsnvcntr { height:39px;background-color:#C91900; } .cnn_hdrsnv { width:1000px;background-color:#C91900;text-align:left; } .cnn_hdrsnvl { margin:8px 0 0 10px;width:130px;float:left;display:inline; } .cnn_hdrsnvl a { font-weight:bold;font-size:11px;line-height:14px; } .cnn_hdrsnvl a:link, .cnn_hdrsnvl a:visited { color:#fff; } .cnn_hdrsnvl img { vertical-align:-5px;margin:0 2px; } .cnn_hdrsnvr { float:right;width:320px;display:inline;margin:8px 10px 0 0;background:url(http://i.cdn.turner.com/cnn/.element/img/3.0/global/header/hdr-search-google.gif) 100% 7px no-repeat; } .cnn_hdrsnvrcntr { position:relative;top:0px;left:0px; } .cnn_hdrsnvr #hdr-search {position:static; right:0; top:0px;} .cnn_hdrsnvr #hdr-search-mag {outline: none; border: 0; position: absolute; top: 6px; left:200px; width: 13px; height: 12px;} .cnn_hdrsnvr #hdr-search form{background-image:none;padding-bottom:0px; } /* VIDEO ERRORS */ .cnn_viderrbx { background-color:#eee;text-align:center;color:#666; } .cnn_viderrbx div { padding:0 80px; } .cnn_viderrbx div b { font-size:14px;line-height:16px;display:block; } .cnn_viderrbx640 { height:406px;width:640px; } .cnn_viderrbx640 div { padding-top:150px; } .cnn_viderrbx416 { height:250px;width:416px; } .cnn_viderrbx416 div { padding-top:100px; } .cnn_viderrbx320 { height:180px;width:320px; } .cnn_viderrbx320 div { padding:0 50px; } .cnn_viderrbx320 div { padding-top:50px; } /* FOOTER LANGUAGE */ .cnn_ftrlarabic a { background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/arabic.png') 0px 0px no-repeat;cursor:pointer; } .cnn_ftrlarabic a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/arabic_over.png'); } .cnn_ftrlkorean a { background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/korean.png') 0px 0px no-repeat;cursor:pointer; } .cnn_ftrlkorean a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/korean_over.png'); } .cnn_ftrljapan a { background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/japanese.png') 0px 0px no-repeat;cursor:pointer; } .cnn_ftrljapan a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/japanese_over.png'); } .cnn_ftrlturkish a { background:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/turkish.png') 0px 0px no-repeat;cursor:pointer; } .cnn_ftrlturkish a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/turkish_over.png'); } .cnn_containerblk .cnn_ftrlarabic a { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/arabic.png'); } .cnn_containerblk .cnn_ftrlarabic a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/arabic_over.png'); } .cnn_containerblk .cnn_ftrlkorean a { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/korean.png'); } .cnn_containerblk .cnn_ftrlkorean a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/korean_over.png'); } .cnn_containerblk .cnn_ftrljapan a { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/japanese.png'); } .cnn_containerblk .cnn_ftrljapan a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/japanese_over.png'); } .cnn_containerblk .cnn_ftrlturkish a { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/turkish.png'); } .cnn_containerblk .cnn_ftrlturkish a:hover { background-image:url('http://i.cdn.turner.com/cnn/.element/img/3.0/global/footer/pngs/blk/turkish_over.png'); } .cnn_containerblk a:link, .cnn_containerblk a:visited { color:#6ab9d3; } .cnn_containerblk a:hover { color:#ca0002; } /* CSS PNG FIXES */ .cnn_vidplyb38x38 a, .cnn_ie6png { behavior: url("/.element/css/3.0/png_fix.htc"); } .cnnWOOL { color:#999999; font-weight:bold;}
css
<filename>src/api/queryToJson.tsx<gh_stars>10-100 import * as React from "react"; function jsonToQuery() { } export default jsonToQuery;
typescript
Prime Minister Narendra Modi on Saturday paid tributes to Sri Aurobindo, a freedom fighter and spiritual philosopher, on his birth anniversary, saying he was synonymous with brilliance and courage. "Tributes to Sri Aurobindo on his Jayanti. He was synonymous with brilliance and courage. His thoughts and ideals, views on spirituality continue to motivate us. "Here are my remarks at the Golden Jubilee celebrations at Auroville," Modi tweeted, sharing his 2018 speech on Aurobindo. The prime minister also remembered Aurobindo, who was born on this day in 1872, in his Independence Day speech earlier in the day. He was a revolutionary nationalist before he turned to spirituality. (This story has not been edited by News18 staff and is published from a syndicated news agency feed - PTI)
english
{"web":[{"value":["厘米","公分","公制长度单位"],"key":"centimeter"},{"value":["厘米","公分","裁剪"],"key":"CM Centimeter"},{"value":["超高频","厘米波"],"key":"centimeter wave"}],"query":"centimeter","translation":["厘米"],"errorCode":"0","dict":{"url":"yddict://m.youdao.com/dict?le=eng&q=centimeter"},"webdict":{"url":"http://m.youdao.com/dict?le=eng&q=centimeter"},"basic":{"us-phonetic":"'sɛntə,mitɚ","phonetic":"ˈsentɪmiːtə(r)","uk-phonetic":"ˈsentɪmiːtə(r)","explains":["n. [计量] 厘米;[计量] 公分"]},"l":"EN2zh-CHS"}
json
What's the story? Prior to an NXT live event in Philadelphia, Tye Dillinger and two other NXT Superstars served hot chocolate to cold fans, who were waiting in line to see the show at the Tower Theater. The temperatures in Philly have been awful over the last few days following a snowstorm, however, these NXT performers were on hand to save the day. Dillinger has been rising up the ranks in NXT for a long time now, with the 35-year-old's Perfect Ten gimmick gaining a great deal of momentum. Even before this act of kindness, he's been on a road to success, and this latest stunt will only serve to improve the WWE Universe’s opinion of him. After all, everyone loves a great good guy. The freezing temperatures left a lot of fans pretty fed up of waiting in the cold, and despite the fact they could've been preparing for their matches indoors Dillinger, Angelo Dawkins and Montez Ford took it upon themselves to help out those in need. They went down the line offering people hot chocolate, interacting with numerous fans in the process. What's next? This video will likely start floating around backstage, and hopefully, somebody will notice the outstanding efforts of these three gentlemen. It seems as if Dillinger, in particular, has all of the requirements necessary to thrive on both NXT and the main roster, and perhaps this will be the help Vince McMahon see how much potential this guy has both in and out of the ring. It's no surprise to us to see Dillinger do something like this because he's just an all-round great guy. A few years back, Dusty Rhodes would reportedly write, "what is he still doing here? " in his reports about Tye because he's been ready for the main roster for such a long time now. It's baffling that he isn't given more of a push, but hopefully, we're starting to see the beginning of that down in NXT. The reactions he receives are so loud that you just can't ignore how popular he is among the WWE Universe. Honestly, within two years he could be a bonafide main eventer on either Raw or SmackDown Live - he's that good. What's next for The Bloodline?
english
<filename>resources/us/abraham-baldwin-agricultural-college.json<gh_stars>10-100 {"name":"<NAME>","alt_name":null,"country":"United States","state":"Georgia","address":{"street":"2802 Moore Highway","city":"Tifton","province":"Georgia","postal_code":"31794"},"contact":{"telephone":"+1(229) 391-5000","website":"http:\/\/www.abac.peachnet.edu","email":"<EMAIL>","fax":null},"funding":"Public","languages":null,"academic_year":null,"accrediting_agency":"Southern Association of Colleges and Schools (SACS)"}
json
// Gossamer Vault (Dificil) // // made by michengs module.exports = (dispatch, handlers, guide, lang) => { let boss = null; return { // 1 BOSS "nd-3201-1000": [ { type: "stop_timers" }, { type: "despawn_all" } ], //"s-3201-1000-103-0": [{ type: "text", class_position: "tank", sub_type: "message", message_PT: "Iframe", message_ES: "Iframe", message: "Iframe!" }], "s-3201-1000-104-0": [{ type: "text", class_position: "tank", sub_type: "message", message_PT: "Stun Frontal", message_ES: "Stun Frontal", message: "Стан!" }], "s-3201-1000-107-0": [ { type: "text", sub_type: "message", message_PT: "Empurrar Atrás (Lento)", message_ES: "Empujar Atrás (Lento)", message: "Back" }, { type: "spawn", func: "vector", args: [553, 90, 139, 173, 800, 0, 3500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 270, 139, -173, 800, 0, 3500] } //Adicionado ], "s-3201-1000-111-0": [{ type: "text", sub_type: "message", message_PT: "Spray Atrás (Lento)", message_ES: "Spray Atrás (Lento)", message: "Back Wave" }, { type: "spawn", func: "vector", args: [553, 0, 100, 112, 800, 0, 3500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 0, 100, -112, 800, 0, 3500] } //Adicionado ], "s-3201-1000-112-0": [{ type: "text", sub_type: "message", message_PT: "<-Spray ESQUERDO e DIREITO->", message_ES: "<-Spray IZQUIERDO e DERECHO->", message: "Left + Right" }], "s-3201-1000-113-0": [ { type: "text", sub_type: "message", message_PT: "Salto (Lento)", message_ES: "Salto (Lento)", message: "Jump (Slow)" }, { type: "text", sub_type: "message", delay: 1900, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe!" } ], "s-3201-1000-118-0": [ { type: "text", sub_type: "message", message_PT: "Salto (Lento)", message_ES: "Salto (Lento)", message: "Jump (Slow)" }, { type: "text", sub_type: "message", delay: 1900, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe!" }, ], "s-3201-1000-119-0": [{ type: "text", sub_type: "message", delay: 0, message_PT: "Spray FRENTE e ATRÁS", message_ES: "Spray FRENTE e ATRÁS", message: "Back + Front" }, { type: "spawn", func: "vector", args: [553, 2, 0, 70, 800, 0, 2500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 2, 0, 110, 800, 0, 2500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 2, 0, 250, 800, 0, 2500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 2, 0, 290, 800, 0, 2500] } //Adicionado ], //"s-3201-1000-121-0": [{ type: "text", class_position: "tank", sub_type: "message", message_PT: "Direita", message_ES: "Derecha", message: "Right" }], //"s-3201-1000-122-0": [{ type: "text", class_position: "tank", sub_type: "message", message_PT: "Esquerda", message_ES: "Izquierda", message: "Left" }], "s-3201-1000-124-0": [{ type: "text", class_position: "tank", sub_type: "message", message_PT: "Stun Frontal", message_ES: "Stun Frontal", message: "Stun attack" }], "s-3201-1000-127-0": [ { type: "text", class_position: "dps", sub_type: "message", message_PT: "Empurrar Atrás (Rápido)", message_ES: "Empujar Atrás (Rápido)", message: "Back (fast)" }, { type: "text", class_position: "heal", sub_type: "message", message_PT: "Empurrar Atrás (Rápido)", message_ES: "Empujar Atrás (Rápido)", message: "Back (fast)" }, { type: "spawn", func: "vector", args: [553, 90, 139, 173, 800, 0, 2000] }, //Adicionado { type: "spawn", func: "vector", args: [553, 270, 139, -173, 800, 0, 2000] } //Adicionado ], //"s-3201-1000-128-0": [{ type: "text", class_position: "tank", sub_type: "message", message_PT: "Triple Attack", message_ES: "Triple Attack", message: "Triple Attack" }], "s-3201-1000-131-0": [ { type: "text", class_position: "dps", sub_type: "message", message_PT: "Spray Atras (Rápido)", message_ES: "Spray Atrás (Rapido)", message: "Back Wave" }, { type: "text", class_position: "heal", sub_type: "message", message_PT: "Spray Atras (Rápido)", message_ES: "Spray Atrás (Rapido)", message: "Back Wave" }, { type: "spawn", func: "vector", args: [553, 0, 100, 112, 800, 0, 2000] }, //Adicionado { type: "spawn", func: "vector", args: [553, 0, 100, -112, 800, 0, 2000] } //Adicionado ], "s-3201-1000-132-0": [{ type: "text", sub_type: "message", message_PT: "<-Spray ESQUERDO e DIREITO->", message_ES: "<-Spray IZQUIERDO e DERECHO->", message: "Left + Right" }], "s-3201-1000-133-0": [{ type: "text", sub_type: "message", delay: 0, message_PT: "Salto (Rápido)", message_ES: "Salto (Rapido)", message: "Jump (Fast)" }, { type: "text", sub_type: "message", delay: 900, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe!" } ], "s-3201-1000-138-0": [{ type: "text", sub_type: "message", delay: 0, message_PT: "Salto (Rapido)", message_ES: "Espanol", message: "Jump P (Fast)" }, { type: "text", sub_type: "message", delay: 900, message_PT: "Iframe", message_ES: "Espanol", message: "Iframe!" } ], "s-3201-1000-139-0": [{ type: "text", sub_type: "message", message_PT: "Spray FRENTE e ATRÁS (Rápido)", message_ES: "Spray FRENTE e ATRÁS (Rapido)", message: "Back + Front (Fast)" }, { type: "spawn", func: "vector", args: [553, 2, 0, 70, 800, 0, 2500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 2, 0, 110, 800, 0, 2500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 2, 0, 250, 800, 0, 2500] }, //Adicionado { type: "spawn", func: "vector", args: [553, 2, 0, 290, 800, 0, 2500] } //Adicionado ], /* "s-3201-1000-143-0": [ { type: "text", class_position: "tank", sub_type: "message", message_PT: "Left > Right", message_ES: "Left > Right", message: "Left > Right" }, { type: "text", class_position: "dps", sub_type: "message", message_PT: "Right > Left", message_ES: "Right > Left", message: "Right > Left" }, { type: "text", class_position: "heal", sub_type: "message", message_PT: "Right > Left", message_ES: "Right > Left", message: "Right > Left" }, { type: "spawn", func: "marker", args: [false, 150, 300, 100, 2715, true, null] }, // 1 { type: "spawn", func: "marker", args: [false, 225, 300, 2800, 4175, true, null] }, // 6 { type: "spawn", func: "marker", args: [false, 30, 300, 100, 1000, true, null] }, // 1 { type: "spawn", func: "marker", args: [false, 330, 300, 1100, 5000, true, null] } // 7 ], "s-3201-1000-145-0": [ { type: "text", class_position: "tank", sub_type: "message", message_PT: "Left > Right", message_ES: "Left > Right", message: "Left > Right" }, { type: "text", class_position: "dps", sub_type: "message", message_PT: "Right > Left", message_ES: "Right > Left", message: "Right > Left" }, { type: "text", class_position: "heal", sub_type: "message", message_PT: "Right > Left", message_ES: "Right > Left", message: "Right > Left" }, { type: "spawn", func: "marker", args: [false, 30, 300, 100, 1000, true, null] }, // 1 { type: "spawn", func: "marker", args: [false, 330, 300, 1100, 5000, true, null] }, // 7 { type: "spawn", func: "marker", args: [false, 150, 300, 100, 2000, true, null] }, // 1 { type: "spawn", func: "marker", args: [false, 225, 300, 2500, 5000, true, null] } // 6 ],*/ "s-3201-1000-148-0": [{ type: "text", sub_type: "message", message_PT: "<NAME> (voando)", message_ES: "<NAME>cha (Volando)", message: "Right Hand (Flying)" }, { type: "spawn", func: "circle", args: [false, 553, 20, 150, 10, 320, 0, 4000] } //Adicionado ], "s-3201-1000-149-0": [{ type: "text", sub_type: "message", message_PT: "<NAME> (voando)", message_ES: "<NAME> (Volando)", message: "Left Hand (Flying)" }, { type: "spawn", func: "circle", args: [false, 553, 340, 150, 10, 320, 0, 4000] } //Adicionado ], "s-3201-1000-151-0": [{ type: "text", sub_type: "message", message_PT: "Ataque Stun", message_ES: "Ataque Stun", message: "Stun Attack!" }], "s-3201-1000-305-0": [{ type: "text", sub_type: "message", message_PT: "Pizza", message_ES: "Pizza", message: "Pizza" }], "s-3201-1000-311-0": [ { type: "text", sub_type: "message", message_PT: "Ataque em Tela Cheia (Lento)", message_ES: "Ataque en Pantalla Llena (Lento)", message: "Slow" }, { type: "text", sub_type: "message", delay: 4200, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe!" } ], "s-3201-1000-312-0": [ { type: "text", sub_type: "message", message_PT: "Ataque em Tela Cheia (Rápido)", message_ES: "Ataque en Pantalla Llena (Rapido)", message: "Fast" }, { type: "text", sub_type: "message", delay: 2200, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe!" } ], "s-3201-1000-313-0": [ { type: "text", sub_type: "message", message_PT: "DENTRO e FORA (Lento)", message_ES: "DENTRO y FUERA (Lento)", message: "Circles (Slow)" }, { type: "spawn", func: "circle", args: [false, 553, 0, 75, 10, 300, 0, 6000] } ], "s-3201-1000-314-0": [ { type: "text", sub_type: "message", message_PT: "DENTRO e FORA (Rapido)", message_ES: "DENTRO y FUERA (Rapido)", message: "Circles (Fast)" }, { type: "spawn", func: "circle", args: [false, 553, 0, 75, 10, 300, 0, 6000] } ], // 2 BOSS "ns-3201-2000": [{ type: "func", func: () => boss = null }], "nd-3201-2000": [ { type: "stop_timers" }, { type: "despawn_all" } ], "am-3201-320126-32010224": [ { type: "func", func: () => boss = 1 }, { type: "text", delay: 52000, sub_type: "alert", message_PT: "REAL Debuff em 5 segundos", message_ES: "REAL Debuff en 5 Secundos", message: "True Debuff in 5 seconds" }, { type: "event", delay: 80000, args: [ { type: "func", check_func: () => boss === 1, func: () => boss = null }, { type: "text", check_func: () => boss === 1, sub_type: "message", message_PT: "Recarregar Debuff", message_ES: "Cargar Debuff", message: "Debuff reload" } ] } ], "am-3201-2000-32010220": [ { type: "func", func: () => { boss = 0; } }, { type: "text", delay: 52000, sub_type: "alert", message_PT: "FAKE Debuff em 5 segundos", message_ES: "FAKE Debuff en 5 Secundos", message: "False Debuff in 5 seconds" }, { type: "event", delay: 80000, args: [ { type: "func", check_func: () => boss === 0, func: () => boss = null }, { type: "text", check_func: () => boss === 0, sub_type: "message", message_PT: "Recarregar Debuff", message_ES: "Cargar Debuff", message: "Debuff reload" } ] } ], "h-3201-2000-81": [{ type: "text", sub_type: "message", message_PT: "80%", message_ES: "80%", message: "80%" }], "h-3201-2000-76": [{ type: "text", sub_type: "message", message_PT: "75%", message_ES: "75%", message: "75%" }], "s-3201-2000-108-0": [{ type: "text", sub_type: "message", message_PT: "Ataque Frente | Atrás", message_ES: "Ataque Frente | Atrás", message: "Back Attack!" }], "s-3201-2000-150-0": [{ type: "text", sub_type: "message", message_PT: "Fantasma", message_ES: "Fantasma", message: "Phantom" }], "s-3201-2000-228-0": [ { type: "text", sub_type: "message", message_PT: "Juntar Time", message_ES: "Juntar Time", message: "Team Up!!!" }, { type: "text", sub_type: "alert", delay: 4000, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe" } ], "s-3201-2000-230-0": [{ type: "text", sub_type: "message", message_PT: "AOE", message_ES: "AOE!!", message: "AOE!!" }, { type: "text", sub_type: "alert", delay: 1150, message_PT: "Iframe", message_ES: "Iframe", message: "Iframe" } ], "s-3201-2000-231-0": [ { type: "text", sub_type: "message", message_PT: "SAIR", message_ES: "SALIR", message: "Out Safe" }, { type: "spawn", func: "circle", args: [false, 553, 0, 0, 10, 300, 0, 3000] } ], "s-3201-2000-232-0": [{ type: "text", sub_type: "message", message_PT: "ENTRAR", message_ES: "ENTRAR", message: "In Safe" }, { type: "spawn", func: "circle", args: [false, 553, 0, 0, 10, 300, 0, 3000] }, { type: "spawn", func: "circle", args: [false, 553, 0, 0, 3, 1000, 0, 3000] } ], "s-3201-2000-235-0": [{ type: "text", sub_type: "message", message_PT: "Debuffs", message_ES: "Debuffs", message: "Debuffs" }], "s-3201-2000-236-0": [{ type: "text", sub_type: "message", message_PT: "Repelir a Frente (bait)", message_ES: "Repelir a Frente (bait)", message: "Counter Attack (Bait)" }] }; };
javascript
Pradhan Mantri Awas Yojana (Urban) (Pmay-U), Smart Cities Mission (SCM) and Atal Mission for Rejuvenation and Urban Transformation (AMRUT) Posted On: Shri Hardeep Singh Puri, Minister of State for Housing and Urban Affairs(I/C)has stated that“India has undertaken one of the most comprehensive planned urbanization programmes in the history of the worl. The vision of our Hon’ble Prime Minister of a New India is closely intertwined with our flagship programme achievements.On 12 May 2020, Hon’ble Prime Minister launched the Atma Nirbhar Bharat Abhiyan which focuses on providing relief as well as help to farmers, cottage industries, home industry, small-scale industries, MSMEs - which are the means of livelihood for crores of people who were adversely impacted by the lockdown measures”.He was addressing a webinar to mark the 5thAnniversary ofPradhan Mantri Awas Yojana(Urban) (PMAY-U), Smart Cities Mission (SCM) and Atal Mission for Rejuvenation and Urban Transformation (AMRUT) in the presence of Shri Durga Shanker Mishra, Secretary, MoHUA. The online event was organized by Ministry of Housing and Urban Affairs to celebrate the achievements and boost implementation of the urban missions. The event was attended by Joint Secretaries and Mission Directors of AMRUT, SCM, PMAY-U, Principal Secretaries (Urban Development) of State Government and UTs, State Mission Directors, Municipal Commissioners/CEOs of Smart Cities, representatives of partner agencies / Bilateral / Multilateral Institutions and other key stakeholders. The key announcements and launch events at the Webinar included : - E-Book of the Ministry of Housing & Urban Affairs showing the progress and achievements of all Missions of the Ministry. - National Institute of Urban Affairs (NIUA) Website is revamped to strengthen it as a knowledge bank for emerging topics on urban development, while continuing to be a source of everyday resources for urban development functionaries and practitioners. - National Urban Learning Platformis a platform for digitally consolidating key skills and knowledge required for capacity building, which is a constant requirement for effective governance and nurturing leadership at city, state and national level. - NIUA Climate Center for Cities (C3) has been setup to consolidate and institutionalize and mainstream the learnings from experiences in our cities on climate change. - NIUA Center for Digital Governance (CDG) isan initiative to take forward the digital efforts of MoHUA and become the anchor to accelerate digital transformation of urban governance across all States and Cities. - Video Launch: Outcomes of PMAY- U: showing the progress and achievements of PMAY-U, along with testimonials of beneficiaries of the Mission. - Video Launch: Outcomes of AMRUT: showing the progress and achievements of AMRUT, along with testimonials of beneficiaries of the Mission. - Book Launch: COVID Diaries: is a collection of personal reflections / opinion articles from members of Smart Cities Mission team as they navigate changes in their daily lives and work routines during COVID-19 pandemic. - Book Launch: The Smart Responses to COVID-19: How Indian Cities are fighting through Action and Innovation (Volume-1) compendium is an attempt to showcase how urban India has responded to the challenges posed by the pandemic. - City Finance Portal: First time effort of getting financial Statements of all cities on single platform to enable sharing and learning of best practices and to help ULBs in accessing market funds. - Cycles4Change Challenge: India Cycles4change Challenge is an initiative of Smart Cities Missionto inspire and support Indian cities to quickly implement cycling-friendly initiatives in response to COVID-19. The idea is to begin by creating low-cost interventions like pop-up cycle lanes and non-motorized zones, launch programs such as community-led cycle rental schemes and promote cycling usage through public events. Progress, Achievements and Outcomes of AMRUT, SCM and PMAY-(U) Atal Mission for Rejuvenation and Urban Transformation (AMRUT) Atal Mission for Rejuvenation and Urban Transformation (AMRUT),launched by Hon’ble Prime Minister on 25 June 2015, has completed 5 successful years. The Mission aims at ensuring universal coverage of drinking water supply and substantial improvement in coverage and treatment capacities of sewerage and septage, along with storm water drainage, non-motorized urban transport and green spaces & parks. The Mission spans across 500 cities, covering more than 60% of urban population. - State Annual Action Plans (SAAPs) worth ₹ 77,640 crore approved and projects worth ₹ 75,829 crore grounded so far. Projectsworth ₹ 10,654 crores completed and ₹ 65,175 crore in advanced stages of implementation. - ₹ 39,011 crore allocated for drinking water supply projects, and ₹ 32,546 crore for sewerage and septage projects. - Concerted effort made at national level to provide water to about 1.39 crore households and sewerage/septage services to about 1.45 crore households. - 79 lakh household water tap connections and 45 lakh sewer connections have been provided, including in slums and low-income habitations. - The Mission helped cities to undertake a set of 11 reforms comprising 54 milestones aimed at strengthening capacities of city level institutions for effective governance and citizen service delivery. - In order to promote energy efficiency across the Indian cities, 76 lakh streetlights replaced with energy efficient LED streetlights. - Online Building Permission System (OBPS), implemented as a digital transformation-based reform is aimed at reducing the overall time taken for approvals of building plans, while ensuring aseamless process. Owing to the implementation of the reform across 2,057 cities, including 444 AMRUT cities, India’s ranking rose to 27th position in the World Bank Doing Business Report (DBR) 2020, in the Ease of Doing Business in Construction Permits, moving up from 181 rank in DBR 2018, showing remarkable improvement since the implementation of the reform. - Credit rating exercise undertaken in 469 of the 500 Mission cities, out of which 163 cities have been found as Investible Grade. During 2019-20, 8 cities raised ₹ 3,390 crore through municipal bonds to undertake capital investment projects aimed at improving service delivery and city level infrastructure. Ministry awarded ₹ 1,839 crores as incentive to 26 States/UTs for reform implementation, including ₹ 181 crores for issuance of municipal bonds. So far 53,000 functionaries have been trained under the Mission, against a target of 45,000 functionaries. Smart Cities Mission (SCM) Smart Cities Mission (SCM) was launched on 25thJune 2015 with the objective of promoting cities that provide core infrastructure and give a decent quality of life to its citizens, a clean and sustainable environment and application of ‘Smart’ solutions. As on date, the value of tendered smart city projects is over ₹1,66,000crores, the value of work orders issued is about₹ 1,25,000 crores and the value of all completed projects is more than ₹ 27,000 crores. - An additional 1000 projects amounting to ₹32,500 crore have been tendered and 1000 projects amounting to ₹ 36,000 crore grounded during last one year. - 180% growth in the completed project in the last one year, amounting to ₹ 12,100 Crore. - The Integrated Command and Control Centres (ICCC) developed under the Smart Cities Mission have helped cities in their fight against COVID. The 47 operational ICCCs became war-rooms and have played an effective role in COVID response. - 33 ICCCs are at various stages of implementation. Smart Roads / Complete Streets, Smart Solar, Smart Water, PPPs and Vibrant Public Spaces projects are heading towards progressive paths in the Mission. - The Urban Learning Internship Program (TULIP)’ is designed for all ULBs and Smart City SPVs to engage fresh graduates as interns. More than 25,000 students have registered on the platform so far and more than 1000 internship positions have been posted by the cities. This will increase the capacity of our cities and positively engage our youth by making them market ready. - ClimateSmart Cities and DataSmart Cities are two important programs under Smart Cities Mission. They are key enablers, driving the future course of action through data driven performance management, urban innovation and institutional capacity building. - 114 India cities participated in the Ease of Living and Municipal Performance Index(EoL and MPI. Many cities have participated in the Citizen Perception Survey exercise undertaken by the Ministry under EoL. More than 3 million people have filled these surveys and given constructive feedback on their cities. - Top 20 cities have been paired as ‘Sister cities’ with 20 cities who were behind in ranking. This has generated great enthusiasm amongst cities and stakeholders, wherein cities are helping each other to learn and perform. - Smart Cities Mission is supporting interested cities in raising finance through Municipal Bonds. Recently, six cities were selected for technical assistance from US Treasury department to raise municipal bonds. - Joint efforts of Smart Cities Mission with AGNI and Invest India is fostering growth of a start-up culture in Smart Cities. The Smart Technology Showcase between the start-ups and our City administrators was undertaken by the Mission. Pradhan Mantri Awas Yojana – Urban (PMAY-U) Pradhan Mantri Awas Yojana – Urban (PMAY-U) completed five years on 25 June 2020. The scheme was launched in 2015 with the objective of providing pucca house to all eligible beneficiaries of Urban India by 2022 with the vision of ‘Housing for All’. The Mission’s journey of five years has seen several milestones. The Ministry of Housing and Urban Affairs (MoHUA) has received a validated demand of about 1.12 Cr houses under PMAY (U). Approvals for 1.05 Cr houses have already been sanctioned, of which 65 lakhs are grounded and 35 lakhs have been built and delivered to beneficiaries across the country. - The number of houses sanctioned in last five years under the Mission is almost eight times more than those sanctioned under earlier urban housing schemes during the span of 10 years. - To ensure regular flow of funds for implementation of PMAY(U), National Urban Housing Fund has been created to mobilize ₹ 60,000 Cr throughExtra Budgetary Resources over and above the budgetary allocation for the Mission. - Through the Credit Link Subsidy Scheme (CLSS),for the first time, the Middle Income Group (MIG) is being provided benefits for their housing needs. More than 10 lakh beneficiaries belonging to Economically Weaker Sections (EWS), Lower Income Group (LIG) and MIG have so far been brought under the fold of CLSS. - Government has identified many alternative and innovative technologies through a Global Housing Technology Challenge- India. 6 Light House Projects are being implementedin six states across the country which will act as live laboratories demonstrating innovative, proven construction technologies for speedier and cost-effective construction of houses which are sustainable green, eco-friendly and disaster resilient. - In 2019 only, MoHUA launched Angikaar- a campaign for change management in more than 4000 cities. The campaign addressed and enabled beneficiaries to adapt to life transformation that comes with shifting to a newly constructed house. The campaign also converged with other government schemes like Ayushman Bharat and Ujjawala so that beneficiaries could avail the benefits of these schemes. Around 20 lakh households were covered in the campaign. - In line with ‘AtmaNirbhar Bharat’, an Affordable Rental Housing Complexes (ARHCs) scheme for providing ease of living to Urban Migrants/ Poor has been announced by the Hon’ble Finance Minister on 14 May, 2020. The beneficiaries for ARHCs scheme would be the urban migrants/poor from EWS/LIG categories including labours, urban poor (street vendor, rickshaw puller, other service providers etc.), industrial workers, educational/ health institutions, hospitality sector, long term tourists, students or any other category as deemed fit by the States/UTs. - Construction activity under the scheme has had a huge impact on the other sectors of the economy with a multiplier effect in employment generation. Employment for approximately 1.65 Cr citizens has been generated through forward and backward linkages. Around 370 lakh metric tonne cement and 84 Lakh metric tonne steel has been consumed due to investment being made in the houses grounded.
english
{"word":"isochronal","definition":"Uniform in time; of equal time; performed in equal times; recurring at regular intervals; isochronal vibrations or oscillations."}
json
Routing in mobile applications presents more then mere navigation between routes (screens). It consists of functionalities and styles which are divided across platforms. Generally, routing systems inside native applications has its own look and feel as well as well defined UX which differs from android and iOS platforms. In order to achieve this “native feel”, RN community implemented a [React Navigation](https://reactnavigation.org/) library. It’s main focus presents “native-look-and-feel” while keeping the performance and extensibility. ### Official documentation [Official documentation](https://reactnavigation.org/docs/getting-started) has a lot of information and contains more than a few code examples of all important parts. Make sure to get familiar with it before continuing to read further. ### 1. Navigation file structure In order to keep your navigation maintainable and easy to upgrade, here are some guidelines which rely on library main concepts: ***Stack***, ***Tab***, ***Drawer*** and ***Parameters***. - navigation/ - stacks/ - tabs/ - drawer/ - params/ - Navigator.tsx #### 1.1 `Navigator.tsx` `Navigator.tsx` is a React functional component which defines navigation entry point. It should contain navigation structure wrapped inside `NavigationContainer`: ```typescript const Navigator: React.FC<INavigatorProps> = (props) => { return <NavigationContainer>// NAVIGATION STRUCTURE</NavigationContainer>; }; ``` #### 1.2 Stacks All navigation stacks should be wrapped as functional components inside `navigation/stacks`. For example, most common application structure consits of authentication (*login*, *register*) and main (*home*, etc..) workflow. In React Navigation terms this means that you should split your navigation stacks between those 2 flows: `AuthenticationStack` and `HomeStack`. Even though we could use only one stack with all screens, this is a bad practice in mobile development and makes the app harder to maintain as your application grows. ```typescript // AuthenticationStack.tsx const AuthenticationStack = createStackNavigator(AuthenticationStackParamList); const AuthenticationStack: React.FC<IAuthenticationStackProps> = (props) => { return ( <Stack.Navigator> <Stack.Screen component={Login} name="Login" /> <Stack.Screen component={Register} name="Register" /> // ... other screens in "Authentication" flow </Stack.Navigator> ); }; // HomeStack.tsx const HomeStack = createStackNavigator(HomeStackParamList); const HomeStack: React.FC<IHomeStackProps> = (props) => { return ( <Stack.Navigator> <Stack.Screen component={Home} name="Home" /> // ... other screens in "Home" flow </Stack.Navigator> ); }; ``` **IMPORTANT**: `NavigationContainer` component accepts single child component. This is not an issue if your application uses `Tab` or `Drawer` navigation. If you use only `Stacks` you need to create `RootStack` component which will then target all other `Stacks` inside separate `Stack.Screen` components. Using example above this `Navigator.tsx` would look like: ```typescript const RootStack = createStackNavigator(); const Navigator: React.FC<INavigatorProps> = (props) => { return ( <NavigationContainer> <RootStack.Navigator> <RootStack.Screen component={AuthenticationStack} name="AuthenticationStack" /> <RootStack.Screen component={HomeStack} name="HomeStack" /> </RootStack.Navigator> </NavigationContainer> ); }; ``` #### 1.3 Tabs Usually, applications have one navigation tab which should be in `navigation/tabs`. When using tab navigation, each `Tab.Screen` component should target a stack with related screens. ```typescript const Tab = createTabNavigator(); const TabNavigator: React.FC<ITabNavigatorProps> = (props) => { return ( <Tab.Navigator> <Tab.Screen component={AuthenticationStack} name="AuthenticationStack" /> <Tab.Screen component={HomeStack} name="HomeStack" /> </Tab.Navigator> ); }; ``` #### 1.4 Drawer Applications with drawer navigation should be defined in `navigation/drawer`. When using drawer navigation, each `Drawer.Screen` component should target a stack or single related screen. ```typescript const Drawer = createDrawerNavigator(); const DrawerNavigator: React.FC<IDrawerNavigatorProps> = (props) => { return ( <Drawer.Navigator> <Drawer.Screen component={AuthenticationStack} name="AuthenticationStack" /> <Drawer.Screen component={HomeStack} name="HomeStack" /> </Drawer.Navigator> ); }; ``` #### 1.4 Parameters (Typescript) To fully use the power of Typescript, `navigation/params` folder should contain types and interfaces for all stacks used inside the application. Since React Navigation handles `Tab` and `Drawer` navigations in the background, there is no need for any type definitions. Each stack should have its parameters defined in a separate file. The parameters file consists of 3 main parts: 1. List of screens used inside of stack with related `route` params defined as `type`. 2. Screen `route` parameters defined as `interface` 3. Stack screen props defined as `type` Example: 1. ```typescript export type HomeStackParamList = { Home: IHomeRouteProps; // ... other HomeStack screens }; ``` 2. ```typescript export interface IHomeRouteProps { propName: propValue; ... }; ``` 3. ```typescript export type HomeStackScreenProps<T extends keyof HomeStackParamList> = { navigation: StackNavigationProp<HomeStackParamList, T>; route: RouteProp<HomeStackParamList, T>; }; ``` Each screen inside the application inherits `navigation` and `route` props from React Navigation. Type (3) should be used as a typing for screen props which basically gives code completion for all navigation and routing parameters inside of the screen. Correct use: 1. Create stack with related types: ```typescript const HomeStack = createStackNavigator<HomeStackParamsList>(); ``` 2. Add screen types to each screen components props: ```typescript const Home: React.FC<HomeStackScreenProps<'Home'>> = ({ navigation, route}) => (...); ``` **IMPORTANT**: Above route types (2) won't work for nested stacks. Correct route types: ```typescript type NestedRouteParams<T> = { [K in keyof T]: undefined extends T[K] ? { screen: K; params?: T[K] } : { screen: K; params: T[K] }; }[keyof T]; ``` Example: `HomeStack` contains `Home` screen and `UserStack`, which then contains `Profile` screen. In that case our params list type looks like: ```typescript export type HomeStackParamList = { Home: IHomeRouteProps; ProfileStack: NestedRouteParams<ProfileStackParamList>; }; ``` This way we can easily navigate to each screen inside `ProfileStack` from anywhere inside `HomeStack`: ```typescript navigation.navigate("ProfileStack", { screen: "Profile", params: { /* params */ }, // route params }); ``` ### Tips 1. `Header` component height differs between android & iOS. `android: 56, iOS: 44 + insetTop`. `insetTop` equals to size of the status bar + top notch. To get the exact size of the notch (top, bottom) you should use `react-native-safe-area-context` library. Library implements `useSafeAreaInsets` hook which returns `inset` object containing definitions of top and bottom insets: `const { top, bottom } = useSafeAreInsets()` Since newer android devices started to add notch as well, you should always define your `Header` height using `height + topInset` value.
markdown
<reponame>JefferyLukas/SRIs {"apexcharts.css":"<KEY>,"apexcharts.js":"<KEY>,"apexcharts.min.css":"<KEY>,"apexcharts.min.js":"<KEY>}
json
{"FearfulSymmetry": ["AsteroidsMonster", "BeamOWar", "SpotTheImposter", "EvilTwin", "JuxtaposedHalvesShot", "MirroredConfrontationShot", "BashBrothers", "MirrorMatch", "DoubleKnockout", "MutualDisadvantage", "DittoFighter", "TropeNamer", "HumongousMecha", "EvilTwin", "BloodKnight", "DownplayedTrope", "SuperMode", "HeroicBuild", "LeanAndMean", "TournamentArc", "DoubleKnockout", "BattleInTheCenterOfTheMind", "ShowWithinAShow", "BeatThemAtTheirOwnGame", "TheMovie", "FinishingMove", "FanNickname", "BattleInTheCenterOfTheMind", "MutualKill", "UpToEleven", "JerkassRealization", "KiManipulation", "AttackReflector", "AlternateUniverse", "TheAce", "RapidFireFisticuffs", "EvilTwin", "BloodKnight", "DownplayedTrope", "SuperMode", "HeroicBuild", "LeanAndMean", "MutualKill", "ExpandedUniverse", "CloningBlues", "PlayedForLaughs", "ExactlyWhatItSaysOnTheTin", "CainAndAbel", "SiblingRivalry", "KarmicDeath", "LaserBlade", "SheatheYourSword", "MirrorUniverse", "FridgeHorror", "CombatPragmatist", "SphereOfDestruction", "FinishingMove", "CrossCounter", "IShallTauntYou", "ClimaxBoss", "BladeRun", "DrunkOnTheDarkSide", "FinishingMove", "OldMaster", "DuelBoss", "BrainwashedAndCrazy", "MirrorBoss", "BFS", "CloningBlues", "ExaggeratedTrope", "ZigZaggedTrope", "PlayerCharacter", "DoubleKnockout", "DrunkOnTheDarkSide", "FinishingMove", "OldMaster", "DuelBoss", "BrainwashedAndCrazy", "MirrorBoss", "BFS", "ExaggeratedTrope", "StormOfBlades", "StoryBreakerPower", "GuileHero", "TheTrickster", "EvilTwin", "SarcasmMode", "Animorphism", "BackToBackBadasses", "CutShort", "CloningBlues", "PunchParry", "WimpFight", "ApologeticAttacker", "ItMakesSenseInContext", "LetsFightLikeGentlemen", "ShootTheBullet"]}
json
Bijnor: The state Sugar Cane Authority has written to the central government to increase the quota of sugar that mills can sell to 10 lakh tonnes per month in view of the pending dues of farmers amounting to Rs 12,000 crore. As per quota fixed by the central government, mills in the state can sell sugar worth Rs 1,650 crore every month, thereby making it all the more difficult for the them to clear pending dues. On its part, state government has announced to provide a subsidy of Rs 5.50 per quintal of sugarcane to the mills but this process will take a long time, say observers. The just concluded crushing season witnessed bumper sugar production in the state. All the 119 sugar mills produced a total of 121 lakh tonnes sugar. As a result, sugar prices have nosedived to Rs 2,500 per quintal. Mill owners demanded that government control sugar prices. They wanted that minimum price of sugar should be fixed like sugarcane crop. With sugar prices tumbling, central government set a quota for the sugar to be sold by all mills. And minimum price of sugar was fixed at Rs 2,900 per quintal. For UP, central government allotted a quota of 6.25 lakh tonnes in June and 5.46 lakh tonnes for July. As per available data, mills are able to sell only around Rs 1,650 crore of sugar every month. At this pace of selling sugar, the mills cannot clear dues even in seven months. According to official sources, if mills want, they can clear the dues by taking loans from banks. But they are unlikely to do so as they have to pay an interest on loans. However, most of the mills owners do not pay interest on dues to farmers. Bijnor: The state Sugar Cane Authority has written to the central government to increase the quota of sugar that mills can sell to 10 lakh tonnes per month in view of the pending dues of farmers amounting to Rs 12,000 crore.
english
Global VC firm Accel has announced a new $4 billion later-stage fund to provide expansion capital to promising companies within its own portfolio worldwide, as well as other aspiring firms. Accel set up local teams and establish a deep presence in exciting regions such as Europe (since 2000) and India (since 2008). The VC firm has a sizable presence in India and has invested in companies like Flipkart (now Walmart-owned), Freshworks, Swiggy, Spinny, Vedantu, Zetwerk, Infra. Market, Moglix, Browserstack and others. In March this year, Accel announced its seventh India fund with $650 million. "Our decades-long experience has also taught us the importance of patience and discipline - especially during periods of volatility and change like we are experiencing today," Accel said in a statement late on Tuesday. "With that in mind, we are announcing the close of a $4 billion global, later-stage fund. This fund is a critical element in our global strategy," the firm said. The $4 billion fund also complements its early-stage and growth-stage funds where "we will stay focused on being the first partner to Seed, Series A, and bootstrapped or lightly-capitalized businesses". Other companies where Accel has invested in include Atlassian (Sydney), Celonis (Munich), Chainalysis (New York), CrowdStrike (Irvine), Slack (Vancouver), Spotify (Stockholm), UiPath (Bucharest) and dozens more. "Through this prepared approach, we can strip away competing distractions and focus on helping these exceptional teams build defining companies," said the VC firm.
english
New Delhi: Ten identical stone-clad, doughnut-shaped buildings housing all the 51 central government ministries with 51,000 employees. An underground shuttle linked to the metro, connecting all the buildings. Smart technology-driven offices surrounded by greenery, a modern conference centre and landscaped lawns. This is how the Central Secretariat complex will look like after one of the most ambitious urban upgrade projects of Lutyens Delhi is completed, government sources told ThePrint. It is part of the Central Vista Redevelopment Project, which also includes a new Parliament building that will be ready by 2022. The first three office buildings of the Central Secretariat complex will come up in the plot where the Indira Gandhi National Centre for the Arts stands and will be completed by 2023. A far more complex project than the new Parliament building, both in terms of size and managing the logistics, preparatory work for the Central Secretariat revamp is under way in full swing, with HCP Design, Planning and Management Private Limited, the project architect giving finishing touches to the design. The Central Secretariat complex currently has offices of 22 Union ministries, housing 41,000 employees, and appears almost run down at many places. The ten stone-clad buildings will come up on four plots along the Central Vista — five on either side of the Rajpath — where different ministries are currently located. The old structures will be demolished to make way for the new buildings. The height of all the buildings will be 42 m (ground + six floors), which will be lower than India Gate. The exteriors of all the buildings will be identical to the other surrounding Lutyens buildings. According to the proposed design, each of the four plots will have a cluster of three doughnut-shaped buildings, housing different offices. And there will be a rectangular courtyard with big trees in the middle. The ground floor of each of the buildings will have shared facilities like conference halls and cafes. An important feature of the proposed plan is the thrust given to transit-oriented development. According to government sources, the design being firmed up by the architectural firm proposes building an underground people mover (kind of an electric vehicle with automated carriages). It will be built in a loop below the ground level and will connect to the metro that runs perpendicularly across the Central Vista, on the lines of the interconnected airport terminals in Dubai or Singapore. “Office goers can get out of the metro, take the shuttle and reach the basement of their respective office block. From there they can take an elevator to go to their office,” a government source said. “Being connected to the metro by an underground people mover, they will also promote the use of public transport,” Patel said. Besides the underground shuttle, an overground bus route will also connect all the buildings. Vigyan Bhawan, the government’s main convention centre, will be among the structures that will be demolished. A modern central conference centre with all the latest amenities will come up adjacent to the National Archives, one of the handful of buildings that is not being demolished. Senior housing ministry officials, who did not want to be named, said the Central Secretariat is being designed to make it compact. “The character of the area is not going to change in any way. It’s just that we are making it more efficient by optimally using the space available to cater to the growing requirement,” said a senior housing ministry official.
english
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.client.event; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.Element; import com.zimbra.common.soap.MailConstants; import com.zimbra.client.ZJSONObject; import org.json.JSONException; public class ZModifyMountpointEvent extends ZModifyFolderEvent { public ZModifyMountpointEvent(Element e) throws ServiceException { super(e); } /** * @param defaultValue value to return if unchanged * @return new name or defaultValue if unchanged */ public String getOwnerDisplayName(String defaultValue) { return mFolderEl.getAttribute(MailConstants.A_OWNER_NAME, defaultValue); } /** * @param defaultValue value to return if unchanged * @return new name or defaultValue if unchanged */ public String getRemoteId(String defaultValue) { return mFolderEl.getAttribute(MailConstants.A_REMOTE_ID, defaultValue); } /** * @param defaultValue value to return if unchanged * @return new name or defaultValue if unchanged */ public String getOwnerId(String defaultValue) { return mFolderEl.getAttribute(MailConstants.A_ZIMBRA_ID, defaultValue); } public ZJSONObject toZJSONObject() throws JSONException { ZJSONObject zjo = super.toZJSONObject(); if (getOwnerId(null) != null) zjo.put("ownerId", getOwnerId(null)); if (getOwnerDisplayName(null) != null) zjo.put("ownerDisplayName", getOwnerDisplayName(null)); if (getRemoteId(null) != null) zjo.put("remoteId", getRemoteId(null)); return zjo; } }
java
<gh_stars>1-10 {"summaries":[{"symbol":{"__symbol":0,"members":[]},"metadata":{"__symbolic":"class"}},{"symbol":{"__symbol":1,"members":[]},"metadata":{"__symbolic":"class"}},{"symbol":{"__symbol":2,"members":[]},"metadata":{"__symbol":3,"members":[]}},{"symbol":{"__symbol":4,"members":[]},"metadata":{"__symbol":5,"members":[]}}],"symbols":[{"__symbol":0,"name":"NativeDateModule","filePath":"/Users/alan/app/ales/salon/node_modules/@angular/material/typings/core/datetime/index.d.ts"},{"__symbol":1,"name":"MdNativeDateModule","filePath":"/Users/alan/app/ales/salon/node_modules/@angular/material/typings/core/datetime/index.d.ts"},{"__symbol":2,"name":"DateAdapter","filePath":"/Users/alan/app/ales/salon/node_modules/@angular/material/typings/core/datetime/index.d.ts"},{"__symbol":3,"name":"DateAdapter","filePath":"/Users/alan/app/ales/salon/node_modules/@angular/material/typings/core/datetime/date-adapter.d.ts"},{"__symbol":4,"name":"NativeDateAdapter","filePath":"/Users/alan/app/ales/salon/node_modules/@angular/material/typings/core/datetime/index.d.ts"},{"__symbol":5,"name":"NativeDateAdapter","filePath":"/Users/alan/app/ales/salon/node_modules/@angular/material/typings/core/datetime/native-date-adapter.d.ts"}]}
json
The Covid-19 pandemic has undone a lot of progress towards ending child labour, globally. What can Bangladesh do to recover some of that progress? We do have a lot of legislative measures in Bangladesh, but there still need to be reforms in terms of defining the age of the child that is consistent with the Children Act 2013 on the rights of the child. The labour law in 2006 focuses more on formal sectors, while children are mainly engaged in non-formal sectors, so that needs to be brought under the legal system. The government-issued circulars of engagement of children in hazardous labour lists 38 different categories of jobs involving hazardous labour. I think we need to simplify this system. There's also a huge gap in the child protection system and we need to strengthen the social service workforce so that families have access to social workers and can prevent the push and pull factors that lead these children into hazardous labour or to being on the streets. Domestic labour of children is still widespread but often overlooked. What can be done to stop this form of child labour? In the domestic sphere, it is mostly girls being employed and there is no regulatory framework to oppose this, because in this particular category of "domestic labour" there is no required minimum age, no fixed payment or working hours, and no union to protect these workers. These children also don't have access to education unless the employer takes initiative for it. Various studies have shown that this is a hazardous form of child labour and it is very risky for children. Many of these child domestic workers, particularly the girls, are experiencing high levels of violence, abuse and exploitation. If they are not compliant they face violence, including corporal punishment, sexual violence and even rape. The government has adopted the Domestic Worker Protection and Welfare Policy 2015, but it does not list it as hazardous work. Many families send their children to domestic work, mostly due to poverty, but there is also a lack of awareness about the impact on children of this work. We need to be doing much larger awareness campaigns, strengthening our social protection support (such as cash for families that are in certain levels of poverty), and we need to be ensuring that children are going to school. We also need to empower girls with life skills and other employability skills so that this is not their only option to get out of poverty. You can really understand why a family would think this is the best option because the assumption is that, in that environment, they will be protected. Awareness campaigns can make people understand that this has a lifelong impact on children and they do miss out on other skill sets that would enable them to help their families to get out of poverty. Otherwise, it creates a cycle where they just stay where they are, which is very dangerous. What are the main challenges when it comes to implementing awareness campaigns about child labour and combatting it on a large scale? I think we are lucky that there are government counterparts in Bangladesh that are really committed to the cause. UNICEF works with the Ministry of Social Welfare (MSW) and the Ministry of Women and Children Affairs (MOWCA) on strengthening the child protection and the social service systems. We are looking into how we can expand them, but it needs to be a national approach so that every location can have a social worker. At the moment, there are just over 3,500 government social workers and we need around 100,000 if we are going to reach about 68,000 villages across the country, where social/community workers can work at the grassroots levels to prevent much of the damage caused by hazardous child labour. Unfortunately due to Covid-19, children have been out of school for a long time and it is easier now for them to be pushed into the workforce. I think being out of school for such a long time is going to have a really big impact on their protection, which we will have to deal with. We also need to make sure we have a child responsive social protection system for children who are very vulnerable. Their families are supposedly receiving cash grants, but we need to ensure that the most vulnerable families are getting them so their children are protected from being pushed into dangerous labour and can eventually go back to school. Do you think the proposed FY2021-22 budget allocations put enough emphasis on protecting children from child labour? It is never enough. In any country, this area is not funded to the extent that we would want. But the good thing is that it has at least been more prioritised with time, and it's really great progress that it has started to increase. People are starting to see that not supporting child protection will have long-term development impacts on the country. The outcomes for child labourers will be far more negative and this will cost the country a lot more money when they are in adulthood. The cost of that in percentage of the GDP is much higher than people would imagine. Child protection has to be more than social protection or cash transfer. We have to look at a more systemic approach on how to increase the social service workforce to physically work with families and communities to shift their thinking regarding child labour. However, the recent budget does not reflect that. There has not been a massive increase in social workers, for example. In view of the pandemic, how likely do you think it is that the Sustainable Development Goal (SDG) target 8. 7 of ending all forms of child labour by 2025 will be achieved? I think it is definitely achievable in Bangladesh because there is a lot of commitment within the MSW and MOWCA towards these SDGs, and we are looking into how we can extend these systems down to the grassroots levels. At the moment, UNICEF has a partnership with the Department of Social Services to create evidence and formulate policies, strategies and legal measures to make the Children Act 2013 more effective, and this includes ensuring the Act has a budget attached to it as soon as possible. They are also very supportive in strengthening the social service workforce. Last year, social workers took over 180,000 calls on the child helpline, which is four times the number of calls they would usually take in a year. This was not only due to the support of UNICEF but also through the government's commitment to not let any child's call go unanswered. I feel very positive about Bangladesh achieving this target also because the government is always open to any creative solutions that we come up with. The child protection service hubs we put up on streets in various cities (with the DSS and MOWCA) last year attracted thousands of children, many of whom were reunited with their families and taken back home because they had access to help from social workers in the hubs. What factors do you think drove child labour during the pandemic? One of the main driving factors was that children were not in school and also did not have access to digital devices (and to online opportunities for education). A lot of people lost their jobs and families were struggling, so they would take any option to earn money and sometimes that would have to be through their children. I do think not having a child protection system that works at the grassroots levels impacts whether someone can intervene. Families resort to child labour due to desperation and not many options being available to them. They are trying as hard as they can to survive and no one should judge them for that. I have been doing child protection for nearly 25 years now and I have never really met families that want to hurt their children. It's always because they don't know any better. They are always looking for options for survival for their children and for themselves. That is why the help of even one social worker, which does not cost a lot of money, can save a life or change a family's trajectory. What was very helpful during the lockdown was the government recognising these social workers as being essential, which allowed them to continue working during that time. In general, what areas must Bangladesh work on first and foremost to eliminate the worst forms of child labour? We have to first look into the industries that produce these kinds of labour. There needs to be a multi-sectoral approach, with the justice, social service and health systems involved. In Bangladesh, though people do not want to talk about it because of how horrifying it is, there is sexual exploitation and abuse of children in child labour. We have to create systems that can respond to this. We have to look at some of the jobs which are not traditionally in the lists of hazardous forms of child labour and try to minimise those as well. It comes down to awareness-building, having people understand the negative long-term impacts on children of child labour, and the need to have a child protection system that reaches the grassroots level—which we don't have here yet. The Children Act 2013 is a really important piece of legislation, but it doesn't have agreed rules or a budget attached to it yet, which has hindered its implementation. We're working with the government now to try and overcome that, which is essential in protecting children. But I really want it to go across that, I've worked in many countries around the world, and the government workers I've worked with here really are committed and they really care. So what we need to do now is to match that with a budget, and we can definitely change the world in the next few years.
english
Tanggal Rilis: Note: To improve the information presented in the history pages and related KBs and make them more useful to our customers, we have created an anonymous survey for you to share your comments and feedback. For information about Windows update terminology, see the article about the types of Windows updates and the monthly quality update types. For an overview of Windows 10, version 1809, see its update history page. Addresses security issues for your Windows operating system. This security update includes improvements that were a part of update KB5012636 (released April 21, 2022) and also addresses the following issues: This update contains miscellaneous security improvements to internal OS functionality. No additional issues were documented for this release. If you installed earlier updates, only the new updates contained in this package will be downloaded and installed on your device. For more information about security vulnerabilities, please refer to the new Security Update Guide website and the May 2022 Security Updates. This update makes quality improvements to the servicing stack, which is the component that installs Windows updates. Servicing stack updates (SSU) ensure that you have a robust and reliable servicing stack so that your devices can receive and install Microsoft updates. After installing KB4493509, devices with some Asian language packs installed may receive the error, "0x800f0982 - PSFX_E_MATCHING_COMPONENT_NOT_FOUND." Note If reinstalling the language pack does not mitigate the issue, reset your PC as follows: Microsoft is working on a resolution and will provide an update in an upcoming release. After installing KB5001342 or later, the Cluster Service might fail to start because a Cluster Network Driver is not found. This issue occurs because of an update to the PnP class drivers used by this service. After about 20 minutes, you should be able to restart your device and not encounter this issue. After installing the Windows updates released January 11, 2022 or later Windows versions on an affected version of Windows, recovery discs (CD or DVD) created by using the Backup and Restore (Windows 7) app in Control Panel might be unable to start. Recovery discs that were created by using the Backup and Restore (Windows 7) app on devices which have installed Windows updates released before January 11, 2022 are not affected by this issue and should start as expected. This issue is addressed in KB5014022. Windows server computers might log Event ID 40 in the System event log each time a Group Policy is updated or refreshed on a server or client. The error is found with the Description, ”The event logging service encountered an error when attempting to apply one or more policy settings.” This issue occurs after installing Windows updates released on or after January 11, 2022. The gpupdate and Group Policy Object (GPO) refresh tasks will trigger this error when they run (default run times for these tasks is every 90-120 minutes on member servers or 5 minutes on domain controllers). This issue occurs specifically after you configure any setting under Computer Configuration > Windows Components > Event Log Service > Security. Settings under Computer Configuration > Policies > WindowsSettings > Security Settings > Event Log do not trigger this error and can be used. IMPORTANT The errors described in this issue do not prevent Security log changes from being applied. This issue is addressed in KB5014022. After installing updates released May 10, 2022 on your domain controllers, you might see machine certificate authentication failures on the server or client for services such as Network Policy Server (NPS), Routing and Remote access Service (RRAS), Radius, Extensible Authentication Protocol (EAP), and Protected Extensible Authentication Protocol (PEAP). An issue has been found related to how the mapping of certificates to machine accounts is being handled by the domain controller. Note Installation of updates released May 10, 2022, on client Windows devices and non-domain controller Windows Servers will not cause this issue. This issue only affects installation of May 10, 2022, updates installed on servers used as domain controllers. The preferred mitigation for this issue is to manually map certificates to a machine account in Active Directory. For instructions, please see Certificate Mapping. Note The instructions are the same for mapping certificates to user or machine accounts in Active Directory. If the preferred mitigation will not work in your environment, please see KB5014754—Certificate-based authentication changes on Windows domain controllers for other possible mitigations in the SChannel registry key section. Note Any other mitigation except the preferred mitigations might lower or disable security hardening. This issue was addressed in out-of-band updates released May 19, 2022 for installation on all Domain Controllers in your environment, as well as all intermediary application servers such as Network Policy Servers (NPS), RADIUS, Certification Authority (CA), or web servers which passes the authentication certificate from the client being authenticated to the authenticating DC. If you used any workaround or mitigations for this issue, they are no longer needed, and we recommend you remove them. This includes the removal of the registry key (CertificateMappingMethods = 0x1F) documented in the SChannel registry key section of KB5014754. There is no action needed on the client side to resolve this authentication issue. To get the standalone package for these out-of-band updates, search for the KB number in the Microsoft Update Catalog. You can manually import these updates into Windows Server Update Services (WSUS) and Microsoft Endpoint Configuration Manager. For WSUS instructions, see WSUS and the Catalog Site. For Configuration Manger instructions, see Import updates from the Microsoft Update Catalog. Note The below updates are not available from Windows Update and will not install automatically. Cumulative updates: Note You do not need to apply any previous update before installing these cumulative updates. If you have already installed updates released May 10, 2022, you do not need to uninstall the affected updates before installing any later updates including the updates listed above. Microsoft now combines the latest servicing stack update (SSU) for your operating system with the latest cumulative update (LCU). SSUs improve the reliability of the update process to mitigate potential issues while installing the LCU. For general information about SSUs, see Servicing stack updates and Servicing Stack Updates (SSU): Frequently Asked Questions. You must install the August 10, 2021 SSU (KB5005112) before installing the LCU. None. This update will be downloaded and installed automatically from Windows Update. None. This update will be downloaded and installed automatically from Windows Update in accordance with configured policies. To get the standalone package for this update, go to the Microsoft Update Catalog website. Windows Server Update Services (WSUS) This update will automatically sync with WSUS if you configure Products and Classifications as follows: To remove the LCU after installing the combined SSU and LCU package, use the DISM/Remove-Package command line option with the LCU package name as the argument. You can find the package name by using this command: DISM /online /get-packages. Running Windows Update Standalone Installer (wusa.exe) with the /uninstall switch on the combined package will not work because the combined package contains the SSU. You cannot remove the SSU from the system after installation. For a list of the files that are provided in this update, download the file information for cumulative update 5013941. For a list of the files that are provided in the servicing stack update, download the file information for the SSU - version 17763.2865.
english
XPENG obtains new energy vehicles specialized license plate, to deliver cars this year. On March 21, Chinese electric car startup Xiaopeng Motors, also known as XPENG, successfully passed its first batch of production model vehicle (1.0) reviews conducted by the Fangcun branch of Guangzhou Traffic Police Detachment’s vehicle management department, obtaining the first specialized license plate for new energy vehicles. XPENG has completed the entire process of automotive design, research and development, manufacturing, delivery and licensing. XPENG‘s 1.0 production model received product qualification in July 2017 from the Ministry of Industry and Information Technology. On Oct. 12 2017, XPENG assembled its first batch of cars and delivered them to internal staff. These cars were not sold on the market. Up to now, the 1.0 model has been delivered to nearly 200 employees and have completed nearly five million kilometers, or three million miles, in testing mileage. The 1.0 models were tested in Heihe, Heilongjiang province; Turpan, Xinjiang province; and Golmud, Qinghai province for nearly 10,000 hours. “The license plate issuance is a critical event for XPENG. The license plate review is a comprehensive assessment of the system capability of the vehicle manufacturer,” said Xiaopeng He, thefounder of XPENG. Kengkun Li, who comes from South Korea, is a performance integration engineer of XPENG Automobile Technology Center. He was the first XPENG 1.0 vehicle owner with the specialized license plate. XPENG will be publicly listed and deliver its first market-oriented mass-produced model, the G3, this year. Based on the 1.0 mass-produced model, the G3 will have more mature manufacturing and supply chain. The G3 is equipped with a roof camera and spacious cabin. Its cockpit will feature a standard 12.3-inch full LCD screen and 15.6-inch touch control panel, which integrates functions such as online music, map navigation, real-time weather and vehicle control. The driver can also control all functions through its voice recognition system. In addition, the G3 will be equipped with autonomous driving hardware, 25 smart sensors for localized autonomous driving, and autonomous parking capabilities.
english
import json import os from requests.auth import HTTPBasicAuth from moneywagon.core import ( Service, NoService, NoData, ServiceError, SkipThisService, currency_to_protocol, decompile_scriptPubKey ) from bitcoin import deserialize import arrow from bs4 import BeautifulSoup import re import hmac, hashlib, time, requests, base64 from requests.auth import AuthBase try: from urllib import urlencode, quote_plus except ImportError: from urllib.parse import urlencode, quote_plus def make_standard_nonce(small=False): num = int(time.time() * 1000) if small: return str(num - 1506215312123) return str(num) def make_stateful_nonce(exchange): path = os.path.expanduser('~/.moneywagon_state') if not os.path.exists(path): # make with open(path, "w+") as f: f.write('{}') with open(path) as f: j = json.loads(f.read()) if exchange not in j: j[exchange] = {'last_used_nonce': 0} nonce = j[exchange].get('last_used_nonce', 0) + 1 j[exchange]['last_used_nonce'] = nonce with open(path, "w") as f: f.write(json.dumps(j)) return nonce def eight_decimal_places(amount, format="str"): """ >>> eight_decimal_places(3.12345678912345) "3.12345679" >>> eight_decimal_places("3.12345678912345") "3.12345679" >>> eight_decimal_places(3.12345678912345, format='float') 3.12345679 >>> eight_decimal_places("3.12345678912345", format='float') 3.12345679 """ if type(amount) == str: return amount if format == 'str': return "%.8f" % amount if format == 'float': return float("%.8f" % amount) class Bitstamp(Service): service_id = 1 supported_cryptos = ['btc'] api_homepage = "https://www.bitstamp.net/api/" name = "Bitstamp" exchange_fee_rate = 0.0025 def __init__(self, customer_id=None, **kwargs): self.customer_id = customer_id super(Bitstamp, self).__init__(**kwargs) def make_market(self, crypto, fiat): return ("%s%s" % (crypto, fiat)).lower() def get_current_price(self, crypto, fiat): url = "https://www.bitstamp.net/api/v2/ticker/%s" % ( self.make_market(crypto, fiat) ) response = self.get_url(url).json() return float(response['last']) def get_pairs(self): return ['btc-usd', 'btc-eur', 'bch-btc', 'bch-usd', 'xrp-usd', 'xrp-eur', 'xrp-btc'] def get_orderbook(self, crypto, fiat): url = "https://www.bitstamp.net/api/v2/order_book/%s/" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']], 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']] } def _make_signature(self, nonce): message = nonce + self.customer_id + self.api_key return hmac.new( self.api_secret, msg=message, digestmod=hashlib.sha256 ).hexdigest().upper() def _auth_request(self, url, params): nonce = make_standard_nonce() params.update({ 'nonce': nonce, 'signature': self._make_signature(nonce), 'key': self.api_key, }) return self.post_url(url, params) def get_exchange_balance(self, currency, type="available"): url = "https://www.bitstamp.net/api/balance/" resp = self._auth_request(url, {}).json() try: return float(resp["%s_%s" % (currency.lower(), type)]) except KeyError: return 0 def get_total_exchange_balances(self): url = "https://www.bitstamp.net/api/balance/" resp = self._auth_request(url, {}).json() return { code[:-8]: float(bal) for code, bal in resp.items() if code.endswith("balance") and float(bal) > 0 } def get_deposit_address(self, currency): if currency.lower() == 'btc': url = "https://www.bitstamp.net/api/bitcoin_deposit_address/" return self._auth_request(url, {}).json() if currency.lower() == 'xrp': url = "https://www.bitstamp.net/api/ripple_address/" return self._auth_request(url, {}).json()['address'] if currency.lower() in ['eth', 'ltc']: url = "https://www.bitstamp.net/api/v2/%s_address/" % currency.lower() return self._auth_request(url, {}).json()['address'] def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): if type == 'limit': url = "https://www.bitstamp.net/api/v2/%s/%s/" % ( side, self.make_market(crypto, fiat) ) resp = self._auth_request(url, { 'amount': eight_decimal_places(amount), 'price': price, }) if type == 'market': url = "https://www.bitstamp.net/api/v2/%s/market/%s/" % ( side, self.make_market(crypto, fiat) ) resp = self._auth_request(url, { 'amount': eight_decimal_places(amount), }) return resp.json() make_order.supported_types = ['limit', 'market'] make_order.minimums = {} class CoinbaseExchangeAuth(AuthBase): def __init__(self, api_key, secret_key, passphrase): self.api_key = api_key self.secret_key = secret_key self.passphrase = passphrase def __call__(self, request): timestamp = str(time.time()) message = timestamp + request.method + request.path_url + (request.body or '') hmac_key = base64.b64decode(self.secret_key) signature = hmac.new(hmac_key, message, hashlib.sha256) signature_b64 = signature.digest().encode('base64').rstrip('\n') request.headers.update({ 'CB-ACCESS-SIGN': signature_b64, 'CB-ACCESS-TIMESTAMP': timestamp, 'CB-ACCESS-KEY': self.api_key, 'CB-ACCESS-PASSPHRASE': self.passphrase, 'Content-Type': 'application/json' }) return request class GDAX(Service): service_id = 59 name = "GDAX" base_url = "https://api.gdax.com" api_homepage = "https://docs.gdax.com/" supported_cryptos = ['btc', 'ltc', 'eth', 'bch'] exchange_fee_rate = 0.0025 def __init__(self, api_pass=None, **kwargs): self.auth = None self.api_pass = api_pass super(GDAX, self).__init__(**kwargs) if self.api_key and self.api_secret and self.api_pass: self.auth = CoinbaseExchangeAuth(self.api_key, self.api_secret, self.api_pass) def check_error(self, response): if response.status_code != 200: j = response.json() raise ServiceError("GDAX returned %s error: %s" % ( response.status_code, j['message']) ) super(GDAX, self).check_error(response) def make_market(self, crypto, fiat): return ("%s-%s" % (crypto, fiat)).upper() def get_current_price(self, crypto, fiat): url = "%s/products/%s/ticker" % (self.base_url, self.make_market(crypto, fiat)) response = self.get_url(url).json() return float(response['price']) def get_pairs(self): url = "%s/products" % self.base_url r = self.get_url(url).json() return [x['id'].lower() for x in r] def get_orderbook(self, crypto, fiat): url = "%s/products/%s/book?level=3" % (self.base_url, self.make_market(crypto, fiat)) r = self.get_url(url).json() return { 'bids': [(float(x[0]), float(x[1])) for x in r['bids']], 'asks': [(float(x[0]), float(x[1])) for x in r['asks']] } def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): time_in_force = 'GTC' if type == 'fill-or-kill': type = 'limit' time_in_force = 'FOK' url = "%s/orders" % self.base_url data = { "size": eight_decimal_places(amount), "type": type, "price": price, "side": side, "time_in_force": time_in_force, "product_id": self.make_market(crypto, fiat) } response = self.post_url(url, json=data, auth=self.auth).json() return response['id'] make_order.supported_types = ['fill-or-kill', 'limit', 'market', 'stop'] make_order.minimums = {'btc': 0.0001, 'eth': 0.001, 'ltc': 0.01, 'usd': 1, 'eur': 1, 'gbp': 1} def list_orders(self, status="open"): url = "%s/orders" % self.base_url response = self.get_url(url, auth=self.auth) return response.json() def cancel_order(self, order_id): url = "%s/orders/%s" % (self.base_url, order_id) response = self.delete_url(url, auth=self.auth) return response.json() def get_exchange_balance(self, currency, type="available"): url = "%s/accounts" % self.base_url resp = self.get_url(url, auth=self.auth).json() try: match = [x for x in resp if currency.upper() == x['currency']][0] except IndexError: return 0 return float(match[type]) def get_total_exchange_balances(self): url = "%s/accounts" % self.base_url resp = self.get_url(url, auth=self.auth).json() return { x['currency'].lower(): float(x['balance']) for x in resp } def initiate_withdraw(self, currency, amount, address): url = "%s/withdrawals/crypto" % self.base_url resp = self.post_url(url, auth=self.auth, json={ 'crypto_address': address, 'currency': currency.upper(), 'amount': eight_decimal_places(amount) }) return resp.json() class BitFinex(Service): service_id = 120 api_homepage = "https://bitfinex.readme.io/v2/reference" exchange_fee_rate = 0.002 def check_error(self, response): j = response.json() if j and type(j) is list and j[0] == 'error': raise SkipThisService( "BitFinex returned Error: %s (%s)" % (j[2], j[1]) ) super(BitFinex, self).check_error(response) def parse_market(self, market): crypto = market[:3] fiat = market[3:] if crypto == 'dsh': crypto = 'dash' if crypto == 'iot': crypto = 'miota' return crypto, fiat def fix_symbol(self, symbol): if symbol == 'dash': return 'dsh' if symbol == 'miota': return 'iot' return symbol def make_market(self, crypto, fiat): return "%s%s" % ( self.fix_symbol(crypto).lower(), self.fix_symbol(fiat).lower() ) def get_pairs(self): url = "https://api.bitfinex.com/v1/symbols" r = self.get_url(url).json() return ["%s-%s" % self.parse_market(x) for x in r] def get_current_price(self, crypto, fiat): url = "https://api.bitfinex.com/v2/ticker/t%s" % self.make_market(crypto, fiat).upper() r = self.get_url(url).json() return r[6] def get_orderbook(self, crypto, fiat): url = "https://api.bitfinex.com/v1/book/%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(float(x['price']), float(x['amount'])) for x in resp['bids']], 'asks': [(float(x['price']), float(x['amount'])) for x in resp['asks']] } def _make_signature(self, path, args, nonce, version=2): if version == 2: msg = '/api/' + path + nonce + json.dumps(args) elif version == 1: msg = nonce # actually payload, but passed in as nonce return hmac.new(self.api_secret, msg, hashlib.sha384).hexdigest() def _auth_request(self, path, params): url = "https://api.bitfinex.com" nonce = make_standard_nonce() if path.startswith("/v2/"): headers = { 'bfx-nonce': nonce, 'bfx-apikey': self.api_key, 'bfx-signature': self._make_signature(path, params, nonce, version=2) } elif path.startswith("/v1/"): params['request'] = path params['nonce'] = nonce payload = base64.b64encode(json.dumps(params)) headers = { 'X-BFX-PAYLOAD': payload, 'X-BFX-APIKEY': self.api_key, 'X-BFX-SIGNATURE': self._make_signature(path, params, payload, version=1) } return self.post_url(url + path, json=params, headers=headers) def get_deposit_address(self, crypto): resp = self._auth_request("/v2/auth/r/wallets", {}) filt = [x[2] for x in resp.json() if x[1] == crypto.upper()] return filt[0] if filt else 0 def get_exchange_balance(self, currency, type="available"): curr = self.fix_symbol(currency) resp = self._auth_request("/v1/balances", {}).json() for item in resp: if item['currency'] == curr.lower(): return float(item[type]) return 0 def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): url = "/v1/order/new" resp = self._auth_request(url, { 'symbol': self.make_market(crypto, fiat), 'amount': eight_decimal_places(amount), 'price': str(price), 'side': side, 'type': 'exchange %s' % type, }) return resp.json() make_order.supported_types = ['fill-or-kill', 'market', 'limit', 'stop', 'trailing-stop'] make_order.minimums = {} def initiate_withdraw(self, crypto, amount, address): from moneywagon.crypto_data import crypto_data if crypto == 'etc': type = "ethereumc" else: type = crypto_data[crypto.lower()]['name'].lower() resp = self._auth_request("/v1/withdraw", { "withdraw_type": type, "walletselected": "exchange", "amount": eight_decimal_places(amount), "address": address, }).json() return resp class NovaExchange(Service): service_id = 89 name = "NovaExchange" api_homepage = "https://novaexchange.com/remote/faq/" def make_market(self, crypto, fiat): return "%s_%s" % (fiat, crypto) def check_error(self, response): if response.json()['status'] == 'error': raise ServiceError("NovaExchange returned error: %s" % response.json()['message']) super(NovaExchange, self).check_error(response) def get_current_price(self, crypto, fiat): url = "https://novaexchange.com/remote/v2/market/info/%s" % self.make_market(crypto, fiat) r = self.get_url(url).json() return float(r['markets'][0]['last_price']) def get_pairs(self): url = "https://novaexchange.com/remote/v2/markets/" r = self.get_url(url).json() ret = [] for pair in r['markets']: fiat = pair['basecurrency'].lower() crypto = pair['currency'].lower() ret.append("%s-%s" % (crypto, fiat)) return ret def get_orderbook(self, crypto, fiat): url = "https://novaexchange.com/remote/v2/market/openorders/%s/both/" % ( self.make_market(crypto, fiat) ) r = self.get_url(url).json() return { 'bids': [(float(x['price']), float(x['amount'])) for x in r['buyorders']], 'asks': [(float(x['price']), float(x['amount'])) for x in r['sellorders']], } def _make_signature(self, url): return base64.b64encode( hmac.new(self.api_secret, url, hashlib.sha512).digest() ) def _auth_request(self, url, params): url += '?nonce=' + make_standard_nonce() params['apikey'] = self.api_key params['signature'] = self._make_signature(url) headers = {'content-type': 'application/x-www-form-urlencoded'} return self.post_url(url, data=params, headers=headers, timeout=60) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): url = "https://novaexchange.com/remote/v2/private/trade/%s/" % ( self.make_market(crypto, fiat) ) params = { 'tradetype': side.upper(), 'tradeamount': eight_decimal_places(amount), 'tradeprice': price, 'tradebase': 0, # indicates "amount" is in crypto units, not fiat units } resp = self._auth_request(url, params) return resp.json()['tradeitems'][0]['orderid'] make_order.minimums = {} def cancel_order(self, order_id): url = "https://novaexchange.com/remote/v2/private/cancelorder/%s/" % order_id resp = self._auth_request(url, {}) return resp.json()['status'] == 'ok' def list_orders(self, status="open"): if status == 'open': url = "https://novaexchange.com/remote/v2/private/myopenorders/" else: NotImplementedError("getting orders by status=%s not implemented yet" % status) resp = self._auth_request(url, {}) return resp.json()['items'] def get_deposit_address(self, crypto): url = "https://novaexchange.com/remote/v2/private/getdepositaddress/%s/" % crypto resp = self._auth_request(url, {}) return resp.json()['address'] def initiate_withdraw(self, crypto, amount, address): url = "https://novaexchange.com/remote/v2/private/withdraw/%s/" % crypto params = {'currency': crypto, 'amount': eight_decimal_places(amount), 'address': address} resp = self._auth_request(url, params) return resp.json() class xBTCe(Service): service_id = 90 name = "xBTCe" api_homepage = "https://www.xbtce.com/tradeapi" def get_current_price(self, crypto, fiat): if crypto.lower() == 'dash': crypto = "dsh" if fiat.lower() == 'rur': fiat = 'rub' if fiat.lower() == 'cny': fiat = 'cnh' pair = "%s%s" % (crypto.upper(), fiat.upper()) url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/ticker/%s" % pair r = self.get_url(url).json() try: return r[0]['LastSellPrice'] except IndexError: raise ServiceError("Pair not found") def get_pairs(self): url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/symbol" r = self.get_url(url).json() ret = [] for pair in r: crypto = pair['MarginCurrency'].lower() fiat = pair['ProfitCurrency'].lower() if crypto.lower() == 'dsh': crypto = "dash" if fiat.lower() == 'rub': fiat = 'rur' if fiat == 'cnh': fiat = 'cny' ret.append(("%s-%s" % (crypto, fiat))) return list(set(ret)) class OKcoin(Service): service_id = 60 name = "OKcoin" exchange_base_url = "https://www.okcoin.cn" block_base_url = "http://block.okcoin.cn" supported_cryptos = ['btc', 'ltc'] api_homepage = "https://www.okcoin.cn/rest_getStarted.html" def get_current_price(self, crypto, fiat): if not fiat == 'cny': raise SkipThisService("Only fiat=CNY supported") url = "%s/api/v1/ticker.do?symbol=%s_%s" % ( self.exchange_base_url, crypto.lower(), fiat.lower() ) response = self.get_url(url).json() return float(response['ticker']['last']) def check_error(self, response): j = response.json() if 'error_code' in j: raise ServiceError("OKcoin returned error code %s" % j['error_code']) super(OKcoin, self).check_error(response) def get_pairs(self): return ['btc-cny', 'ltc-cny'] def get_block(self, crypto, block_hash=None, block_number=None, latest=False): if latest: args = 'latest_block.do?' if block_number or block_number == 0: args = "block_height.do?block_height=%s&" % block_number if block_hash: raise SkipThisService("Block by hash not supported") url = "%s/api/v1/%ssymbol=%s" % ( self.block_base_url, args, crypto.upper() ) r = self.get_url(url).json() ret = dict( block_number=r['height'], size=r['size'], time=arrow.get(r['time'] / 1000).datetime, hash=r['hash'], txids=r['txid'], tx_count=r['txcount'], version=r['version'], mining_difficulty=r['difficulty'], total_fees=r['fee'], sent_value=r['totalOut'] ) if r.get('relayed_by'): ret['miner'] = r['relayed_by'] if r.get('previousblockhash'): ret['previous_hash'] = r['previousblockhash'] if r.get('nextblockhash'): ret['next_hash'] = r['nextblockhash'] return ret class FreeCurrencyConverter(Service): service_id = 61 base_url = "http://free.currencyconverterapi.com" api_homepage = "http://www.currencyconverterapi.com/docs" def get_fiat_exchange_rate(self, from_fiat, to_fiat): pair = "%s_%s" % (to_fiat.upper(), from_fiat.upper()) url = "%s/api/v3/convert?q=%s&compact=y" % ( self.base_url, pair ) response = self.get_url(url).json() return response[pair]['val'] class BTCChina(Service): service_id = 62 api_homepage = "https://www.btcc.com/apidocs/spot-exchange-market-data-rest-api#ticker" name = "BTCChina" def get_current_price(self, crypto, fiat): if fiat == 'usd': url = "https://spotusd-data.btcc.com/data/pro/ticker?symbol=%sUSD" % crypto.upper() key = "Last" else: url = "https://data.btcchina.com/data/ticker?market=%s%s" % ( crypto.lower(), fiat.lower() ) key = "last" response = self.get_url(url).json() if not response: raise ServiceError("Pair not supported (blank response)") return float(response['ticker'][key]) class Gemini(Service): service_id = 63 api_homepage = "https://docs.gemini.com/rest-api/" name = "Gemini" exchange_fee_rate = 0.0025 def check_error(self, response): j = response.json() if 'result' in j and j['result'] == 'error': raise ServiceError("Gemini returned error: %s" % j['reason']) super(Gemini, self).check_error(response) def make_market(self, crypto, fiat): return "%s%s" % (crypto.lower(), fiat.lower()) def get_current_price(self, crypto, fiat): url = "https://api.gemini.com/v1/pubticker/%s" % self.make_market(crypto, fiat) response = self.get_url(url).json() return float(response['last']) def get_orderbook(self, crypto, fiat): url = "https://api.gemini.com/v1/book/%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(float(x['price']), float(x['amount'])) for x in resp['bids']], 'asks': [(float(x['price']), float(x['amount'])) for x in resp['asks']] } def _make_signature(self, payload): return hmac.new(self.api_secret, payload, hashlib.sha384).hexdigest() def _auth_request(self, path, params): params['nonce'] = make_standard_nonce() params['request'] = path payload = base64.b64encode(json.dumps(params)) headers = { 'X-GEMINI-APIKEY': self.api_key, 'X-GEMINI-PAYLOAD': payload, 'X-GEMINI-SIGNATURE': self._make_signature(payload) } return self.post_url("https://api.gemini.com" + path, headers=headers) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): path = "/v1/order/new" #order_token = "" % datetime.datetime.now() opts = [] if type == 'fill-or-kill': opts = ['immediate-or-cancel'] type = "limit" if type == 'post-only': opts = ["maker-or-cancel"] type = 'limit' if type != "limit": raise NotImplementedError("Only limit orders currently supported") params = { #"client_order_id": order_token, # A client-specified order token "symbol": self.make_market(crypto, fiat), # Or any symbol from the /symbols api "amount": eight_decimal_places(amount), # Once again, a quoted number "price": str(price), "side": side, # must be "buy" or "sell" "type": "exchange %s" % type, # the order type; only "exchange limit" supported "options": opts # execution options; may be omitted for a standard limit order } resp = self._auth_request(path, params).json() return resp make_order.supported_types = ['post-only', 'limit', 'fill-or-kill'] make_order.minimums = {} def get_deposit_address(self, currency): path = "/v1/deposit/%s/newAddress" % currency.lower() resp = self._auth_request(path, {}) return resp.json()['address'] def get_exchange_balance(self, currency, type="available"): path = "/v1/balances" resp = self._auth_request(path, {}) try: match = [x for x in resp.json() if x['currency'] == currency.upper()][0] except IndexError: return 0 return float(match[type]) def get_total_exchange_balances(self): path = "/v1/balances" resp = self._auth_request(path, {}) return { x['currency'].lower(): float(x['amount']) for x in resp.json() if float(x['amount']) > 0 } class CexIO(Service): service_id = 64 api_homepage = "https://cex.io/rest-api" name = "Cex.io" exchange_fee_rate = 0.002 def __init__(self, user_id=None, **kwargs): self.user_id = user_id super(CexIO, self).__init__(**kwargs) def check_error(self, response): super(CexIO, self).check_error(response) j = response.json() if 'error' in j: raise ServiceError("CexIO returned error: %s" % j['error']) def get_current_price(self, crypto, fiat): url = "https://cex.io/api/ticker/%s/%s" % (crypto.upper(), fiat.upper()) response = self.get_url(url).json() return float(response['last']) def get_pairs(self): url = "https://cex.io/api/currency_limits" r = self.get_url(url).json()['data']['pairs'] return [("%s-%s" % (x['symbol1'], x['symbol2'])).lower() for x in r] def get_orderbook(self, crypto, fiat): url = "https://cex.io/api/order_book/%s/%s/" % (crypto.upper(), fiat.upper()) resp = self.get_url(url).json() return { 'bids': [(x[0], x[1]) for x in resp['bids']], 'asks': [(x[0], x[1]) for x in resp['asks']] } def _make_signature(self, nonce): message = nonce + self.user_id + self.api_key return hmac.new(self.api_secret, message, hashlib.sha256).hexdigest().upper() def _auth_request(self, url, params): nonce = make_standard_nonce() params['nonce'] = nonce params['signature'] = self._make_signature(nonce) params['key'] = self.api_key return self.post_url(url, params) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): url = "https://cex.io/api/place_order/%s/%s" % (crypto.upper(), fiat.upper()) if type in ('limit', 'market'): print("about to send amount to cex:", eight_decimal_places(amount)) params = { 'type': side, 'amount': eight_decimal_places(amount), } if type == 'market': params['order_type'] = 'market' if type == 'limit': params['price'] = price else: raise Exception("Order with type=%s not yet supported" % type) resp = self._auth_request(url, params).json() return resp['id'] make_order.supported_types = ['limit', 'market'] make_order.minimums = {'btc': 0.01} def list_orders(self): url = "https://cex.io/api/open_orders/" resp = self._auth_request(url, {}) return resp.json() def cancel_order(self, order_id): url = "https://cex.io/api/cancel_order/" resp = self._auth_request(url, {'id': order_id}) return resp.content == 'true' def get_deposit_address(self, crypto): url = "https://cex.io/api/get_address" resp = self._auth_request(url, {'currency': crypto.upper()}) return resp.json()['data'] def get_exchange_balance(self, currency, type="available"): url = "https://cex.io/api/balance/" resp = self._auth_request(url, {}) try: return float(resp.json()[currency.upper()]['available']) except KeyError: return 0 def get_total_exchange_balances(self): url = "https://cex.io/api/balance/" resp = self._auth_request(url, {}) return { code.lower(): float(data['available']) for code, data in resp.json().items() if code not in ['timestamp', 'username'] and float(data['available']) > 0 } class Poloniex(Service): service_id = 65 api_homepage = "https://poloniex.com/support/api/" name = "Poloniex" exchange_fee_rate = 0.0025 def check_error(self, response): j = response.json() if 'error' in j: raise ServiceError("Poloniex returned error: %s" % j['error']) super(Poloniex, self).check_error(response) def fix_symbol(self, symbol): symbol = symbol.lower() if symbol == 'usd': return 'usdt' if symbol == 'xlm': return 'str' return symbol def reverse_fix_symbol(self, symbol): symbol = symbol.lower() if symbol == 'usdt': return 'usd' if symbol == 'str': return 'xlm' return symbol def get_current_price(self, crypto, fiat): url = "https://poloniex.com/public?command=returnTicker" response = self.get_url(url).json() is_usd = False if fiat.lower() == 'usd': fiat = 'usdt' is_usd = True find_pair = "%s_%s" % (fiat.upper(), crypto.upper()) for pair, data in response.items(): if pair == find_pair: return float(data['last']) reverse_pair = "%s_%s" % (crypto.upper(), fiat.upper()) for pair, data in response.items(): if pair == reverse_pair: return 1 / float(data['last']) btc_pair = "BTC_%s" % crypto.upper() if is_usd and btc_pair in response: btc_rate = float(response['USDT_BTC']['last']) fiat_exchange = float(response[btc_pair]['last']) return fiat_exchange * btc_rate raise SkipThisService("Pair %s not supported" % find_pair) def get_pairs(self): url = "https://poloniex.com/public?command=returnTicker" r = self.get_url(url).json() ret = [] for pair in r.keys(): fiat, crypto = pair.lower().split('_') ret.append("%s-%s" % (self.reverse_fix_symbol(crypto), self.reverse_fix_symbol(fiat))) return ret def get_orderbook(self, crypto, fiat): url = "https://poloniex.com/public?command=returnOrderBook&currencyPair=%s" % ( self.make_market(crypto, fiat) ) resp = self.get_url(url).json() return { 'asks': [(float(x[0]), x[1]) for x in resp['asks']], 'bids': [(float(x[0]), x[1]) for x in resp['bids']] } def make_market(self, crypto, fiat): return ("%s_%s" % (self.fix_symbol(fiat), self.fix_symbol(crypto))).upper() def _make_signature(self, args): str_args = urlencode(args) return hmac.new(self.api_secret, str_args, hashlib.sha512).hexdigest() def _auth_request(self, args): url = "https://poloniex.com/tradingApi" args["nonce"] = make_standard_nonce() headers = { 'Sign': self._make_signature(args), 'Key': self.api_key } return self.post_url(url, args, headers=headers) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): params = {} if type == "fill-or-kill": params = {'fillOrKill': 1} if type == 'post-only': params = {'postOnly': 1} params.update({ "command": side, "currencyPair": self.make_market(crypto, fiat), "rate": price, "amount": eight_decimal_places(amount) }) r = self._auth_request(params) return r.json()['orderNumber'] make_order.supported_types = ['limit', 'fill-or-kill', 'post-only'] make_order.minimums = {} def cancel_order(self, order_id): r = self._auth_request({ "command": "cancelOrder", "orderNumber": order_id }) return r['success'] == 1 def list_orders(self, crypto=None, fiat=None): if not crypto and not fiat: pair = "all" else: self.make_market(crypto, fiat) resp = self._auth_request({ "command": "returnOpenOrders", "currencyPair": pair, }) return resp.json() def initiate_withdraw(self, crypto, amount, address): resp = self._auth_request({ "command": "withdrawl", "currency": crypto, "amount": eight_decimal_places(amount), "address": address }) return resp.json() def get_deposit_address(self, currency): c = self.fix_symbol(currency) resp = self._auth_request({"command": "returnDepositAddresses"}) address = resp.json().get(c.upper()) if not address: return self.generate_new_deposit_address(c) return address def generate_new_deposit_address(self, crypto): resp = self._auth_request({ "command": "generateNewAddress", "currency": crypto.upper() }) return resp.json()['response'] def get_exchange_balance(self, currency, type="available"): resp = self._auth_request({"command": "returnBalances"}) return float(resp.json().get(self.reverse_fix_symbol(currency).upper())) def get_total_exchange_balances(self): resp = self._auth_request({"command": "returnBalances"}) return { self.reverse_fix_symbol(code): float(bal) for code, bal in resp.json().items() if float(bal) > 0 } class Bittrex(Service): service_id = 66 api_homepage = "https://bittrex.com/home/api" exchange_fee_rate = 0.0025 def check_error(self, response): j = response.json() if not j['success']: raise ServiceError("Bittrex returned error: %s" % j['message']) super(Bittrex, self).check_error(response) def fix_symbol(self, symbol): if symbol.lower() == 'usd': return 'usdt' if symbol == 'xmy': return 'myr' if symbol == 'bcc': raise SkipThisService("BCC not supported (maybe you want BCH?)") if symbol == 'bch': return 'bcc' return symbol.lower() def reverse_fix_symbol(self, symbol): symbol = symbol.lower() if symbol == 'usdt': return 'usd' if symbol == 'bcc': return 'bch' return symbol def make_market(self, crypto, fiat): return "%s-%s" % ( self.fix_symbol(fiat).upper(), self.fix_symbol(crypto).upper() ) def get_current_price(self, crypto, fiat): url = "https://bittrex.com/api/v1.1/public/getticker?market=%s" % ( self.make_market(crypto, fiat) ) r = self.get_url(url).json() return r['result']['Last'] def get_orderbook(self, crypto, fiat): url = "https://bittrex.com/api/v1.1/public/getorderbook?market=%s&type=both" % ( self.make_market(crypto, fiat) ) r = self.get_url(url).json()['result'] return { 'bids': [(x['Rate'], x['Quantity']) for x in r['buy']], 'asks': [(x['Rate'], x['Quantity']) for x in r['sell']], } def get_pairs(self): url = "https://bittrex.com/api/v1.1/public/getmarkets" r = self.get_url(url).json()['result'] ret = [] for x in r: crypto = x['MarketCurrency'].lower() fiat = x['BaseCurrency'].lower() if fiat == 'usdt': fiat = 'usd' ret.append("%s-%s" % (crypto, fiat)) return ret def _make_signature(self, url): return hmac.new( self.api_secret.encode(), url.encode(), hashlib.sha512 ).hexdigest() def _auth_request(self, path, params): if not self.api_key or not self.api_secret: raise Exception("Trade API requires an API key and secret.") params["apikey"] = self.api_key params["nonce"] = make_standard_nonce() url = "https://bittrex.com/api" + path + "?" + urlencode(params) return self.get_url(url, headers={"apisign": self._make_signature(url)}) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): path = "/v1.1/market/%slimit" % side r = self._auth_request(path, { 'market': self.make_market(crypto, fiat), 'quantity': eight_decimal_places(amount), 'rate': price }) return r.json()['result']['uuid'] make_order.supported_types = ['limit'] make_order.minimums = {} def cancel_order(self, order_id): path = "/v1.1/market/cancel" r = self._auth_request(path, {'uuid': order_id}) return r['success'] def get_exchange_balance(self, currency, type="available"): currency = self.fix_symbol(currency) path = "/v1.1/account/getbalance" resp = self._auth_request(path, {'currency': self.fix_symbol(currency)}).json()['result'] return resp[type.capitalize()] or 0 def get_total_exchange_balances(self): path = "/v1.1/account/getbalances" resp = self._auth_request(path, {}).json()['result'] return { self.reverse_fix_symbol(x['Currency']): x['Balance'] for x in resp if x['Balance'] > 0 } def get_deposit_address(self, crypto): path = "/v1.1/account/getdepositaddress" resp = self._auth_request(path, {'currency': self.fix_symbol(crypto)}) return resp.json()['result']['Address'] def initiate_withdraw(self, crypto, amount, address): path = "/v1.1/account/withdraw" resp = self._auth_request(path, { 'currency': self.fix_symbol(crypto), 'quantity': eight_decimal_places(amount), 'address': address }) return resp.json() class Huobi(Service): service_id = 67 api_homepage = "https://github.com/huobiapi/API_Docs_en/wiki" name = "Huobi" def check_error(self, response): if response.status_code != 200: j = response.json() raise ServiceError("Huobi returned error: %s" % j['error']) super(Huobi, self).check_error(response) def get_current_price(self, crypto, fiat): if fiat.lower() == "cny": fiat = 'static' elif fiat.lower() == 'usd': pass else: raise SkipThisService("CNY and USD only fiat supported") url = "http://api.huobi.com/%smarket/detail_%s_json.js" % ( fiat.lower(), crypto.lower() ) r = self.get_url(url).json() return r['p_last'] class BTER(Service): service_id = 25 api_homepage = "https://bter.com/api" name = "BTER" def fix_symbol(self, symbol): if symbol == 'bch': return 'bcc' return symbol def make_market(self, crypto, fiat): return ("%s_%s" % (self.fix_symbol(crypto), fiat)).lower() def get_current_price(self, crypto, fiat): url = "http://data.bter.com/api/1/ticker/%s" % self.make_market(crypto, fiat) response = self.get_url(url).json() if response.get('result', '') == 'false': raise ServiceError("BTER returned error: " + r['message']) return float(response['last'] or 0) def get_pairs(self): url = "http://data.bter.com/api/1/pairs" r = self.get_url(url).json() return [x.replace("_", "-") for x in r] def get_orderbook(self, crypto, fiat): url = "http://data.bter.com/api2/1/orderBook/%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']], 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']], } def _make_signature(self, params): return hmac.new( self.api_secret, urlencode(params), hashlib.sha512 ).hexdigest() def _auth_request(self, url, params): raise Exception("Not tested") return self.post_url(url, headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Key': self.api_key, 'Sign': self._make_signature(params) }) def get_exchange_balance(self, currency, type="available"): url = "https://api.bter.com/api2/1/private/balances" resp = self._auth_request(url, {}) for curr, bal in resp.json()[type].items(): if curr == currency.upper(): return float(bal) def get_deposit_address(self, currency): url = "https://bter.com/api2/1/private/depositAddress" resp = self._auth_request(url, {'currency': currency.upper()}) return resp.json()['addr'] class Wex(Service): service_id = 7 api_homepage = "https://wex.nz/api/documentation" name = "Wex" exchange_fee_rate = 0.002 def check_error(self, response): try: j = response.json() except: raise ServiceError("Wex returned error: %s" % response.content) if 'error' in j: raise ServiceError("Wex returned error: %s" % j['error']) super(Wex, self).check_error(response) def make_market(self, crypto, fiat): return "%s_%s" % ( self.fix_symbol(crypto).lower(), self.fix_symbol(fiat).lower() ) def fix_symbol(self, symbol): if symbol == 'dash': return 'dsh' return symbol def reverse_fix_symbol(self, symbol): if symbol == 'dsh': return 'dash' return symbol def _fix_fiat_symbol(self, fiat): return fiat def get_current_price(self, crypto, fiat): pair = self.make_market(crypto, fiat) url = "https://wex.nz/api/3/ticker/" + pair response = self.get_url(url).json() return response[pair]['last'] def get_pairs(self): url = "https://wex.nz/api/3/info" r = self.get_url(url).json() return [x.replace('_', '-') for x in r['pairs'].keys()] def get_orderbook(self, crypto, fiat): m = self.make_market(crypto, fiat) url = "https://wex.nz/api/3/depth/%s" % m resp = self.get_url(url).json() return { 'bids': [(x[0], x[1]) for x in resp[m]['bids']], 'asks': [(x[0], x[1]) for x in resp[m]['asks']] } def _make_signature(self, params): return hmac.new( self.api_secret, urlencode(params), hashlib.sha512 ).hexdigest() def _auth_request(self, params): # max nonce wex will accept is 4294967294 params['nonce'] = make_stateful_nonce(self.name) headers = {"Key": self.api_key, "Sign": self._make_signature(params)} return self.post_url("https://wex.nz/tapi", params, headers=headers) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): params = { 'method': 'Trade', 'pair': self.make_market(crypto, fiat), 'type': side, 'rate': price, 'amount': eight_decimal_places(amount), } return self._auth_request(params) make_order.supported_types = ['limit'] make_order.minimums = {'btc': 0.001, 'ltc': 0.1} def get_deposit_address(self, crypto): params = {'coinName': crypto.lower(), 'method': 'CoinDepositAddress'} resp = self._auth_request(params).json() return resp['return']['address'] def get_exchange_balance(self, currency, type="available"): resp = self._auth_request({'method': 'getInfo'}).json() try: return resp['return']['funds'][self.fix_symbol(currency).lower()] except IndexError: return 0 def get_total_exchange_balances(self): resp = self._auth_request({'method': 'getInfo'}).json()['return']['funds'] return { self.reverse_fix_symbol(code): bal for code, bal in resp.items() if not code.endswith("et") and bal > 0 } def initiate_withdraw(self, currency, amount, address): resp = self._auth_request({ 'method': 'WithdrawCoin', 'coinName': self.fix_symbol(currency), 'amount': amount, 'address': address, }) return resp.json() class ViaBTC(Service): service_id = 116 def get_current_price(self, crypto, fiat): url = "https://www.viabtc.com/api/v1/market/ticker?market=%s%s" % ( crypto.upper(), fiat.upper() ) return float(self.get_url(url).json()['data']['ticker']['last']) class CryptoDao(Service): service_id = 115 api_homepage = "https://cryptodao.com/doc/api" def get_current_price(self, crypto, fiat): url = "https://cryptodao.com/api/ticker?source=%s&target=%s" % ( fiat.upper(), crypto.upper() ) r = self.get_url(url).json() return r['last'] def get_orderbook(self, crypto, fiat): url = "https://cryptodao.com/api/depth?source=%s&target=%s" % ( fiat.upper(), crypto.upper() ) resp = self.get_url(url).json() return resp class HitBTC(Service): service_id = 109 api_homepage = "https://hitbtc.com/api" exchange_fee_rate = 0.001 def check_error(self, response): j = response.json() if response.status_code in (400, 401) and 'error' in j: e = j['error'] raise SkipThisService("HitBTC returned %s %s: %s" % ( e['code'], e['message'], e['description'] )) if 'code' in j: raise SkipThisService("HitBTC returned %s: %s" % (j['code'], j['message'])) super(HitBTC, self).check_error(response) def fix_symbol(self, symbol): return symbol.lower() def make_market(self, crypto, fiat): return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper() def get_pairs(self): url = 'https://api.hitbtc.com/api/1/public/symbols' r = self.get_url(url).json()['symbols'] return [("%s-%s" % (x['commodity'], x['currency'])).lower() for x in r] def get_current_price(self, crypto, fiat): url = "https://api.hitbtc.com/api/1/public/%s/ticker" % self.make_market(crypto, fiat) r = self.get_url(url).json() return float(r['last']) def get_orderbook(self, crypto, fiat): url = "https://api.hitbtc.com/api/1/public/%s/orderbook" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']], 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']] } def _auth_request(self, path, params, method="post"): path = path + "?" + urlencode({ 'nonce': make_standard_nonce(), 'apikey': self.api_key }) headers = {"X-Signature": self._make_signature(path, params)} return self._external_request( method, "https://api.hitbtc.com" + path, params, headers=headers ) def _make_signature(self, path, params): msg = path + urlencode(params) return hmac.new(self.api_secret, msg, hashlib.sha512).hexdigest() def get_exchange_balance(self, currency, type="available"): resp = self._auth_request("/api/1/trading/balance", {}, method="get").json() c = self.fix_symbol(currency).upper() try: matched = [x for x in resp['balance'] if x['currency_code'] == c][0] except IndexError: return 0 if type == 'available': return float(matched['cash']) raise NotImplemented() def get_total_exchange_balances(self): resp = self._auth_request("/api/1/trading/balance", {}, method="get") return { self.fix_symbol(x['currency_code']): float(x['cash']) for x in resp.json()['balance'] if float(x['cash']) > 0 } def get_deposit_address(self, currency): path = "/api/1/payment/address/%s" % self.fix_symbol(currency).upper() resp = self._auth_request(path, {}, method="get").json() return resp['address'] def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): path = "/api/1/trading/new_order" import random, string clientOrderId = "".join(random.choice(string.digits + string.ascii_lowercase) for _ in range(30)) params = { 'symbol': self.make_market(crypto, fiat), 'side': side, 'price': price, 'quantity': eight_decimal_places(amount), 'clientOrderId': clientOrderId } if type == 'fill-or-kill': params['timeInForce'] = 'FOK' resp = self._auth_request(path, params).json() return resp make_order.minimums = {} make_order.supported_types = ['fill-or-kill', 'limit'] class Liqui(Service): service_id = 106 def parse_market(self, market): crypto, fiat = market.split("_") if fiat == 'usdt': fiat = 'usd' return crypto, fiat def get_pairs(self): url = "https://api.liqui.io/api/3/info" r = self.get_url(url).json()['pairs'] return ["%s-%s" % self.parse_market(x) for x in r.keys()] def make_market(self, crypto, fiat): return "%s_%s" % ( self.fix_symbol(crypto).lower(), self.fix_symbol(fiat).lower() ) def fix_symbol(self, symbol): if symbol == 'usd': return 'usdt' return symbol def get_current_price(self, crypto, fiat): pair = self.make_market(crypto, fiat) url = "https://api.liqui.io/api/3/ticker/%s" % pair return self.get_url(url).json()[pair]['last'] def get_orderbook(self, crypto, fiat): pair = self.make_market(crypto, fiat) url = "https://api.liqui.io/api/3/depth/%s" % pair return self.get_url(url).json()[pair] def _make_signature(self, params): return hmac.new( self.api_secret, "?" + urlencode(params), hashlib.sha512 ).hexdigest() def _auth_request(self, params): params['nonce'] = make_standard_nonce(small=True) headers = { 'Key':self.api_key, 'Sign': self._make_signature(params) } return self.post_url('https://api.liqui.io', params, headers=headers) def get_exchange_balance(self, currency): resp = self._auth_request({'method': 'getInfo'}).json() return resp def list_orders(self, crypto=None, fiat=None): resp = self._auth_request({'method': 'ActiveOrders'}).json() return resp class CoinOne(Service): service_id = 105 def get_pairs(self): return ['btc-krw', 'eth-krw', 'xrp-krw', 'etc-krw'] def get_current_price(self, crypto, fiat): url = "https://api.coinone.co.kr/ticker?currency=%s" % crypto.lower() return float(self.get_url(url).json()['last']) class CryptoBG(Service): service_id = 102 def get_current_price(self, crypto, fiat): url = "https://crypto.bg/api/v1/public_rates" if crypto != 'btc' or fiat != 'bgn': raise SkipThisService("Only btc-bgn supported") return float(self.get_url(url).json()['rates']['bitcoin']['bid']) class Bitso(Service): service_id = 101 def get_current_price(self, crypto, fiat): url = "https://api.bitso.com/v3/ticker/?book=%s_%s" % (crypto, fiat) r = self.get_url(url.lower()).json() return float(['payload']['last']) def get_pairs(self): url = "https://api.bitso.com/v3/available_books/" r = self.get_url(url).json()['payload'] return [x['book'].replace("_", '-') for x in r] class TradeSatoshi(Service): service_id = 96 def get_pairs(self): url = "https://tradesatoshi.com/api/public/getmarketsummaries" r = self.get_url(url).json() return [x['market'].replace("_", '-').lower() for x in r['result']] def get_current_price(self, crypto, fiat): url = "https://tradesatoshi.com/api/public/getticker?market=%s_%s" % ( crypto.upper(), fiat.upper() ) return self.get_url(url).json()['result']['last'] class UseCryptos(Service): service_id = 95 def get_pairs(self): url = "https://usecryptos.com/jsonapi/pairs" r = self.get_url(url).json() return r def get_current_price(self, crypto, fiat): pair = "%s-%s" % (crypto.lower(), fiat.lower()) url = "https://usecryptos.com/jsonapi/ticker/%s" % pair return self.get_url(url).json()['lastPrice'] class BitcoinIndonesia(Service): service_id = 94 api_homepage = "https://blog.bitcoin.co.id/wp-content/uploads/2014/03/API-Documentation-Bitcoin.co_.id_.pdf" def get_current_price(self, crypto, fiat): url = "https://vip.bitcoin.co.id/api/%s_%s/ticker" % (crypto.lower(), fiat.lower()) return float(self.get_url(url).json()['ticker']['last']) class Kraken(Service): service_id = 93 def check_error(self, response): if response.json()['error']: raise ServiceError("Kraken returned error: %s" % response.json()['error'][0]) super(Kraken, self).check_error(response) def get_pairs(self): url = "https://api.kraken.com/0/public/AssetPairs" r = self.get_url(url).json()['result'] ret = [] for name, data in r.items(): crypto = data['base'].lower() if len(crypto) == 4 and crypto.startswith('x'): crypto = crypto[1:] fiat = data['quote'].lower() if fiat.startswith("z"): fiat = fiat[1:] if crypto == 'xbt': crypto = 'btc' if fiat == 'xxbt': fiat = 'btc' if fiat == 'xeth': fiat = 'eth' ret.append("%s-%s" % (crypto, fiat)) return list(set(ret)) def get_current_price(self, crypto, fiat): if crypto != 'bch': crypto = "x" + crypto.lower() if crypto == 'xbtc': crypto = 'xxbt' fiat = "z" + fiat.lower() if fiat == 'zbtc': fiat = 'xxbt' else: # bch pairs have completely different format for some reason # my god kraken's api is terrible if fiat.lower() == 'btc': fiat = 'xbt' pair = "%s%s" % (crypto.upper(), fiat.upper()) url = "https://api.kraken.com/0/public/Ticker?pair=%s" % pair r = self.get_url(url).json()['result'] return float(r[pair]['c'][0]) class BTC38(Service): service_id = 92 api_homepage = "http://www.btc38.com/help/document/2581.html" def get_current_price(self, crypto, fiat): url = 'http://api.btc38.com/v1/ticker.php?c=%s&mk_type=%s' % (crypto, fiat) return self.get_url(url).json()['ticker']['last'] def get_pairs(self): url = "http://api.btc38.com/v1/ticker.php?c=all&mk_type=cny" cny_bases = self.get_url(url).json().keys() url = "http://api.btc38.com/v1/ticker.php?c=all&mk_type=btc" btc_bases = self.get_url(url).json().keys() return ["%s-cny" % x for x in cny_bases] + ["%s-btc" % x for x in btc_bases] class BleuTrade(Service): service_id = 91 api_homepage = 'https://bleutrade.com/help/API' def get_pairs(self): url = 'https://bleutrade.com/api/v2/public/getmarkets' r = self.get_url(url).json()['result'] return [x['MarketName'].lower().replace("_", '-') for x in r] def get_current_price(self, crypto, fiat): url = "https://bleutrade.com/api/v2/public/getticker?market=%s_%s" % ( crypto.upper(), fiat.upper() ) r = self.get_url(url).json() return float(r['result'][0]['Last']) class xBTCe(Service): service_id = 90 name = "xBTCe" api_homepage = "https://www.xbtce.com/tradeapi" def get_current_price(self, crypto, fiat): if crypto.lower() == 'dash': crypto = "dsh" if fiat.lower() == 'rur': fiat = 'rub' if fiat.lower() == 'cny': fiat = 'cnh' pair = "%s%s" % (crypto.upper(), fiat.upper()) url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/ticker/%s" % pair r = self.get_url(url).json() try: return r[0]['LastSellPrice'] except IndexError: raise ServiceError("Pair not found") def get_pairs(self): url = "https://cryptottlivewebapi.xbtce.net:8443/api/v1/public/symbol" r = self.get_url(url).json() ret = [] for pair in r: crypto = pair['MarginCurrency'].lower() fiat = pair['ProfitCurrency'].lower() if crypto.lower() == 'dsh': crypto = "dash" if fiat.lower() == 'rub': fiat = 'rur' if fiat == 'cnh': fiat = 'cny' ret.append(("%s-%s" % (crypto, fiat))) return list(set(ret)) class Cryptopia(Service): service_id = 82 api_homepage = "https://www.cryptopia.co.nz/Forum/Thread/255" exchange_fee_rate = 0.002 def check_error(self, response): r = response.json() error = r.get('Error', False) if error is not None: raise ServiceError("Cryptopia returned error: %s" % r['Error']) super(Cryptopia, self).check_error(response) def fix_symbol(self, symbol): if symbol.lower() in ['nzd', 'usd']: symbol += "t" return symbol def reverse_fix_symbol(self, symbol): symbol = symbol.lower() if symbol in ['nzdt', 'usdt']: symbol = symbol[:-1] return symbol def make_market(self, crypto, fiat): return "%s_%s" % ( self.fix_symbol(crypto).upper(), self.fix_symbol(fiat).upper() ) def get_current_price(self, crypto, fiat): url = "https://www.cryptopia.co.nz/api/GetMarket/%s" % self.make_market(crypto, fiat) r = self.get_url(url).json() return r['Data']['LastPrice'] def get_pairs(self): url = "https://www.cryptopia.co.nz/api/GetTradePairs" r = self.get_url(url).json()['Data'] ret = [] for pair in r: crypto = pair['Symbol'] fiat = pair['BaseSymbol'] if fiat.lower() == 'usdt': fiat = 'usd' ret.append(("%s-%s" % (crypto, fiat)).lower()) return ret def get_orderbook(self, crypto, fiat): url = "https://www.cryptopia.co.nz/api/GetMarketOrders/%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(x['Price'], x['Total']) for x in resp['Data']['Buy']], 'asks': [(x['Price'], x['Total']) for x in resp['Data']['Sell']] } def _make_signature_header(self, url, params): nonce = str(int(time.time())) post_data = json.dumps(params); m = hashlib.md5() m.update(post_data) requestContentBase64String = base64.b64encode(m.digest()) signature = self.api_key + "POST" + quote_plus(url).lower() + nonce + requestContentBase64String hmacsignature = base64.b64encode( hmac.new(base64.b64decode(self.api_secret), signature, hashlib.sha256).digest() ) header_value = "amx " + self.api_key + ":" + hmacsignature + ":" + nonce return {'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' } def _auth_request(self, method, args): url = "https://www.cryptopia.co.nz/Api/" + method return self.post_url(url, json=args, headers=self._make_signature_header(url, args)) def make_order(self, crypto, fiat, amount, price, type="limit", side="buy"): args = { 'Market': ("%s/%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper(), 'Type': side, 'Rate': price, 'Amount': eight_decimal_places(amount) } resp = self._auth_request("SubmitTrade", args).json() return resp['Data']['OrderId'] make_order.minimums = {} make_order.supported_types = ['limit'] def get_exchange_balance(self, currency): curr = self.fix_symbol(currency).upper() try: resp = self._auth_request('GetBalance', {'Currency': curr}) except ServiceError: return 0 for item in resp.json()['Data']: if item['Symbol'] == curr: return item['Total'] def get_total_exchange_balances(self): resp = self._auth_request('GetBalance', {}).json() #return resp.json() return { self.reverse_fix_symbol(x['Symbol']): x['Total'] for x in resp['Data'] if x['Total'] > 0 } def get_deposit_address(self, currency): curr = self.fix_symbol(currency).upper() resp = self._auth_request('GetDepositAddress', {'Currency': curr}) return resp.json()['Data']['Address'] def initiate_withdraw(self, currency, amount, address): curr = self.fix_symbol(currency).upper() resp = self._auth_request('SubmitWithdraw', { 'Currency': curr, 'Address': address, 'Amount': amount }) return resp.json() class YoBit(Service): service_id = 77 api_homepage = "https://www.yobit.net/en/api/" def get_current_price(self, crypto, fiat): pair = "%s_%s" % (crypto.lower(), fiat.lower()) url = "https://yobit.net/api/3/ticker/%s" % pair r = self.get_url(url).json() if 'error' in r: raise SkipThisService(r['error']) return r[pair]['last'] def get_pairs(self): url = 'https://yobit.net/api/3/info' r = self.get_url(url).json() return [x.replace("_", '-') for x in r['pairs'].keys()] class Yunbi(Service): service_id = 78 api_homepage = "https://yunbi.com/swagger" def get_current_price(self, crypto, fiat): if fiat.lower() != "cny": raise SkipThisService("Only CNY markets supported") url = "https://yunbi.com/api/v2/tickers/%s%s.json" % (crypto.lower(), fiat.lower()) r = self.get_url(url, headers={"Accept": "application/json"}).json() return float(r['ticker']['last']) def get_pairs(self): url = "https://yunbi.com/api/v2/markets.json" r = self.get_url(url).json() ret = [] for pair in r: ret.append(pair['name'].replace("/", '-').lower()) return ret class Vircurex(Service): service_id = 70 base_url = "https://api.vircurex.com/api" api_homepage = "https://vircurex.com/welcome/api" def check_error(self, response): j = response.json() if j['status'] != 0: raise ServiceError("Vircurex returned error: %s" % j['status_text']) super(Vircurex, self).check_error(response) def get_current_price(self, crypto, fiat): if crypto == 'blk': crypto = 'bc' url = "%s/get_last_trade.json?base=%s&alt=%s" % ( self.base_url, crypto.upper(), fiat.upper() ) r = self.get_url(url).json() return float(r['value']) def get_pairs(self): url = "%s/get_info_for_currency.json" % self.base_url r = self.get_url(url).json() ret = [] for fiat, data in r.items(): if fiat == 'status': continue for crypto, exchange_data in data.items(): pair = "%s-%s" % (crypto.lower(), fiat.lower()) ret.append(pair) return ret class LiveCoin(Service): service_id = 110 base_url = "https://api.livecoin.net" api_homepage = "https://www.livecoin.net/api/public" def get_pairs(self): url = "%s/exchange/ticker" % (self.base_url) r = self.get_url(url).json() return [x['symbol'].replace('/', '-').lower() for x in r] def get_current_price(self, crypto, fiat): url = "%s/exchange/ticker/?currencyPair=%s/%s" % ( self.base_url, crypto.upper(), fiat.upper() ) return self.get_url(url).json()['last'] class Bithumb(Service): service_id = 129 def get_current_price(self, crypto, fiat): if fiat != 'krw': raise SkipThisService("Only KRW supported") url = "https://api.bithumb.com/public/ticker/%s" % crypto.upper() resp = self.get_url(url).json() return float(resp['data']['average_price']) def get_orderbook(self, crypto, fiat): if fiat != 'krw': raise SkipThisService("Only KRW supported") url = "https://api.bithumb.com/public/orderbook/%s" % crypto resp = self.get_url(url).json()['data'] return { 'bids': [(float(x['price']), float(x['quantity'])) for x in resp['bids']], 'asks': [(float(x['price']), float(x['quantity'])) for x in resp['asks']] } class Binance(Service): service_id = 130 def check_error(self, response): j = response.json() if 'code' in j: raise ServiceError("Binance returned error: %s %s" % (j['code'], j['msg'])) super(Binance, self).check_error(response) def make_market(self, crypto, fiat): return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper() def parse_market(self, market): market = market.lower() if market.endswith("usdt"): crypto, fiat = market[:-4], "usd" elif market.endswith("eth"): crypto, fiat = market[:-3], "eth" elif market.endswith("btc"): crypto, fiat = market[:-3], "btc" else: crypto, fiat = market[:-3], market[-3:] if crypto == 'iota': crypto = 'miota' if crypto == 'bcc': crypto = 'bch' return "%s-%s" % (crypto, fiat) def fix_symbol(self, symbol): if symbol.lower() == 'usd': return 'usdt' if symbol == 'miota': return 'iota' if symbol == 'bch': return "bcc" return symbol def get_current_price(self, crypto, fiat): url = "https://www.binance.com/api/v1/ticker/allPrices" resp = self.get_url(url).json() for data in resp: if data['symbol'] == self.make_market(crypto, fiat): return float(data['price']) raise SkipThisService("Market not found") def get_pairs(self): url = "https://www.binance.com/api/v1/ticker/allPrices" resp = self.get_url(url).json() symbols = [] for data in resp: symbols.append(self.parse_market(data['symbol'])) return symbols def get_orderbook(self, crypto, fiat): url = "https://www.binance.com/api/v1/depth" resp = self.get_url(url, {'symbol': self.make_market(crypto, fiat)}).json() return { 'bids': [(float(x[1]), float(x[0])) for x in resp['bids']], 'asks': [(float(x[1]), float(x[0])) for x in resp['asks']] } def _auth_request(self, path, params, method="post"): params['timestamp'] = make_standard_nonce() params['signature'] = self._make_signature(params) headers = {"X-MBX-APIKEY": self.api_key} return self._external_request( method, "https://www.binance.com" + path, params, headers=headers ) def _make_signature(self, params): return hmac.new( self.api_secret, urlencode(params), hashlib.sha256 ).hexdigest() def get_exchange_balance(self, currency, type="available"): if type == 'available': type = 'free' else: type == 'locked' path = "/api/v3/account" resp = self._auth_request(path, {}, method="get").json() for data in resp['balances']: if data['asset'].lower() == currency.lower(): return float(data[type]) return 0 class BitFlyer(Service): service_id = 111 api_homepage = "https://bitflyer.jp/API?top_link&footer" def get_current_price(self, crypto, fiat): url = "https://api.bitflyer.jp/v1/getticker?product_code=%s" % ( self.make_market(crypto, fiat) ) r = self.get_url(url).json() return r['ltp'] def get_pairs(self): return ['btc-jpy', 'eth-btc', 'btc-usd'] def make_market(self, crypto, fiat): return ("%s_%s" % (crypto, fiat)).upper() def get_orderbook(self, crypto, fiat): if fiat.lower() == 'jpy': domain = "api.bitflyer.jp" elif fiat.lower() == 'usd': domain = "api.bitflyer.com" else: raise SkipThisService("Only jpy and usd suppported") url = "https://%s/v1/getboard?product_code=%s" % ( domain, self.make_market(crypto, fiat) ) resp = self.get_url(url).json() return { 'bids': [(x['price'], x['size']) for x in resp['bids']], 'asks': [(x['price'], x['size']) for x in resp['asks']], } def get_block(self, crypto, block_number=None, block_hash=None, latest=False): url = "https://chainflyer.bitflyer.jp/v1/block/%s" % ( block_hash or ('height/%s' % block_number if block_number else None) or ('latest' if latest else 'None') ) r = self.get_url(url).json() return dict( block_number=r['height'], time=arrow.get(r['timestamp']).datetime, #mining_difficulty=r['difficulty'], hash=r['block_hash'], next_hash=r.get('nextblockhash', None), previous_hash=r.get('prev_block'), txids=r['tx_hashes'], version=r['version'] ) class BitX(Service): service_id = 131 api_homepage = "https://www.luno.com/en/api" def parse_market(self, market): if market.startswith("XBT"): crypto = "BTC" fiat = market[3:] return crypto, fiat def fix_symbol(self, symbol): if symbol.lower() == 'btc': return 'XBT' return symbol def make_market(self, crypto, fiat): return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper() def get_current_price(self, crypto, fiat): url = "https://api.mybitx.com/api/1/ticker?pair=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return float(resp['last_trade']) def get_pairs(self): url = "https://api.mybitx.com/api/1/tickers" resp = self.get_url(url).json()['tickers'] return [ ("%s-%s" % self.parse_market(x['pair'])).lower() for x in resp ] def get_orderbook(self, crypto, fiat): url = "https://api.mybitx.com/api/1/orderbook?pair=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(float(x['price']), float(x['volume'])) for x in resp['bids']], 'asks': [(float(x['price']), float(x['volume'])) for x in resp['asks']] } class ItBit(Service): service_id = 132 def fix_symbol(self, symbol): if symbol.lower() == 'btc': return 'XBT' return symbol def make_market(self, crypto, fiat): return ("%s%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper() def get_current_price(self, crypto, fiat): url = "https://api.itbit.com/v1/markets/%s/ticker" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return float(resp['lastPrice']) def get_pairs(self): return ['btc-usd', 'btc-sgd', 'btc-eur'] def get_orderbook(self, crypto, fiat): url = "https://api.itbit.com/v1/markets/%s/order_book" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']], 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']] } def _make_signature(self): pass # https://github.com/itbit/itbit-restapi-python/blob/master/itbit_api.py class KuCoin(Service): service_id = 133 symbol_mapping = ( ('usd', 'usdt'), ) def make_market(self, crypto, fiat): return ("%s-%s" % (self.fix_symbol(crypto), self.fix_symbol(fiat))).upper() def parse_market(self, market): return super(KuCoin, self).parse_market(market.lower(), '-') def get_pairs(self): url = "https://api.kucoin.com/v1/market/open/symbols" resp = self.get_url(url).json() pairs = [] for pair in resp['data']: crypto, fiat = self.parse_market(pair['symbol']) pairs.append("%s-%s" % (crypto, fiat)) return pairs def get_orderbook(self, crypto, fiat): url = "https://api.kucoin.com/v1/open/orders?symbol=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json()['data'] return { 'bids': [(x[0], x[1]) for x in resp['BUY']], 'asks': [(x[0], x[1]) for x in resp['SELL']] } def get_current_price(self, crypto, fiat): url = "https://api.kucoin.com/v1/open/tick?symbol=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json()['data'] return resp['lastDealPrice'] class CCex(Service): service_id = 134 api_homepage = "https://c-cex.com/?id=api" base_url = "https://c-cex.com/t/api_pub.html" def check_error(self, response): if response.content == "Maintenance...": raise ServiceError("C-Cex is down for maintenance") super(CCex, self).check_error(response) def make_market(self, crypto, fiat): return "%s-%s" % (crypto.lower(), fiat.lower()) def get_current_price(self, crypto, fiat): url = "https://c-cex.com/t/%s.json" % ( self.make_market(crypto, fiat) ) response = self.get_url(url).json() return float(response['ticker']['lastprice']) def get_pairs(self): url = "https://c-cex.com/t/pairs.json" r = self.get_url(url).json() return r['pairs'] def get_orderbook(self, crypto, fiat): url = "%s?a=getorderbook&market=%s&type=both" % ( self.base_url, self.make_market(crypto, fiat) ) resp = self.get_url(url).json()['result'] return { 'bids': [(x["Rate"], x["Quantity"]) for x in resp['buy']], 'asks': [(x["Rate"], x["Quantity"]) for x in resp['sell']] } def _auth_request(self, params): params['nonce'] = make_standard_nonce() params['apikey'] = self.api_key url = "%s?%s" % (self.base_url, urlencode(params)) headers = {'apisign': self._make_signature(url)} return self.get_url(url, headers=headers) def _make_signature(self, url): return hmac.new( self.api_secret, msg=url, digestmod=hashlib.sha512 ).hexdigest() def get_exchange_balance(self, currency, type="available"): resp = self._auth_request({'a': 'getbalance', 'currency': currency}) if type == 'available': return resp.json()['Available'] def get_deposit_address(self, currency): resp = self._auth_request({'a': 'getbalance', 'currency': currency}) return resp.json()['CryptoAddress'] class CoinEx(Service): service_id = 138 def __init__(self, access_id=None, **kwargs): self.access_id = access_id return super(CoinEx, self).__init__(**kwargs) def get_pairs(self): url = "https://api.coinex.com/v1/market/list" resp = self.get_url(url).json()['data'] return [("%s-%s" % (x[:-3], x[-3:])).lower() for x in resp] def make_market(self, crypto, fiat): return ("%s%s" % (crypto, fiat)).upper() def get_current_price(self, crypto, fiat): url = "https://api.coinex.com/v1/market/ticker?market=%s" % ( self.make_market(crypto, fiat) ) resp = self.get_url(url).json() return float(resp['data']['ticker']['last']) def _auth_request(self, url, params=None): params['tonce'] = make_standard_nonce() params['access_id'] = self.access_id str_params = urlencode(sorted(params.items(), key=lambda x: x[0])) to_sign = str_params + "&secret_key=%s" % self.api_secret digest = hashlib.md5(to_sign).hexdigest().upper() return self.get_url(url + "?" + str_params, headers={ 'Content-Type': 'application/json', 'authorization': digest }) def get_exchange_balance(self, crypto): url = "https://api.coinex.com/v1/balance/" resp = self._auth_request(url, {}).json() return resp class OKEX(Service): service_id = 139 api_homepage = 'https://www.okex.com/rest_api.html' symbol_mapping = ( ('usd', 'usdt'), ) def check_error(self, response): j = response.json() if 'error_code' in j: raise ServiceError("OKEX returned error: %s" % j['error_code']) super(OKEX, self).check_error(response) def get_current_price(self, crypto, fiat): url = "https://www.okex.com/api/v1/ticker.do?symbol=%s" % ( self.make_market(crypto, fiat) ) resp = self.get_url(url).json() return float(resp['ticker']['last']) class BitZ(Service): service_id = 140 def check_error(self, response): j = response.json() if not j['code'] == 0: raise ServiceError("BitZ returned error: %s: %s" % ( j['code'], j['msg'] )) super(BitZ, self).check_error(response) def get_current_price(self, crypto, fiat): url = "https://www.bit-z.com/api_v1/ticker?coin=%s" % (self.make_market(crypto, fiat)) resp = self.get_url(url).json() return float(resp['data']['last']) class Zaif(Service): service_id = 141 def check_error(self, response): j = response.json() if 'error' in j: raise ServiceError("Zaif returned error: %s" % (j['error'])) super(Zaif, self).check_error(response) def get_current_price(self, crypto, fiat): url = "https://api.zaif.jp/api/1/ticker/%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return resp['last'] class Korbit(Service): service_id = 142 api_homepage = "https://apidocs.korbit.co.kr/" def get_current_price(self, crypto, fiat): url = "https://api.korbit.co.kr/v1/ticker?currency_pair=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return float(resp['last']) def get_orderbook(self, crypto, fiat): url = "https://api.korbit.co.kr/v1/orderbook?currency_pair=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']], 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']] } class CoinEgg(Service): service_id = 143 api_homepage = "https://www.coinegg.com/explain.api.html#partone" def get_current_price(self, crypto, fiat): if fiat.lower() != 'btc': raise SkipThisService("Only BTC markets supported") url = "https://api.coinegg.com/api/v1/ticker/?coin=%s" % crypto resp = self.get_url(url).json() return float(resp['last']) def get_orderbook(self, crypto, fiat): if fiat.lower() != 'btc': raise SkipThisService("Only BTC markets supported") url = "https://api.coinegg.com/api/v1/depth/" resp = self.get_url(url).json() return { 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']], 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']] } class ZB(Service): service_id = 144 api_homepage = "https://www.zb.com/i/developer" symbol_mapping = ( ('usd', 'usdt'), ('bch', 'bcc') ) def get_pairs(self): url = "http://api.zb.com/data/v1/markets" resp = self.get_url(url).json() pairs = [] for pair in resp.keys(): pairs.append("%s-%s" % self.parse_market(pair)) return pairs def get_current_price(self, crypto, fiat): url = "http://api.zb.com/data/v1/ticker?market=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return float(resp['ticker']['last']) def get_orderbook(self, crypto, fiat): url = "http://api.zb.com/data/v1/depth?market=%s&size=3" % self.make_market(crypto, fiat) resp = self.get_url(url).json() del resp['timestamp'] return resp class CoinNest(Service): service_id = 145 api_homepage = "https://www.coinnest.co.kr/doc/intro.html" def get_current_price(self, crypto, fiat): if fiat.lower() != 'krw': raise SkipThisService("Only KRW markets supported") url = "https://api.coinnest.co.kr/api/pub/ticker?coin=%s" % crypto resp = self.get_url(url).json() return resp['last'] def get_orderbook(self, crypto, fiat): if fiat.lower() != 'krw': raise SkipThisService("Only KRW markets supported") url = "https://api.coinnest.co.kr/api/pub/depth?coin=%s" % crypto resp = self.get_url(url).json() del resp['result'] return resp class BitBank(Service): service_id = 147 api_homepage = "https://docs.bitbank.cc/" symbol_mapping = ( ('bch', 'bcc'), ) def get_current_price(self, crypto, fiat): url = "https://public.bitbank.cc/%s/ticker" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return float(resp['data']['last']) def get_orderbook(self, crypto, fiat): url = "https://public.bitbank.cc/%s/depth" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'asks': [(float(x[0]), float(x[1])) for x in resp['data']['asks']], 'bids': [(float(x[0]), float(x[1])) for x in resp['data']['bids']] } class EXX(Service): service_id = 148 symbol_mapping = ( ('usd', 'usdt'), ('bch', 'bcc') ) def get_pairs(self): url = "https://api.exx.com/data/v1/markets" resp = self.get_url(url).json() pairs = [] for pair in resp.keys(): pairs.append("%s-%s" % self.parse_market(pair)) return pairs def get_current_price(self, crypto, fiat): url = "https://api.exx.com/data/v1/ticker?currency=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return float(resp['ticker']['last']) def get_orderbook(self, crypto, fiat): url = "https://api.exx.com/data/v1/depth?currency=%s" % self.make_market(crypto, fiat) resp = self.get_url(url).json() return { 'asks': [(float(x[0]), float(x[1])) for x in resp['asks']], 'bids': [(float(x[0]), float(x[1])) for x in resp['bids']] } class BL3P(Service): service_id = 150 def check_error(self, response): j = response.json() if j['result'] == 'error': d = j['data'] raise ServiceError("BL3P returned error: %s, %s" % (d['code'], d['message'])) super(BL3P, self).check_error(response) def get_current_price(self, crypto, fiat): url = "https://api.bl3p.eu/1/%s/ticker" % self.make_market(crypto, fiat, '-') return self.get_url(url).json() class BTCbox(Service): service_id = 151 def get_current_price(self, crypto, fiat): if fiat.lower() != 'jpy': raise SkipThisService("Only JPY trading pairs supported") url = "https://www.btcbox.co.jp/api/v1/ticker/?coin=%s" % crypto r = self.get_url(url).json() return r['last'] class Bibox(Service): service_id = 152 api_homepage = "https://github.com/Biboxcom/api_reference/wiki/api_reference" symbol_mapping = ( ('usd', 'usdt'), ) def get_current_price(self, crypto, fiat): url = "https://api.bibox.com/v1/mdata?cmd=ticker&pair=%s" % ( self.make_market(crypto, fiat).upper() ) r = self.get_url(url).json() return float(r['result']['last']) def get_pairs(self): url ="https://api.bibox.com/v1/mdata?cmd=pairList" r = self.get_url(url).json() markets = [] for data in r['result']: pair = data['pair'] crypto, fiat = self.parse_market(pair) markets.append("%s-%s" % (crypto, fiat)) return markets def get_orderbook(self, crypto, fiat): url = "https://api.bibox.com/v1/mdata?cmd=depth&pair=%s&size=200" % ( self.make_market(crypto, fiat).upper() ) resp = self.get_url(url).json()['result'] return { 'asks': [(float(x['price']), float(x['volume'])) for x in resp['asks']], 'bids': [(float(x['price']), float(x['volume'])) for x in resp['bids']] }
python
We are just a day away from the World Cup taking over the cricketing world, enticing each and every fan to gorge on the competition before reaching its conclusion on November 19 in Ahmedabad. Last-minute preparations, of course, are in order for several teams as they battle injuries and rummage to find the perfect combination. For fans and keen watchers, though, this is a time to indulge in those pre-tournament predictions – wild, weird, warranted – all of those count. Getting them right to the tee is very difficult (those who have done this before will testify). But if you are not predicting stuff for an ICC event that will ebb and flow at every juncture, what are you even doing?! So, here it is – a look at how the teams will finish post the culmination of the World Cup group stage. Remember, these are these sides’ final positions, and there might yet be time for knockout predictions later in the piece. The Netherlands have done exceedingly well to get here. They stunned Scotland and the West Indies to book their spot and showcased plenty of big-game temperament while doing so. At the World Cup, though, things will only get tougher, and while the Dutch will certainly not die wondering, making massive waves in this 10-team tournament might be a bridge too far. Much of that is down to how fragile their batting seems. Even at the World Cup Qualifier, their top order blew hot and cold. Captain Scott Edwards and middle-order batter Teja Nidamanuru dug them out of trouble at times. But if they find themselves in similar situations at the World Cup, they might not be able to recover. Their bowling, with the addition of Roelof van der Merwe, looks sturdy if not world-beating. If the surfaces provide help, they might be able to restrict teams to middling totals. But again, it comes down to how many runs their batters would be able to score, and if they can chase down totals at the World Cup. Effort, enthusiasm, and zeal will not be a problem for the Dutch, who are playing their first ODI World Cup since 2011. Quality, however, could be a bit of an issue, and while they will always remain capable of springing the odd upset, they might have to consign themselves to a place at the foot of the ladder this time out. Akin to the Netherlands, Afghanistan also have batting quandaries to solve. Ibrahim Zadran has taken to ODI cricket like a duck to water. Rahmanullah Gurbaz, however, has been a lot more inconsistent. Rahmat Shah, too, has also not delivered on the early promise he showed at the beginning of his ODI career. Quite often, the lack of runs from the top puts pressure on Afghanistan’s middle order, which is capable of mounting a comeback but cannot always be expected to perform salvaging acts. Their batting line-up, in general, has also encountered snags when trying to work out the perfect tempo for 50-over cricket. On some days, they blow the opposition away as Sri Lanka found out in the warm-up fixture. On other days, even rotating strike becomes an issue. Their bowling, it could be argued, is among the top-five attacks at the World Cup (with their spin-bowling quartet perhaps the best). Rashid Khan has oodles of experience playing in India, as does Mohammad Nabi. Mujeeb Ur Rahman, especially if the pitches turn, could be a handful. Noor Ahmad is the latest spin-bowling sensation to emerge from the country and could cause a ripple. Their World Cup games against New Zealand and Pakistan, which will be held in Chennai, could see this quartet play a massive role too. If their batters and pacers can back them up, though, remains to be seen, and that is where they might come unstuck. Due to the variety in their bowling attack, they will cause teams headaches at different junctures. Unfortunately, that might not be enough to guarantee a top-four berth. Bangladesh have been shrouded by controversy, and the World Cup has not even begun. That, to an extent, sums things up and explains the predicament they find themselves in – a predicament that they have, in many ways, brought upon themselves. The Tamim Iqbal row has been splashed across all the back pages, with captain Shakib Al Hasan also not mincing his words on the topic. Shakib, who is also their best player, has picked up a niggle too, and it remains unclear if he will be fully fit for their first World Cup game against Afghanistan on Saturday. Such a manic sequence of events, though, has a silver lining – that things cannot get any worse, and that the only way is upwards. It could also galvanize those in the squad, for they could now have even more to prove, especially to shut out the noise. Bangladesh did that well against Sri Lanka in their first World Cup warm-up game. Their top order, comprising Liton Das, Najmul Hossain Shanto, Tanzid Hasan, and Towhid Hridoy brings verve and effervescence to the batting unit. Mehidy Hasan Miraz has also done his bit whenever promoted up the order – the most recent example being against England at Guwahati. The middle order then has captain Shakib, Mushfiqur Rahim and Mahmudullah, meaning that experience will not be a problem. Each of them is a good player of spin too, and that should hold the Tigers in good stead at the World Cup. The bowling attack, especially if the pitches are sluggish, could be tough to get away. However, if the tracks are conducive to stroke-play, they might miss genuine wicket-taking options, with Mustafizur Rahman not as penetrative as he once was, leaving Taskin Ahmed to do the heavy lifting. On their day, Bangladesh can beat anyone, as they showed at the Asia Cup by getting the better of India. How many of those days will they have at the World Cup, though? Well, there could be a few, but probably not enough to make their fans realistically dream of a semi-final spot. Well, where to start? Predicting what Sri Lanka will do on any given day has become as difficult as predicting the weather (yes, climate change is real, folks). When things are clicking into place, they will be the most exciting team in the world. On some other occasions, they will get blown away – like Afghanistan and Bangladesh have done in the warm-up games, and like India famously did at the Asia Cup final not long ago. Batting, as it was at that Asia Cup, still remains a concern, despite Kusal Mendis being in smashing form. Pathum Nissanka and Dimuth Karunaratne add solidity but if Kusal Perera is fit, only one of them might start. Charith Asalanka has been their clutch player at times, but far too often, Sri Lanka leave him with too much to do. Oh, and we are not even getting into the wretched run of scores captain Dasun Shanaka has put together. Their matters have not been helped by the injury to talismanic leg-spinner Wanindu Hasaranga. Maheesh Theekshana, if he regains fitness himself, will have to shoulder a chunk of the burden, considering Dilshan Madushanka, Dunith Wellalage and Matheesha Pathirana are relatively inexperienced in this format. Kasun Rajitha and Lahiru Kumara, if they hit their straps, can run through batting units but again it comes down to how regularly they might be able to do it, especially under pressure at the World Cup. Thus, this World Cup, for this set of players, might just have come a year or so early. Sri Lanka will push teams close but they might not be able to do so frequently enough to have a real shot at the top four. Entertainment, whenever they are out playing, will not be a problem. The end product might be. Two months ago, Pakistan were deemed one of the favourites to win the World Cup. Their top order looked ominous. Haris Rauf, Naseem Shah and Shaheen Shah Afridi were blowing teams away. Their middle order had the requisite firepower, and they seemed primed to have a tilt at the biggest prize in ODI cricket. Two months, though, is a long time in Pakistan cricket, and things, unsurprisingly, have changed. Naseem has been ruled out of the entirety of the World Cup, leaving them short on fast-bowling power. Rauf is also coming back from a niggle that sidelined him at the Asia Cup, with Shaheen also losing a bit of his rhythm in recent weeks. To offset it, they have recalled Hasan Ali, a vital part of their 2017 Champions Trophy success. However, his ODI returns, whenever he has played lately (which has not been often anyway), have not been great. The other problem is that Fakhar Zaman has encountered a barren run. Abdullah Shafique can replace him at the top of the order but in Fakhar’s absence, Pakistan lack oomph and run the risk of having four batters who bat at a similar tempo in their top four. This bunch has also not played a lot of cricket in India, with Pakistan having last played a competitive fixture in India in 2016. Adaptation, thus, could also be a bit of a sticky point, especially in the absence of one of their most potent pacers. With Babar Azam and Mohammad Rizwan around, they will always enter games at the World Cup with a chance to win it. Plus, Iftikhar Ahmed, if he gets on a roll, can pound the opposition into submission too. The last time South Africa played an ODI World Cup, they finished seventh, winning just three of their nine games. In 2023, though, they seem better equipped to cause a bigger flutter, and perhaps even challenge for the top four. That is largely down to how power-packed their batting unit is. Quinton de Kock remains a match-winner at the top. Captain Temba Bavuma complements him beautifully, with Rassie van der Dussen a prolific run-scorer in this format. Aiden Markram has also found his feet in ODI cricket and has morphed into a solid middle-order batter, capable of alternating between grafting and taking down the opposition. South Africa’s X-Factor, though, could be Heinrich Klaasen, who has established himself as one of the best (if not the best) hitters of spin on the planet. David Miller can also increase the scoring rate against spin and this particular pair could offset the Proteas’ slight lack of batting depth. The bowling, however, could be a cause for concern. Anrich Nortje, who is often their enforcer, has been ruled out. Kagiso Rabada has not been in great form recently, and the likes of Lungi Ngidi and Marco Jansen can be expensive. Although Keshav Maharaj offers solidity and control with his left-arm spin, Tabraiz Shamsi, a left-arm wrist-spinner, remains a bit of a wildcard, especially against line-ups that play spin well. Because of their batting might, there will be games where the likes of de Kock, Klaasen, Markram and Miller obliterate oppositions and give their bowlers a big enough cushion. Doing that across nine games, however, is not easy and for that reason, the Proteas might just miss the cut. Here we are again. New Zealand have arrived at the World Cup with little fanfare. One of their premier spin-bowling all-rounders (Michael Bracewell) has been ruled out altogether. There is a question mark over how much of a role their captain and best batter (Kane Williamson, for those guessing) will play. Devon Conway does not have an outright opening partner (although Will Young is a very good option), and Tim Southee is recovering from a broken thumb. So, New Zealand has to qualify for the semi-final, at least, right? Well, they almost always do at these ICC events. And while there seem to be a ton of problems, they might also have solutions in their ranks. Rachin Ravindra has been touted as the next big thing for a while. His time might have finally come. In the series away to England, he was impressive with both the bat and ball. Against Pakistan in the warm-up fixture, he was sensational at the top of the order, and he seems best suited to bat at the top of the order. Another batter to keep an eye on at this World Cup is Mark Chapman, a highly improved player of spin, who can sweep, reverse-sweep and has nimble footwork. He polished off the run-chase against Pakistan and has been in a rich vein of form. Daryl Mitchell has also taken his game to another level lately, and with him, Chapman, Tom Latham and Glenn Phillips (possibly) making up the middle order, the Kiwis have plenty of dexterity, experience and firepower. The big news on the bowling front is that Trent Boult is back. With most places in India expected to be humid in October, he will get swing (not that he needs much anyway). Matt Henry has slotted into the bowling unit seamlessly, while Lockie Ferguson remains a point-of-difference bowler. Ish Sodhi and Mitchell Santner might not be dubbed world-class, but they seem to always turn up at these ICC events, giving the Black Caps incision through the middle overs. Thus, they seem to have the resources to not just adapt to these conditions but also make the most of them. They might be a little short on star names, but that has never been an issue for them. Might not be an issue this time either. The defending champions have not changed much since their triumph in 2019, both in terms of personnel and approach. Most of the star cast that helped them win the title in 2019 is still around. There was a possibility that the Player of the Match of the final aka Ben Stokes would not be there to defend England’s crown but that fear has since been vanquished. And as far as the approach is concerned, England have perhaps decided to go harder under Jos Buttler. Speaking of Buttler, he arrives having guided England to their second T20 World Cup crown less than a year ago. His captaincy credentials are well-established, and there is no doubting his ability as a middle-order match-winner. In fact, England’s squad is glittered with match-winners. Jonny Bairstow is arguably their greatest-ever ODI opener. Dawid Malan averages more than 60. Harry Brook is a generational talent. Liam Livingstone and Moeen Ali can annihilate any bowling attack. And Stokes is, well, Stokes. Their bowling also seems in fine fettle, despite the obvious absence of Jofra Archer. Mark Wood is bowling as quick as he has ever done. In Gus Atkinson, England have a pacer who can bowl just as rapidly. David Willey, Reece Topley and Sam Curran maximise the left-arm angle, while Chris Woakes remains a threat with the new ball. England’s lynchpin, though, could be 35-year-old Adil Rashid. The leg-spinner has often flown under the radar but has almost always played a pivotal role in England’s biggest white-ball successes. That should not be too different in India, where spin is expected to play a major part. Moeen, having played tons of IPL matches, should also be a proper wicket-taking option on these shores. The only problem they might encounter is injuries. While they have enough in the squad to offset it, the long nature of the group stage, plus how cavalier their brand of cricket is, could mean that they stumble a couple of times in the round-robin phase of the World Cup. Nothing to impact their qualification. But just enough to rid them of a top-two finish. It has been more than eight years since Australia last won the ODI World Cup. That number may seem inflated because, well, World Cups happen once every four years, but it highlights how a team that has won five times previously, would be chomping at the bit to reaffirm their status as the premier ODI side on the planet. On paper, there are not many teams that can rival Australia. Even with Travis Head absent at the start, they have a devastating opening pair in David Warner and Mitchell Marsh. Marnus Labuschagne and Steve Smith know how to keep things ticking, while Glenn Maxwell, Marcus Stoinis and Cameron Green (to an extent) can rip any bowling unit to shreds. Josh Inglis, if he is given a go, is also an archetypal 360-degree batter, capable of hitting around the dial. Their bowling attack needs no introduction either. Mitchell Starc is a bona-fide World Cup legend. Josh Hazlewood keeps hitting that nagging hard length just outside off and Pat Cummins, in his first World Cup as captain, can extract assistance off the most docile surfaces. Spin might seem a bit of a weakness, considering they have opted for just one specialist spinner in Adam Zampa. But when the spinner is that good, and when the second possible option is Maxwell, who is really tough to line up, Australia seem to have that base covered too. The only impediment could be the start of their campaign – away to Chennai against India. They have the resources to topple India (as they did earlier in the year), but a string of injuries has meant that their ideal playing eleven has not played as much cricket together as, say, India. That might just pull them down, although they will, because of the players they have, still finish in the top two. And probably become the team no one wants to face when the semi-final dawns. India have been in the so-near-yet-so-far boat very often in recent World Cups (across formats). As far as the ODI iteration is concerned, they have made at least the semi-final since the 2011 edition, but have made the final only once – when they won it 12 years ago. During this stretch, the Indian team has been at the centre of numerous social media memes. When a nation as richly resourced as India fail to win an ICC trophy for 10 years, some of that criticism is warranted, but this time, it just feels different. Much of that is because India will be playing this ODI World Cup at home, where they have an almost impregnable record. Rohit Sharma and Shubman Gill have been irresistible as an opening pair. Virat Kohli’s appetite for runs has only burgeoned, and their middle order has plenty of options – emphasized by the fact that two of Ishan Kishan, Shreyas Iyer and Suryakumar Yadav might be on the bench at all times. The big point of difference, however, is Jasprit Bumrah, fit and firing on all cylinders. If he can last the entirety of the tournament, India will have a bowler, not just capable of restricting the opposition but also bundling them out swiftly. Mohammed Siraj has experience of doing the latter too, having demolished Sri Lanka lately. Mohammed Shami, who might feature a little more intermittently, is also in decent form and picked up a five-wicket haul against Australia at Mohali towards the end of September. In the spin-bowling department, Kuldeep Yadav has rediscovered the magic that made him the toast of the nation. Ravichandran Ashwin can also be relied upon in helpful conditions, and Ravindra Jadeja is bowling as well as he has ever done in this format. Buccaneering batters, penetrative spinners, skilful fast bowlers – India have it all. During the group stage of any World Cup, it is often the quality throughout the squad that stands out – something that India have in abundance. If they go all the way is a different debate altogether, but as far as the first nine games of the World Cup are concerned, well, there is not a lot that could stop this Indian juggernaut.
english
package util; import android.os.Bundle; import android.os.ResultReceiver; public class IMMResult extends ResultReceiver { public int result = -1; public IMMResult() { super(null); } @Override public void onReceiveResult(int r, Bundle data) { result = r; } // poll result value for up to 500 milliseconds public int getResult() { try { int sleep = 0; while (result == -1 && sleep < 500) { Thread.sleep(100); sleep += 100; } } catch (InterruptedException e) { ; } return result; } }
java
package api // ResourcePlan is the structure of an app's resource plan. type ResourcePlan struct { // ID is a unique string for resource plan. ID string `json:"id,omitempty"` // Name is a unique string for resource plan. Name string `json:"name,omitempty"` // Description is a detailed description of the resource plan Description string `json:"description,omitempty"` } type ResourcePlans []ResourcePlan // ResourceService is the structure of an app's resource service. type ResourceService struct { // ID is a unique string for resource service. ID string `json:"id,omitempty"` // Name is a unique string for resource service. Name string `json:"name,omitempty"` // Updatable is the plans of the current resource can be upgraded Updateable bool `json:"updateable,omitempty"` } type ResourceServices []ResourceService // Resource is the structure of an app's resource. type Resource struct { // Owner is the app owner. Owner string `json:"owner,omitempty"` // App is the app the tls settings apply to and cannot be updated. App string `json:"app,omitempty"` // Created is the time that the resource was created and cannot be updated. Created string `json:"created,omitempty"` // Updated is the last time the TLS settings was changed and cannot be updated. Updated string `json:"updated,omitempty"` // UUID is a unique string reflecting the resource in its current state. // It changes every time the resource is changed and cannot be updated. UUID string `json:"uuid,omitempty"` // Resource's name Name string `json:"name,omitempty"` // Resource's Plan Plan string `json:"plan,omitempty"` // Resource connet info Data map[string]interface{} `json:"data,omitempty"` // Resource's status Status string `json:"status,omitempty"` // Resource's binding status Binding string `json:"binding,omitempty"` // Resource Options Options map[string]interface{} `json:"options,omitempty"` } type Resources []Resource // Binding is the definition of PATCH /v2/apps/<app_id>/resources/<name>/binding/. type ResourceBinding struct { BindAction string `json:"bind_action,omitempty"` }
go
<reponame>caughtclean/but-thats-wrong-blog { "_args": [ [ { "raw": "react-spinner-children@^1.0.5", "scope": null, "escapedName": "react-spinner-children", "name": "react-spinner-children", "rawSpec": "^1.0.5", "spec": ">=1.0.5 <2.0.0", "type": "range" }, "/Users/nathaneyerley/lighthouse/Projects/but-thats-wrong-blog/node_modules/react-facebook" ] ], "_from": "react-spinner-children@>=1.0.5 <2.0.0", "_id": "react-spinner-children@1.0.5", "_inCache": true, "_location": "/react-spinner-children", "_nodeVersion": "5.7.0", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", "tmp": "tmp/react-spinner-children-1.0.5.tgz_1461189645236_0.6722048809751868" }, "_npmUser": { "name": "zlatkofedor", "email": "<EMAIL>" }, "_npmVersion": "3.6.0", "_phantomChildren": {}, "_requested": { "raw": "react-spinner-children@^1.0.5", "scope": null, "escapedName": "react-spinner-children", "name": "react-spinner-children", "rawSpec": "^1.0.5", "spec": ">=1.0.5 <2.0.0", "type": "range" }, "_requiredBy": [ "/react-facebook" ], "_resolved": "https://registry.npmjs.org/react-spinner-children/-/react-spinner-children-1.0.5.tgz", "_shasum": "22326add38b88581681d2b775d02170b81124f3a", "_shrinkwrap": null, "_spec": "react-spinner-children@^1.0.5", "_where": "/Users/nathaneyerley/lighthouse/Projects/but-thats-wrong-blog/node_modules/react-facebook", "author": { "name": "<NAME>", "email": "<EMAIL>", "url": "http://www.cherrysro.com/" }, "bugs": { "url": "https://github.com/seeden/react-spinner-children/issues" }, "dependencies": { "spin.js": "^2.3.2" }, "description": "A React component wrapper for spin.js with support for children", "devDependencies": { "babel-cli": "^6.7.5", "babel-core": "^6.7.6", "babel-eslint": "^6.0.3", "babel-plugin-transform-class-properties": "^6.6.0", "babel-plugin-transform-decorators": "^6.6.5", "babel-preset-es2015": "^6.6.0", "babel-preset-react": "^6.5.0", "babel-preset-stage-0": "^6.5.0", "babel-preset-stage-1": "^6.5.0", "eslint": "^2.8.0", "eslint-config-airbnb": "^7.0.0", "eslint-loader": "^1.3.0", "eslint-plugin-jsx-a11y": "^0.6.2", "eslint-plugin-react": "^4.3.0", "gulp": "^3.9.1", "gulp-babel": "^6.1.2", "gulp-coveralls": "^0.1.4", "gulp-jsx-coverage": "^0.3.8", "gulp-util": "^3.0.7", "jsdom": "^3.1.2 || ^6.5.1", "mocha": "^2.4.5", "react": "^15.0.1", "react-addons-test-utils": "^15.0.1", "react-dom": "^15.0.1", "should": "^8.3.1" }, "directories": {}, "dist": { "shasum": "22326add38b88581681d2b775d02170b81124f3a", "tarball": "https://registry.npmjs.org/react-spinner-children/-/react-spinner-children-1.0.5.tgz" }, "engines": { "node": ">= 0.12.0" }, "gitHead": "57a1597b1dc5ac606fc1da5e733c1f58e94d66c2", "homepage": "https://github.com/seeden/react-spinner-children#readme", "keywords": [ "react", "react-component", "spin", "spin.js", "spinner", "loading", "children", "isomorphic", "server" ], "license": "MIT", "main": "./dist/index.js", "maintainers": [ { "name": "zlatkofedor", "email": "<EMAIL>" } ], "name": "react-spinner-children", "optionalDependencies": {}, "peerDependencies": { "react": "15.x || 0.14.x" }, "private": false, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git://github.com/seeden/react-spinner-children.git" }, "scripts": { "build": "babel-node ./node_modules/gulp/bin/gulp.js build", "coveralls": "babel-node ./node_modules/gulp/bin/gulp.js coveralls", "eslint": "node ./node_modules/eslint/bin/eslint.js --ext .js,.jsx .", "prepublish": "npm run build", "test": "babel-node ./node_modules/gulp/bin/gulp.js test" }, "version": "1.0.5" }
json
RM (BTS) Image: JYP Entertainment. Jackson Wang (GOT7) Image: SM Entertainment. Minho (SHINee) Image: Pledis Entertainment. Hoshi (SEVENTEEN) Jin (BTS) J-Hope (BTS) Image: JYP Entertainment. JB (GOT7) Image: SM Entertainment. Heechul (Super Junior) Suga (BTS) With his mischievous grin and knack for mimicking others, Wooyoung brings chaos and laughter wherever he goes. Wooyoung (ATEEZ)
english
import torch from viz.visualizer import Visualizer from modules.deepmil import Attention from msidata.dataset_msi_features_with_patients import PreProcessedMSIFeatureDataset from testing.logistic_regression import get_precomputed_dataloader import argparse from experiment import ex from utils import post_config_hook @ex.automain def main(_run, _log): args = argparse.Namespace(**_run.config) args = post_config_hook(args, _run) args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Get test data to be visualized _, test_loader = get_precomputed_dataloader(args, args.use_precomputed_features_id) # Load model to be used model = Attention() # Initialize visualizer.. not necessary? viz = Visualizer() viz.visualize_first_patient(test_loader, model, method='deepmil') print('done') # for step, data in enumerate(loader): # optimizer.zero_grad() # x = data[0] # y = data[1] if __name__=="__main__": main()
python
The US is going to donate the vaccines against COVID-19 to Nepal in a few days. The US has detailed plans to donate 7 million doses of anti-COVID vaccine to Nepal and other Asian countries. US Ambassador to Nepal Randy Berry wrote on Twitter, "In the coming days, the US will donate at no cost to Neal enough vaccines to fully vaccinate 1. 5 million people. I could not be any prouder of our 73-year long partnership. America will always stand with Nepalis, and will continue to work tirelessly to improve their lives. " The US has detailed plans to donate 7 million doses of anti-COVID vaccine to Nepal and other Asian countries. The White House on June 3 on the fact sheet said it would donate at least 80 million doses of vaccine globally by the end of June as Washington aims to close the gap with Beijing in vaccine diplomacy. Among the first tranche of 25 million doses, about 7 million will be allocated to Asia via the World Health Organisation (WHO)-led COVAX vaccine access program, according to the White House. At least three-quarters of all donated doses will be distributed through COVAX — prioritising South Asia, Southeast Asia and certain other regions — while the rest will go directly to such places as countries in need and their neighbours. A total of 2,611,807 people have been vaccinated against COVID-19 while 964,508 people have been administered the second dose of vaccines in Nepal. As per the Central Bureau of Statics, the population of Nepal at present stands at 30,338,104. READ ALSO:
english
- I gravitate towards gravitas. - [on his hesitation to do Along Came a Spider (2001)] I had a philosophic aversion to it. I didn't want to do the same thing twice. Then I realized that my philosophical aversion was bullshit. I realized I liked Alex Cross. And the fact that he's black is totally incidental. That's a rare thing for a black actor to find. - [on the failure of The Big Bounce (2004)] It was a wonderful experience. Steve Bing was the producer and was very generous. But the movie didn't turn out very well. The director [George Armitage] fell ill and we shut down production for a few weeks while he recuperated. And I think when he came back he just didn't pick up the ball and run with it the way he should have, and the movie suffered greatly for that.. - I've been living with myself all of my life, so I know all of me. So when I watch me, all I see is me. It's boring. - on why he dislikes watching his own films. - I'm not intimidated by lead roles. I'm better in them. I don't feel pressure - I feel released at times like that. That's what I'm born to do. - I was in Africa when I got the call for Unforgiven (1992). Clint called my agency and made an offer for a western. I was like "He called for me?" It was jaw-dropping. - [on the box-office failure of The Shawshank Redemption (1994)] It took a long time for word of mouth to kick in because no one could say it. It was "The Shimshunk Reduction", "The Hudsucker Redemption"; I mean people just couldn't say it, which really made me angry because I knew that at the time! The movie we made was called "Rita Hayworth and the Shawshank Redemption". Isn't that a great title? But they were like "That won't fit on the marquee". So it took a year or two for people to say it. Some people still can't say it. - [on the violence in Se7en (1995)] If you don't show the actual violence and the audience provides their own violence, it's much more gruesome. This is a guy who spent a lot time planning and preparing, and what was he doing? He was punishing people for their sins. He had a moral agenda. A twisted moral agenda, but do you know how many people do? People in high places. - [on the box-office failure of Amistad (1997)] People thought it was a picture about slavery. But it wasn't about slavery at all. It was about American jurisprudence. The point of the film ultimately was that the President in not the king. But I think people were like "Jesus, not another movie about slavery!" We really do have a negative response to negative history. Which is a shame. - [on the failure of The Bonfire of the Vanities (1990)] I knew that movie wasn't going to work. I don't think Brian De Palma had a clue. It struck me that he didn't read the book - or that he didn't like the book. It was the one time Tom Hanks was awfully miscast. Originally, they hired Alan Arkin to play my role. I thought that was perfect casting. But then they thought they had to be politically correct and make the judge black. So they fired Alan Arkin and hired me. Not a great way to get a role. I was kind of a suck-a-- for not turning it down, but they weren't going to give it back to Alan anyway. I never did get around to seeing the movie. - [on the character Hoke Colburn in Driving Miss Daisy (1989)] It's a tricky character, right on the edge of Uncle Remus. But I knew how to play him right away. I knew when I read it. I just saw him -- the dignity in the character. The only time I ever worried about it was when I was doing the show Off-Broadway, and all these Southerners would come back wiping their eyes and talking about how nostalgic it made them feel. How their grandmother had a chauffeur just like that. I was like "God damn it! I made these people nostalgic for the good ol' days!" But, then, I had some black friends see it, and they said, 'Oh, my grandfather was exactly like that.' So that made me feel okay.. - [on working on The Shawshank Redemption (1994)] That was a strange production. There were moments of extreme tension on the set. Between the producers and actors, between the director and actors, between everybody. Just this personality stuff between different groups. Very strange. Let's stop talking about that one. - [on Se7en (1995)] There's all this loss and angst and death and sense of helplessness in that movie - if I saw it in the theater, I probably wouldn't have liked it. I saw Fight Club (1999) and I didn't like it much. It's a great movie, well made, fabulous acting, but it just made me feel so bad. But David Fincher is an extraordinarily good director. - When I was doing press for Deep Impact (1998), reporters would always ask me how it felt to play the first black president, and I'd tell them, "I'm not playing the first black president. I'm playing a president who happens to be black." Or they'd ask me what sort of research I did for the role. Research? What kind of research do you need to play the president? He's a guy. Besides, we all know what presidents are like standing up there in a press conference. Hell, you don't have to do any research to play a president. - I saw Neil LaBute's first movie, In the Company of Men (1997), and I thought it sucked deeply. I mean, talk about a couple of scuzzy guys. Man, they were turds. But I was intrigued by the mind that would think this up and film it. Then I saw LaBute's second movie, Your Friends and Neighbors (1998). Not any better, but still intriguing. So then I got the script for Nurse Betty (2000), and I loved it and I went and met him. And it turns out he's married, has these lovely kids. He's just this big bear of a man. Cuddly, even. It didn't take any persuading to convince me to do the film. - When I got nominated for the Oscar [for Street Smart (1987)], it put rocket boosters in my career. Since childhood, all I wanted to do was make movies. I love the stage, but I wanted to be a movie actor. - Is there a movie I think I should have won the Oscar for? Yeah. All of them. - I don't know what my favorite film of mine is... But I think the most important film I was in was Glory (1989). - It was my idea to just do The Electric Company (1971) for a couple of years and go on. But you get trapped by that money thing. It's golden handcuffs. It gets a lot of people, including soap opera actors and commercial actors. Then, they don't want to see you in serious work. That was going to be me, having people come up to me saying "My kids love you!" I was there three years too long. - I find it difficult to watch myself... I find it boring. - I was talking to Bob Hoskins when we were making Unleashed together. We were talking about the joy of doing bad guys. And he confirmed exactly what I was thinking. With bad guys you get to let it all out. All those dark places in your psyche? You can let 'em go. When you play good guys, it's kind of boring. It's one note. - Once you've gotten the job, there's nothing to it. If you're an actor, you're an actor. Doing it is not the hard part. The hard part is getting to do it. - [Accepting his UCLA Tracy award]: To be included among this group of highly accomplished actors is just magical. - I'm very worried about what's going on in the world at the moment because we have this Napoleonic president; by Napoleonic I mean he's a man who just seems to need to search himself. It doesn't make sense. I don't have any love lost on Saddam Hussein. If he needs to be removed from office, fine. You have to find the right way to do it, but going to war, nah, with the people. To do what. What is the real reason? Because he's harboring weapons of mass destruction? So it is with North Korea. Why are we acting to acquiesce to this? We do not need the Iraqi oil. We have Kuwait oil. It's the same pool. That's why Kuwait's there. That's why Kuwait was set up. You think that country could exist there without somebody backing it? We're talking about a piece of Iraq. So, we keep this. That's my noise. I am terribly upset about the whole thing. - You know, I was hanging out with Sidney Poitier and we were trying to decide if he or I were the better actor. We decided it was me as I convinced the world I could sing. (Freeman debuted on Broadway in 1968 in "Hello, Dolly!") - Stop talking about it. I'm going to stop calling you a white man. And I'm going to ask you to stop calling me a black man. - when asked how to get rid of racism in an interview with Mike Wallace on 60 Minutes (1968). - Ridiculous... I don't want a Black History Month. Black history is American history. - when asked what he thinks of Black History Month on 60 Minutes (1968). - The American Indians have this saying. 'Look at the day, look at the sunlight, the grass and the trees! It's a good day to die!' - You couldn't possibly try to entertain all of the people who seem to be offering you entertainment. Because most of them want some compensation for it. - [upon waking up face down in a door way and not knowing how he got there] I recognised that it had become a problem, so I just quit. I do have self-control. Once I realise that I've got to change something I just do it. - If you wake up and the snow is knee-deep outside, you are not filled with rage. It's just something that you've got to cope with. If you're living in a situation it's the only situation that you know, and you've got to deal with it. - I don't have to work. I could stop and never have to worry about paying the rent. I'm working for the joy of doing it. - Sometimes, you want to upset an audience so you can engage them. I've done so-called Hollywood films, and I know that it's all about wanting the audience to feel upbeat, give them a happy ending. But they also like complete stories. If your story's complete it doesn't have to have a happy ending. - They say there's no fool like an old fool. But blessings be upon my wife because I think without her, I'd be somebody's fool by now. - If you live a life of make-believe, your life isn't worth anything until you do something that does challenge your reality. And to me, sailing the open ocean is a real challenge, because it's life or death. - [upon getting work as an off-Broadway actor in 1967] I made $70 a week as an actor and I'd been making $60 in L.A. Making more than that as an actor was just unbelievable to me. I never went back to typing but had some real lean times in-between. But I didn't have to go to work for anybody else. I didn't have to wash dishes, I didn't have to wait tables, I didn't have to drive a cab or wash cars. I deliberately left myself nothing to fall back on. If you've got a cushion, where you land, you stay. You can't climb a mountain with a net. If you've got the net, you'll let go. - I work about half the year. I'm just a guy who enjoys his work and enjoys working with people who enjoy their work. When that happens you get a bonding situation and if it come out with a good product, then that ties you even closer together. It's almost like a great love affair. - I've never been a mechanic. Throughout my life, what I have been is an actor, a pretender. I do have the wife and the family and the stuff like that but on the other hand, I'm - knock on wood - outstandingly healthy. - I think we all have a private bucket list. It may not be written down, but I'm constantly checking them off. I just checked off Jack Nicholson. Every day was a holiday because I've been praying at the temple of Jack ever since Five Easy Pieces (1970). I had a chance to ride with him on the Warner Brothers plane with Clint [Eastwood]. I got to jawing what a fan I was, and as actors will do, he expressed how he liked my work. Then we started talking about how we could make a sequel to [the 1973 Nicholson film] The Last Detail (1973). But that didn't pan out. - My aim in life, when I graduated from high school, was to get out of Mississippi. I started coming back [to Mississippi] in about 1979, because my parents moved back, which I couldn't understand. What in the world would make you come back here? It took me about 20 years to figure that out. - I'm not a campaigner or a crusader for ending racism, or anything for that matter. I believe you should live your life according to your own tenets. If there are people you don't like, avoid them. But not liking people based on generalities is stupid. - No, but a lot of roles I refuse because it's not me. -- on if he ever feels he's been miscast. - Isn't there a big, 800-pound gorilla missing here? Money, money, money. You work all your life so you don't have to wash dishes or sweep floors or pump gas, and still pay the rent. That's very germane to what you call a career. - I don't know about anyone else, but my kids didn't have me. I was busy trying to be somebody. Now I have all these debts to pay. -- on the personal toll being an actor can take on a person. - I don't think that anything where you start off with something is an art form. If you start off with a blank page or a blank canvas or a blank slab or a blank stone, you're going to create something. If someone brings it to you and says, "Can you enlarge upon it?". - I'm not good at anything else. Certainly not golf. -- on why he is an actor. - The fact that the people who are making the decisions about moviemaking are not moviemakers is a big problem. - I don't do accents. But I was going to have to do some sort of accent and do my best to sound like Mandela. I really fretted over that because he's an iconic figure. If you screw it up you've screwed it up. But once we got into production, it all fell into place. -- on the toughest aspect of preparing for "Invictus" - I don't like tension on a set -- at all, of any kind. - Glory (1989) does what I think movies are best at, and that is giving you a lesson in history. Glory is a story that nobody knew. It's American history that was completely ignored, and there is an awful lot of that. It is because the people who tell the story tell their own story. So if you ever ask, any time down the line, that's always the film I'll be most proud of.
english
__name__ = "redispycompss"
python
The long-awaited Routes feature has finally come to Pokemon GO, and with it, players are also receiving a brand-new legendary beast for free. Zygarde, also known as the Order Pokemon, is the critter in frame, and it is unlike anything you have seen or dealt with before in Pokemon GO's meta. It can only be obtained through a Special Research called "From A to Zygarde," which is connected to the "Blaze New Trails" event in the game. Zygarde boasts three different formes: 10% forme, 50% forme, and 100% or Complete forme. When you will first encounter Zygarde, it will be in its 10% forme, which you can evolve using Zygarde Cells. The critter becomes progressively more potent with each evolution. However, getting the Cells is no easy task. The only way to obtain Zygarde Cells is by following the new Routes feature in Pokemon GO. Even then, these cells are quite tough to come by. Given that the new Routes are a bit broken, you might have even lesser odds of getting these Zygarde Cells. In this article, we will talk about the different forms of Zygarde and how you can trade them in Pokemon GO. First, we shall discuss why you want to trade Zygarde in the game. Since it has just been released, you would generally expect trainers to keep Zygarde in their account and make them their Best Buddy. This is not the case, though. People have tried to trade this critter to reduce the base Combat Power (CP). Doing this would allow them to evolve their Zygarde into its even stronger 100% forme while restricting the CP within the Great League regulations. If you were to evolve Zygarde as you obtain it from the Special Research, it would then surpass the 1500 CP mark. As a result, you will not be able to use it in the Great League. While you could still use it in the Ultra League format of Pokemon GO PvP, there are far better options at that CP range. Thus, it makes more sense to evolve Zygarde while containing the CP within 1500. Looking at the stats of the different Zygarde forms, we can see that 50% Zygarde is the hardest-hitting critter with a base attack stat of 213, 10% Zygarde sits at 205, and 100% Zygarde at 184. However, the Complete Zygarde forme towers over the other two regarding bulk, with a base HP stat of 389. This makes it better than 10% and 50% forms in Pokemon GO PvP. Given its enormous bulk paired with a decent hitting force, you would want Complete Zygarde to be on your roster. Now, if you evolve the base CP Zygarde from the Research, you can use it in the Great League only if you trade it. This is where it gets complicated. Niantic has blocked trading for this critter, and no one quite understands why. This could be because the folks at Niantic know that this critter will be too overpowered in the Great League, and they don't want to make balance changes right after releasing Zygarde. Thus, many trainers feel that the trade ban on Zygarde is intentional on Niantic's part to prevent this beast from dominating the GL meta in Pokemon GO PvP. It could also be a bug that will get fixed through a patch. Only time will tell. So, when writing this article, trading Zygarde is not allowed in the game. We will keep you posted if and when changes are implemented. How to catch Zygarde in Pokemon GO? You can catch (acquire) Zygarde by completing the "From A to Zygarde" Special Research that comes with the "Blaze New Trails" event. You can read more about this in our article here. Besides this Special Research, you cannot get Zygarde through any other procedure.
english
<gh_stars>1-10 export interface Position { line: number; ch: number; } export interface Marker { path?: string; severity: string; message: string; from: Position; to: Position; }
typescript
{"nom":"Domptin","circ":"5ème circonscription","dpt":"Aisne","inscrits":462,"abs":288,"votants":174,"blancs":11,"nuls":5,"exp":158,"res":[{"nuance":"REM","nom":"<NAME>","voix":97},{"nuance":"FN","nom":"<NAME>","voix":61}]}
json
{ "name": "@writetome51/array-get-between", "version": "1.0.4", "lockfileVersion": 1, "requires": true, "dependencies": { "@writetome51/array-get-adjacent-at": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@writetome51/array-get-adjacent-at/-/array-get-adjacent-at-1.0.4.tgz", "integrity": "<KEY> "requires": { "error-if-array-too-short-to-meet-adjacent-items-request": "~1.0.1", "error-if-index-how-many-or-array-are-not-valid": "~1.0.0" } }, "@writetome51/index-is-valid": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@writetome51/index-is-valid/-/index-is-valid-1.0.1.tgz", "integrity": "sha512-<KEY> "requires": { "error-if-not-integer": "~1.0.0" } }, "@writetome51/is-array-not-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@writetome51/is-array-not-array/-/is-array-not-array-1.0.0.tgz", "integrity": "sha512-u3L1FTbTXKbC1lBVSnBwJ24qtrnyz10IbSAk7E9UgoYnn7jFw9+HuIVseoSIxPnPbn6JXesPDVLI/MYSey4rJQ==" }, "@writetome51/is-finite-number": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@writetome51/is-finite-number/-/is-finite-number-1.0.0.tgz", "integrity": "<KEY> }, "@writetome51/is-integer-is-float": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@writetome51/is-integer-is-float/-/is-integer-is-float-1.0.0.tgz", "integrity": "<KEY> "requires": { "@writetome51/is-finite-number": "~1.0.0" } }, "error-if-array-too-short-to-meet-adjacent-items-request": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/error-if-array-too-short-to-meet-adjacent-items-request/-/error-if-array-too-short-to-meet-adjacent-items-request-1.0.1.tgz", "integrity": "<KEY> }, "error-if-index-how-many-or-array-are-not-valid": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/error-if-index-how-many-or-array-are-not-valid/-/error-if-index-how-many-or-array-are-not-valid-1.0.1.tgz", "integrity": "<KEY> "requires": { "error-if-index-not-valid": "~1.0.0", "error-if-not-array": "~1.0.0", "error-if-not-integer-zero-or-greater": "~1.0.0" } }, "error-if-index-not-valid": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/error-if-index-not-valid/-/error-if-index-not-valid-1.0.0.tgz", "integrity": "<KEY> "requires": { "@writetome51/index-is-valid": "~1.0.0" } }, "error-if-not-array": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/error-if-not-array/-/error-if-not-array-1.0.0.tgz", "integrity": "<KEY> "requires": { "@writetome51/is-array-not-array": "~1.0.0" } }, "error-if-not-finite-number": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/error-if-not-finite-number/-/error-if-not-finite-number-1.0.0.tgz", "integrity": "<KEY> "requires": { "@writetome51/is-finite-number": "~1.0.0" } }, "error-if-not-integer": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/error-if-not-integer/-/error-if-not-integer-1.0.0.tgz", "integrity": "<KEY> "requires": { "@writetome51/is-integer-is-float": "~1.0.0", "error-if-not-finite-number": "~1.0.0" } }, "error-if-not-integer-zero-or-greater": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/error-if-not-integer-zero-or-greater/-/error-if-not-integer-zero-or-greater-1.0.0.tgz", "integrity": "sha512-m+KocWV9yaF0eZaLbwtz8jD7cfpiZWqDc9cOLe/4QJfp/lpqlJUVan1CcbUsGciFwUYQdSybyy6gxD9jsDkSIw==", "requires": { "error-if-not-integer": "~1.0.0" } } } }
json
<gh_stars>0 {"expireTime":9007200893392118000,"key":"transformer-remark-markdown-ast-21ace03af4bc42e3d07c473701d3064b-gatsby-remark-imagesgatsby-remark-responsive-iframegatsby-remark-prismjsgatsby-remark-copy-linked-filesgatsby-remark-smartypants-","val":{"type":"root","children":[{"type":"heading","depth":2,"children":[{"type":"text","value":"These are my texts choice:","position":{"start":{"line":2,"column":3,"offset":3},"end":{"line":2,"column":29,"offset":29},"indent":[]}}],"position":{"start":{"line":2,"column":1,"offset":1},"end":{"line":2,"column":29,"offset":29},"indent":[]}},{"type":"html","value":"<!-- ![](=250x250) -->","position":{"start":{"line":3,"column":1,"offset":30},"end":{"line":3,"column":23,"offset":52},"indent":[]}},{"type":"heading","depth":3,"children":[{"type":"text","value":"Vlog - Existentialism:","position":{"start":{"line":4,"column":4,"offset":56},"end":{"line":4,"column":26,"offset":78},"indent":[]}}],"position":{"start":{"line":4,"column":1,"offset":53},"end":{"line":4,"column":26,"offset":78},"indent":[]}},{"type":"list","ordered":false,"start":null,"spread":true,"children":[{"type":"listItem","spread":false,"checked":null,"children":[{"type":"paragraph","children":[{"type":"text","value":"Frankenstein ","position":{"start":{"line":5,"column":3,"offset":81},"end":{"line":5,"column":16,"offset":94},"indent":[]}},{"type":"image","title":null,"url":"https://humanities.drury.edu/wp-content/uploads/2016/01/Picture1.jpg\n=250x250","alt":null,"position":{"start":{"line":5,"column":16,"offset":94},"end":{"line":6,"column":10,"offset":176},"indent":[1]}}],"position":{"start":{"line":5,"column":3,"offset":81},"end":{"line":6,"column":10,"offset":176},"indent":[1]}}],"position":{"start":{"line":5,"column":1,"offset":79},"end":{"line":7,"column":1,"offset":177},"indent":[1,1]}},{"type":"listItem","spread":false,"checked":null,"children":[{"type":"paragraph","children":[{"type":"text","value":"The Metamorphosis","position":{"start":{"line":8,"column":3,"offset":180},"end":{"line":8,"column":20,"offset":197},"indent":[]}}],"position":{"start":{"line":8,"column":3,"offset":180},"end":{"line":8,"column":20,"offset":197},"indent":[]}}],"position":{"start":{"line":8,"column":1,"offset":178},"end":{"line":8,"column":20,"offset":197},"indent":[]}},{"type":"listItem","spread":false,"checked":null,"children":[{"type":"paragraph","children":[{"type":"text","value":"Lord of the Flies","position":{"start":{"line":9,"column":3,"offset":200},"end":{"line":9,"column":20,"offset":217},"indent":[]}}],"position":{"start":{"line":9,"column":3,"offset":200},"end":{"line":9,"column":20,"offset":217},"indent":[]}}],"position":{"start":{"line":9,"column":1,"offset":198},"end":{"line":9,"column":20,"offset":217},"indent":[]}}],"position":{"start":{"line":5,"column":1,"offset":79},"end":{"line":9,"column":20,"offset":217},"indent":[1,1,1,1]}},{"type":"heading","depth":3,"children":[{"type":"text","value":"Blog:","position":{"start":{"line":12,"column":4,"offset":223},"end":{"line":12,"column":9,"offset":228},"indent":[]}}],"position":{"start":{"line":12,"column":1,"offset":220},"end":{"line":12,"column":9,"offset":228},"indent":[]}},{"type":"list","ordered":false,"start":null,"spread":false,"children":[{"type":"listItem","spread":false,"checked":null,"children":[{"type":"paragraph","children":[{"type":"text","value":"The Picture of <NAME>","position":{"start":{"line":13,"column":3,"offset":231},"end":{"line":13,"column":29,"offset":257},"indent":[]}}],"position":{"start":{"line":13,"column":3,"offset":231},"end":{"line":13,"column":29,"offset":257},"indent":[]}}],"position":{"start":{"line":13,"column":1,"offset":229},"end":{"line":13,"column":29,"offset":257},"indent":[]}},{"type":"listItem","spread":false,"checked":null,"children":[{"type":"paragraph","children":[{"type":"text","value":"The Importance of Being Earnest","position":{"start":{"line":14,"column":3,"offset":260},"end":{"line":14,"column":34,"offset":291},"indent":[]}}],"position":{"start":{"line":14,"column":3,"offset":260},"end":{"line":14,"column":34,"offset":291},"indent":[]}}],"position":{"start":{"line":14,"column":1,"offset":258},"end":{"line":14,"column":34,"offset":291},"indent":[]}},{"type":"listItem","spread":false,"checked":null,"children":[{"type":"paragraph","children":[{"type":"text","value":"The Happy Prince and Other Tales","position":{"start":{"line":15,"column":3,"offset":294},"end":{"line":15,"column":35,"offset":326},"indent":[]}}],"position":{"start":{"line":15,"column":3,"offset":294},"end":{"line":15,"column":35,"offset":326},"indent":[]}}],"position":{"start":{"line":15,"column":1,"offset":292},"end":{"line":15,"column":35,"offset":326},"indent":[]}}],"position":{"start":{"line":13,"column":1,"offset":229},"end":{"line":15,"column":35,"offset":326},"indent":[1,1]}}],"position":{"start":{"line":1,"column":1,"offset":0},"end":{"line":15,"column":35,"offset":326}}}}
json
Mumbai experienced heavy rain throughout the intervening night of Friday and Saturday, leading to India Meteorological Department’s (IMD) Santacruz observatory recording 114 mm of rainfall in the last 24 hours. Officials at IMD said that Saturday witnessed the highest rainfall recorded within a 24-hour span in October. Last year, the highest single day October rainfall was recorded at 86. 5 mm. The overall highest single day figure in October was recorded in 1988, when it had rained 140. 8 mm on October 15. The IMD’s Colaba observatory recorded 85 mm of rainfall, which is also labelled as heavy rain, since as per department rules, rainfall recorded between 64. 5 mm and 115. 5 mm is described as heavy. Meanwhile, the figures recorded by the BMC also showed several areas in the island city recording rainfall in three digits. While Lower Parel recorded 210 mm of rain, CSMT recorded 208 mm of rain, followed by 151 mm in Nariman Point. Overall, the island city recorded 156. 79 mm of rain, followed by 99. 19 mm in eastern suburbs and 95. 84 mm of rain in western suburbs. The IMD forecast for the next five days stated that showers will continue on Sunday and Monday, with possibility of light to moderate rainfall accompanied by thunderstorm. Mahesh Palawat, meteorologist from Skymet, said that light spells of rain will continue till October 13, following which there is a possibility of monsoon retreating from Mumbai. “Two successive low pressure areas have been created in Bay of Bengal and coastal region of Maharashtra, due to which rainfall continues in Mumbai and several parts of northwest India,” he added. A senior IMD official said that there is presence of moisture in the air, due to which, there has been no significant rise in temperature.
english
# :smiley_cat: Mango Page Manager Plugin <br/> [![Taylor Swift](https://img.shields.io/badge/secured%20by-taylor%20swift-brightgreen.svg)](https://twitter.com/SwiftOnSecurity) [![Volkswagen](https://auchenberg.github.io/volkswagen/volkswargen_ci.svg?v=1)](https://github.com/auchenberg/volkswagen) [![TypeScript](https://badges.frapsoft.com/typescript/awesome/typescript.png?v=101)](https://github.com/ellerbrock/typescript-badges/) [![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) ## Getting Started > requires a `node` version >= 6 and an `npm` version >= 3.x.x > we do provide a `help` command to display all possible arguments ```bash # Install the base package and the plugin (could also be global -g) npm i @axelspringer/mango-api @axelspringer/mango-plugin-pagemanager ``` ## Installation Try to install this package before rendering. ```bash npm i @axelspringer/mango-api @axelspringer/mango-plugin-pagemanager ``` In you app, use the plugin and configure it. Use an extra file `pagemanager.ts` for it. ```javascript import Vue from 'vue' import PageManager from '@axelspringer/mango-plugin-pagemanager' import { SelectedArticles } from '../components/selectedArticles' // inject mango Vue.use(PageManager) export default new PageManager({ blocks: [ { pageBlock: 'selected_articles', component: SelectedArticles } ] }) ``` Then install it in your vue app options. ```javascript import Vue from 'vue' import pagemanager // create function export default function () { // constructing app const app = new Vue({ pagemanager, render: (h) => h(App) }) return { app } } ``` ## Usage in Components There are some components available with in the plugin. ### Renderer To use the Page Manager Render `<pagemanager-render>` you have to provide data to the `blocks` property. ```javascript import Vue from 'vue' import Component from 'vue-class-component' @Component export class Demo extends Vue { public render(h) { return ( <div> <pagemanager-renderer blocks={example} /> </div> ) } } ``` ## License [MIT](/LICENSE)
markdown
{"ast":null,"code":"import { createAppContainer } from \"react-navigation\";\nimport { createStackNavigator } from \"react-navigation-stack\";\nimport { HomeScreen, LoginScreen, RegisterScreen, AdminForgotPasswordScreen, AuthLoadingScreen, Dashboard, Adlist, AdminDashboard, PriorityIndex, AdminProcessList, AdminResolvedlist, Serviceroute, ServiceIssuelist } from \"./screens\";\nvar Router = createStackNavigator({\n AdminResolvedlist: AdminResolvedlist,\n Serviceroute: Serviceroute,\n ServiceIssuelist: ServiceIssuelist,\n AdminProcessList: AdminProcessList,\n Adlist: Adlist,\n HomeScreen: HomeScreen,\n LoginScreen: LoginScreen,\n RegisterScreen: RegisterScreen,\n AdminDashboard: AdminDashboard,\n AdminForgotPasswordScreen: AdminForgotPasswordScreen,\n Dashboard: Dashboard,\n PriorityIndex: PriorityIndex,\n AuthLoadingScreen: AuthLoadingScreen\n}, {\n initialRouteName: \"AuthLoadingScreen\",\n headerMode: \"none\"\n});\nexport default createAppContainer(Router);","map":{"version":3,"sources":["/home/op-pro/Desktop/Finalyear project/Admin/src/index.js"],"names":["createAppContainer","createStackNavigator","HomeScreen","LoginScreen","RegisterScreen","AdminForgotPasswordScreen","AuthLoadingScreen","Dashboard","Adlist","AdminDashboard","PriorityIndex","AdminProcessList","AdminResolvedlist","Serviceroute","ServiceIssuelist","Router","initialRouteName","headerMode"],"mappings":"AAAA,SAASA,kBAAT,QAAmC,kBAAnC;AACA,SAASC,oBAAT,QAAqC,wBAArC;AAEA,SACEC,UADF,EAEEC,WAFF,EAGEC,cAHF,EAIEC,yBAJF,EAKEC,iBALF,EAMEC,SANF,EAOEC,MAPF,EAQEC,cARF,EASEC,aATF,EAUEC,gBAVF,EAWEC,iBAXF,EAYEC,YAZF,EAaEC,gBAbF;AAgBA,IAAMC,MAAM,GAAGd,oBAAoB,CACjC;AACEW,EAAAA,iBAAiB,EAAjBA,iBADF;AAEEC,EAAAA,YAAY,EAAZA,YAFF;AAGEC,EAAAA,gBAAgB,EAAhBA,gBAHF;AAIEH,EAAAA,gBAAgB,EAAhBA,gBAJF;AAKEH,EAAAA,MAAM,EAANA,MALF;AAMEN,EAAAA,UAAU,EAAVA,UANF;AAOEC,EAAAA,WAAW,EAAXA,WAPF;AAQEC,EAAAA,cAAc,EAAdA,cARF;AASEK,EAAAA,cAAc,EAAdA,cATF;AAUEJ,EAAAA,yBAAyB,EAAzBA,yBAVF;AAWEE,EAAAA,SAAS,EAATA,SAXF;AAYEG,EAAAA,aAAa,EAAbA,aAZF;AAaEJ,EAAAA,iBAAiB,EAAjBA;AAbF,CADiC,EAiBjC;AACEU,EAAAA,gBAAgB,EAAE,mBADpB;AAEEC,EAAAA,UAAU,EAAE;AAFd,CAjBiC,CAAnC;AAuBA,eAAejB,kBAAkB,CAACe,MAAD,CAAjC","sourcesContent":["import { createAppContainer } from \"react-navigation\";\nimport { createStackNavigator } from \"react-navigation-stack\";\n\nimport {\n HomeScreen,\n LoginScreen,\n RegisterScreen,\n AdminForgotPasswordScreen,\n AuthLoadingScreen,\n Dashboard,\n Adlist,\n AdminDashboard,\n PriorityIndex,\n AdminProcessList,\n AdminResolvedlist,\n Serviceroute,\n ServiceIssuelist\n} from \"./screens\";\n\nconst Router = createStackNavigator(\n {\n AdminResolvedlist,\n Serviceroute,\n ServiceIssuelist,\n AdminProcessList,\n Adlist,\n HomeScreen,\n LoginScreen,\n RegisterScreen,\n AdminDashboard,\n AdminForgotPasswordScreen,\n Dashboard,\n PriorityIndex,\n AuthLoadingScreen,\n \n },\n {\n initialRouteName: \"AuthLoadingScreen\",\n headerMode: \"none\"\n }\n);\n\nexport default createAppContainer(Router);\n"]},"metadata":{},"sourceType":"module"}
json
Affincome Training Kit Unrestricted PLR review is a total training program envelops detailed screen tape-recorded videos, training guide, graphics, etc. that will certainly lead you with every step for establishing your own eCommerce organization as well as running it productively online. Affincome Training Kit PLR Review - What is it? This Unrestricted PLR opportunity with all the sales components will establish you up for lasting success in just minutes. With 'Unrestricted' Private Label Rights, also you can establish your r own on the internet realm as well as offer as numerous PLR licenses as you intend to bank huge revenues. This is A total, detailed video training encompassing whatever you need to know to instantly thrust yourself right into the major leagues as a professional affiliate marketing expert and see considerable amount of cash money flowing right into your savings account. This secret plan included countless bucks to the vendor's savings account. This is conserving you hundreds of dollars well worth of outsourcing and also releasing you lots of working hours. Gone are the days where you as a marketing professional hires a graphic assistant to create layouts for you for hundreds of dollars monthly. You can integrate principles as well as styles if you understand a little bit concerning graphics editing. What is Pligg? Pligg is an open source content management system that lets you easily create your own user-powered website.
english
Although the WWE Universe has enjoyed two nights of WrestleMania 38, there might be a few things from the event they haven't seen on television. WrestleMania 38 has seen many entertaining moments. Stone Cold Steve Austin, for example, returned to the ring for the first time in 19 years to defeat Kevin Owens in a No Holds Barred Match. Vince McMahon also made his in-ring return, defeating Pat McAfee before getting stunned by the Texas Rattlesnake. The WWE Universe may have seen everything that happened inside the ring during WrestleMania 38. Nevertheless, they may not have seen everything that went on outside the squared circle. Throughout the two WrestleMania nights, fans in attendance and WWE have posted several unseen footage from before, during, and after the event on social media. Here are ten things that happened at WrestleMania 38 you did not see on TV. Ronda Rousey and Charlotte Flair fought fiercely inside the ring for the SmackDown Women's Championship on the first night of WrestleMania 38. However, the crowd might have gotten somewhat distracted during the bout as another fight broke out outside the squared circle. According to some fans who attended WrestleMania, a fight started among the crowd during the SmackDown Women's Championship match. One fan even posted a photo of it on his Twitter account. However, it seems that WWE's security contained the situation successfully. Flair and Rousey's match ended with The Queen defeating The Baddest Woman on the Planet to retain her SmackDown Women's Championship. Johnny Knoxville went head-to-head against Sami Zayn on the second night of WrestleMania 38. With the help of his Jackass teammates, the 51-year-old defeated the former Intercontinental Champion. However, a day before scoring his first victory at WrestleMania, Knoxville got into a heated argument with a fan inside the AT&T Stadium. WWE Analyst for FOX Sports Ryan Satin posted a video of the incident on his Twitter account. After appearing on the WrestleMania Panel on Sunday, Becky Lynch broke character to greet and sign autographs for her young fans. One older fan also asked her to say hello to his four-year-old boy, and she immediately did. The father then posted the video on his Twitter account, thanking Big Time Becks for greeting his little kid. Stone Cold Steve Austin finally made his in-ring return at WrestleMania 38. He defeated Kevin Owens at the main event of the first night. After his victory, The Texas Rattlesnake invited his brother, Kevin Williams, to the ring to share a beer. However, Austin was not the only one his brother shared a beer with at WrestleMania. A fan captured a video of Austin's sibling also sharing a drink with San Francisco 49ers' tight end George Kittle among the crowd at the end of the first night of WrestleMania. The two seemed to enjoy celebrating Austin style. Several celebrities and athletes have attended this year's WrestleMania. A few wrestlers from other companies were also in attendance. On Sunday, former AEW star Big Swole tweeted a photo with Impact Knockouts World Champion Tasha Steelz while sitting among the WrestleMania 38 crowd. In the caption, Swole disclosed that they were celebrating Steelz's birthday. "It's my dawg birthday!! Had to do it big and what's bigger than #WrestleMania Happy birthday to my Day 365 @RealTSteelz love you to the moon boo!" she wrote. The former AEW star has now deleted her tweet. Cody Rhodes made a surprise return to WWE at WrestleMania 38 to face Seth Rollins. The two had an epic battle that finally ended with Rhodes defeating the former Universal Champion. After the match, WWE posted a behind-the-scenes video of Rhodes' WrestleMania return. However, it did not capture the moment he met Kevin Owens backstage. Several fans have shared a photo of the two wrestlers sharing a special moment backstage after Rhodes' return to Vince McMahon's company. Owens and Rhodes shared the ring a few times in 2016 before Dusty Rhodes' son left WWE. They seem to have a good relationship. Sasha Banks finally broke her WrestleMania losing streak after scoring her first victory yesterday at this year's Show of Shows. The Boss teamed up with Naomi to capture the WWE Women's Tag Team Titles after defeating Queen Zelina & Carmella, Rhea Ripley & Liv Morgan, and Natalya & Shayna Baszler. Banks seemed extremely happy to break her losing streak. On her way back after the match, she celebrated with her fans. Some of these fans posted videos of Banks' crazy celebrations on Twitter. Another thing fans never saw on television was Trish Stratus having fun riding Stone Cold Steve Austin's quad bike backstage. The WWE Hall of Famer attended WrestleMania 38, alongside several other legends like The Bella Twins, Lita, and Michelle McCool. Last night, the seven-time Women's Champion posted a video of herself riding Austin's quad bike backstage at WrestleMania on Instagram. The WWE Hall of Famer seemed very excited about using The Texas Rattlesnake's vehicle. Bianca Belair defeated Becky Lynch to capture the RAW Women's Championship for the first time at WrestleMania 38. After the bout, The EST of WWE took her celebrations backstage, where her husband, Montez Ford, waited for her. WWE's Instagram account posted a video of the emotional moment between the couple as they shared a kiss and a hug as soon as Belair walked backstage. The newly-crowned RAW Women's Champion also later started singing and dancing. Brock Lesnar and Roman Reigns went head-to-head yesterday at the main event of the second night of WrestleMania 38. Although The Beast Incarnate was very close to defeating The Tribal Chief several times during the match, it was Reigns who came out on top at the end to become the Undisputed WWE Universal Champion. The show ended with Reigns celebrating his victory while Lesnar lay in pain on the mat. However, after WrestleMania went off the air, Lesnar stood in the middle of the ring to acknowledge the fans. Fans also gave a standing ovation to the former WWE Champion. Some fans captured the emotional moment on video and posted it on Twitter.
english
This car is quite nice, although some improvements are needed in terms of comfort. Nevertheless, it remains the best car available within this price range. Tata has done a commendable job this time, demonstrating their dedication to producing quality vehicles. - Performance (133) - Engine (96) - Interior (79) It's amazing, with a great-looking body, outstanding safety features, and amazing mileage.
english
{ "name": "projects/project-name-1", "parent": "organizations/xsoar-organization", "projectId": "project-id-1", "state": "ACTIVE", "displayName": "My First Project", "createTime": "2021-11-01T10:43:50.858Z", "updateTime": "2021-11-01T10:43:53.026Z", "etag": "SIVTMlYY9sE1j3K0iNDLcw==" }
json
Netflix's hit comedy-drama 'Emily in Paris' creator Darren Star said that Emily (Lilly Collins) will assimilate more to French culture in Season 2 to assure the French critics who said the drama didn't showcase the culture in a way it should have. Netflix's hit comedy-drama 'Emily in Paris' creator Darren Star said that Emily (Lilly Collins) will assimilate more to French culture in Season 2 to assure the French critics who said the drama didn't showcase the culture in a way it should have. After the success of 'Emily in Paris', Netflix is all set to renew the popular romantic comedy series for the second season. The news broke in November 2020- less than two months after the launch of the show that created an online stir and drew a sniffy response from French critics. According to Variety, the show has been a strong performer for Netflix in the viewership department, breaking into Nielsen's list of the top 10 most-watched streaming shows for the week after its premiere. But, despite the popularity, the show was also met with critique for its handling of French culture, with some saying the series showcases a glamorized view of Paris through an American girl's eyes, according to Variety. Breaking the silence on if the same would happen in season 2, the show's creator Darren Star said to Variety, "For me, it's the evolution of the character. I think when someone goes to Paris for the first time, they are overwhelmed by the beauty of the city and that's what they're seeing. " He shared, "I think, perhaps, a lot of viewers who lived in Paris for a long time didn't quite understand that this was through the lens of a character who was experiencing the city for the first time. That's how she was perceiving it -- she was really struck by the beauty that was all around her. " The show that is shot entirely in Paris and other parts of France revolves around the life of a girl named Emily who is an ambitious girl in her twenties working as a marketing executive in Chicago. She unexpectedly lands a job in Paris when her company acquires a French luxury marketing company. As the story proceeds, Emily gets tasked with the revamping of the social media strategy of the company and then embarks on a new life in Paris. Teasing the titular character's journey in the second season, which just began production on Monday and will shoot in Paris, St. Tropez and other locations in the South of France, Darren told, "Certainly, the more quotidian aspects of life start to come in and I think that's what's going to happen to her. " In its forthcoming season, Darren shared that Emily will have to continue to adjust to French culture, but "that's not a response to the viral reaction to Season 1". "The first season didn't cover that much chronological time," Darren admitted while speaking to Variety, meng the episodes largely captured Emily's arrival in Paris, focusing heavily on her awe of the city. Darren further explained that the coming season will see Emily embracing the city a little bit more, while also still struggling with her French. "When she got there, she got a bit of a free pass in the beginning and I don't think it will be quite as easy for her in the second season. I think she will be more assimilated, in terms of living in Paris and stepping up to the challenges of learning the language," he shared. While teasing about the romantic plot, the 59-year-old shared that there are "many unexpected storylines" for Emily in the upcoming season. "There was a twist a the end of the first season that she did not see coming, and I think there's a lot of fallout that happens from the that in the new season," Darren told Variety, alluding to the cliffhanger with her chef love interest, Gabriel (Lucas Bravo). The show has not set a premiere date for its next season yet, but to celebrate the beginning of production, Collins released a statement on the show saying it was an honour for her to be associated with a project that provided people with some much-needed relief during a trying time when everyone was looking for a reason to smile and laugh. "Not only did playing Emily teach me more about myself, but also about the world around me. I couldn't be happier to be back in Season 2 to expand upon those lessons, to continue to grow, and learn even more about this beautiful city and all of its character with Emily," she said at that time, according to Variety. ( With inputs from ANI )
english
UPI Payment done in wrong account you can get money back know step by step procedure how to get refund By Lokmat English Desk | Published: November 18, 2022 02:52 PM2022-11-18T14:52:35+5:302022-11-18T14:52:35+5:30Next UPI (Unified Payment Interface) has made digital money transfer quite simple. A lot of focus is being placed on digital payment with new technology. The challenges associated with financial transactions have been significantly decreased by UPI, net banking, and mobile wallet. Nowadays, as digital transactions are going high, as a result, money is often transferred to the wrong UPI address. In case of a wrong UPI money transfer, the first thing you can you is to raise the issue at the support section of the respective UPI app you were using to transfer the money. Every UPI has their mechanism to provide support to customers in such cases. The second thing you can do in this case is to reach out to the BHIM Toll-Free number 18001201740 with queries or complaints. You can contact the given Toll-Free number and raise the issue with all the details to the representative. As soon as you know the money was transferred to the wrong UPI address, first take a screenshot of the message and contact your bank by phone or email. As soon as it's possible, schedule a meeting with the branch manager. The only bank that can address this issue is the one from whom the funds were transferred. Inform your bank about this transaction and contact the branch manager at the earliest. Describe everything that occurred to the customer care department of your bank. TagsBhim UpiUPI PaymentsGoogle PayShare :
english
<gh_stars>0 public class EmployeeDemo { public static void main(String[] args) { String name; int idNumber; String department; String position; Employee worker1 = new Employee(); Employee worker2 = new Employee(); Employee worker3 = new Employee(); worker1.setName("<NAME>"); worker2.setName("<NAME>"); worker3.setName("<NAME>"); worker1.setIdNumber(47899); worker2.setIdNumber(39119); worker3.setIdNumber(81774); worker1.setDepartment("Accounting"); worker2.setDepartment("IT"); worker3.setDepartment("Manufacturing"); worker1.setPosition("Vice President"); worker2.setPosition("Programmer"); worker3.setPosition("Engineer"); System.out.println("Name" +" " + "ID Number" + " " + "Department" +" " + "Position"); System.out.println("=============================================================" + "========"); System.out.println(worker1.getName() + " " + worker1.getIdNumber() + " " + worker1.getDepartment() + " "+ worker1.getPosition()); System.out.println(worker2.getName() + " " + worker2.getIdNumber() + " " + worker2.getDepartment() + " "+ worker2.getPosition()); System.out.println(worker3.getName() + " " + worker3.getIdNumber() + " " + worker3.getDepartment() + " "+ worker3.getPosition()); } }
java
<reponame>Lattay/bottlecap /** * Initialize a new Canvas * @param {number} width * @param {number} height * @param {string} background - background color */ export function createCanvas(width = 400, height = 400, background) { const canvas = document.createElement('canvas'); // canvas canvas.width = width; // set width canvas.height = height; // set height if(background) canvas.style.background = background; // change background return canvas; }
javascript
@font-face { font-family: Wave; font-weight: normal; font-style: normal; src: url('../fonts/Wave.ttf') format('truetype'), url('../fonts/Wave.woff') format('woff'), url('../fonts/Wave.svg') format('svg'); } .icon::before { display: inline-block; font: normal normal normal 24px/1 Wave, sans-serif; font-size: inherit; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; line-height: inherit; text-rendering: auto; } .icon-chevron-left::before { content: "\e929"; } .icon-chevron-right::before { content: "\e92a"; } .icon-arrow-left::before { content: "\e92b"; } .icon-arrow-right::before { content: "\e92c"; } .icon-menu-down::before { content: "\e92e"; } .icon-menu-up::before { content: "\e900"; } .icon-window-close::before { content: "\e92f"; } .icon-white-balance-sunny::before { content: "\e930"; } .icon-brightness-2::before { content: "\e931"; } .icon-bookmark::before { content: "\e933"; } .icon-star::before { content: "\e901"; } .icon-map-marker::before { content: "\e92d"; } .icon-web::before { content: "\e91c"; } .icon-facebook::before { content: "\e936"; } .icon-twitter::before { content: "\e940"; } .icon-apple::before { content: "\e934"; } .icon-google::before { content: "\e914"; } .icon-overcast::before { content: "\e935"; } .icon-spotify::before { content: "\e937"; } .icon-stitcher::before { content: "\e938"; } .icon-rss::before { content: "\e939"; } .icon-play::before { content: "\e932"; } .icon-pause::before { content: "\e902"; } .icon-rewind-10::before { content: "\e903"; } .icon-fast-forward-30::before { content: "\e904"; } .icon-download::before { content: "\e905"; } .icon-menu::before { content: "\e906"; }
css
Manchester City left it late to seal a 100-point Premier League season but Gabriel Jesus was the champions' final day hero as he snatched a 1-0 win deep into stoppage time at Southampton. City have set competition records for wins, goals scored and points acquired during their march to glory in 2017-18, although little of their usual panache was in evidence during a listless opening half at St Mary's. The unlikely 10-goal swing required to put Saints in danger of relegation never looked to be on the cards and Mark Hughes' well-manned defence coped assuredly with mounting City pressure after the break. That was until Kevin De Bruyne's exquisite lofted pass – a 16th league assist of the campaign for the Belgium playmaker - sent substitute Jesus clear to loft a cool finish over goalkeeper Alex McCarthy. Southampton defender Wesley Hoedt came closest to opening the scoring before the break when he hit the crossbar in the eighth minute, while Dusan Tadic almost settled the match in the hosts' favour before Brazil striker Jesus signed off ahead of the World Cup with a thrilling last-gasp salvo. Claudio Bravo was given another outing in the City goal and grasped an attempt from the marauding Jack Stephens at the second attempt. Stephens' fellow centre-back Hoedt then headed Tadic's corner against the bar amid an ambling start from the champions. Hoedt had another chance in the 25th minute but dragged wide at the far post following Tadic's latest set-piece delivery. Sterling was the man who scored a dramatic winner at the death when the sides met in November and the England winger scythed over looking for the spectacular as a forgettable first half reached its conclusion. John Stones just failed to get on the end of De Bruyne's teasing free-kick four minutes into the second period, which City began in the manner of a team stung by some sharp words from their manager. In the 56th-minute Fernandinho should have done better than smash a volley horribly over from inside the Southampton box and Jesus was introduced in place of Fabian Delph to give them an attacking focal point. The pressure was piling up for Southampton, with Sterling crashing a deflected shot against the post and Stones forcing McCarthy to tip over from the resulting corner before De Bruyne fizzed one wide from the edge of the box. A twinkle-toed Tadic almost won it for Southampton in the 78th minute – dancing around Bravo but seeing Fernandinho clout his shot off the line. City academy products Brahim Diaz and Phil Foden came off the bench to make their fifth appearances of the season, meaning they will both collect a league-winners' medal. And the teenagers had a front-row view as Jesus capitalised on De Bruyne's expert service in ice-cool fashion, prompting a jubilant Guardiola to leap on to the field – another piece of history achieved by his superb team. Key Opta stats: - This is the first time in his career that Pep Guardiola has won 100 points in a single season as manager. - Manchester City trailed for a total of just 153 minutes in Premier League matches this season – the fewest by a side in a single campaign. - The Citizens set a new Premier League record for the biggest goal difference in a single season (+79). - Before becoming Manchester City manager in 2008, Mark Hughes was unbeaten against them in the Premier League (W4 D4 L0). Since leaving, he’s won only two of his 14 league meetings against the Citizens (D3 L9). - Kevin De Bruyne provided more assists than any other player in the Premier League this season (16). He also set a record for most wins by a player in a single PL season (31).
english
Aparshakti Khurana has a carved a niche for himself, thanks to films like Dangal, Stree, and Pati Patni Aur Woh. With no qualms of acting for supporting roles, Aparshakti gives an interesting insight into how he has slowly made his way to the top. "The love and respect that I have received, I wouldn't have gotten it otherwise. I would have just been a star brother who got up one day and wanted to act," said Khurana. He elaborates, "Whenever things happen overnight, it changes your mindset. Then I would have not had the 700k followers on Instagram. I would not have been so chirpy and jumpy. It would have got into my head. We are people from the generation who are unable to handle fame and we tend to get too full of ourselves. I am extremely happy with how things have been going for me one step at a time," he said. "Not getting a lead role is not the end of the world. At the same time, it is important to have rejection and failure after two-three years to keep you grounded. It's important to take that criticism constructively," he said. A person of many talents, Khurana tried his hands at being a lawyer, a cricketer and a radio jockey among other things. However, he is now happy to have finally settled in for acting. He explained, "Our generation is indecisive and fickle-minded. An inner calling never happened to me for the rest of the professions. " He recently featured in a song Teri Yaari with Milind Gaba and King Kaazi. The song has received a warm response. "The song is a hit, we have achieved our aim and are extremely happy with the response," he said. The actor will now be seen playing a lead in his upcoming movie Helmet, which also features Pranutan Behl, Abhishek Banerjee and Ashish Verma in the lead roles. Talking about the film, he shared, "It's the year 2020 and we still have so many taboos. Even in big cities like Mumbai, it a big deal to go and ask for a condom. This one is a quirky comedy about the same. "
english
Ahead of Chief Minister M. K. Stalin’s visit to Erode on August 25 and 26, members of the Perundurai SIPCOT Affected People Welfare Association have urged him to include 26 left-out water bodies in villages located around the Sipcot under the Athikadavu-Avinashi Ground Water Recharge and Drinking Water Supply Scheme. In an email sent to the Chief Minister, association coordinator S. Chinnasamy, said that a total of 1,045 water bodies in the districts of Coimbatore, Erode and Tiruppur have been included in the project. But water bodies in the panchayats of Perundurai, Ingur, Vadamugam Vellode, Vaipadi, Kambiliyampatti, Panayampalli, Ottaparai and Mugasi Pidariyur were left out causing shock to the people. The mail claimed that the discharge of untreated effluents from the dyeing and tannery units functioning at the Sipcot Industrial Estate at Perundurai had polluted the water bodies around the premises. “The Total Dissolved Solids is 10,000 parts per million and the water cannot be used,” the email said. People depend on water from River Cauvery to quench their thirst. But, the water is also inadequate, the email said. “A long-term solution to the problem is to include the water bodies under the scheme”, the email said. The email said that many representations were made to the previous government, but no action was taken. “The Executive Engineer of the Public Works Department had promised that when inspection is done for Phase 2 of the project, the department would consider including the water bodies”, the email said and added that inspection was done and a report was submitted to the government. Since the water requirement for refilling the water bodies is very less, the government should take steps and include the water bodies, the email said.
english
<filename>demo-extended/src/main/java/com/novoda/sqliteprovider/demo/ui/base/NovodaActivity.java package com.novoda.sqliteprovider.demo.ui.base; import android.support.v4.app.FragmentActivity; import com.novoda.sqliteprovider.demo.NovodaApplication; public class NovodaActivity extends FragmentActivity { public NovodaApplication getApp() { return (NovodaApplication) getApplication(); } }
java
<filename>rest_framework_security/brute_force_protection/exceptions.py<gh_stars>1-10 class BruteForceProtectionException(Exception): pass class BruteForceProtectionBanException(BruteForceProtectionException): pass class BruteForceProtectionCaptchaException(BruteForceProtectionException): pass
python
<filename>dataset/khvn/19510424.json version https://git-lfs.github.com/spec/v1 oid sha256:cf7a1ceea338b7a8ac2f7724b1bb2e5e7f0512ed5ed53c4e33402f8032d64783 size 13767
json
package ca.uwaterloo.jrefactoring.template; import ca.uwaterloo.jrefactoring.node.RFNodeDifference; import ca.uwaterloo.jrefactoring.utility.ASTNodeUtil; import ca.uwaterloo.jrefactoring.utility.FileLogger; import ca.uwaterloo.jrefactoring.utility.RenameUtil; import ca.uwaterloo.jrefactoring.visitor.MethodVisitor; import org.eclipse.jdt.core.*; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jface.text.Document; import org.eclipse.text.edits.TextEdit; import org.slf4j.Logger; import java.util.*; import static org.eclipse.jdt.core.dom.CompilationUnit.IMPORTS_PROPERTY; public class RFTemplate { private static Logger log = FileLogger.getLogger(RFTemplate.class); private static final String TYPE_NAME_PREFIX = "T"; private static final String CLAZZ_NAME_PREFIX = "clazz"; private static final String CLASS_NAME = "Class"; private static final String EXCEPTION_NAME = "Exception"; private static final String THROWABLE_NAME = "Throwable"; private static final String DEFAULT_LAMBDA_VARIABLE_NAME = "f"; private static final String DEFAULT_LAMBDA_PARAMETER_NAME = "x"; private static final String DEFAULT_LAMBDA_FUNCTION_CLASS_TEMPLATE = "java.util.function.To%sFunction"; private static final String DEFAULT_ADAPTER_VARIABLE_NAME = "adapter"; private static final String DEFAULT_ADAPTER_METHOD_NAME = "action"; private static final String DEFAULT_TEMPLATE_CLASS_NAME = "TestTemplates"; public static final String NULL_PARAMETER_OBJECT = "nullParameterObject"; private static final String JAVA_LANG_CLASS = "java.lang.Class"; private static final String ASSERT_KEYWORD = "assert"; private static final String NEW_KEYWORD = "new"; private static final String CASE_KEYWORD = "case"; private static final String SHORT_KEYWORD = "short"; private static final String FOR_KEYWORD = "for"; private static final Set<String> keywords = new HashSet<>(Arrays.asList(ASSERT_KEYWORD, NEW_KEYWORD, CASE_KEYWORD, SHORT_KEYWORD, FOR_KEYWORD)); private static final String KEYWORD_SUFFIX = "Action"; private static final String OBJECT_NAME = "Object"; private static final String JAVA_OBJECT_FULL_NAME = "java.lang.Object"; private static final Set<String> javaObjectMethodNames = new HashSet<>(Arrays.asList("hashCode", "equals", "clone", "toString", "finalize")); private static final boolean ENABLE_LAMBDA = true; private AST ast; private MethodDeclaration templateMethod; private TypeDeclaration templateClass; private CompilationUnit templateCU; private TypeDeclaration adapter; private TypeDeclaration adapterImpl1; private TypeDeclaration adapterImpl2; private Map<TypePair, String> typeMap; private Map<String, TypePair> genericTypeMap; private Map<MethodInvocationPair, String> methodInvocationMap; private Map<String, String> clazzInstanceMap; private Map<String, String> nameMap1; private Map<String, String> nameMap2; private Map<String, Integer> parameterMap; private SingleVariableDeclaration lambdaVariable; private SingleVariableDeclaration adapterVariable; private Set<String> adapterTypes; private Map<ClassInstanceCreation, Type> instanceCreationTypeMap; private List<Expression> templateArguments1; private List<Expression> templateArguments2; private MethodDeclaration method1; private MethodDeclaration method2; private CompilationUnit compilationUnit1; private CompilationUnit compilationUnit2; private PackageDeclaration packageDeclaration1; private PackageDeclaration packageDeclaration2; private CompilationUnit adapterInterfaceCU; private CompilationUnit adapterImplCU1; private CompilationUnit adapterImplCU2; private List<Name> cuImports1; private List<Name> cuImports2; private List<Name> templateCUImports; private int clazzCount; private int typeCount; private int actionCount; private int variableCount; private boolean hasLambda; private boolean lambdaParameterAdded; private Type lambdaParameterType; private boolean hasAdapterVariable; private List<NodePair> unrefactoredList; private Map<String, Integer> adapterActionNameMap; private Map<String, Integer> genericTypeNameMap; private ICompilationUnit iCU1; private ICompilationUnit iCU2; private IPackageFragmentRoot packageFragmentRoot; private boolean refactorable; private boolean hasNullParameterObject; private Set<String> templateVariableNames; private boolean throwsAllException; private boolean accessIssue; public RFTemplate(AST ast, MethodDeclaration method1, MethodDeclaration method2, String templateName, String adapterName, String[] adapterImplNamePair, ICompilationUnit iCU1, ICompilationUnit iCU2) { assert adapterImplNamePair.length == 2; this.ast = ast; this.typeMap = new HashMap<>(); this.genericTypeMap = new HashMap<>(); this.methodInvocationMap = new HashMap<>(); this.clazzInstanceMap = new HashMap<>(); this.nameMap1 = new HashMap<>(); this.nameMap2 = new HashMap<>(); this.parameterMap = new HashMap<>(); this.adapterTypes = new HashSet<>(); this.instanceCreationTypeMap = new HashMap<>(); this.clazzCount = 1; this.typeCount = 1; this.actionCount = 1; this.variableCount = 1; this.hasLambda = false; this.lambdaParameterAdded = false; this.lambdaParameterType = null; this.hasAdapterVariable = false; this.templateArguments1 = new ArrayList<>(); this.templateArguments2 = new ArrayList<>(); this.method1 = (MethodDeclaration) ASTNode.copySubtree(this.ast, method1); this.method2 = (MethodDeclaration) ASTNode.copySubtree(this.ast, method2); this.compilationUnit1 = (CompilationUnit) method1.getRoot(); this.compilationUnit2 = (CompilationUnit) method2.getRoot(); this.packageDeclaration1 = compilationUnit1.getPackage(); this.packageDeclaration2 = compilationUnit2.getPackage(); this.cuImports1 = new ArrayList<>(); this.cuImports2 = new ArrayList<>(); this.templateCUImports = new ArrayList<>(); this.unrefactoredList = new ArrayList<>(); this.adapterActionNameMap = new HashMap<>(); this.genericTypeNameMap = new HashMap<>(); this.iCU1 = iCU1; this.iCU2 = iCU2; this.packageFragmentRoot = (IPackageFragmentRoot) iCU1.getAncestor(3); this.refactorable = true; this.hasNullParameterObject = false; this.templateVariableNames = new HashSet<>(); this.throwsAllException = false; this.accessIssue = false; init(templateName, adapterName, adapterImplNamePair); } private void init(String templateName, String adapterName, String[] adapterImplNamePair) { initTemplate(templateName); initAdapter(adapterName); initAdapterImpl(adapterImplNamePair[0], adapterImplNamePair[1]); initPackageDeclaration(); } private void initTemplate(String templateName) { templateMethod = ast.newMethodDeclaration(); templateMethod.setBody(ast.newBlock()); templateMethod.setName(ast.newSimpleName(templateName)); String name1 = compilationUnit1.getJavaElement().getElementName(); String name2 = compilationUnit2.getJavaElement().getElementName(); if (!packageDeclaration1.getName().getFullyQualifiedName().equals(packageDeclaration2.getName().getFullyQualifiedName()) || !name1.equals(name2)) { templateMethod.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); templateMethod.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); templateClass = ast.newTypeDeclaration(); templateClass.setName(ast.newSimpleName(templateName.substring(0, 1).toUpperCase() + templateName.substring(1))); templateClass.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); templateClass.bodyDeclarations().add(templateMethod); templateCU = ast.newCompilationUnit(); templateCU.types().add(templateClass); } else { templateClass = null; templateCU = null; templateMethod.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); } if (method1.thrownExceptionTypes().size() > 0 || method2.thrownExceptionTypes().size() > 0) { throwsAllException = true; } } private void initAdapter(String adapterName) { // init lambda variable this.lambdaVariable = ast.newSingleVariableDeclaration(); lambdaVariable.setName(ast.newSimpleName(DEFAULT_LAMBDA_VARIABLE_NAME)); // init Adapter interface adapter = ast.newTypeDeclaration(); Modifier publicModifier = ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); adapter.modifiers().add(publicModifier); adapter.setInterface(true); adapter.setName(ast.newSimpleName(adapterName)); // init Adapter CU adapterInterfaceCU = ast.newCompilationUnit(); adapterInterfaceCU.types().add(adapter); // init adapter variable this.adapterVariable = ast.newSingleVariableDeclaration(); Type type = ast.newSimpleType((SimpleName) ASTNode.copySubtree(ast, adapter.getName())); adapterVariable.setType(type); adapterVariable.setName(ast.newSimpleName(DEFAULT_ADAPTER_VARIABLE_NAME)); //String adapterVariableName = adapterName.substring(0, 1).toLowerCase() + adapterName.substring(1); //adapterVariable.setName(ast.newSimpleName(adapterVariableName)); } private void initAdapterImpl(String adapterImplName1, String adapterImplName2) { // init Adapter impl class adapterImpl1 = ast.newTypeDeclaration(); adapterImpl2 = ast.newTypeDeclaration(); Modifier publicModifier1 = ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); Modifier publicModifier2 = ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); adapterImpl1.modifiers().add(publicModifier1); adapterImpl2.modifiers().add(publicModifier2); adapterImpl1.setName(ast.newSimpleName(adapterImplName1)); adapterImpl2.setName(ast.newSimpleName(adapterImplName2)); Type interfaceType = ast.newSimpleType(ast.newSimpleName(adapter.getName().getIdentifier())); adapterImpl1.superInterfaceTypes().add(ASTNode.copySubtree(ast, interfaceType)); adapterImpl2.superInterfaceTypes().add(ASTNode.copySubtree(ast, interfaceType)); // init Adapter impl CU adapterImplCU1 = ast.newCompilationUnit(); adapterImplCU2 = ast.newCompilationUnit(); adapterImplCU1.types().add(adapterImpl1); adapterImplCU2.types().add(adapterImpl2); } private void initPackageDeclaration() { PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); String commonPackageName = ASTNodeUtil.getCommonPackageName(packageDeclaration1.getName().getFullyQualifiedName(), packageDeclaration2.getName().getFullyQualifiedName()); if (commonPackageName != null && commonPackageName.length() > 0) { Name packageName = ASTNodeUtil.createPackageName(ast, commonPackageName); if (packageName != null) { packageDeclaration.setName(packageName); adapterInterfaceCU.setPackage(packageDeclaration); adapterImplCU1.setPackage((PackageDeclaration) ASTNode.copySubtree(ast, packageDeclaration)); adapterImplCU2.setPackage((PackageDeclaration) ASTNode.copySubtree(ast, packageDeclaration)); if (templateCU != null) { templateCU.setPackage((PackageDeclaration) ASTNode.copySubtree(ast, packageDeclaration)); initImportDeclaration(commonPackageName); } } } } private void initImportDeclaration(String commonPackageName) { String templateName = commonPackageName + "." + templateClass.getName().getIdentifier(); if (!commonPackageName.equals(packageDeclaration1.getName().getFullyQualifiedName())) { String adapterImplName1 = commonPackageName + "." + adapterImpl1.getName().getIdentifier(); cuImports1.add(ASTNodeUtil.createPackageName(ast, templateName)); cuImports1.add(ASTNodeUtil.createPackageName(ast, adapterImplName1)); } if (!commonPackageName.equals(packageDeclaration2.getName().getFullyQualifiedName())) { String adapterImplName2 = commonPackageName + "." + adapterImpl2.getName().getIdentifier(); cuImports2.add(ASTNodeUtil.createPackageName(ast, templateName)); cuImports2.add(ASTNodeUtil.createPackageName(ast, adapterImplName2)); } } public enum Pair { member1, member2 } public AST getAst() { return ast; } public void setModifier(Modifier.ModifierKeyword modifier) { templateMethod.modifiers().add(ast.newModifier(modifier)); } public boolean containsTypePair(TypePair typePair) { return typeMap.containsKey(typePair); } public boolean containsGenericType(String type) { return clazzInstanceMap.containsKey(type); } public String getClazz(String type) { return clazzInstanceMap.get(type); } public String getGenericTypeName(TypePair typePair) { return typeMap.get(typePair); } public ICompilationUnit getiCU1() { return iCU1; } public ICompilationUnit getiCU2() { return iCU2; } public boolean containsGenericNameInMap(String genericName) { return genericTypeMap.containsKey(genericName); } public TypePair getTypePairFromGenericMap(String genericName) { return genericTypeMap.get(genericName); } public boolean containTypeBound(String fromType, String toType) { List<TypeParameter> typeParameters = templateMethod.typeParameters(); for (TypeParameter typeParameter : typeParameters) { if (typeParameter.getName().getIdentifier().equals(fromType)) { List<Type> typeBounds = typeParameter.typeBounds(); for (Type typeBound : typeBounds) { if (typeBound.isParameterizedType()) { if (typeBound.toString().equals(toType)) { return true; } } else { if (((SimpleType) typeBound).getName().getFullyQualifiedName().equals(toType)) { return true; } } } } } return false; } public List<Expression> getTemplateArguments1() { return templateArguments1; } public List<Expression> getTemplateArguments2() { return templateArguments2; } public CompilationUnit getTemplateCU() { return templateCU; } public boolean isRefactorable() { return refactorable && !hasUnrefactorableNodePair(); } public void markAsUnrefactorable() { refactorable = false; } public void markAccessIssue() { accessIssue = true; } public boolean getAccessIssue() { return accessIssue; } public Type getTypeByInstanceCreation(ClassInstanceCreation instanceCreation) { return this.instanceCreationTypeMap.get(instanceCreation); } public boolean hasUnrefactorableNodePair() { return unrefactoredList.size() > 0; } public boolean comesFromSamePackage() { return packageDeclaration1.getName().getFullyQualifiedName().equals( packageDeclaration2.getName().getFullyQualifiedName()); } public void addUnrefactoredNodePair(Expression node1, Expression node2, RFNodeDifference diff) { NodePair nodePair = new NodePair(node1, node2, diff); unrefactoredList.add(nodePair); } public void addTemplateArgumentPair(Expression arg1, Expression arg2) { this.templateArguments1.add((Expression) ASTNode.copySubtree(ast, arg1)); this.templateArguments2.add((Expression) ASTNode.copySubtree(ast, arg2)); } public boolean addVariableName(String name) { return templateVariableNames.add(name); } public void addStatement(Statement statement) { templateMethod.getBody().statements().add(statement); } public void addInstanceCreation(ClassInstanceCreation instanceCreation, Type type) { if (instanceCreation != null) { this.instanceCreationTypeMap.put(instanceCreation, type); } } public void addNullParameterObject() { if (!hasNullParameterObject) { VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment(); variableDeclarationFragment.setName(ast.newSimpleName(NULL_PARAMETER_OBJECT)); variableDeclarationFragment.setInitializer(ast.newNullLiteral()); VariableDeclarationStatement variableDeclarationStatement = ast.newVariableDeclarationStatement(variableDeclarationFragment); variableDeclarationStatement.setType(ast.newSimpleType(ast.newSimpleName("Object"))); templateMethod.getBody().statements().add(0, variableDeclarationStatement); hasNullParameterObject = true; } } public String resolveTypePair(TypePair typePair, boolean extendsCommonSuperClass) { if (!typeMap.containsKey(typePair)) { // get common super class ITypeBinding commonSuperClass = getLowestCommonSuperClass(typePair); ITypeBinding commonInterface = getLowestCommonInterface(typePair); // if (commonSuperClass == null && commonInterface == null && (typePair.getType1().isParameterizedType() || typePair.getType2().isParameterizedType())) { markAsUnrefactorable(); throw new IllegalStateException("no common super class for parameterized types: " + typePair.getType1().getQualifiedName() + ", " + typePair.getType2().getQualifiedName()); } // set type name String commonName = RenameUtil.constructCommonName(typePair.getType1().getName(), typePair.getType2().getName(), true); if (commonInterface != null && commonInterface.isParameterizedType()) { commonName = commonInterface.getName(); } commonName = RenameUtil.encodeParameterizedName(commonName); String typeName; if (!commonName.equals("")) { int nameCount = genericTypeNameMap.getOrDefault(commonName, 0); if (nameCount == 0) { typeName = TYPE_NAME_PREFIX + commonName; } else { typeName = TYPE_NAME_PREFIX + commonName + nameCount; } genericTypeNameMap.put(commonName, nameCount + 1); } else if (commonSuperClass != null) { String commonSuperClassName = commonSuperClass.getName(); String[] nameComponents = RenameUtil.splitCamelCaseName(commonSuperClassName); StringBuilder newCommonSuperClassName = new StringBuilder(); for (String component : nameComponents) { if (!component.equals("Abstract")) { newCommonSuperClassName.append(component); } } int nameCount = genericTypeNameMap.getOrDefault(newCommonSuperClassName.toString(), 0); if (nameCount == 0) { typeName = TYPE_NAME_PREFIX + newCommonSuperClassName.toString(); } else { typeName = TYPE_NAME_PREFIX + newCommonSuperClassName.toString() + nameCount; } genericTypeNameMap.put(newCommonSuperClassName.toString(), nameCount + 1); } else { typeName = TYPE_NAME_PREFIX + typeCount++; } typeMap.put(typePair, typeName); genericTypeMap.put(typeName, typePair); addGenericType(typeName); // add common generic type bound if (extendsCommonSuperClass) { if (commonSuperClass == null && commonInterface != null) { commonSuperClass = commonInterface; } if (commonSuperClass != null) { if (commonSuperClass.isParameterizedType()) { List<TypeParameter> typeParameters = templateMethod.typeParameters(); for (TypeParameter typeParameter : typeParameters) { if (typeParameter.getName().getIdentifier().equals(typeName)) { typeParameter.typeBounds().add(ASTNodeUtil.typeFromBinding(ast, commonSuperClass)); } } } else { addGenericTypeBound(typeName, commonSuperClass.getName()); } String commonSuperClassPackageName = commonSuperClass.getPackage().getName(); // get common super class full name String commonSuperClassFullName; if (commonSuperClass.isParameterizedType()) { commonSuperClassFullName = commonSuperClass.getErasure().getQualifiedName(); } else { commonSuperClassFullName = commonSuperClass.getQualifiedName(); } if (templateCU == null && !commonSuperClassPackageName.equals(packageDeclaration1.getName().getFullyQualifiedName())) { templateCUImports.add(ASTNodeUtil.createPackageName(ast, commonSuperClassFullName)); } if (templateCU != null && !commonSuperClassPackageName.equals(templateCU.getPackage().getName().getFullyQualifiedName())) { addImportDeclaration(templateCU, ASTNodeUtil.createPackageName(ast, commonSuperClassFullName), false); } } } } return typeMap.get(typePair); } public static ITypeBinding getLowestCommonSuperClass(TypePair typePair) { ITypeBinding p1 = typePair.getType1(); ITypeBinding p2 = typePair.getType2(); while (p1 != null || p2 != null) { if (p1 != null && p2 != null && p1.getBinaryName().equals(p2.getBinaryName())) { return p1; } else { if (p1 == null) { p1 = typePair.getType2(); } else { p1 = p1.getSuperclass(); } if (p2 == null) { p2 = typePair.getType1(); } else { p2 = p2.getSuperclass(); } } } return null; } public static ITypeBinding getLowestCommonInterface(TypePair typePair) { ITypeBinding p1 = typePair.getType1(); ITypeBinding p2 = typePair.getType2(); Set<String> interfaceSet = new HashSet<>(); Queue<ITypeBinding> queue1 = new ArrayDeque<>(); Queue<ITypeBinding> queue2 = new ArrayDeque<>(); if (p1.isInterface()) { queue1.offer(p1); } else { for (ITypeBinding iTypeBinding : p1.getInterfaces()) { queue1.offer(iTypeBinding); } } if (p2.isInterface()) { queue2.offer(p2); } else { for (ITypeBinding iTypeBinding : p2.getInterfaces()) { queue2.offer(iTypeBinding); } } while(!queue2.isEmpty()) { ITypeBinding cur = queue2.poll(); interfaceSet.add(cur.getQualifiedName()); for (ITypeBinding iTypeBinding : cur.getInterfaces()) { queue2.offer(iTypeBinding); } } while(!queue1.isEmpty()) { ITypeBinding cur = queue1.poll(); if (interfaceSet.contains(cur.getQualifiedName())) { return cur; } else { for (ITypeBinding iTypeBinding : cur.getInterfaces()) { queue1.offer(iTypeBinding); } } } return null; } public boolean containsVariableNamePair(String name1, String name2) { String resolvedName1 = nameMap1.getOrDefault(name1, ""); String resolvedName2 = nameMap2.getOrDefault(name2, ""); assert resolvedName1.equals(resolvedName2); return !resolvedName1.equals(""); } public String resolveVariableName(String name1, String name2, String prefix) { String resolvedName1 = nameMap1.getOrDefault(name1, ""); String resolvedName2 = nameMap2.getOrDefault(name2, ""); assert resolvedName1.equals(resolvedName2); if (resolvedName1.equals("")) { String commonName = RenameUtil.renameVariable(name1, name2, variableCount++, prefix); while (!templateVariableNames.add(commonName)) { commonName = RenameUtil.renameVariable(name1, name2, variableCount++, prefix); } nameMap1.put(name1, commonName); nameMap2.put(name2, commonName); return commonName; } else { return resolvedName1; } } public String resolveGenericType(String genericType) { if (!clazzInstanceMap.containsKey(genericType)) { String clazzName = CLAZZ_NAME_PREFIX + genericType; //String clazzName = CLAZZ_NAME_PREFIX + genericType + clazzCount++; clazzInstanceMap.put(genericType, clazzName); recordLambdaForParameter(genericType); addClazzInParameter(genericType); } return clazzInstanceMap.get(genericType); } private void addTypeParameterAdapterImpl(Type type, List<Type> superInterfaceTypes) { Type interfaceType = superInterfaceTypes.get(0); ParameterizedType parameterizedType; if (interfaceType instanceof SimpleType) { parameterizedType = ast.newParameterizedType((Type) ASTNode.copySubtree(ast, interfaceType)); parameterizedType.typeArguments().add(type); superInterfaceTypes.remove(0); superInterfaceTypes.add(parameterizedType); } else { parameterizedType = (ParameterizedType) interfaceType; parameterizedType.typeArguments().add(type); } } private Type resolveAdapterActionArgumentType(Expression expr, ITypeBinding iTypeBinding) { // get exprType Type exprType; if (iTypeBinding != null && expr instanceof NullLiteral) { exprType = ASTNodeUtil.typeFromBinding(ast, iTypeBinding); } else { exprType = (Type) expr.getProperty(ASTNodeUtil.PROPERTY_TYPE_BINDING); } if (exprType != null) { if (typeMap.values().contains(exprType.toString()) && !adapterTypes.contains(exprType.toString())) { // add type parameter in adapter interface TypeParameter typeParameter = ast.newTypeParameter(); typeParameter.setName(ast.newSimpleName(exprType.toString())); adapter.typeParameters().add(typeParameter); // add type parameter in adapter impl TypePair typePair = genericTypeMap.get(exprType.toString()); if (typePair != null) { Type type1 = ASTNodeUtil.typeFromBinding(ast, typePair.getType1()); Type type2 = ASTNodeUtil.typeFromBinding(ast, typePair.getType2()); addTypeParameterAdapterImpl(type1, adapterImpl1.superInterfaceTypes()); addTypeParameterAdapterImpl(type2, adapterImpl2.superInterfaceTypes()); } // add adapter variable addAdapterVariableTypeParameter(exprType); adapterTypes.add(exprType.toString()); } } else if (iTypeBinding != null) { exprType = ASTNodeUtil.typeFromBinding(ast, iTypeBinding); } else { exprType = ASTNodeUtil.typeFromBinding(ast, expr.resolveTypeBinding()); } return exprType; } public void addImportDeclaration(CompilationUnit cu, Name name, boolean isStatic) { if (cu != null && name != null) { List<ImportDeclaration> importDeclarations = cu.imports(); for (ImportDeclaration importDeclaration : importDeclarations) { if (importDeclaration.getName().getFullyQualifiedName().equals(name.getFullyQualifiedName())) { return; } } if (name.isQualifiedName() && !isStatic) { QualifiedName qualifiedName = (QualifiedName) name; if (qualifiedName.getQualifier().getFullyQualifiedName().equals(cu.getPackage().getName().getFullyQualifiedName())) { return; } } ImportDeclaration importDeclaration = ast.newImportDeclaration(); importDeclaration.setName((Name) ASTNode.copySubtree(ast, name)); importDeclaration.setStatic(isStatic); importDeclarations.add(importDeclaration); } } public void addImportInTemplateImportList(Name name) { if (name != null) { templateCUImports.add(name); } } public void addGenericTypeBound(String fromType, String toType) { List<TypeParameter> typeParameters = templateMethod.typeParameters(); for (TypeParameter typeParameter : typeParameters) { if (typeParameter.getName().getIdentifier().equals(fromType)) { typeParameter.typeBounds().add(ast.newSimpleType(ast.newSimpleName(toType))); return; } } } private void addThrowsException() { if (templateMethod.thrownExceptionTypes().size() == 0) { templateMethod.thrownExceptionTypes().add(ast.newSimpleType(ast.newSimpleName(EXCEPTION_NAME))); } } private void addGenericType(String genericTypeName) { TypeParameter typeParameter = ast.newTypeParameter(); typeParameter.setName(ast.newSimpleName(genericTypeName)); templateMethod.typeParameters().add(typeParameter); } private void recordLambdaForParameter(String genericTypeName) { lambdaParameterType = computeLambdaVariableReturnType(genericTypeName); } private void actuallyAddLambdaParameter() { if (!lambdaParameterAdded && lambdaParameterType != null) { lambdaParameterAdded = true; addVariableParameter(lambdaParameterType, ast.newSimpleName(DEFAULT_LAMBDA_VARIABLE_NAME), 0); } } private void addClazzInParameter(String genericTypeName) { Type genericType = ast.newSimpleType(ast.newSimpleName(genericTypeName)); Type classType = ast.newSimpleType(ast.newSimpleName(CLASS_NAME)); ParameterizedType classTypeWithGenericType = ast.newParameterizedType(classType); classTypeWithGenericType.typeArguments().add(genericType); SimpleName clazzName = ast.newSimpleName(resolveGenericType(genericTypeName)); addVariableParameter(classTypeWithGenericType, clazzName); TypePair typePair = genericTypeMap.get(genericTypeName); if (typePair != null) { TypeLiteral typeLiteral1 = ast.newTypeLiteral(); Type type1; if (typePair.getType1().isParameterizedType()) { type1 = ASTNodeUtil.typeFromBinding(ast, typePair.getType1().getErasure()); } else { type1 = ASTNodeUtil.typeFromBinding(ast, typePair.getType1()); } typeLiteral1.setType(type1); templateArguments1.add(typeLiteral1); TypeLiteral typeLiteral2 = ast.newTypeLiteral(); Type type2; if (typePair.getType2().isParameterizedType()) { type2 = ASTNodeUtil.typeFromBinding(ast, typePair.getType2().getErasure()); } else { type2 = ASTNodeUtil.typeFromBinding(ast, typePair.getType2()); } typeLiteral2.setType(type2); templateArguments2.add(typeLiteral2); } throwsAllException = true; //addThrowsException(); } public String addVariableParameter(Type type) { int count = parameterMap.getOrDefault(type.toString(), 0) + 1; String variableParameter = RenameUtil.rename(type, count); while (!addVariableName(variableParameter)) { count++; variableParameter = RenameUtil.rename(type, count); } parameterMap.put(type.toString(), count); addVariableParameter(type, ast.newSimpleName(variableParameter)); return variableParameter; } private void addVariableParameter(Type type, SimpleName name) { addVariableParameter(type, name, templateMethod.parameters().size()); } private void addVariableParameter(Type type, SimpleName name, int index) { SingleVariableDeclaration variableParameter = ast.newSingleVariableDeclaration(); variableParameter.setType(type); variableParameter.setName(name); templateMethod.parameters().add(index, variableParameter); } private void addAdapterVariableTypeParameter(Type type) { Type adapterType = adapterVariable.getType(); if (adapterType.isSimpleType()) { ParameterizedType parameterizedType = ast.newParameterizedType((Type) ASTNode.copySubtree(ast, adapterType)); parameterizedType.typeArguments().add(ASTNode.copySubtree(ast, type)); adapterVariable.setType(parameterizedType); } else if (adapterType.isParameterizedType()) { ParameterizedType parameterizedType = (ParameterizedType) adapterType; parameterizedType.typeArguments().add(ASTNode.copySubtree(ast, type)); } else { throw new IllegalStateException("unexpected adapter type"); } } private void addMethodInAdapterInterface(SimpleName name, List<Type> argTypes, Type returnType, List<ITypeBinding> thrownExceptions, boolean isVarargs) { MethodDeclaration methodDeclaration = ast.newMethodDeclaration(); // set return type methodDeclaration.setReturnType2((Type) ASTNode.copySubtree(ast, returnType)); // add return type import declaration String returnTypeQualifiedName = (String) returnType.getProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME); if (returnTypeQualifiedName != null) { addImportDeclaration(adapterInterfaceCU, ASTNodeUtil.createPackageName(ast, returnTypeQualifiedName), false); } // set interface action name methodDeclaration.setName((SimpleName) ASTNode.copySubtree(ast, name)); Map<String, Integer> argMap = new HashMap<>(); for (int i = 0; i < argTypes.size(); i++) { Type argType = argTypes.get(i); if (argType == null) continue; SingleVariableDeclaration arg = ast.newSingleVariableDeclaration(); // set arg type if (i == argTypes.size() - 1 && isVarargs) { ArrayType arrayType = (ArrayType) argType; arg.setType((Type) ASTNode.copySubtree(ast, arrayType.getElementType())); arg.setVarargs(true); } else { arg.setType((Type) ASTNode.copySubtree(ast, argType)); } // add import declaration String qualifiedName = (String) argType.getProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME); if (qualifiedName != null && templateCU != null) { addImportDeclaration(adapterInterfaceCU, ASTNodeUtil.createPackageName(ast, qualifiedName), false); } // set arg name String argName = RenameUtil.rename(argType, 0); int argCount = argMap.getOrDefault(argName, 1); argMap.put(argName, argCount + 1); arg.setName(ast.newSimpleName(RenameUtil.rename(argType, argCount))); // add parameter methodDeclaration.parameters().add(arg); } // add throw exception for (ITypeBinding throwsException : thrownExceptions) { addThrownExceptionTypesInMethodDeclaration(methodDeclaration, throwsException); addImportDeclaration(templateCU, ASTNodeUtil.createPackageName(ast, throwsException.getBinaryName()), false); } adapter.bodyDeclarations().add(methodDeclaration); } private void addThrownExceptionTypesInMethodDeclaration(MethodDeclaration methodDeclaration, ITypeBinding throwsException) { List<Type> thrownExceptionTypes = methodDeclaration.thrownExceptionTypes(); for (Type exceptionType : thrownExceptionTypes) { ITypeBinding cur = throwsException; while (cur != null) { if (cur.getName().equals(exceptionType.toString())) { return; } cur = cur.getSuperclass(); } } thrownExceptionTypes.add(ASTNodeUtil.typeFromBinding(ast, throwsException)); } private MethodDeclaration addMethodInAdapterImpl(SimpleName actionName, List<Type> argTypes, MethodInvocationPair methodInvocationPair, ITypeBinding returnTypeBinding, Pair pair) { Expression expr; SimpleName name; List<Expression> arguments; IMethodBinding iMethodBinding; MethodInvocation curMethodInvocation; ITypeBinding[] parameterTypeBinding; // get cu CompilationUnit cu; if (pair == Pair.member1) { cu = adapterImplCU1; } else { cu = adapterImplCU2; } switch (pair) { case member1: expr = methodInvocationPair.getExpr1(); name = methodInvocationPair.getName1(); arguments = methodInvocationPair.getArgument1(); iMethodBinding = methodInvocationPair.getMethod1().resolveMethodBinding(); curMethodInvocation = methodInvocationPair.getMethod1(); parameterTypeBinding = methodInvocationPair.getExtendArgTypeBinding1(); break; case member2: default: expr = methodInvocationPair.getExpr2(); name = methodInvocationPair.getName2(); arguments = methodInvocationPair.getArgument2(); iMethodBinding = methodInvocationPair.getMethod2().resolveMethodBinding(); curMethodInvocation = methodInvocationPair.getMethod2(); parameterTypeBinding = methodInvocationPair.getExtendArgTypeBinding2(); } MethodDeclaration method = ast.newMethodDeclaration(); method.setBody(ast.newBlock()); // set return type Type returnType; if (returnTypeBinding != null) { if (!returnTypeBinding.isPrimitive() && !returnTypeBinding.getBinaryName().startsWith(JAVA_LANG_CLASS)) { addImportDeclaration(cu, ASTNodeUtil.createPackageName(ast, returnTypeBinding.getBinaryName()), false); } returnType = ASTNodeUtil.typeFromBinding(ast, returnTypeBinding); } else { returnType = ast.newSimpleType(ast.newSimpleName(OBJECT_NAME)); returnType.setProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME, JAVA_OBJECT_FULL_NAME); } method.setReturnType2((Type) ASTNode.copySubtree(ast, returnType)); // set interface action name method.setName((SimpleName) ASTNode.copySubtree(ast, actionName)); // set modifier method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); // create method invocation MethodInvocation methodInvocation = ast.newMethodInvocation(); methodInvocation.setName((SimpleName) ASTNode.copySubtree(ast, name)); Map<String, Integer> argMap = new HashMap<>(); for (int i = 0; i < argTypes.size(); i++) { // set method variable declaration type SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); Type curType = argTypes.get(i); if (i == argTypes.size() - 1 && iMethodBinding.isVarargs()) { curType = ((ArrayType) curType).getElementType(); variableDeclaration.setVarargs(true); } if (curType == null) { if (expr instanceof SimpleName && ((SimpleName) expr).resolveBinding().getKind() == 2) { // Type static call methodInvocation.setExpression((Expression) ASTNode.copySubtree(ast, expr)); } continue; } String argTypeName = curType.toString(); Type argType; if (genericTypeMap.containsKey(argTypeName)) { TypePair typePair = genericTypeMap.get(argTypeName); //Type argType; if (pair == Pair.member1) { argType = ASTNodeUtil.typeFromBinding(ast, typePair.getType1()); } else { argType = ASTNodeUtil.typeFromBinding(ast, typePair.getType2()); } } else { argType = ASTNodeUtil.copyTypeWithProperties(ast, curType); } variableDeclaration.setType(argType); // add import declaration addImportDeclaration(cu, ASTNodeUtil.createPackageName(ast, (String) argType.getProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME)), false); // get current expression Expression curExpr; if (i == 0) { curExpr = expr; } else { curExpr = arguments.get(i - 1); } // set method expr variable name SimpleName curName; if (curExpr instanceof SimpleName) { SimpleName curExprSimpleName = (SimpleName) curExpr; if (argMap.containsKey(curExprSimpleName.getIdentifier())) { int argCount = argMap.get(curExprSimpleName.getIdentifier()) + 1; curName = ast.newSimpleName(curExprSimpleName.getIdentifier() + argCount); argMap.put(curExprSimpleName.getIdentifier(), argCount); } else { curName = curExprSimpleName; argMap.put(curExprSimpleName.getIdentifier(), 0); } } else { String argName = RenameUtil.rename(curType, 0); int argCount = argMap.getOrDefault(argName, 1); curName = ast.newSimpleName(RenameUtil.rename(curType, argCount)); argMap.put(argName, argCount + 1); } variableDeclaration.setName((SimpleName) ASTNode.copySubtree(ast, curName)); method.parameters().add(variableDeclaration); if (i == 0) { methodInvocation.setExpression((Expression) ASTNode.copySubtree(ast, curName)); } else { // check if argType matches iMethodBinding ITypeBinding parameterType = parameterTypeBinding[i - 1]; String qualifiedName = (String) argType.getProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME); if (qualifiedName != null && !parameterType.getBinaryName().equals(qualifiedName)) { // check if argType is subType of parameterType if (ASTNodeUtil.hasAncestor(parameterType, qualifiedName)) { if (!parameterType.isPrimitive()) { addImportDeclaration(cu, ASTNodeUtil.createPackageName(ast, parameterType.getBinaryName()), false); } CastExpression castExpression = ast.newCastExpression(); castExpression.setExpression((Expression) ASTNode.copySubtree(ast, curName)); castExpression.setType(ASTNodeUtil.typeFromBinding(ast, parameterType)); methodInvocation.arguments().add(castExpression); } else { methodInvocation.arguments().add(ASTNode.copySubtree(ast, curName)); } } else { methodInvocation.arguments().add(ASTNode.copySubtree(ast, curName)); } } } // add statement to method Statement statement; if (returnType.isPrimitiveType() && ((PrimitiveType) returnType).getPrimitiveTypeCode() == PrimitiveType.VOID) { statement = ast.newExpressionStatement(methodInvocation); } else { ReturnStatement returnStatement = ast.newReturnStatement(); // check if return type is compatible CastExpression castExpression = ast.newCastExpression(); castExpression.setType(ASTNodeUtil.copyTypeWithProperties(ast, returnType)); boolean isSameType = true; if (returnTypeBinding != null && curMethodInvocation.resolveTypeBinding() != null) { if (returnTypeBinding.isParameterizedType() && curMethodInvocation.resolveTypeBinding().isParameterizedType()) { ITypeBinding[] typeArgs1 = returnTypeBinding.getTypeArguments(); ITypeBinding[] typeArgs2 = curMethodInvocation.resolveTypeBinding().getTypeArguments(); if (typeArgs1.length != typeArgs2.length) { isSameType = false; } else { for (int i = 0; i < typeArgs1.length; i++) { ITypeBinding typeArg1 = typeArgs1[i]; ITypeBinding typeArg2 = typeArgs2[i]; if (typeArg1.isCapture()) { typeArg1 = typeArg1.getWildcard(); } if (typeArg2.isCapture()) { typeArg2 = typeArg2.getWildcard(); } if (!typeArg1.getQualifiedName().equals(typeArg2.getQualifiedName())) { isSameType = false; break; } } } } else { if (!returnTypeBinding.getQualifiedName().equals(curMethodInvocation.resolveTypeBinding().getQualifiedName()) && !curMethodInvocation.resolveTypeBinding().isAssignmentCompatible(returnTypeBinding)) { isSameType = false; } } } if (isSameType) { returnStatement.setExpression(methodInvocation); } else { castExpression.setExpression(methodInvocation); returnStatement.setExpression(castExpression); } statement = returnStatement; } method.getBody().statements().add(statement); // add throws exception for (ITypeBinding thrownException : iMethodBinding.getExceptionTypes()) { addThrownExceptionTypesInMethodDeclaration(method, thrownException); } return method; } private MethodDeclaration addMethodInAdapterImpl(SimpleName actionName, List<Type> argTypes, Type returnType, Pair pair) { MethodDeclaration method = ast.newMethodDeclaration(); method.setBody(ast.newBlock()); // set return type method.setReturnType2((Type) ASTNode.copySubtree(ast, returnType)); // set interface action name method.setName((SimpleName) ASTNode.copySubtree(ast, actionName)); // set modifier method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); assert argTypes.size() == 2; // get cu CompilationUnit cu; if (pair == Pair.member1) { cu = adapterImplCU1; } else { cu = adapterImplCU2; } // set method parameters Map<String, Integer> argMap = new HashMap<>(); for (Type argType : argTypes) { SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.setType((Type) ASTNode.copySubtree(ast, argType)); // add import declaration if (templateCU != null) { addImportDeclaration(cu, ASTNodeUtil.createPackageName(ast, (String) argType.getProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME)), false); } int argCount = argMap.getOrDefault(argType.toString(), 1); variableDeclaration.setName(ast.newSimpleName(RenameUtil.rename(argType, argCount))); argMap.put(argType.toString(), argCount + 1); method.parameters().add(variableDeclaration); } // get return variable name SimpleName returnVariableName; if (pair == Pair.member1) { returnVariableName = ((SingleVariableDeclaration) method.parameters().get(0)).getName(); } else { returnVariableName = ((SingleVariableDeclaration) method.parameters().get(1)).getName(); } // add return statement to method ReturnStatement returnStatement = ast.newReturnStatement(); returnStatement.setExpression((Expression) ASTNode.copySubtree(ast, returnVariableName)); method.getBody().statements().add(returnStatement); return method; } private void addAdapterActionImpl(SimpleName actionName, List<Type> argTypes, MethodInvocationPair pair, TypePair returnTypePair) { ITypeBinding returnTypeBinding1; ITypeBinding returnTypeBinding2; TypePair boundPair = ASTNodeUtil.getJavaLangClassCaptureBounds(returnTypePair); if (containsTypePair(returnTypePair) || (boundPair != null && containsTypePair(boundPair))) { returnTypeBinding1 = returnTypePair.getType1(); returnTypeBinding2 = returnTypePair.getType2(); } else { ITypeBinding returnTypeBinding = ASTNodeUtil.getAssignmentCompatibleTypeBinding(returnTypePair); returnTypeBinding1 = returnTypeBinding; returnTypeBinding2 = returnTypeBinding; } MethodDeclaration method1 = addMethodInAdapterImpl(actionName, argTypes, pair, returnTypeBinding1, Pair.member1); MethodDeclaration method2 = addMethodInAdapterImpl(actionName, argTypes, pair, returnTypeBinding2, Pair.member2); adapterImpl1.bodyDeclarations().add(method1); adapterImpl2.bodyDeclarations().add(method2); } private void addAdapterActionImpl(SimpleName actionName, List<Type> argTypes, Type returnType) { MethodDeclaration method1 = addMethodInAdapterImpl(actionName, argTypes, returnType, Pair.member1); MethodDeclaration method2 = addMethodInAdapterImpl(actionName, argTypes, returnType, Pair.member2); adapterImpl1.bodyDeclarations().add(method1); adapterImpl2.bodyDeclarations().add(method2); } private void addAdapterVariableParameter() { if (!hasAdapterVariable) { templateMethod.parameters().add(0, adapterVariable); hasAdapterVariable = true; } } private void addLambda() { if (ENABLE_LAMBDA) { hasLambda = true; } } private boolean containsTypeVariable(ITypeBinding iTypeBinding) { if (iTypeBinding == null) { return false; } if (iTypeBinding.isArray()) { return containsTypeVariable(iTypeBinding.getElementType()); } else if (iTypeBinding.isParameterizedType()) { for (ITypeBinding typeArg: iTypeBinding.getTypeArguments()) { if (containsTypeVariable(typeArg)) { return true; } } return containsTypeVariable(iTypeBinding.getErasure()); } else if (iTypeBinding.isWildcardType()) { return containsTypeVariable(iTypeBinding.getBound()); } return iTypeBinding.isTypeVariable(); } private Type computeLambdaVariableReturnType(String rt) { String olTypeName = String.format(DEFAULT_LAMBDA_FUNCTION_CLASS_TEMPLATE, "Long"); Type openLambdaType = ast.newSimpleType(ast.newName(olTypeName)); ParameterizedType lType = ast.newParameterizedType(openLambdaType); Type t = ast.newSimpleType(ast.newSimpleName(rt)); lType.typeArguments().add(t); return lType; } @SuppressWarnings("unchecked") public MethodInvocation createLambdaActionMethodInvocation(Expression expr, List<Expression> arguments, MethodInvocationPair pair, TypePair returnTypePair) { // create new method invocation MethodInvocation newMethodInvocation = ast.newMethodInvocation(); newMethodInvocation.setExpression(ast.newSimpleName(lambdaVariable.getName().getIdentifier())); List<Expression> newArgs = newMethodInvocation.arguments(); List<Type> argTypes = new ArrayList<>(); // XXX PL need to handle lambdas that return other than int, long, double Type returnType = computeReturnTypeFromPair(returnTypePair); boolean foundWinningType = false; if (returnType.isPrimitiveType()) { PrimitiveType pt = (PrimitiveType) returnType; if (pt.getPrimitiveTypeCode() == PrimitiveType.INT) { newMethodInvocation.setName(ast.newSimpleName("applyAsInt")); lambdaVariable.setType(computeLambdaVariableReturnType("Int")); foundWinningType = true; } else if (pt.getPrimitiveTypeCode() == PrimitiveType.LONG) { newMethodInvocation.setName(ast.newSimpleName("applyAsLong")); lambdaVariable.setType(computeLambdaVariableReturnType("Long")); foundWinningType = true; } else if (pt.getPrimitiveTypeCode() == PrimitiveType.DOUBLE) { newMethodInvocation.setName(ast.newSimpleName("applyAsDouble")); lambdaVariable.setType(computeLambdaVariableReturnType("Double")); foundWinningType = true; } } if (!foundWinningType) { log.info("could not do a lambda with return type "+returnType); } if (expr != null) { newArgs.add((Expression) ASTNode.copySubtree(ast, expr)); argTypes.add(resolveAdapterActionArgumentType(expr, null)); } if (foundWinningType) { addLambda(); actuallyAddLambdaParameter(); return newMethodInvocation; } else return null; } public MethodInvocation createAdapterActionMethod(Expression expr, List<Expression> arguments, MethodInvocationPair pair, TypePair returnTypePair) { boolean ENABLE_THIS_LAMBDA = true; // XXX PL need to figure out when lambdas should be created vs adapters... if (ENABLE_LAMBDA && ENABLE_THIS_LAMBDA) { // stash away (in global state) the body --- which expr we're supposed to put in place of method1/method2 method1.setProperty(ASTNodeUtil.PROPERTY_LAMBDA_PARAM, pair.getMethod1()); method2.setProperty(ASTNodeUtil.PROPERTY_LAMBDA_PARAM, pair.getMethod2()); MethodInvocation mi = createLambdaActionMethodInvocation(expr, arguments, pair, returnTypePair); if (mi != null) return mi; } addAdapterVariableParameter(); // create new method invocation MethodInvocation newMethod = ast.newMethodInvocation(); newMethod.setExpression(ast.newSimpleName(adapterVariable.getName().getIdentifier())); List<Expression> newArgs = newMethod.arguments(); List<Type> argTypes = new ArrayList<>(); // check expr if (expr != null) { Type exprType = (Type) expr.getProperty(ASTNodeUtil.PROPERTY_TYPE_BINDING); String methodName1 = pair.getMethod1().getName().getIdentifier(); String methodName2 = pair.getMethod2().getName().getIdentifier(); if (exprType != null && JAVA_OBJECT_FULL_NAME.equals(exprType.getProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME)) && (!javaObjectMethodNames.contains(methodName1) || !javaObjectMethodNames.contains(methodName2))) { markAsUnrefactorable(); log.info("cannot refactor incompatible method calls in java.lang.Object: " + methodName1 + ", " + methodName2); } } // copy and resolve method expr if (expr != null) { if (expr instanceof SimpleName && ((SimpleName) expr).resolveBinding().getKind() == 2) { argTypes.add(null); } else { newArgs.add((Expression) ASTNode.copySubtree(ast, expr)); argTypes.add(resolveAdapterActionArgumentType(expr, null)); } } else { // mark adapter impl as inner class to make use of class private methods //innerImplClass = true; argTypes.add(null); } // copy and resolve arguments for (int i = 0; i < arguments.size(); i++) { Expression argument = arguments.get(i); newArgs.add((Expression) ASTNode.copySubtree(ast, argument)); } ITypeBinding[] iTypeBindings1 = pair.getMethod1().resolveMethodBinding().getParameterTypes(); ITypeBinding[] iTypeBindings2 = pair.getMethod2().resolveMethodBinding().getParameterTypes(); boolean isVarargs = pair.getMethod1().resolveMethodBinding().isVarargs(); for (int i = 0; i < iTypeBindings1.length; i++) { if (containsTypeVariable(iTypeBindings1[i]) || containsTypeVariable(iTypeBindings2[i])) { log.info("unable to refactor type pair [" + iTypeBindings1[i].getQualifiedName() + ", " + iTypeBindings2[i].getQualifiedName() + "] with type variable when creating adapter action method."); markAsUnrefactorable(); } if (iTypeBindings1[i].getQualifiedName().equals(iTypeBindings2[i].getQualifiedName())) { argTypes.add(ASTNodeUtil.typeFromBinding(ast, iTypeBindings1[i])); } else { argTypes.add(resolveAdapterActionArgumentType(arguments.get(i), iTypeBindings1[i])); } } // add method in adapter interface if (methodInvocationMap.containsKey(pair)) { String methodName = methodInvocationMap.get(pair); newMethod.setName(ast.newSimpleName(methodName)); for (MethodDeclaration methodDeclaration : adapter.getMethods()) { if (methodDeclaration.getName().getIdentifier().equals(methodName)) { Type returnType = methodDeclaration.getReturnType2(); newMethod.setProperty(ASTNodeUtil.PROPERTY_TYPE_BINDING, ASTNodeUtil.copyTypeWithProperties(ast, returnType)); } } } else { // set adapter action name String newActionName; if (pair.getName1() != null && pair.getName2() != null) { String commonName = RenameUtil.constructCommonName(pair.getName1().getIdentifier(), pair.getName2().getIdentifier(), false); if (!commonName.equals("")) { if (keywords.contains(commonName)) { commonName += KEYWORD_SUFFIX; } int nameCount = adapterActionNameMap.getOrDefault(commonName, 0); if (nameCount == 0) { newActionName = commonName; } else { newActionName = commonName + nameCount; } adapterActionNameMap.put(commonName, nameCount + 1); } else { newActionName = DEFAULT_ADAPTER_METHOD_NAME + actionCount++; } } else { newActionName = DEFAULT_ADAPTER_METHOD_NAME + actionCount++; } newMethod.setName(ast.newSimpleName(newActionName)); // add method in adapter interface Type returnType = computeReturnTypeFromPair(returnTypePair); // check if it needs to throw exception IMethodBinding methodBinding1 = pair.getMethod1().resolveMethodBinding(); IMethodBinding methodBinding2 = pair.getMethod2().resolveMethodBinding(); List<ITypeBinding> thrownExceptions = new ArrayList<>(); for (ITypeBinding iTypeBinding : methodBinding1.getExceptionTypes()) { thrownExceptions.add(iTypeBinding); } for (ITypeBinding iTypeBinding : methodBinding2.getExceptionTypes()) { thrownExceptions.add(iTypeBinding); } addMethodInAdapterInterface(newMethod.getName(), argTypes, returnType, thrownExceptions, isVarargs); newMethod.setProperty(ASTNodeUtil.PROPERTY_TYPE_BINDING, ASTNodeUtil.copyTypeWithProperties(ast, returnType)); methodInvocationMap.put(pair, newActionName); // create adapter action impl addAdapterActionImpl(newMethod.getName(), argTypes, pair, returnTypePair); // add throws exception in template method for (ITypeBinding thrownException : thrownExceptions) { addThrownExceptionTypesInMethodDeclaration(templateMethod, thrownException); } } return newMethod; } private Type computeReturnTypeFromPair(TypePair returnTypePair) { ITypeBinding returnTypeBinding = ASTNodeUtil.getAssignmentCompatibleTypeBinding(returnTypePair); TypePair boundPair = ASTNodeUtil.getJavaLangClassCaptureBounds(returnTypePair); Type returnType; if (containsTypePair(returnTypePair)) { // add type parameter in adapter interface String genericName = resolveTypePair(returnTypePair, false); returnType = ast.newSimpleType(ast.newSimpleName(genericName)); if (!adapterTypes.contains(genericName)) { TypeParameter typeParameter = ast.newTypeParameter(); typeParameter.setName(ast.newSimpleName(genericName)); adapter.typeParameters().add(typeParameter); // add type parameter in adapter impl Type type1 = ASTNodeUtil.typeFromBinding(ast, returnTypePair.getType1()); Type type2 = ASTNodeUtil.typeFromBinding(ast, returnTypePair.getType2()); addTypeParameterAdapterImpl(type1, adapterImpl1.superInterfaceTypes()); addTypeParameterAdapterImpl(type2, adapterImpl2.superInterfaceTypes()); // add adapter variable addAdapterVariableTypeParameter(returnType); adapterTypes.add(genericName); } } else if (boundPair != null && containsTypePair(boundPair)) { String genericName = resolveTypePair(boundPair, false); ParameterizedType parameterizedType = ast.newParameterizedType(ASTNodeUtil.typeFromBinding(ast, returnTypePair.getType1().getErasure())); WildcardType capType = ast.newWildcardType(); capType.setBound(ast.newSimpleType(ast.newSimpleName(genericName)), true); parameterizedType.typeArguments().add(capType); returnType = parameterizedType; } else { if (returnTypeBinding == null) { returnType = ast.newSimpleType(ast.newSimpleName(OBJECT_NAME)); returnType.setProperty(ASTNodeUtil.PROPERTY_QUALIFIED_NAME, JAVA_OBJECT_FULL_NAME); } else { if (!returnTypeBinding.isPrimitive() && !returnTypeBinding.getBinaryName().startsWith(JAVA_LANG_CLASS)) { addImportDeclaration(templateCU, ASTNodeUtil.createPackageName(ast, returnTypeBinding.getBinaryName()), false); } returnType = ASTNodeUtil.typeFromBinding(ast, returnTypeBinding); } } return returnType; } public MethodInvocation createAdapterActionMethod(Expression e1, Expression e2, Type returnType) { addAdapterVariableParameter(); MethodInvocation newMethod = ast.newMethodInvocation(); newMethod.setExpression(ast.newSimpleName(adapterVariable.getName().getIdentifier())); String newActionName = DEFAULT_ADAPTER_METHOD_NAME + actionCount++; newMethod.setName(ast.newSimpleName(newActionName)); List<Expression> newArgs = newMethod.arguments(); List<Type> argTypes = new ArrayList<>(); newArgs.add((Expression) ASTNode.copySubtree(ast, e1)); newArgs.add((Expression) ASTNode.copySubtree(ast, e2)); argTypes.add(resolveAdapterActionArgumentType(e1, null)); argTypes.add(resolveAdapterActionArgumentType(e2, null)); // add method in adapter interface addMethodInAdapterInterface(newMethod.getName(), argTypes, returnType, new ArrayList<>(), false); // create adapter action impl addAdapterActionImpl(newMethod.getName(), argTypes, returnType); return newMethod; } /* public MethodInvocation createAdapterActionMethod(Type returnType) { addAdapterVariableParameter(); MethodInvocation newMethod = ast.newMethodInvocation(); newMethod.setExpression(ast.newSimpleName(adapterVariable.getName().getIdentifier())); String newActionName = DEFAULT_ADAPTER_METHOD_NAME + actionCount++; newMethod.setName(ast.newSimpleName(newActionName)); addMethodInAdapterInterface(newMethod.getName(), new ArrayList<>(), returnType); return newMethod; } */ private boolean methodContainsThrowable() { List<Type> thrownExceptionTypes1 = method1.thrownExceptionTypes(); List<Type> thrownExceptionTypes2 = method2.thrownExceptionTypes(); for (Type thrownExceptionType : thrownExceptionTypes1) { if (thrownExceptionType.toString().equals(THROWABLE_NAME)) { return true; } } for (Type thrownExceptionType : thrownExceptionTypes2) { if (thrownExceptionType.toString().equals(THROWABLE_NAME)) { return true; } } return false; } public void modifyTestMethods() { if (throwsAllException || templateMethod.thrownExceptionTypes().size() > 1) { throwsAllException = true; templateMethod.thrownExceptionTypes().clear(); if (methodContainsThrowable()) { templateMethod.thrownExceptionTypes().add(ast.newSimpleType(ast.newSimpleName(THROWABLE_NAME))); } else { templateMethod.thrownExceptionTypes().add(ast.newSimpleType(ast.newSimpleName(EXCEPTION_NAME))); } } modifyMethod(method1, adapterImpl1, templateArguments1, Pair.member1); modifyMethod(method2, adapterImpl2, templateArguments2, Pair.member2); } /** swaps out the implementation of method body with a call to templateMethod */ private void modifyMethod(MethodDeclaration method, TypeDeclaration adapterImpl, List<Expression> arguments, Pair pair) { // create new method invocation MethodInvocation methodInvocation = ast.newMethodInvocation(); methodInvocation.setName((SimpleName) ASTNode.copySubtree(ast, templateMethod.getName())); if (templateClass != null) { methodInvocation.setExpression(ast.newSimpleName(templateClass.getName().getIdentifier())); } else { methodInvocation.setExpression(ast.newThisExpression()); } // add method arguments List<Expression> args = methodInvocation.arguments(); // add type parameter in template method invocation if (!hasAdapterVariable && arguments.isEmpty()) { List<TypeParameter> typeParameters = templateMethod.typeParameters(); for (TypeParameter typeParameter : typeParameters) { TypePair typePair = genericTypeMap.get(typeParameter.getName().getIdentifier()); if (typePair != null) { Type type; if (pair == Pair.member1) { type = ASTNodeUtil.typeFromBinding(ast, typePair.getType1()); } else { type = ASTNodeUtil.typeFromBinding(ast, typePair.getType2()); } methodInvocation.typeArguments().add(type); } } } if (ENABLE_LAMBDA && hasLambda) { // currently support single-arg lambdas that return int, long, or double LambdaExpression lambdaExpression = ast.newLambdaExpression(); // XXX PL args and body // was: target.get() // want: (AtomicInteger target) -> target.get(); VariableDeclarationFragment arg = ast.newVariableDeclarationFragment(); arg.setName(ast.newSimpleName(DEFAULT_LAMBDA_VARIABLE_NAME)); lambdaExpression.parameters().add(arg); MethodInvocation body = ast.newMethodInvocation(); if (method.properties().containsKey(ASTNodeUtil.PROPERTY_LAMBDA_PARAM)) { body = (MethodInvocation) ASTNode.copySubtree(ast, (ASTNode)method.getProperty(ASTNodeUtil.PROPERTY_LAMBDA_PARAM)); body.setExpression(ast.newSimpleName(DEFAULT_LAMBDA_VARIABLE_NAME)); } lambdaExpression.setBody(body); args.add(lambdaExpression); } if (hasAdapterVariable) { ClassInstanceCreation classInstanceCreation = ast.newClassInstanceCreation(); SimpleName simpleName = (SimpleName) ASTNode.copySubtree(ast, adapterImpl.getName()); classInstanceCreation.setType(ast.newSimpleType(simpleName)); args.add(classInstanceCreation); } for (Expression arg : arguments) { args.add((Expression) ASTNode.copySubtree(ast, arg)); } // add method invocation to method body Block body = ast.newBlock(); body.statements().add(ast.newExpressionStatement(methodInvocation)); method.setBody(body); // rename methods //method.getName().setIdentifier(method.getName().getIdentifier() + "RF"); // remove javadoc //method.setJavadoc(null); // add Exception handling if necessary if (throwsAllException) { method.thrownExceptionTypes().clear(); if (methodContainsThrowable()) { method.thrownExceptionTypes().add(ast.newSimpleType(ast.newSimpleName(THROWABLE_NAME))); } else { method.thrownExceptionTypes().add(ast.newSimpleType(ast.newSimpleName(EXCEPTION_NAME))); } } } public String getTemplatName() { return templateMethod.getName().getFullyQualifiedName(); } public void updateSourceFiles() throws Exception { log.info("refactoring method pair: " + packageDeclaration1.getName().getFullyQualifiedName() + "." + compilationUnit1.getJavaElement().getElementName() + "#" + method1.getName().getIdentifier() + " <---> " + packageDeclaration2.getName().getFullyQualifiedName() + "." + compilationUnit2.getJavaElement().getElementName() + "#" + method2.getName().getIdentifier()); if (templateCU == null) { // duplicate methods are in the same file saveMethod(iCU1, templateMethod, templateCUImports, false); if (hasAdapterVariable) { insertInnerClass(iCU1, adapterInterfaceCU, true); insertInnerClass(iCU1, adapterImplCU1, true); insertInnerClass(iCU1, adapterImplCU2, true); } cleanImportDeclarations(iCU1); } else if (packageDeclaration1.getName().getFullyQualifiedName().equals(packageDeclaration2.getName().getFullyQualifiedName())) { // duplicate methods are in the same package but different files ICompilationUnit iCompilationUnit = saveCU(packageFragmentRoot, templateCU, false); if (hasAdapterVariable) { insertInnerClass(iCompilationUnit, adapterInterfaceCU, false); insertInnerClass(iCU1, adapterImplCU1, true); insertInnerClass(iCU2, adapterImplCU2, true); } cleanImportDeclarations(iCompilationUnit); cleanImportDeclarations(iCU1); cleanImportDeclarations(iCU2); } else { // duplicate methods are in different packages log.info("duplicate methods are in different packages"); return; /* saveCU(packageFragmentRoot, adapterInterfaceCU, false); saveCU(packageFragmentRoot, adapterImplCU1, false); saveCU(packageFragmentRoot, adapterImplCU2, false); saveCU(packageFragmentRoot, templateCU, false); */ } saveMethod(iCU1, method1, cuImports1, true); saveMethod(iCU2, method2, cuImports2, true); packageFragmentRoot.getJavaProject().getProject().getWorkspace().save(true, null); } private ICompilationUnit saveCU(IPackageFragmentRoot packageFragmentRoot, CompilationUnit cu, boolean force) throws JavaModelException { String packageName = cu.getPackage().getName().getFullyQualifiedName(); String name = ((TypeDeclaration) cu.types().get(0)).getName().getIdentifier() + ".java"; String contents = cu.toString(); IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(packageName); return packageFragment.createCompilationUnit(name, contents, force, null); } private void insertInnerClass(ICompilationUnit cu, CompilationUnit classCU, boolean inner) throws Exception { // creation of a Document Document document = new Document(cu.getSource()); // creation of DOM/AST from a ICompilationUnit ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(cu); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); // description of the change ListRewrite classListRewrite; if (inner) { String typeDeclarationName = cu.getElementName().split("\\.")[0]; TypeDeclaration typeDeclaration = null; List<TypeDeclaration> typeDeclarations = astRoot.types(); for (TypeDeclaration curTypeDeclaration : typeDeclarations) { if (curTypeDeclaration.getName().getIdentifier().equals(typeDeclarationName)) { typeDeclaration = curTypeDeclaration; } } if (typeDeclaration == null) { throw new IllegalStateException("cannot find target typeDeclaration: " + typeDeclarationName); } classListRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); } else { classListRewrite = rewrite.getListRewrite(astRoot, CompilationUnit.TYPES_PROPERTY); } List<AbstractTypeDeclaration> types = classCU.types(); for (AbstractTypeDeclaration type : types) { type.modifiers().clear(); classListRewrite.insertLast(type, null); } ListRewrite imports = rewrite.getListRewrite(astRoot, IMPORTS_PROPERTY); List<ImportDeclaration> importDeclarations = classCU.imports(); for (ImportDeclaration importDeclaration : importDeclarations) { imports.insertFirst(importDeclaration, null); } // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); String newSource = document.get(); // update of the compilation unit cu.getBuffer().setContents(newSource); cu.getBuffer().save(null, true); } private void cleanImportDeclarations(ICompilationUnit cu) throws Exception { // creation of a Document Document document = new Document(cu.getSource()); // creation of DOM/AST from a ICompilationUnit ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(cu); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); // description of the change ListRewrite imports = rewrite.getListRewrite(astRoot, IMPORTS_PROPERTY); Set<String> uniqueImportsSet = new HashSet<>(); List<ImportDeclaration> importDeclarations = astRoot.imports(); for (ImportDeclaration importDeclaration : importDeclarations) { String importDeclarationName = importDeclaration.getName().getFullyQualifiedName(); if (importDeclaration.isOnDemand()) { importDeclarationName += ".*"; } if (!uniqueImportsSet.add(importDeclarationName)) { imports.remove(importDeclaration, null); } } // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); String newSource = document.get(); // update of the compilation unit cu.getBuffer().setContents(newSource); cu.getBuffer().save(null, true); } private void saveMethod(ICompilationUnit cu, MethodDeclaration method, List<Name> imports, boolean replace) throws Exception { // creation of a Document Document document = new Document(cu.getSource()); // creation of DOM/AST from a ICompilationUnit ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(cu); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); Annotation ignoreCloneAnnotation = method.getAST().newMarkerAnnotation(); Name ignoreCloneAnnotationName = method.getAST().newSimpleName("ca"); ignoreCloneAnnotationName = method.getAST().newQualifiedName(ignoreCloneAnnotationName, method.getAST().newSimpleName("uwaterloo")); ignoreCloneAnnotationName = method.getAST().newQualifiedName(ignoreCloneAnnotationName, method.getAST().newSimpleName("jrefactoring")); ignoreCloneAnnotationName = method.getAST().newQualifiedName(ignoreCloneAnnotationName, method.getAST().newSimpleName("autogenerated")); ignoreCloneAnnotationName = method.getAST().newQualifiedName(ignoreCloneAnnotationName, method.getAST().newSimpleName("IgnoreClone")); ignoreCloneAnnotation.setTypeName(ignoreCloneAnnotationName); // description of the change MethodVisitor methodVisitor = ASTNodeUtil.retrieveMethodDeclaration(astRoot, method); if (methodVisitor.getResult() != null) { if (replace) { ListRewrite methodDeclarations = rewrite.getListRewrite(methodVisitor.getTypeDeclaration(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY); methodDeclarations.replace(methodVisitor.getResult(), method, null); methodDeclarations.insertBefore(ignoreCloneAnnotation, method, null); ListRewrite cuImports = rewrite.getListRewrite(astRoot, IMPORTS_PROPERTY); for (Name importName : imports) { ImportDeclaration importDeclaration = astRoot.getAST().newImportDeclaration(); importDeclaration.setName((Name) ASTNode.copySubtree(astRoot.getAST(), importName)); cuImports.insertFirst(importDeclaration, null); } } else { //log.info("repeated method found when the target method is not replaceable"); throw new IllegalStateException("repeated method found when the target method is not replaceable"); } } else { ListRewrite methodDeclarations = rewrite.getListRewrite(methodVisitor.getTypeDeclaration(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY); methodDeclarations.insertLast(ignoreCloneAnnotation, null); methodDeclarations.insertLast(method, null); ListRewrite cuImports = rewrite.getListRewrite(astRoot, IMPORTS_PROPERTY); for (Name importName : imports) { ImportDeclaration importDeclaration = astRoot.getAST().newImportDeclaration(); importDeclaration.setName((Name) ASTNode.copySubtree(astRoot.getAST(), importName)); cuImports.insertFirst(importDeclaration, null); } } // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); String newSource = document.get(); // update of the compilation unit cu.getBuffer().setContents(newSource); cu.getBuffer().save(null, true); } @Override public String toString() { StringBuilder unrefactoredPairs = new StringBuilder(); unrefactoredPairs.append("non-refactored node pairs: \n"); for (NodePair nodePair : unrefactoredList) { unrefactoredPairs.append(nodePair.toString()); unrefactoredPairs.append("\n"); } return unrefactoredPairs.toString() + "\n" + (templateClass == null ? templateCUImports + "\n" + templateMethod.toString() : templateCU.toString()) + "\n" + adapterInterfaceCU.toString() + "\n" + adapterImplCU1.toString() + "\n" + adapterImplCU2.toString() + "\n" + cuImports1.toString() + "\n" + method1.toString() + "\n" + cuImports2.toString() + "\n" + method2.toString(); } }
java
Kim Jong-un, North Korea Supreme Leader, has given a very destructive order to his armed forces. He has asked North Korea armies to be ready for Nuclear attack and reciprocation. Kim Jong-un is known for his hatred towards South Korea and USA. As US armed forces have strategically moved closer to shared International waters, he made this announcement. Kim Jong-un has been warning US about nuclear reciprocation for their aggression. Previous President of US, Donald Trump, called Kim Jong-un has his friend in the start of his tenure. But towards the end, the relations have been damaged and he warned North Korea about Nuclear reciprocation. North Korea, right now has tested a ballistic missile that can hit target after travelling 800kms and at 800M, height. Kim Jong-un made this announcement after the successful completion of ballistic missile test. US did not react to this warning yet. But if Kim Jong-un decides to attack US forces in shared waters, US will reciprocate. Already, Pandemic and Ukraine – Russia War has hit world financial status. Now, if US and North Korea go for Nuclear War it will drive World into even bigger crisis than ever. Kim Jong-un and US President Joe Biden need to act wisely to avoid such a war that destructs World further! Stock Markets Update: Markets crash again!
english
{"name": "Non-Sampling Error Definition", "@id": "https://www.investopedia.com/terms/n/non-samplingerror.asp", "related": ["https://www.investopedia.com/terms/s/simple-random-sample.asp", "https://www.investopedia.com/terms/s/samplingerror.asp", "https://www.investopedia.com/terms/s/statistical-significance.asp", "https://www.investopedia.com/terms/p/population.asp", "https://www.investopedia.com/terms/t/type-ii-error.asp", "https://www.investopedia.com/terms/s/statistics.asp"], "body": ["\nA non-sampling error is a statistical term that refers to an error that results during data collection, causing the data to differ from the true values. A non-sampling error differs from a <a data-component=\"link\" data-ordinal=\"1\" data-source=\"inlineLink\" data-type=\"internalLink\" href=\"https://www.investopedia.com/terms/s/samplingerror.asp\">sampling error.</a> A sampling error is limited to any differences between sample values and universe values that arise because the sample size was limited. (The entire universe cannot be sampled in a survey or a census.)\n", "\nA sampling error can result even when no mistakes of any kind are made. The \"errors\" result from the mere fact that data in a sample is unlikely to perfectly match data in the universe from which the sample is taken. This \"error\" can be minimized by increasing the sample size.\n", "\nNon-sampling errors cover all other discrepancies, including those that arise from a poor sampling technique.\n", "\nNon-sampling errors may be present in both samples and censuses in which an entire population is surveyed. Non-sampling errors fall under two categories: random and systematic.\n", "\nRandom errors are believed to offset each other and therefore, most often, are of little concern. Systematic errors, on the other hand, affect the entire sample and therefore present a more significant issue. Random errors, generally, will not result in scrapping a sample or a census, whereas a systematic error will most likely render the data collected unusable.\n", "\nThere are many ways non-sampling errors can occur. For example, non-sampling errors can include but are not limited to, <a data-component=\"link\" data-ordinal=\"1\" data-source=\"inlineLink\" data-type=\"internalLink\" href=\"https://www.investopedia.com/articles/active-trading/013015/worst-mistakes-beginner-traders-make.asp\">data entry errors</a>, biased survey questions, biased processing/decision making, non-responses, inappropriate analysis conclusions, and false information provided by respondents.\n", "\nWhile increasing sample size can help minimize sampling errors, it will not have any effect on reducing non-sampling errors. This is because non-sampling errors are often difficult to detect, and it is virtually impossible to eliminate them.\n", "\nNon-sampling errors include non-response errors, coverage errors, interview errors, and processing errors. A coverage error would occur, for example, if a person were counted twice in a survey, or their answers were duplicated on the survey. If an interviewer is <a data-component=\"link\" data-ordinal=\"1\" data-source=\"inlineLink\" data-type=\"internalLink\" href=\"https://www.investopedia.com/articles/investing/050813/4-behavioral-biases-and-how-avoid-them.asp\">biased</a> in their sampling, the non-sampling error would be considered an interviewer error.\n", "\nIn addition, it is difficult to prove that respondents in a survey are providing false information\u2014either by mistake or on purpose. Either way, misinformation provided by respondents count as non-sampling errors and they are described as response errors.\n", "\nTechnical errors exist in a different category. If there are any data-related entries\u2060\u2014such as coding, collection, entry, or editing\u2014they are considered processing errors.\n"]}
json
'''Load image/class/box from a annotation file. The annotation file is organized as: image_name #obj xmin ymin xmax ymax class_index .. ''' from __future__ import print_function import os import sys import os.path import random import numpy as np import torch import torch.utils.data as data import torchvision.transforms as transforms from encoder import DataEncoder from PIL import Image, ImageOps class ListDataset(data.Dataset): img_size = 300 def __init__(self, root, list_file, train, transform): ''' Args: root: (str) ditectory to images. list_file: (str) path to index file. train: (boolean) train or test. transform: ([transforms]) image transforms. ''' self.root = root self.train = train self.transform = transform self.fnames = [] self.boxes = [] self.labels = [] self.data_encoder = DataEncoder() with open(list_file) as f: lines = f.readlines() self.num_samples = len(lines) for line in lines: splited = line.strip().split() self.fnames.append(splited[0]) num_objs = int(splited[1]) box = [] label = [] for i in range(num_objs): xmin = splited[2+5*i] ymin = splited[3+5*i] xmax = splited[4+5*i] ymax = splited[5+5*i] c = splited[6+5*i] box.append([float(xmin),float(ymin),float(xmax),float(ymax)]) label.append(int(c)) self.boxes.append(torch.Tensor(box)) self.labels.append(torch.LongTensor(label)) def __getitem__(self, idx): '''Load a image, and encode its bbox locations and class labels. Args: idx: (int) image index. Returns: img: (tensor) image tensor. loc_target: (tensor) location targets, sized [8732,4]. conf_target: (tensor) label targets, sized [8732,]. ''' # Load image and bbox locations. fname = self.fnames[idx] img = Image.open(os.path.join(self.root, fname)) boxes = self.boxes[idx].clone() labels = self.labels[idx] # Data augmentation while training. if self.train: img, boxes = self.random_flip(img, boxes) img, boxes, labels = self.random_crop(img, boxes, labels) # Scale bbox locaitons to [0,1]. w,h = img.size boxes /= torch.Tensor([w,h,w,h]).expand_as(boxes) img = img.resize((self.img_size,self.img_size)) img = self.transform(img) # Encode loc & conf targets. loc_target, conf_target = self.data_encoder.encode(boxes, labels) return img, loc_target, conf_target def random_flip(self, img, boxes): '''Randomly flip the image and adjust the bbox locations. For bbox (xmin, ymin, xmax, ymax), the flipped bbox is: (w-xmax, ymin, w-xmin, ymax). Args: img: (PIL.Image) image. boxes: (tensor) bbox locations, sized [#obj, 4]. Returns: img: (PIL.Image) randomly flipped image. boxes: (tensor) randomly flipped bbox locations, sized [#obj, 4]. ''' if random.random() < 0.5: img = img.transpose(Image.FLIP_LEFT_RIGHT) w = img.width xmin = w - boxes[:,2] xmax = w - boxes[:,0] boxes[:,0] = xmin boxes[:,2] = xmax return img, boxes def random_crop(self, img, boxes, labels): '''Randomly crop the image and adjust the bbox locations. For more details, see 'Chapter2.2: Data augmentation' of the paper. Args: img: (PIL.Image) image. boxes: (tensor) bbox locations, sized [#obj, 4]. labels: (tensor) bbox labels, sized [#obj,]. Returns: img: (PIL.Image) cropped image. selected_boxes: (tensor) selected bbox locations. labels: (tensor) selected bbox labels. ''' imw, imh = img.size while True: min_iou = random.choice([None, 0.1, 0.3, 0.5, 0.7, 0.9]) if min_iou is None: return img, boxes, labels for _ in range(100): w = random.randrange(int(0.1*imw), imw) h = random.randrange(int(0.1*imh), imh) if h > 2*w or w > 2*h: continue x = random.randrange(imw - w) y = random.randrange(imh - h) roi = torch.Tensor([[x, y, x+w, y+h]]) center = (boxes[:,:2] + boxes[:,2:]) / 2 # [N,2] roi2 = roi.expand(len(center), 4) # [N,4] mask = (center > roi2[:,:2]) & (center < roi2[:,2:]) # [N,2] mask = mask[:,0] & mask[:,1] #[N,] if not mask.any(): continue selected_boxes = boxes.index_select(0, mask.nonzero().squeeze(1)) iou = self.data_encoder.iou(selected_boxes, roi) if iou.min() < min_iou: continue img = img.crop((x, y, x+w, y+h)) selected_boxes[:,0].add_(-x).clamp_(min=0, max=w) selected_boxes[:,1].add_(-y).clamp_(min=0, max=h) selected_boxes[:,2].add_(-x).clamp_(min=0, max=w) selected_boxes[:,3].add_(-y).clamp_(min=0, max=h) return img, selected_boxes, labels[mask] def __len__(self): return self.num_samples
python
package com.hjq.demo.base; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import com.gyf.barlibrary.ImmersionBar; import com.hjq.base.BaseLazyFragment; /** * author : HJQ * github : https://github.com/getActivity/AndroidProject * time : 2018/10/18 * desc : 支持沉浸式Fragment懒加载基类(默认不开启沉浸式) */ public abstract class UILazyFragment extends BaseLazyFragment { private ImmersionBar mImmersionBar;//状态栏沉浸 @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //初始化沉浸式状态栏 if (isFragmentVisible() && isStatusBarEnabled() && isLazyLoad()) { statusBarConfig().init(); } //设置标题栏 if (getTitleBarId() > 0) { ImmersionBar.setTitleBar(mActivity, findViewById(getTitleBarId())); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser && isStatusBarEnabled() && isLazyLoad()) { // 重新初始化状态栏 statusBarConfig().init(); } } /** * 是否在Fragment使用沉浸式 */ public boolean isStatusBarEnabled() { return false; } /** * 获取状态栏沉浸的配置对象 */ protected ImmersionBar getStatusBarConfig() { return mImmersionBar; } /** * 初始化沉浸式 */ private ImmersionBar statusBarConfig() { //在BaseActivity里初始化 mImmersionBar = ImmersionBar.with(this) .statusBarDarkFont(statusBarDarkFont()) //默认状态栏字体颜色为黑色 .keyboardEnable(true); //解决软键盘与底部输入框冲突问题,默认为false,还有一个重载方法,可以指定软键盘mode return mImmersionBar; } /** * 获取状态栏字体颜色 */ protected boolean statusBarDarkFont() { //返回true表示黑色字体 return true; } @Override public void onDestroy() { super.onDestroy(); if (mImmersionBar != null) mImmersionBar.destroy(); } }
java
With the hustle bustle of the Christmas season now over, FPL managers can heave a sigh of relief as the fixture frequencies reduce and rotation is now less likely. As the Premier League season spills into its second half, there are templates in place with many managers opting for similar players in their teams. It is at this time, that the differentials become crucial. Having the right set of differentials at the right time, can propel one's overall rank considerably. Let's quickly take a look at differentials not only at each position, but at different price ranges as well. Marko Arnautovic is finally back for the Hammers and he delivered in style against Brighton, bagging 2 goals to save the game for West Ham. At 6.9, Arnautovic is a terrific FPL prospect and could be a great differential in the short run, before he is shipped in by many managers. It's hard to ignore Sergio Aguero (11.2) for long. The Argentine spearhead was injured for a brief while, before returning to the squad against Crystal Palace in late December. The striker has found the back of the net once and assisted another in his 3 appearances since. With a huge loss in the percentage selected by FPL managers, it could be the time to get in the Argentine early, who could explode in any game, and at any time! Jamie Vardy has not been in the limelight as much since the miracle Leicester season back in 2015/16. However, the Englishman has quietly been racking up the goals, having scored 7 goals so far this season. With a paltry 4.4% of managers having bought him, he could be an excellent differential to rely on. In the lower price range, Watford skipper Troy Deeney (5.8) is a huge threat in front of goal, having scored a brace and assisted a third in his recent fixture against Bournemouth. With the focus understandably on Mo Salah, there has been an alarming drop in the number of managers buying Sadio Mane (9.5). Priced nearly 4.0 million lesser than his teammate, the Senegal international has been impressive this season and has been unlucky to not rack up more points in the recent games. Opting for Mane can save a hefty amount of money which can be used to spread the funds across the team. This move could be a crucial one for FPL managers this season, as it could prove to be the difference. Christian Eriksen has been an FPL favourite for many seasons now, but has been bought by a measly 6.1% of managers owing to his long absence due to injury. However, the Dane has come back all guns blazing, having scored 4 goals in the last 5 games. With easy fixtures up ahead, the Dane could rack up big points and make up for the time he lost in the first half of the season. In the lower price range, David Brooks (5.0) of Bournemouth has been impressive with 2 goals and an assist in his last 4 games. The Cherries have good firepower up front, and Brooks could be a steal at his price range. In the same range, Cardiff City offer exciting prospects, especially considering the fact that they have a great run of fixtures lined up ahead of them. Victor Camarasa (4.6) and Callum Paterson (5.1) are both good value-for-money. Picking defenders based on upcoming fixtures is important as easier fixtures increase chances of keeping clean sheets. Having the right backline at the right time can help boost your overall rank considerably! FPL tagged defenders who play out of position are gems in the fantasy world. Jeffrey Schlupp of Crystal Palace plays at the left wing for Crystal Palace, despite being marked as a defender in FPL. At 4.4, he could be a great steal, having scored 2 goals recently. The Eagles also have a favourable run of fixtures at Selhurst Park, where their defence is particularly solid. Another addition to the out-of-position defender is Ricardo Pereira, who was deployed as a left winger for Leicester City in their away game against Everton. Pereira not only assisted Vardy in the lone goal of the game, but also racked up a clean sheet and maximum bonus points. Sead Kolasinac may be part of a leaky Arsenal defence, but is highly effective owing to his attacking returns and knack to rack up bonus points. He's got bonus points in 4 games out of the 10 he's featured in, and surprisingly Arsenal didn't even keep a clean sheet in 3 of these 4 games! Liverpool has conceded just 8 goals so far this season, and this makes it hard to look past Dejan Lovren (4.9) and Trent Alexander-Arnold (5.1). The latter is especially exciting, owing to his set piece duties for the club. Manchester United seem rejuvenated under Ole Gunnar Solskjaer and Luke Shaw has been impressive following his return from injury. 4.9 million is an attractive price for the United defender, especially considering that they have relatively easy fixtures coming up. Until Matt Ryan's return from international duty, David Button of Brighton could be a good shout if you're looking for a short-term addition to your squad at a mere 4.0 million. Cardiff's Neil Etheridge is the second-highest scoring goalkeeper this season and is truly a steal at his price tag of 4.5 million. With a neat run of fixtures on the horizon, the Cardiff man could bring some valuable saves and bonus points to add to your tally.
english
<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright (C) 2018-2020 Nokia """ Runner abstraction goal is to hide concurrency machinery used to make it exchangeable (threads, asyncio, twisted, curio) """ __author__ = '<NAME>, <NAME>, <NAME>' __copyright__ = 'Copyright (C) 2018-2020, Nokia' __email__ = '<EMAIL>, <EMAIL>, <EMAIL>' import atexit import concurrent.futures import logging import threading import time from abc import abstractmethod, ABCMeta from concurrent.futures import ThreadPoolExecutor, wait from functools import partial from six import add_metaclass from moler.exceptions import CommandTimeout from moler.exceptions import ConnectionObserverTimeout from moler.exceptions import MolerException from moler.exceptions import CommandFailure from moler.util.loghelper import log_into_logger @add_metaclass(ABCMeta) class ConnectionObserverRunner(object): @abstractmethod def shutdown(self): """Cleanup used resources.""" @abstractmethod def submit(self, connection_observer): """ Submit connection observer to background execution. Returns Future that could be used to await for connection_observer done. """ @abstractmethod def wait_for(self, connection_observer, connection_observer_future, timeout=10.0): """ Await for connection_observer running in background or timeout. :param connection_observer: The one we are awaiting for. :param connection_observer_future: Future of connection-observer returned from submit(). :param timeout: Max time (in float seconds) you want to await before you give up. :return: """ @abstractmethod def wait_for_iterator(self, connection_observer, connection_observer_future): """ Version of wait_for() intended to be used by Python3 to implement iterable/awaitable object. Note: we don't have timeout parameter here. If you want to await with timeout please do use timeout machinery of selected parallelism. :param connection_observer: The one we are awaiting for. :param connection_observer_future: Future of connection-observer returned from submit(). :return: iterator """ @abstractmethod def feed(self, connection_observer): """ Feeds connection_observer with data to let it become done. This is a place where runner is a glue between words of connection and connection-observer. Should be called from background-processing of connection observer. """ @abstractmethod def timeout_change(self, timedelta): """ Call this method to notify runner that timeout has been changed in observer :param timedelta: delta timeout in float seconds :return: None """ def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.shutdown() return False # exceptions (if any) should be reraised def time_out_observer(connection_observer, timeout, passed_time, runner_logger, kind="background_run"): """Set connection_observer status to timed-out""" if not connection_observer.life_status.was_on_timeout_called: connection_observer.life_status.was_on_timeout_called = True if not connection_observer.done(): if hasattr(connection_observer, "command_string"): exception = CommandTimeout(connection_observer=connection_observer, timeout=timeout, kind=kind, passed_time=passed_time) else: exception = ConnectionObserverTimeout(connection_observer=connection_observer, timeout=timeout, kind=kind, passed_time=passed_time) # TODO: secure_data_received() may change status of connection_observer # TODO: and if secure_data_received() runs inside threaded connection - we have race connection_observer.set_exception(exception) connection_observer.on_timeout() observer_info = "{}.{}".format(connection_observer.__class__.__module__, connection_observer) timeout_msg = "has timed out after {:.2f} seconds.".format(passed_time) msg = "{} {}".format(observer_info, timeout_msg) # levels_to_go_up: extract caller info to log where .time_out_observer has been called from connection_observer._log(logging.INFO, msg, levels_to_go_up=2) log_into_logger(runner_logger, level=logging.DEBUG, msg="{} {}".format(connection_observer, timeout_msg), levels_to_go_up=1) def result_for_runners(connection_observer): """ When runner takes result from connection-observer it should not modify ConnectionObserver._not_raised_exceptions :param connection_observer: observer to get result from :return: result or raised exception """ if connection_observer._exception: raise connection_observer._exception return connection_observer.result() class CancellableFuture(object): def __init__(self, future, observer_lock, stop_running, is_done, stop_timeout=0.5): """ Wrapper to allow cancelling already running concurrent.futures.Future Assumes that executor submitted function with following parameters fun(stop_running, is_done) and that such function correctly handles that events (threading.Event) :param future: wrapped instance of concurrent.futures.Future :param stop_running: set externally to finish thread execution of function :param is_done: set when function finished running in thread :param stop_timeout: timeout to await is_done after setting stop_running """ self._future = future self.observer_lock = observer_lock # against threads race write-access to observer self._stop_running = stop_running self._stop_timeout = stop_timeout self._is_done = is_done def __getattr__(self, attr): """Make it proxy to embedded future""" attribute = getattr(self._future, attr) return attribute def __str__(self): """Make it proxy to embedded future""" f_str = str(self._future) return "CancellableFuture({})".format(f_str) def cancel(self, no_wait=False): """ Cancel embedded future :param no_wait: if True - just set self._stop_running event to let thread exit loop :return: """ if self.running(): self._stop(no_wait) if no_wait: return True # after exiting threaded-function future.state == FINISHED # we need to change it to PENDING to allow for correct cancel via concurrent.futures.Future with self._condition: self._future._state = concurrent.futures._base.PENDING return self._future.cancel() def _stop(self, no_wait=False): self._stop_running.set() # force threaded-function to exit if no_wait: return if not self._is_done.wait(timeout=self._stop_timeout): err_msg = "Failed to stop thread-running function within {} sec".format(self._stop_timeout) # TODO: should we break current thread or just set this exception inside connection-observer # (is it symetric to failed-start ?) # may cause leaking resources - no call to moler_conn.unsubscribe() raise MolerException(err_msg) class ThreadPoolExecutorRunner(ConnectionObserverRunner): def __init__(self, executor=None): """Create instance of ThreadPoolExecutorRunner class""" self._tick = 0.005 # Tick for sleep or partial timeout self._in_shutdown = False self._i_own_executor = False self._was_timeout_called = False self.executor = executor self.logger = logging.getLogger('moler.runner.thread-pool') self.logger.debug("created") atexit.register(self.shutdown) if executor is None: max_workers = 1000 # max 1000 threads in pool try: # concurrent.futures v.3.2.0 introduced prefix we like :-) self.executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix='ThrdPoolRunner') except TypeError as exc: if ('unexpected' in str(exc)) and ('thread_name_prefix' in str(exc)): self.executor = ThreadPoolExecutor(max_workers=max_workers) else: raise self.logger.debug("created own executor {!r}".format(self.executor)) self._i_own_executor = True else: self.logger.debug("reusing provided executor {!r}".format(self.executor)) def shutdown(self): self.logger.debug("shutting down") self._in_shutdown = True # will exit from feed() without stopping executor (since others may still use that executor) if self._i_own_executor: self.executor.shutdown() # also stop executor since only I use it def submit(self, connection_observer): """ Submit connection observer to background execution. Returns Future that could be used to await for connection_observer done. """ assert connection_observer.life_status.start_time > 0.0 # connection-observer lifetime should already been # started observer_timeout = connection_observer.timeout remain_time, msg = his_remaining_time("remaining", timeout=observer_timeout, from_start_time=connection_observer.life_status.start_time) self.logger.debug("go background: {!r} - {}".format(connection_observer, msg)) # TODO: check dependency - connection_observer.connection # Our submit consists of two steps: # 1. _start_feeding() which establishes data path from connection to observer # 2. scheduling "background feed" via executor.submit() # # By using the code of _start_feeding() we ensure that after submit() connection data could reach # data_received() of observer - as it would be "virtually running in background" # Another words, no data will be lost-for-observer between runner.submit() and runner.feed() really running # # We do not await here (before returning from submit()) for "background feed" to be really started. # That is in sync with generic nature of threading.Thread - after thread.start() we do not have # running thread - it is user responsibility to await for threads switch. # User may check "if thread is running" via Thread.is_alive() API. # For concurrent.futures same is done via future.running() API. # # However, lifetime of connection_observer starts in connection_observer.start(). # It gains it's own timer so that timeout is calculated from that connection_observer.life_status.start_time # That lifetime may start even before this submit() if observer is command and we have commands queue. # # As a corner case runner.wait_for() may timeout before feeding thread has started. stop_feeding = threading.Event() feed_done = threading.Event() observer_lock = threading.Lock() # against threads race write-access to observer subscribed_data_receiver = self._start_feeding(connection_observer, observer_lock) connection_observer_future = self.executor.submit(self.feed, connection_observer, subscribed_data_receiver, stop_feeding, feed_done, observer_lock) if connection_observer_future.done(): # most probably we have some exception during submit(); it should be stored inside future try: too_early_result = connection_observer_future.result() err_msg = "PROBLEM: future returned {} already in runner.submit()".format(too_early_result) self.logger.debug("go background: {} - {}".format(connection_observer, err_msg)) except Exception as err: err_msg = "PROBLEM: future raised {!r} during runner.submit()".format(err) self.logger.warning("go background: {} - {}".format(connection_observer, err_msg)) self.logger.exception(err_msg) raise finalizer = partial(self._feed_finish_callback, connection_observer=connection_observer, subscribed_data_receiver=subscribed_data_receiver, feed_done=feed_done, observer_lock=observer_lock) connection_observer_future.add_done_callback(finalizer) c_future = CancellableFuture(connection_observer_future, observer_lock, stop_feeding, feed_done) connection_observer.life_status.last_feed_time = time.time() return c_future def wait_for(self, connection_observer, connection_observer_future, timeout=None): """ Await for connection_observer running in background or timeout. :param connection_observer: The one we are awaiting for. :param connection_observer_future: Future of connection-observer returned from submit(). :param timeout: Max time (in float seconds) you want to await before you give up. If None then taken from connection_observer :return: """ # TODO: calculate remaining timeout before logging + done(result/exception) info if connection_observer.done(): # 1. done() might mean "timed out" before future created (future is None) # Observer lifetime started with its timeout clock so, it might timeout even before # future created by runner.submit() - may happen for nonempty commands queue # 2. done() might mean "timed out" before future start # Observer lifetime started with its timeout clock so, it might timeout even before # connection_observer_future started - since future's thread might not get control yet # 3. done() might mean "timed out" before wait_for() # wait_for() might be called so late after submit() that observer already "timed out" # 4. done() might mean have result or got exception # wait_for() might be called so late after submit() that observer already got result/exception # # In all above cases we want to stop future if it is still running self.logger.debug("go foreground: {} is already done".format(connection_observer)) self._cancel_submitted_future(connection_observer, connection_observer_future) return None max_timeout = timeout observer_timeout = connection_observer.timeout # we count timeout from now if timeout is given; else we use .life.status.start_time and .timeout of observer start_time = time.time() if max_timeout else connection_observer.life_status.start_time await_timeout = max_timeout if max_timeout else observer_timeout if max_timeout: remain_time, msg = his_remaining_time("await max.", timeout=max_timeout, from_start_time=start_time) else: remain_time, msg = his_remaining_time("remaining", timeout=observer_timeout, from_start_time=start_time) self.logger.debug("go foreground: {} - {}".format(connection_observer, msg)) if connection_observer_future is None: end_of_life, remain_time = await_future_or_eol(connection_observer, remain_time, start_time, await_timeout, self.logger) if end_of_life: return None if not self._execute_till_eol(connection_observer=connection_observer, connection_observer_future=connection_observer_future, max_timeout=max_timeout, await_timeout=await_timeout, remain_time=remain_time): # code below is to close ConnectionObserver and future objects self._end_of_life_of_future_and_connection_observer(connection_observer, connection_observer_future) return None def _execute_till_eol(self, connection_observer, connection_observer_future, max_timeout, await_timeout, remain_time): eol_remain_time = remain_time # either we wait forced-max-timeout or we check done-status each 0.1sec tick if eol_remain_time > 0.0: future = connection_observer_future or connection_observer._future assert future is not None if max_timeout: done, not_done = wait([future], timeout=remain_time) if (future in done) or connection_observer.done(): self._cancel_submitted_future(connection_observer, future) return True self._wait_for_time_out(connection_observer, connection_observer_future, timeout=await_timeout) if connection_observer.life_status.terminating_timeout > 0.0: connection_observer.life_status.in_terminating = True done, not_done = wait([future], timeout=connection_observer.life_status.terminating_timeout) if (future in done) or connection_observer.done(): self._cancel_submitted_future(connection_observer, future) return True else: while eol_remain_time > 0.0: done, not_done = wait([future], timeout=self._tick) if (future in done) or connection_observer.done(): self._cancel_submitted_future(connection_observer, future) return True already_passed = time.time() - connection_observer.life_status.start_time eol_timeout = connection_observer.timeout + connection_observer.life_status.terminating_timeout eol_remain_time = eol_timeout - already_passed timeout = connection_observer.timeout remain_time = timeout - already_passed if remain_time <= 0.0: self._wait_for_time_out(connection_observer, connection_observer_future, timeout=await_timeout) if not connection_observer.life_status.in_terminating: connection_observer.life_status.in_terminating = True else: self._wait_for_not_started_connection_observer_is_done(connection_observer=connection_observer) return False def _wait_for_not_started_connection_observer_is_done(self, connection_observer): # Have to wait till connection_observer is done with terminaing timeout. eol_remain_time = connection_observer.life_status.terminating_timeout start_time = time.time() while not connection_observer.done() and eol_remain_time > 0.0: time.sleep(self._tick) eol_remain_time = start_time + connection_observer.life_status.terminating_timeout - time.time() def _end_of_life_of_future_and_connection_observer(self, connection_observer, connection_observer_future): future = connection_observer_future or connection_observer._future if future: future.cancel(no_wait=True) connection_observer.set_end_of_life() @staticmethod def _cancel_submitted_future(connection_observer, connection_observer_future): future = connection_observer_future or connection_observer._future if future and (not future.done()): future.cancel(no_wait=True) def _wait_for_time_out(self, connection_observer, connection_observer_future, timeout): passed = time.time() - connection_observer.life_status.start_time future = connection_observer_future or connection_observer._future if future: with future.observer_lock: time_out_observer(connection_observer=connection_observer, timeout=timeout, passed_time=passed, runner_logger=self.logger, kind="await_done") else: # sorry, we don't have lock yet (it is created by runner.submit() time_out_observer(connection_observer=connection_observer, timeout=timeout, passed_time=passed, runner_logger=self.logger, kind="await_done") def wait_for_iterator(self, connection_observer, connection_observer_future): """ Version of wait_for() intended to be used by Python3 to implement iterable/awaitable object. Note: we don't have timeout parameter here. If you want to await with timeout please do use timeout machinery of selected parallelism. :param connection_observer: The one we are awaiting for. :param connection_observer_future: Future of connection-observer returned from submit(). :return: iterator """ while not connection_observer_future.done(): yield None # return result_for_runners(connection_observer) # May raise too. # Python > 3.3 res = result_for_runners(connection_observer) raise StopIteration(res) # Python 2 compatibility def _start_feeding(self, connection_observer, observer_lock): """ Start feeding connection_observer by establishing data-channel from connection to observer. """ def secure_data_received(data, timestamp): try: if connection_observer.done() or self._in_shutdown: return # even not unsubscribed secure_data_received() won't pass data to done observer with observer_lock: connection_observer.data_received(data, timestamp) connection_observer.life_status.last_feed_time = time.time() except Exception as exc: # TODO: handling stacktrace # observers should not raise exceptions during data parsing # but if they do so - we fix it with observer_lock: self.logger.warning("Unhandled exception from '{} 'caught by runner.".format(connection_observer)) ex_msg = "Unexpected exception from {} caught by runner when processing data >>{}<< at '{}':" \ " >>>{}<<< -> repr: >>>{}<<<".format(connection_observer, data, timestamp, exc, repr(exc)) if connection_observer.is_command(): ex = CommandFailure(command=connection_observer, message=ex_msg) else: ex = MolerException(ex_msg) connection_observer.set_exception(ex) finally: if connection_observer.done() and not connection_observer.cancelled(): if connection_observer._exception: self.logger.debug("{} raised: {!r}".format(connection_observer, connection_observer._exception)) else: self.logger.debug("{} returned: {}".format(connection_observer, connection_observer._result)) moler_conn = connection_observer.connection self.logger.debug("subscribing for data {}".format(connection_observer)) with observer_lock: moler_conn.subscribe(observer=secure_data_received, connection_closed_handler=connection_observer.connection_closed_handler) # after subscription we have data path so observer is started remain_time, msg = his_remaining_time("remaining", timeout=connection_observer.timeout, from_start_time=connection_observer.life_status.start_time) connection_observer._log(logging.INFO, "{} started, {}".format(connection_observer.get_long_desc(), msg)) if connection_observer.is_command(): connection_observer.send_command() return secure_data_received # to know what to unsubscribe def _stop_feeding(self, connection_observer, subscribed_data_receiver, feed_done, observer_lock): with observer_lock: if not feed_done.is_set(): moler_conn = connection_observer.connection self.logger.debug("unsubscribing {}".format(connection_observer)) moler_conn.unsubscribe(observer=subscribed_data_receiver, connection_closed_handler=connection_observer.connection_closed_handler) # after unsubscription we break data path so observer is finished remain_time, msg = his_remaining_time("remaining", timeout=connection_observer.timeout, from_start_time=connection_observer.life_status.start_time) connection_observer._log(logging.INFO, "{} finished, {}".format(connection_observer.get_short_desc(), msg)) feed_done.set() def _feed_finish_callback(self, future, connection_observer, subscribed_data_receiver, feed_done, observer_lock): """Callback attached to concurrent.futures.Future of submitted feed()""" self._stop_feeding(connection_observer, subscribed_data_receiver, feed_done, observer_lock) def feed(self, connection_observer, subscribed_data_receiver, stop_feeding, feed_done, observer_lock): """ Feeds connection_observer by transferring data from connection and passing it to connection_observer. Should be called from background-processing of connection observer. """ remain_time, msg = his_remaining_time("remaining", timeout=connection_observer.timeout, from_start_time=connection_observer.life_status.start_time) self.logger.debug("thread started for {}, {}".format(connection_observer, msg)) if not subscribed_data_receiver: subscribed_data_receiver = self._start_feeding(connection_observer, observer_lock) time.sleep(self._tick) # give control back before we start processing self._feed_loop(connection_observer, stop_feeding, observer_lock) remain_time, msg = his_remaining_time("remaining", timeout=connection_observer.timeout, from_start_time=connection_observer.life_status.start_time) self.logger.debug("thread finished for {}, {}".format(connection_observer, msg)) self._stop_feeding(connection_observer, subscribed_data_receiver, feed_done, observer_lock) return None def _feed_loop(self, connection_observer, stop_feeding, observer_lock): start_time = connection_observer.life_status.start_time while True: if stop_feeding.is_set(): # TODO: should it be renamed to 'cancelled' to be in sync with initial action? self.logger.debug("stopped {}".format(connection_observer)) break if connection_observer.done(): self.logger.debug("done {}".format(connection_observer)) break current_time = time.time() run_duration = current_time - start_time # we need to check connection_observer.timeout at each round since timeout may change # during lifetime of connection_observer timeout = connection_observer.timeout if connection_observer.life_status.in_terminating: timeout = connection_observer.life_status.terminating_timeout if (timeout is not None) and (run_duration >= timeout): if connection_observer.life_status.in_terminating: msg = "{} underlying real command failed to finish during {} seconds. It will be forcefully" \ " terminated".format(connection_observer, timeout) self.logger.info(msg) connection_observer.set_end_of_life() else: with observer_lock: time_out_observer(connection_observer, timeout=connection_observer.timeout, passed_time=run_duration, runner_logger=self.logger) if connection_observer.life_status.terminating_timeout >= 0.0: start_time = time.time() connection_observer.life_status.in_terminating = True else: break else: self._call_on_inactivity(connection_observer=connection_observer, current_time=current_time) if self._in_shutdown: self.logger.debug("shutdown so cancelling {}".format(connection_observer)) connection_observer.cancel() time.sleep(self._tick) # give moler_conn a chance to feed observer def _call_on_inactivity(self, connection_observer, current_time): """ Call on_inactivity on connection_observer if needed. :param connection_observer: ConnectionObserver object. :param current_time: current time in seconds. :return: None """ life_status = connection_observer.life_status if (life_status.inactivity_timeout > 0.0) and (life_status.last_feed_time is not None): expected_feed_timeout = life_status.last_feed_time + life_status.inactivity_timeout if current_time > expected_feed_timeout: connection_observer.on_inactivity() connection_observer.life_status.last_feed_time = current_time def timeout_change(self, timedelta): pass # utilities to be used by runners def his_remaining_time(prefix, timeout, from_start_time): """ Calculate remaining time of "he" object assuming that "he" has .life_status.start_time attribute :param prefix: string to be used inside 'remaining time description' :param he: object to calculate remaining time for :param timeout: max lifetime of object :param from_start_time: start of lifetime for the object :return: remaining time as float and related description message """ already_passed = time.time() - from_start_time remain_time = timeout - already_passed if remain_time < 0.0: remain_time = 0.0 msg = "{} {:.3f} [sec], already passed {:.3f} [sec]".format(prefix, remain_time, already_passed) return remain_time, msg def await_future_or_eol(connection_observer, remain_time, start_time, timeout, logger): # Observer lifetime started with its timeout clock # but setting connection_observer._future may be delayed by nonempty commands queue. # In such case we have to wait either for _future or timeout. end_of_life = False while (connection_observer._future is None) and (remain_time > 0.0): time.sleep(0.005) if connection_observer.done(): logger.debug("{} is done before creating future".format(connection_observer)) end_of_life = True break now = time.time() already_passed = now - start_time remain_time = timeout - already_passed observer_lifetime_passed = now - connection_observer.life_status.start_time remain_observer_lifetime = connection_observer.timeout + connection_observer.life_status.terminating_timeout\ - observer_lifetime_passed # we timeout on earlier timeout (timeout or connection_observer.timeout) if remain_observer_lifetime <= 0.0: remain_time = 0.0 if remain_time <= 0.0: logger.debug("{} timeout before creating future".format(connection_observer)) return end_of_life, remain_time
python