text
stringlengths
1
1.04M
language
stringclasses
25 values
System Win 98 FE, IE 5.0. While conected I randomly get the error security warning as below. On Clicking on 'Yes' Button I am directed to the next screen as given below. What may be the reason ? Is it due to any virus ?
english
The United States Department of Defense was blasted on social media after posting a tweet touting the need for "diversity" and "inclusion" in the military. "NEWS: Diversity, Equity, Inclusion Are Necessities in U. S. Military," the Department of Defense posted Wednesday along with an article outlining the many ways the military is pushing for diversity in its ranks and says that the "need for diversity, equity and inclusion to be a consideration or a part of all decisions in the military. " "I would hope that as many leaders and members of the total force as possible see [diversity, equity and inclusion] efforts as a force multiplier," Bishop Garrison, the senior advisor to the secretary of defense for human capital and diversity, equity and inclusion, said in the article, which added that the diversity program can be a "way to make the U. S. military more successful in achieving critical missions and in making forces more lethal. " The tweet immediately drew criticism from conservatives on Twitter who slammed the military for focusing on "woke" politics. "Does China have that in their military? " author Ryan Girdusky tweeted. PENTAGON SPOX JOHN KIRBY DISMISSES CONCERNS ABOUT 'WOKENESS' IN THE MILITARY: 'RIDICULOUS' "Our enemies laugh at us," comedian Tim Young tweeted. "You guys going to hand out copies of ‘White Fragility’ to the Russians? " the Libertarian Party of New Hampshire tweeted. "FYI, there are no safe spaces on the Eastern Front. " "We’re gonna lose a major war," conservative commentator Jesse Kelly tweeted. "If your military’s priorities are anything other than killing your nation’s enemies you are royally screwed," Blaze writer Sam Mangold-Lenett tweeted. The Pentagon did not immediately respond to a request for comment from Fox News. Last month, Pentagon spokesman John Kirby downplayed concerns about woke identity politics in the military. "It depends on what they are, but I think a lot of it, quite frankly, is driving a stake through a straw man, here," Kirby told Fox News’ Dana Perino. "This argument of ‘wokeness’ in the military. I was in the military for 30 years, and I can tell you, things like diversity and inclusion, that makes us a better military because it brings to the fore in the decisionmaking, operational decisionmaking that we conduct, better ideas, more unique perspectives, somebody else's lived experiences which might actually make us smarter on the battlefield. " Kirby added, "So we know, those kinds of arguments, I think, are ridiculous because we are a stronger military because of our diversity and because we represent all Americans, just like we defend all Americans. " In a statement to Fox News, Kirby told Fox News that he is "proud of our efforts to become a more diverse force. " "Last week, that same force took down the leader of ISIS, helped shore up NATO’s eastern flank and continued to take the pressure off hospital staff throughout the country, just to name a few critical missions," Kirby said.
english
import { SentryConfig, TranslationsConfig, DefaultTranslations, BIConfig, ExperimentsConfig, } from 'yoshi-flow-editor-runtime/build/constants'; import t from './template'; type Opts = Record< 'settingsWrapperPath' | 'componentFileName' | 'baseUIPath', string > & { translationsConfig: TranslationsConfig | null; defaultTranslations: DefaultTranslations | null; projectName: string; experimentsConfig: ExperimentsConfig | null; ownerBiLoggerPath: string | null; appName: string | null; sentry: SentryConfig | null; biConfig: BIConfig | null; }; export default t<Opts>` import React from 'react'; import ReactDOM from 'react-dom'; import SettingsWrapper from '${({ settingsWrapperPath }) => settingsWrapperPath}'; import Settings from '${({ componentFileName }) => componentFileName}'; import '${({ baseUIPath }) => baseUIPath}'; var translationsConfig = ${({ translationsConfig }) => translationsConfig ? JSON.stringify(translationsConfig) : 'null'}; var defaultTranslations = ${({ defaultTranslations }) => defaultTranslations ? JSON.stringify(defaultTranslations) : 'null'}; var biConfig = ${({ biConfig }) => biConfig ? JSON.stringify(biConfig) : 'null'}; var experimentsConfig = ${({ experimentsConfig }) => experimentsConfig ? JSON.stringify(experimentsConfig) : 'null'}; var projectName = '${({ projectName }) => projectName}'; var appName = '${({ appName }) => appName || 'null'}'; ${({ ownerBiLoggerPath }) => ownerBiLoggerPath ? `import biLogger from '${ownerBiLoggerPath}'` : 'var biLogger = null'}; var sentry = ${({ sentry }) => sentry ? `{ DSN: '${sentry.DSN}', id: '${sentry.id}', projectName: '${sentry.projectName}', teamName: '${sentry.teamName}', }` : 'null'}; ReactDOM.render(React.createElement(SettingsWrapper({ Settings, sentry, translationsConfig, experimentsConfig, defaultTranslations, biConfig, biLogger, projectName, appName }), null), document.getElementById('root')); `;
typescript
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { // Connecting try (Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://192.168.164.129:10087", "neo4j", "ledwaf")) { // Querying String query = "MATCH (n:UserDemo) where n.user_id = 1 RETURN n LIMIT 1"; try(Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query); while(rs.next()) { System.out.println(rs.getString("p.age")+":"+rs.getString("p.school")); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java
import { ConnectionStatus } from "../../ConnectionStatus"; import { ConnectionState, ConnectionActionTypes, SET_CONNECTION_STATUS, } from "./types"; const initialState: ConnectionState = { status: ConnectionStatus.NotConnected, }; export function connectionReducer( state = initialState, action: ConnectionActionTypes ): ConnectionState { switch (action.type) { case SET_CONNECTION_STATUS: { return { ...state, status: action.status, }; } default: return state; } }
typescript
<reponame>andrico1234/lydia-homepage import React from "react" import { navigate } from "gatsby" import { ChoreographerImage } from "./images/ChoregrapherImage" import { ChoreographerMobileImage } from "./images/ChoregrapherMobileImage" import { DanceArtistImage } from "./images/DanceArtistImage" import { DanceArtistMobileImage } from "./images/DanceArtistMobileImage" import { TeacherImage } from "./images/TeacherImage" import { TeacherMobileImage } from "./images/TeacherMobileImage" import { ExperienceBlock } from "./ExperienceBlock" async function directToGallery() { window.scrollTo(0, 0) setTimeout(() => { navigate("/gallery") }, 500) } export function Experience() { return ( <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "center" }} > <ExperienceBlock title="Dance Artist" img={<DanceArtistImage />} mobileImg={<DanceArtistMobileImage />} description={ <p> As a professional dance artist in the Classical and Contemporary genres, Lydia will offer her skills and expertise and adapt to the needs of your project or event. Whether it be for stage, screen or functions. You can see Lydia's capabilities as a dance artist in the{" "} <span style={{ textDecoration: "underline", cursor: "pointer" }} onClick={directToGallery} > gallery </span> </p> } /> <ExperienceBlock title="Teacher" img={<TeacherImage />} mobileImg={<TeacherMobileImage />} reverse description={ <> <p> Offering tuition in the dance and fitness industries with over 5 years of experience, Lydia teaches at several gyms and studios across London. Her classes specialise in Ballet and low-impact exercise and are ideal for anyone looking to tone and gain strength while improving their core-stability, flexibility and balance. </p> <p> Please contact Lydia if you would like to know more about these classes or are seeking private tuition. </p> </> } /> <ExperienceBlock title="Choreographer" img={<ChoreographerImage />} mobileImg={<ChoreographerMobileImage />} description={ <p> Lydia has choreographed many works, both small and large scale. Her clients range from students, dance artists, and music professionals. Lydia's choreography is both engaging and emotive, which have come as a result of following her two key principles; open collaboration and clear communication. </p> } /> </div> ) }
typescript
<filename>api/api_fanfic.py from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.mail import BadHeaderError, send_mail from rest_framework import permissions, views, status from rest_framework.response import Response from fanfics.models import Fanfic class ShareFanficAPIView(views.APIView): """ Share fanfiction with e-mail """ permission_classes = (permissions.AllowAny,) authentication_classes = () def post(self, request, *args, **kwargs): fanfic_id = request.data.get('id') fanfic = Fanfic.objects.get(id=fanfic_id) current_site = get_current_site(request) name = request.data.get('name') email = request.data.get('email') to = request.data.get('to') comments = request.data.get('comments') try: fanfic_url = current_site.domain + '/#/' + 'fanfic/detail/' + fanfic.slug subject = '{} ({}) recommends you reading "{}"'.format(name, email, fanfic.title) message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(fanfic.title, fanfic_url,name, comments) send_mail(subject, message, settings.SERVER_EMAIL, [to]) sent = True return Response({"message": sent}, status=status.HTTP_200_OK) except BadHeaderError: return Response({"status": "invalid headers"}, status=status.HTTP_400_BAD_REQUEST)
python
<reponame>kevinrhidalgo/salud const nutritionAppID = "f73c3581"; const nutritionAppKey = "<KEY>"; const nutritionInstantURL = "https://trackapi.nutritionix.com/v2/search/instant"; const nutritionDetailGeneric = "https://trackapi.nutritionix.com/v2/natural/nutrients"; const nutritionDetailBranded = "https://trackapi.nutritionix.com/v2/search/item"; function errorHandeling(resJSON){ console.log("ERROR: Nutritionix"); console.log(resJSON.message); } //Sets the metadata (old function) export const setData = (payload) => dispatch => { dispatch({ type: 'SET_DATA', payload: payload }) } //Swap dates using the DateNavigation component export const changeDate = (payload) => dispatch => { dispatch({ type: 'CHANGE_DATE', payload: payload }) } //Toggle action for focusing/unfocusing search bar export const setSearchFocus = (payload) => dispatch => { dispatch({ type: 'SEARCHBAR_FOCUS', payload: payload }) } //Reset parameters when search cancel export const setSearchDefocus = (payload) => dispatch => { dispatch({ type:'SEARCHBAR_DEFOCUS', payload: payload }) } //Retrieve a quick list of data to populate the autofill, based on search string export const quickSearchFoods = (payload) => dispatch => { //When empty, set no search items if (payload === ''){ dispatch({ type: 'SET_QUICK_SEARCH_DATA', payload: { 'common': [], 'branded': [] } }); } //Fetch else { let configBody = { "query": payload }; let configHeaders = { 'x-app-id': nutritionAppID, 'x-app-key': nutritionAppKey, 'Content-Type': 'application/json' }; fetch(nutritionInstantURL, { method: 'POST', body: JSON.stringify(configBody), headers: configHeaders }) .then((res) => { return res.json(); }) .then((myJSON) => { if (myJSON.hasOwnProperty('message')){ errorHandeling(myJSON); } else { dispatch({ type: 'SET_QUICK_SEARCH_DATA', payload: myJSON }); } }).catch((e) => { console.log("ERROR: occured when fetching."); }); } } export const setInspectFocus = (payload) => dispatch => { dispatch({ type: 'SET_INSPECT_FOCUS', payload: payload }); } //Get data from selected food using the nutrition data url export const setInspectFood = (payload) => dispatch => { let configHeaders = { 'x-app-id': nutritionAppID, 'x-app-key': nutritionAppKey, 'Content-Type': 'application/json' }; //Branded if (payload.hasOwnProperty('nix_item_id')) { fetch(nutritionDetailBranded + "?nix_item_id=" + payload.nix_item_id, { method: 'GET', headers: configHeaders }) .then((res) => { return res.json(); }) .then((myJSON) => { if (myJSON.hasOwnProperty('message')){ errorHandeling(myJSON); } else { dispatch({ type: 'SET_INSPECT_FOOD', payload: myJSON.foods[0] }); } }).catch((e) => { console.log("ERROR: occured when fetching."); }); } //Non-Branded else if (payload.hasOwnProperty('food_name')) { let configBody = { "query": payload.food_name }; fetch(nutritionDetailGeneric, { method: 'POST', body: JSON.stringify(configBody), headers: configHeaders }) .then((res) => { return res.json(); }) .then((myJSON) => { if (myJSON.hasOwnProperty('message')){ errorHandeling(myJSON); } else { dispatch({ type: 'SET_INSPECT_FOOD', payload: myJSON.foods[0] }); } }); } //Clean fields (for closing app) else { dispatch({ type: 'SET_INSPECT_FOOD', payload: {} }); } } //Add food to list of Todays consumption export const appendFood = (food, servings, meal) => dispatch => { let compiledFood = { "food_name": food.food_name, "serving_unit": food.serving_unit, "serving_weight_grams": food.serving_weight_grams, "serving_qty": food.serving_qty, "nf_calories": food.nf_calories, "serving_size" : Number(servings), "meal_type": meal, "thumb": food.photo.thumb } //Add branded if exists if (food.nix_item_id) { compiledFood["nix_item_id"] = food.nix_item_id } dispatch({ type: 'ADD_FOOD', payload: compiledFood }); }
javascript
{"PREVALENCE_BY_GENDER_AGE_YEAR":{"TRELLIS_NAME":[],"SERIES_NAME":[],"X_CALENDAR_YEAR":[],"Y_PREVALENCE_1000PP":[]},"PREVALENCE_BY_MONTH":{"X_CALENDAR_MONTH":[],"Y_PREVALENCE_1000PP":[]},"CONDITIONS_BY_TYPE":{"CONCEPT_NAME":"Observation recorded from EHR","COUNT_VALUE":19},"AGE_AT_FIRST_DIAGNOSIS":{"CATEGORY":["FEMALE","MALE"],"MIN_VALUE":[0,1],"P10_VALUE":[1,1],"P25_VALUE":[24,1],"MEDIAN_VALUE":[28,1],"P75_VALUE":[35,24],"P90_VALUE":[58,37],"MAX_VALUE":[67,37]}}
json
http://data.doremus.org/expression/ee384566-5a57-39fa-8df9-61714c1b93f7 http://data.doremus.org/expression/2f0f2872-28ab-37d2-adc1-ba181e95e6d9 http://data.doremus.org/expression/a03d8372-31f1-33ab-a06a-b205286896af http://data.doremus.org/expression/3ce2599f-cdb4-372a-a893-d0be8340b96c http://data.doremus.org/expression/104be366-cff4-37eb-8e60-c97a9eb282f6 http://data.doremus.org/expression/f57375c1-f709-3aa1-a317-caddbfb3382c http://data.doremus.org/expression/3a87a017-a3bf-39f3-b2d4-fe3b067905fd http://data.doremus.org/expression/61beec62-b012-3e22-96e7-ed49a840bfe3 http://data.doremus.org/expression/df8ca40d-c7c8-3b0f-b35f-7502778d1260 http://data.doremus.org/expression/879c266f-21ea-32f8-a78b-bd23444bcc30 http://data.doremus.org/expression/c7ff2f06-93d8-3361-930f-44d92b87e7cd http://data.doremus.org/expression/82a40154-e37f-3bcc-b49c-d836674adda3 http://data.doremus.org/expression/8033d7a4-2a34-3bf0-a1be-8cd1fbb93101 http://data.doremus.org/expression/9ae97e62-33ca-3fb4-90fd-a9a657ebcf27
json
{"name":"pocketlab","short_name":"pocketlab","description":"<service-description>","icons":[{"src":"/images/logo-128x128.png","sizes":"128x128","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
json
{ "title": "Партнеры", "description": "Партнеры RESF представляют собой постоянные отношения, имеющие стратегическое значение для проекта Rocky Linux. Их поддержка, выражающаяся в предоставлении инженерного опыта, инфраструктурных ресурсов или других средств, имеет решающее значение для нашего успеха и долгосрочной стабильности.", "partners": [ { "name": "CIQ", "grade": "Партнер-основатель", "description": "Мы верим в то, что помогаем людям совершать великие дела. Именно поэтому CIQ является партнером-основателем RESF. Мы предоставляем коммерческую поддержку и услуги для Rocky Linux клиентам из научно-исследовательской, академической, правительственной, корпоративной, партнерской и всех других сфер." }, { "name": "NAVER Cloud", "grade": "Основной партнер", "description": "NAVER Cloud Platform - это южнокорейский облачный сервис, который начал свою работу в 2017 году под эгидой NAVER Cloud, дочерней компании NAVER. В 2021 году она предоставляет более 170 отдельных услуг и имеет различные сертификаты безопасности, включая CSA STAR GOLD, GDPR и другие. В настоящее время он также предоставляет облачные услуги в 10 точках по всему миру." }, { "name": "Mattermost", "grade": "Основной партнер", "description": "Mattermost - это решение для обмена сообщениями с открытым исходным кодом, созданное для организаций с самыми высокими требованиями к безопасности. Будучи убежденными сторонниками использования открытого исходного кода, компания Mattermost рада сотрудничать с RESF, чтобы помочь технологическому сообществу представить дистрибутив Linux корпоративного уровня." }, { "name": "Fosshost", "grade": "Основной партнер", "description": "Fosshost (UK CIC #13356530) предлагает бесплатный хостинг корпоративного уровня и управляемые услуги исключительно для сообщества FOSS. Наша миссия заключается в расширении возможностей и поддержке каждого проекта свободного программного обеспечения с открытым исходным кодом. Вместе мы идем дальше. Наша работа никогда не останавливается. Подайте заявку сегодня!" }, { "name": "Arm", "grade": "Основной партнер", "description": "Компания Arm стремится к тому, чтобы ее архитектура была первоклассным решением для Rocky Linux с первого дня работы. Мы сотрудничаем с RESF, предоставляя специализированные инженерные усилия в дополнение к командам разработчиков и тестировщиков Rocky Linux, тесно сотрудничая для тестирования, проверки и поддержки ARM сейчас и в будущем." }, { "name": "Fastly", "grade": "Основной партнер", "description": "Облачная платформа Fastly позволяет клиентам быстро, безопасно и надежно создавать превосходные цифровые услуги, обрабатывая, обслуживая и защищая приложения наших клиентов как можно ближе к конечным пользователям - непосредственно на границе сети Интернет." }, { "name": "OSU Open Source Labs", "grade": "Основной партнер", "description": "Лаборатория открытого кода Университета штата Орегон - это некоммерческая организация, работающая на благо развития технологий с открытым исходным кодом. OSL предлагает услуги хостинга мирового класса, профессиональную разработку программного обеспечения и обучение на месте для перспективных студентов, заинтересованных в управлении и программировании с открытым исходным кодом." }, { "name": "Supermicro", "grade": "Основной партнер", "description": "Будучи мировым лидером в области высокопроизводительных, высокоэффективных серверных технологий и инноваций, компания Supermicro рада сотрудничать с RESF и поставлять серверы и системы хранения данных для центров обработки данных, оптимизированные для Rocky Linux." }, { "name": "Equinix", "grade": "Основной партнер", "description": "Equinix - всемирная компания в области цифровой инфраструктуры. Лидеры цифровых технологий используют нашу надежную платформу для объединения и взаимосвязи основополагающей инфраструктуры, которая обеспечивает их успех." } ] }
json
#include "Common.h" #include "MissileWeaponEntity.h" MissileWeaponEntity::MissileWeaponEntity(const Vec2& startingPosition, weak_ptr<DamageableEntity> target) : SpecialWeaponEntity(startingPosition, target) { mTexture = ResourceCache::inst().getTexture("missile.png"); Vec2 textureSize((float)mTexture->getSize().x, (float)mTexture->getSize().y); mSprite.setTexture(*mTexture); mSprite.setOrigin(textureSize * 0.5f); mSprite.setRotation(180.0f); } MissileWeaponEntity::~MissileWeaponEntity() { } void MissileWeaponEntity::update(float dt) { float currentAngle = mSprite.getRotation(); // Rotate towards target using lerp float speed = 600.0f; shared_ptr<DamageableEntity> target = mTarget.lock(); if (target != shared_ptr<DamageableEntity>()) { Vec2 targetDirection = target->getSprite().getPosition() - mPosition; float targetAngle = atan2(targetDirection.y, targetDirection.x) * RAD_TO_DEG + 90.0f; if (targetAngle > currentAngle) { while (targetAngle - currentAngle > 180.0f) targetAngle -= 360.0f; } else { while (targetAngle - currentAngle < -180.0f) targetAngle += 360.0f; } float swayFactor = 1.0f + sin(random(0.0f, TWO_PI)); mSprite.setRotation(step(currentAngle, targetAngle, 500.0f * swayFactor * dt)); speed = 600.0f / (1.0f + abs(targetAngle - currentAngle) / 180.0f); } // Move Vec2 direction(sin(currentAngle * DEG_TO_RAD), -cos(currentAngle * DEG_TO_RAD)); mPosition += direction * speed * dt; } void MissileWeaponEntity::render(sf::RenderWindow& window) { mSprite.setPosition(mPosition); window.draw(mSprite); } void MissileWeaponEntity::onCollision(shared_ptr<Entity> other) { } sf::Sprite& MissileWeaponEntity::getSprite() { return mSprite; }
cpp
16 How much less one who is (A)abominable and corrupt,Man, who (B)drinks [a]unrighteousness like water! 12 “Though (A)evil is sweet in his mouthAnd he hides it under his tongue,13 Though he [a]desires it and will not forsake it,And holds it (B)to his palate, 7 What man is like Job,Who (A)drinks up mocking like water, Legacy Standard Bible Copyright ©2021 by The Lockman Foundation. All rights reserved. Managed in partnership with Three Sixteen Publishing Inc. LSBible.org For Permission to Quote Information visit https://www.LSBible.org.
english
Two fighter aircraft of IAF were involved in an accident when they were on routine operational flying training mission. Two Indian Air Force (IAF) fighter aircraft -- Sukhoi-30 and Mirage-2000 – crashed in the Pahadgarh area of Morena in Madhya Pradesh on Saturday. The two fighter jets were involved in an accident when they were on a routine training mission. An inquiry has been ordered to probe the cause. Morena superintendent of police Ashutosh Bagri, while confirming the crash, said that two jets took off from Gwalior on Saturday morning. While one of them had two pilots aboard, the other one had one on board. Two pilots were safely rescued while the third sustained fatal injuries. Defence Minister Rajnath Singh was also briefed by Chief of Air Staff Air Chief Marshal VR Chaudhari about the incident. 1. Until the central government took the decision of acquiring the 4. 5 generation Rafale fighters (from Dassault), Mirage 2000 was India’s front-line fighter. 2. Mirage 2000, manufactured by France’s Dassault Aviation, is one of the Indian Air Force (IAF)’s most versatile fighter jets, which is capable of dropping a range of bombs and missiles. 3. Mirage 2000 is equipped with a single, light and simple engine SNECMA M53 and can attain a maximum speed of Mach 2. 2 (2,336 kmph). They can be flown at a maximum height of 59000 ft. These jets are also fitted with Thales RDY 2 radar which can strike at targets with 100% accuracy. 4) Mirage 2000 aircraft were deployed in Kargil war in 1999 and Balakot airstrike against the terror camp of the Jaish-e-Mohammed (JeM) outfit in Pakistan in February 2019 for its capability to hit targets with "pinpoint" accuracy. 5) Twelve fully armed Mirage 2000 entered Pakistani airspace and dropped laser-guided bombs on the terror camps across the LOC.
english
import { Link as A } from "theme-ui" import Link from "next/link" import { useRouter } from "next/router" type Props = { children: React.ReactNode href: string } const NavLink = ({ children, href }: Props) => { const router = useRouter() return ( <Link href={href} passHref> <A sx={{ py: [2, 3], px: 3, fontSize: 3, fontWeight: 200, display: "inline-block", textDecoration: "none", borderBottom: "1px solid", borderColor: router.pathname === href && href !== "/" ? "primary" : "white", }} > {children} </A> </Link> ) } export default NavLink
typescript
<reponame>pawsen/pyvib #!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from numpy.linalg import norm from scipy.integrate import odeint from scipy.interpolate import interp1d from .nonlinear_elements import NLS from .statespace import NonlinearStateSpace, StateSpaceIdent # http://www.brendangregg.com/books.html class NLSS(NonlinearStateSpace, StateSpaceIdent): """Nonlinear Time Invariant system in state-space form. x(t+1) = A x(t) + B u(t) + E g(x(t),y(t),u(t)) y(t) = C x(t) + D u(t) + F h(x(t),u(t)) `NLSS` systems inherit additional functionality from the :class:`statespace.NonlinearStateSpace` and :class:`statespace.StateSpaceIdent` classes. Examples -------- """ def __init__(self, *system, **kwargs): if len(system) == 1: # and isinstance(system[0], StateSpace): sys = system kwargs['dt'] = sys[0].dt else: # given as A,B,C,D sys = system if kwargs.get('dt') is None: kwargs['dt'] = 1 # unit sampling # TODO: if dt is not given, we should initialize a ct model # if kwargs.get('dt') is None: # kwargs['dt'] = None # print(f'NOTE: {self.__class__.__name__} model initialized as cont. time model. ' # 'If you want disc. model, be sure to specify dt when initializing') super().__init__(*sys, **kwargs) self.nlx = NLS() self.nly = NLS() def add_nl(self, nlx=None, nly=None): """Add nonlinear elements""" # active elements can only be set when the system size is known. # for fnsi this happens when we do subspace ID # prevent wrapping nls in nls. if isinstance(nlx, NLS): nlx = nlx.nls self.nlx = NLS(nlx) if isinstance(nly, NLS): nly = nly.nls self.nly = NLS(nly) # only set NLs if system is defined if self.n is not None: self._set_active() def _set_active(self): self.nlx.set_active(self.n, self.m, self.p, self.n) self.nly.set_active(self.n, self.m, self.p, self.p) if self.E.size == 0: self.E = np.zeros((self.n, self.nlx.n_nl)) if self.F.size == 0 and self.nly.n_nl: self.F = np.zeros((self.p, self.nly.n_nl)) def set_signal(self, signal): self.signal = signal self.dt = 1/signal.fs if self.p is None: self.p, self.m = signal.p, signal.m def output(self, u, t=None, x0=None): """Simulate output of a discrete-time nonlinear system.""" return dnlsim(self, u, t=t, x0=x0) def jacobian(self, x0, weight=False): return jacobian(x0, self, weight=weight) def nlsim2(system, u, t=None, x0=None, **kwargs): """Simulate output of a continuous-time nonlinear system by using the ODE solver `scipy.integrate.odeint`. Calculate the output and the states of a nonlinear state-space model. ẋ(t) = A x(t) + B u(t) + E g(x(t),y(t),u(t)) y(t) = C x(t) + D u(t) + F h(x(t),u(t)) Parameters ---------- system : cont. time instance of `nlss` u : ndarray(ns) or ndarray(ns,p) An input array describing the input at each time `t` (interpolation is assumed between given times). If there are multiple inputs, then each column of the rank-2 array represents an input. t : ndarray, optional The time steps at which the input is defined and at which the output is desired. The default is 101 evenly spaced points on the interval [0,10]. x0: ndarray(n), optional The initial conditions on the state vector (zero by default). kwargs : dict Additional keyword arguments are passed on to the function `odeint`. See the notes below for more details. Returns ------- tout : ndarray(ns) Time values for the output, as a 1-D array. yout : ndarray(ns,p) System response xout : ndarray(ns,n) Time-evolution of the state-vector. Notes ----- If `u` is a array it will be interpolated as u = scipy.interpolate.interp1d(t, u, kind='linear', axis=0, bounds_error=False) Be sure this is OK or give `u` as a callable function. This function uses `scipy.integrate.odeint` to solve the system's differential equations. Additional keyword arguments given to `dnlsim2` are passed on to `odeint`. See the documentation for `scipy.integrate.odeint` for the full list of arguments. """ if x0 is None: x0 = np.zeros(system.B.shape[0], system.A.dtype) if t is None: t = np.linspace(0, 10, 101) t = np.atleast_1d(t) if len(t.shape) != 1: raise ValueError("t must be a rank-1 array.") if not callable(u): if len(u.shape) == 1: u = u[:, np.newaxis] su = u.shape assert su[0] == len(t), \ ("u must have the same number of rows as elements in t.") assert su[1] == system.inputs, \ (f"The number of inputs in u ({su[1]}) is not the same as system " "inputs ({system.inputs})") # Create a callable that uses linear interpolation to calculate the # input at any time. ufunc = interp1d(t, u, kind='linear', axis=0, bounds_error=False) else: ufunc = u def fprime(x, t, sys, ufunc): """The vector field of the nonlinear system.""" ut = ufunc(t) hvec = system.nly.fnl(x, 0, ut) y = np.dot(sys.C, x) + np.squeeze(sys.D @ ut.T) + np.dot(sys.F, hvec) gvec = sys.nlx.fnl(x, y, ut) return sys.A @ x + np.squeeze(sys.B @ ut.T) + sys.E @ gvec xout = odeint(fprime, x0, t, args=(system, ufunc), **kwargs) # fnl returns empty array in case of no NL; to broadcast we transpose ut = ufunc(t) hvec = system.nly.fnl(xout, 0, ut) yout = (system.C @ xout.T + system.D @ ut.T).T + system.F @ hvec return t, yout, xout def dnlsim(system, u, t=None, x0=None): """Simulate output of a discrete-time nonlinear system. Calculate the output and the states of a nonlinear state-space model. x(t+1) = A x(t) + B u(t) + E g(x(t),y(t),u(t)) y(t) = C x(t) + D u(t) + F h(x(t),u(t)) Parameters ---------- system : discrete time instance of `nlss` u : ndarray(ns) or ndarray(ns,p) An input array describing the input at each time `t` (interpolation is assumed between given times). If there are multiple inputs, then each column of the rank-2 array represents an input. t : ndarray, optional The time steps at which the input is defined. If `t` is given, it must be the same length as `u`, and the final value in `t` determines the number of steps returned in the output using system.dt x0: ndarray(n), optional The initial conditions on the state vector (zero by default). Returns ------- tout : ndarray(ns) Time values for the output, as a 1-D array. yout : ndarray(ns,p) System response xout : ndarray(ns,n) Time-evolution of the state-vector. """ # if not isinstance(system, NLSS): # raise ValueError(f'System must be a NLSS object {type(system)}') u = np.atleast_1d(u) if u.ndim == 1: u = np.atleast_2d(u).T if t is None: out_samples = len(u) stoptime = (out_samples - 1) * system.dt else: stoptime = t[-1] out_samples = int(np.floor(stoptime / system.dt)) + 1 # Pre-build output arrays xout = np.empty((out_samples, system.A.shape[0])) yout = np.empty((out_samples, system.C.shape[0])) tout = np.linspace(0.0, stoptime, num=out_samples) # Check initial condition if x0 is None: xout[0, :] = np.zeros((system.A.shape[1],)) else: xout[0, :] = np.asarray(x0) # Pre-interpolate inputs into the desired time steps if t is None: u_dt = u else: if len(u.shape) == 1: u = u[:, np.newaxis] u_dt_interp = interp1d(t, u.transpose(), copy=False, bounds_error=True) u_dt = u_dt_interp(tout).transpose() # Simulate the system for i in range(0, out_samples - 1): # Output equation y(t) = C*x(t) + D*u(t) + F*eta(x,u) # TODO hvec: must not depend on y! hvec = system.nly.fnl(xout[i], 0, u_dt[i]) yout[i, :] = (np.dot(system.C, xout[i, :]) + np.dot(system.D, u_dt[i, :]) + np.dot(system.F, hvec)) # State equation x(t+1) = A*x(t) + B*u(t) + E*zeta(x,[y,ẏ],u) gvec = system.nlx.fnl(xout[i, :], yout[i, :], u_dt[i, :]) xout[i+1, :] = (np.dot(system.A, xout[i, :]) + np.dot(system.B, u_dt[i, :]) + np.dot(system.E, gvec)) # Last point hvec = system.nly.fnl(xout[-1, :], 0, u_dt[-1, :]) yout[-1, :] = (np.dot(system.C, xout[-1, :]) + np.dot(system.D, u_dt[-1, :]) + np.dot(system.F, hvec)) return tout, yout, xout def jacobian(x0, system, weight=False): """Compute the Jacobians of a steady state nonlinear state-space model x(t+1) = A x(t) + B u(t) + E h(x(t),u(t)) + G i(y(t),ẏ(t)) y(t) = C x(t) + D u(t) + F j(x(t),u(t)) i.e. the partial derivatives of the modeled output w.r.t. the active elements in the A, B, E, F, D, and C matrices, fx: JA = ∂y/∂Aᵢⱼ Parameters ---------- x0: ndarray(npar) flattened array of state space matrices system: instance of `nlss` NLSS system weight: bool, optional Weight the jacobian. Default is False Returns ------- jac: ndarray(p*ns, npar) derivative of output equation wrt. each active element in ss matrices """ n, m, p = system.n, system.m, system.p try: R, npp = system.signal.R, system.signal.npp except: R, npp = system.R, system.npp # total number of points ns = R*npp # TODO without_T2 = system.without_T2 # Collect states and outputs with prepended transient sample y_trans = system.y_mod[system.idx_trans] x_trans = system.x_mod[system.idx_trans] try: u_trans = system.signal.um[system.idx_trans] except: u_trans = system.um[system.idx_trans] nts = u_trans.shape[0] # nts: number of total samples(including transient) A, B, C, D, Efull, F = system.extract(x0) # split E in x- and y dependent part G = Efull[:, system.nlx.idy] E = Efull[:, system.nlx.idx] fnl = system.nlx.fnl(x_trans, y_trans, u_trans) # (n_nx, nts) hvec = fnl[system.nlx.idx].T # (nts, nlx.n_nx) ivec = fnl[system.nlx.idy].T # (nts, nlx.n_ny) jvec = system.nly.fnl(x_trans, y_trans, u_trans).T # (nts, n_ny) # derivatives of nonlinear functions wrt x or y # (n_nx,n,ns) dhdx = system.nlx.dfdx(x_trans, y_trans, u_trans) didy = system.nlx.dfdy(x_trans, y_trans, u_trans) djdx = system.nly.dfdx(x_trans, y_trans, u_trans) if E.size == 0: A_Edhdx = np.zeros(shape=(*A.shape, nts)) else: A_Edhdx = np.einsum('ij,jkl->ikl', E, dhdx) # (n,n,nts) if G.size == 0: Gdidy = np.zeros(shape=(*C.shape[::-1], nts)) else: Gdidy = np.einsum('ij,jkl->ikl', G, didy) # (n,p,nts) if F.size == 0: C_Fdjdx = np.zeros(shape=(*C.shape, nts)) else: C_Fdjdx = np.einsum('ij,jkl->ikl', F, djdx) # (p,n,nts) A_Edhdx += A[..., None] C_Fdjdx += C[..., None] # calculate output jacobians wrt state space matrices in output eq JC = np.kron(np.eye(p), system.x_mod) # (p*ns,p*n) try: JD = np.kron(np.eye(p), system.signal.um) # (p*ns, p*m) except: JD = np.kron(np.eye(p), system.um) # (p*ns, p*m) if system.nly.xactive.size: JF = np.kron(np.eye(p), jvec) # Jacobian wrt all elements in F # all active elements in F. (p*nts,nactiveF) JF = JF[:, system.nly.xactive] JF = JF[system.idx_remtrans] # (p*ns,nactiveF) else: JF = np.array([]).reshape(p*ns, 0) # calculate Jacobian by filtering an alternative state-space model # reshape so first row of JA is the derivative wrt all elements in A for # first time step, first output, then second output, then next time,... # JA: (p,n*n,nts)->(nts,p,n*n)->(nts*p,n*n) JA = element_jacobian(x_trans, A_Edhdx, Gdidy, C_Fdjdx, np.arange(n**2)) JA = JA.transpose((2, 0, 1)).reshape((nts*p, n**2), order='F') JA = JA[system.idx_remtrans] # (p*ns,n**2) JB = element_jacobian(u_trans, A_Edhdx, Gdidy, C_Fdjdx, np.arange(n*m)) JB = JB.transpose((2, 0, 1)).reshape((nts*p, n*m), order='F') JB = JB[system.idx_remtrans] # (p*ns,n*m) if system.nlx.xactive.size: JE = element_jacobian(hvec, A_Edhdx, Gdidy, C_Fdjdx, system.nlx.xactive) JE = JE.transpose((2, 0, 1)).reshape( (nts*p, len(system.nlx.xactive)), order='F') JE = JE[system.idx_remtrans] # (p*ns,nactiveE) else: JE = np.array([]).reshape(p*ns, 0) if system.nlx.yactive.size: JG = element_jacobian(ivec, A_Edhdx, Gdidy, C_Fdjdx, system.nlx.yactive) JG = JG.transpose((2, 0, 1)).reshape( (nts*p, len(system.nlx.yactive)), order='F') JG = JG[system.idx_remtrans] # (p*ns,nactiveE) else: JG = np.array([]).reshape(p*ns, 0) # combine JE/JG and permute, so the columns correspond to nlx.active # this is important when parameters are flattened to θ and back again. # Note this returns a copy(as is always the case with fancy indexing) permution = np.concatenate((system.nlx.jac_x, system.nlx.jac_y)) idx = np.argsort(permution) # get the indices that would sort the array. jac = np.hstack((JA, JB, JC, JD, np.hstack((JE, JG)) [:, idx], JF)) # TODO [without_T2] npar = jac.shape[1] return jac def element_jacobian(samples, A_Edhdx, Gdidy, C_Fdjdx, active): """Compute Jacobian of the output y wrt. single state space matrix The Jacobian is calculated by filtering an alternative state-space model ∂x∂Aᵢⱼ(t+1) = Iᵢⱼx(t) + (A + E*∂h∂x) ∂x∂Aᵢⱼ(t) + G*∂i∂y*∂y∂Aᵢⱼ(t) ∂y∂Aᵢⱼ(t) = (C + F)*∂x∂Aᵢⱼ(t) ∂x∂Bᵢⱼ(t+1) = Iᵢⱼu(t) + (A + E*∂h∂x) ∂x∂Bᵢⱼ(t) + G ∂i∂y*∂y∂Bᵢⱼ(t) ∂y∂Bᵢⱼ(t) = (C + F)*∂x∂Bᵢⱼ(t) ∂x∂Eᵢⱼ(t+1) = Iᵢⱼh(t) + (A + E*∂h∂x) ∂x∂Eᵢⱼ(t) + G ∂i∂y*∂y∂Eᵢⱼ(t) ∂y∂Eᵢⱼ(t) = (C + F)*∂x∂Eᵢⱼ(t) ∂x∂Gᵢⱼ(t+1) = Iᵢⱼi(t) + (A + E*∂h∂x) ∂x∂Gᵢⱼ(t) + G ∂i∂y*∂y∂Gᵢⱼ(t) ∂y∂Gᵢⱼ(t) = (C + F)*∂x∂Gᵢⱼ(t) We use the notation: JA = ∂y∂Aᵢⱼ Parameters ---------- samples : ndarray(nt,npar) x, u, h or i corresponding to JA, JB, JE or JG A_Edhdx : ndarray(n,n,nts) The result of ``A + E*∂h∂x`` Gdidy : ndarray(n,p,nts) The result of ``G*∂i∂y`` C_Fdwdx : ndarray(p,n,nts) The result of ``C + F*∂j∂x`` active : ndarray(nactive) Array with index of the active elements. For JA: np.arange(n**2), JB: n*m, JE: xactive, JG: yactive Returns ------- out : ndarray (p,nactive,nt) Jacobian; JA, JB, JE or JG depending on the samples given as input See fJNL """ # Number of outputs and number of states n, n, nt = A_Edhdx.shape p, n, nt = C_Fdjdx.shape # number of inputs and number of samples in alternative state-space model nt, npar = samples.shape nactive = len(active) # Number of active parameters in A, B, or E out = np.zeros((p, nactive, nt)) for k, activ in enumerate(active): # Which column in A, B, or E matrix j = np.mod(activ, npar) # Which row in A, B, or E matrix i = (activ-j)//npar # partial derivative of x(0) wrt. A(i,j), B(i,j), or E(i,j) J = np.zeros(n) for t in range(0, nt-1): # Calculate output alternative state-space model at time t out[:, k, t] = C_Fdjdx[:, :, t] @ J J = A_Edhdx[:, :, t] @ J + Gdidy[:, :, t] @ out[:, k, t] J[i] += samples[t, j] # last time point out[:, k, -1] = C_Fdjdx[:, :, t] @ J return out # from pyvib.nonlinear_elements import Polynomial, NLS, Polynomial_x, NLS # test linear system #m = 1 #k = 2 #d = 3 #fex = 1 #dt = 0.1 # # cont. time formulation #A = np.array([[0, 1],[-k/m, -d/m]]) #B = np.array([[0], [fex/m]]) #C = np.array([[1, 0]]) #D = np.array([[0]]) #sys = signal.StateSpace(A, B, C, D).to_discrete(dt) # # add polynomial in state eq #exponent = [3] # w = [1] # need to be same length as number of ouputs #poly1 = Polynomial(exponent,w) #poly2 = Polynomial_x(exponent,w=[0,1]) #poly3 = Polynomial_x(exponent=[2],w=[0,1]) #poly4 = Polynomial(exponent=[5],w=[-1]) #poly5 = Polynomial(exponent=[2],w=[1]) # # nl_x = NLS([poly1, poly2, poly3, poly4,poly5]) # nls in state eq # nl_y = NLS() # nls in output eq # #nlsys = NLSS(nl_x,nl_y,sys) # nlsys.output(u=[1,2,3]) # # #R, npp = 1,10 #x = np.arange(20).reshape(10,2) #y = np.arange(10).reshape(10,1) #u = np.ones(10).reshape(10,1) #nlsys.x_mod = x #nlsys.y_mod = y #nlsys.um = u #nlsys.R, nlsys.npp = R,npp #nlsys.idx_trans = np.arange(R*npp) #nlsys.idx_remtrans = np.s_[:] #x0 = nlsys.flatten() #jacobian(x0, nlsys) # direction = # #exponents = [2] #exponents = np.array(exponents) #w = [1,0,0] #w = np.atleast_2d(w) #y = np.arange(3*10).reshape((3,10)) #ynl = np.inner(w, y.T) #f = np.prod(ynl.T**exponents, axis=1) # # print(dfdy) # #exponents = [2,2] #exponents = np.array(exponents) #w = np.array([[1,0,0],[0,0,1]]) #w = np.atleast_2d(w) #y = np.arange(3*10).reshape((3,10)) #ynl = np.inner(w, y.T) #f = np.prod(ynl.T**exponents, axis=1) #dfdy = exponents[:,None] * ynl**(exponents-1) # # print(dfdy*w.T) #x = np.arange(3*100).reshape((3,100))/0.01
python
With Pokemon GO's Adventure Week event just hours away, many players are excited about the new types of creatures that will soon appear on live servers. While the return of Fossil Pokemon is always the highlight of this yearly event, this iteration is bringing in Mega Tyranitar, as well as the shiny variants of two Fossil Pokemon: Amaura and Tyrunt. Although many shiny hunters will just be happy to have these creatures in their collection, some players may be wondering how they can use their new Shiny Pokemon to their fullest potential in the game's competitive Battle League or raids. However, using any specific species of creature takes a certain level of game knowledge. Here's what you need to know to utilize Aurorus in the game. What is Aurorus' best PvP moveset in Pokemon GO? Aurorus has a surprisingly deep movepool, which makes it a great mixed-bag attacker for those looking to invest resources in acquiring its secondary charged attack slot. Since Aurorus is an Ice-type, any attacks that match this element pack a serious punch. Aurorus sees the most success in Pokemon GO's PvP scene running a moveset of Frost Breath, Thunderbolt, and Weather Ball with an Ice typing. However, you are truly free to run whatever moveset you like since each of Aurorus' charged attacks is bound to have some utility. What is Aurorus' best moveset for PvE in Pokemon GO? Aurorus gets more options for viable movesets in the raid and NPC battles of Pokemon GO. With the AI in trainer battles being very easy to trick, Aurorus is not constricted to a strict moveset. As such, you have a lot more freedom when it comes to assembling an arsenal capable of dealing massive damage. A great moveset would be one that capitalizes on Aurorus' great offensive type combination. Frost Breath or Powder Snow for a Fast Attack, paired with an Ice-type Weather Ball or Meteor Beam Charged Attack, is a great option. Of course, this moveset differs drastically depending on the Raid Boss you want to take your Aurorus into or what type of Rocket Grunt you'll face. Is Aurorus good in Pokemon GO PvP? The cold truth about this Ice-type dinosaur is that it sits in a middle grade in terms of its viability in every tier of the Battle League. While some trainers may get lucky and win a couple of matches with it, there are much better Ice and Rock-type creatures that you can use. However, unlike other creatures that fall off in relevancy as the tiers of play increase, Aurorus maintains its mid status over all tiers. In a circumstance where you have no other Ice-type attackers in your collection, Aurorus is a decent option. However, aside from this one scenario, the Pokemon simply falls flat.
english
// Copyright 2008-2016 <NAME> (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ //! \addtogroup wall_clock //! @{ //! Class for measuring time intervals class wall_clock { public: inline wall_clock(); inline ~wall_clock(); inline void tic(); //!< start the timer inline arma_warn_unused double toc(); //!< return the number of seconds since the last call to tic() private: bool valid = false; std::chrono::steady_clock::time_point chrono_time1; }; //! @}
cpp
<reponame>VictoriaPlum-com/deviance<filename>src/helpers.js function getEnvironment(processArgs = process.argv) { const envFlags = ['-e', '--env']; const envIndex = processArgs.findIndex(arg => envFlags.includes(arg)) + 1; return (envIndex > 0 && envIndex < processArgs.length) ? processArgs[envIndex] : 'default'; } function hasProperty(object, property) { return Object.prototype.hasOwnProperty.call(object, property); } function hasValidThreshold(threshold) { return !(typeof threshold !== 'number' || threshold < 0 || threshold > 1); } function buildCaptureAreas(element, viewport) { const numXRequired = Math.ceil(element.width / viewport.width); const numYRequired = Math.ceil(element.height / viewport.height); const xCapture = viewport.left; const yCapture = viewport.top; const captureAreas = []; for (let x = 0; x < numXRequired; x += 1) { for (let y = 0; y < numYRequired; y += 1) { captureAreas.push({ left: xCapture + (viewport.width * x), top: yCapture + (viewport.height * y), behavior: 'instant', }); } } return captureAreas; } function scrollAndPosition(scrollToOptions) { window.scrollTo(JSON.parse(scrollToOptions)); return { left: window.pageXOffset, top: window.pageYOffset, }; } function elementAndViewportData(selector) { const htmlElement = document.querySelector(selector); let results = {}; if (htmlElement) { const isBody = htmlElement === document.body; let bounding = { left: 0, top: 0 }; if (!isBody) { bounding = htmlElement.getBoundingClientRect(); bounding.left += window.pageXOffset; bounding.top += window.pageYOffset; } window.scrollTo({ left: bounding.left, top: bounding.top, behavior: 'instant', }); bounding = htmlElement.getBoundingClientRect(); const viewport = { left: Math.round(window.pageXOffset), top: Math.round(window.pageYOffset), width: window.innerWidth, height: window.innerHeight, }; const body = { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight, }; const element = { top: isBody ? 0 : Math.round(bounding.top + window.pageYOffset), left: isBody ? 0 : Math.round(bounding.left + window.pageXOffset), width: isBody ? body.width : Math.round(bounding.width), height: isBody ? body.height : Math.round(bounding.height), }; results = { devicePixelRatio: window.devicePixelRatio, element, viewport, body, }; } return results; } function handleElement(element) { try { return typeof element === 'string' ? element : element.selector; } catch (e) { throw new Error('Invalid argument provided for either selector or filename'); } } export { hasProperty, getEnvironment, hasValidThreshold, buildCaptureAreas, scrollAndPosition, elementAndViewportData, handleElement, };
javascript
<mat-card> <mat-card-title>Simple lists</mat-card-title> <mat-card-content> <mat-list> <mat-list-item> Pepper </mat-list-item> <mat-list-item> Salt </mat-list-item> <mat-list-item> Paprika </mat-list-item> </mat-list> </mat-card-content> </mat-card> <mat-card> <mat-card-title>Navigation lists</mat-card-title> <mat-card-content> <mat-nav-list> <a mat-list-item *ngFor="let link of links"> {{ link }} </a> </mat-nav-list> <mat-nav-list> <mat-list-item *ngFor="let link of links"> <a matLine>{{ link }}</a> <button mat-icon-button> <mat-icon>info</mat-icon> </button> </mat-list-item> </mat-nav-list> </mat-card-content> </mat-card> <mat-card> <mat-card-title>Selection lists</mat-card-title> <mat-selection-list #shoes> <mat-list-option *ngFor="let shoe of typesOfShoes"> {{shoe}} </mat-list-option> </mat-selection-list> <p> Options selected: {{shoes.selectedOptions.selected.length}} </p> </mat-card> <mat-card> <mat-card-title>Multi-line lists</mat-card-title> <mat-list> <mat-list-item *ngFor="let message of messages"> <h3 matLine> {{message.from}} </h3> <p matLine> <span> {{message.subject}} </span> <span class="demo-2"> -- {{message.content}} </span> </p> </mat-list-item> </mat-list> <mat-list> <mat-list-item *ngFor="let message of messages"> <h3 matLine> {{message.from}} </h3> <p matLine> {{message.subject}} </p> <p matLine class="demo-2"> {{message.content}} </p> </mat-list-item> </mat-list> </mat-card> <mat-card> <mat-card-title> Lists with icons</mat-card-title> <mat-card-content> <mat-list> <mat-list-item *ngFor="let message of messages"> <mat-icon matListIcon>folder</mat-icon> <h3 matLine> {{message.from}} </h3> <p matLine> <span> {{message.subject}} </span> <span class="demo-2"> -- {{message.content}} </span> </p> </mat-list-item> </mat-list> </mat-card-content> </mat-card> <mat-card> <mat-card-title> Lists with avatars </mat-card-title> <mat-card-content> <mat-list> <mat-list-item *ngFor="let message of messages"> <img matListAvatar src="assets/images/avatars/noavatar.png" alt="assets/images/avatars/noavatar.png"> <h3 matLine> {{message.from}} </h3> <p matLine> <span> {{message.subject}} </span> <span class="demo-2"> -- {{message.content}} </span> </p> </mat-list-item> </mat-list> </mat-card-content> </mat-card> <mat-card> <mat-card-title> Dense lists </mat-card-title> <mat-card-content> <mat-list dense> <mat-list-item> Pepper </mat-list-item> <mat-list-item> Salt </mat-list-item> <mat-list-item> Paprika </mat-list-item> </mat-list> </mat-card-content> </mat-card> <mat-card> <mat-card-title> Lists with multiple sections </mat-card-title> <mat-card-content> <mat-list> <h3 matSubheader>Folders</h3> <mat-list-item *ngFor="let folder of folders"> <mat-icon matListIcon>folder</mat-icon> <h4 matLine>{{folder.name}}</h4> <p matLine class="demo-2"> {{folder.updated}} </p> </mat-list-item> <mat-divider></mat-divider> <h3 matSubheader>Notes</h3> <mat-list-item *ngFor="let note of notes"> <mat-icon matListIcon>note</mat-icon> <h4 matLine>{{note.name}}</h4> <p matLine class="demo-2"> {{note.updated}} </p> </mat-list-item> </mat-list> </mat-card-content> </mat-card>
html
from decimal import Decimal from unittest import TestCase import copy import unittest import os import sys from importlib import reload from mock import Mock, call from mockextras import stub sys.path = [os.path.abspath(os.path.join('..', os.pardir))] + sys.path from digesters.charges.charge_card_digester import ChargeCardDigester PIMORONI_CHARGE = { 1460185000: { "amt": Decimal(4.00), "type": "Charge", "curr": "GBP", "vendor": "Pimoroni", "card": "Amex 1234" } } PIMORONI_CHARGE_WITH_WHEN_STR = copy.deepcopy(PIMORONI_CHARGE) PIMORONI_CHARGE_WITH_WHEN_STR[1460185000]['when_str'] = 'Apr---09 02:56' PIHUT_CHARGE = { 1460184000: { "amt": Decimal(5.00), "type": "Charge", "curr": "USD", "vendor": "PiHut", "card": "Amex 1234" } } PIHUT_CHARGE_WITH_WHEN_STR = copy.deepcopy(PIHUT_CHARGE) PIHUT_CHARGE_WITH_WHEN_STR[1460184000]['when_str'] = 'Apr---09 02:40' PIHUT_AND_PIMORONI_CHARGE_WITH_WHEN_STR = copy.deepcopy(PIMORONI_CHARGE_WITH_WHEN_STR) PIHUT_AND_PIMORONI_CHARGE_WITH_WHEN_STR[1460184000] = copy.deepcopy(PIHUT_CHARGE_WITH_WHEN_STR[1460184000]) MAIL_HDR = """From: "Charge Cards" <<EMAIL>> Date: Sat, 09 Apr 2016 06:56:40 -0000 Content-Transfer-Encoding: 8bit Content-Type: multipart/alternative; boundary="---NOTIFICATION_BOUNDARY-5678" MIME-Version: 1.0 This is a multi-part message in MIME format. -----NOTIFICATION_BOUNDARY-5678 Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 8bit """ class TestChargeCardDigester(TestCase): def __init__(self, methodName='runTest'): super(TestChargeCardDigester, self).__init__(methodName) reload(sys) # sys.setdefaultencoding('utf8') # print "P1 " + str(PIMORONI_CHARGE) # print "P2 " + str(PIMORONI_CHARGE_WITH_WHEN_STR) def test_no_previous_email_yet_one_old_and_one_new_charge_yields_only_the_newer_charge_in_the_email(self): store_writer = Mock() store_writer.get_from_binary.side_effect = stub( (call('charges'), { "charges": PIHUT_CHARGE, "most_recent_seen": 1460184000 }), (call('most-recently-seen'), 1460184000) ) store_writer.store_as_binary.side_effect = stub( (call('charges', { 'charges': PIMORONI_CHARGE_WITH_WHEN_STR, 'most_recent_seen': 1460184000 }), True), (call('most-recently-seen', 1460184000), True) ) digester = ChargeCardDigester(store_writer) ## What we are testing expected_payload = """<table> <tr style="background-color: #acf;"> <th>Type</th><th>Vendor</th><th>When</th><th>Curr</th><th>Amt</th><th>Card</th> </tr> <tr style=""> <td>Charge</td> <td>Pimoroni</td> <td>Apr&nbsp;09 02:56</td> <td>GBP</td> <td style="text-align: right;"><b>4</b></td> <td>Amex 1234</td> </tr> </table>""" expected_message = ("Subject: Spending Digest\n" + MAIL_HDR + expected_payload + "\n\n-----NOTIFICATION_BOUNDARY-5678") digest_inbox_proxy = Mock() digest_inbox_proxy.delete_previous_message.side_effect = stub((call(), True)) digest_inbox_proxy.append.side_effect = stub((call(expected_message), True)) digester.new_charge_summary = PIMORONI_CHARGE digester.notification_boundary_rand = "5678" digester.rewrite_digest_emails(digest_inbox_proxy, False, False, "<EMAIL>") self.assertEqual(digest_inbox_proxy.mock_calls, [call.append(expected_message)]) calls = store_writer.mock_calls self.assertEqual(calls, [ call.get_from_binary('charges'), call.store_as_binary('charges', { 'charges': PIMORONI_CHARGE_WITH_WHEN_STR, 'most_recent_seen': 1460184000 }) ]) def test_with_a_previous_email_and_one_old_and_one_new_charge_yields_both_charges_in_the_email(self): store_writer = Mock() store_writer.get_from_binary.side_effect = stub( (call('charges'), { "charges": PIHUT_CHARGE, "most_recent_seen": 1460184000 }), (call('most-recently-seen'), 1460184000) ) store_writer.store_as_binary.side_effect = stub( (call('charges', { 'charges': PIHUT_AND_PIMORONI_CHARGE_WITH_WHEN_STR, 'most_recent_seen': 1460184000 }), True), (call('most-recently-seen', 1460184000), True) ) digester = ChargeCardDigester(store_writer) ## What we are testing expected_payload = """<table> <tr style="background-color: #acf;"> <th>Type</th><th>Vendor</th><th>When</th><th>Curr</th><th>Amt</th><th>Card</th> </tr> <tr style=""> <td>Charge</td> <td>Pimoroni</td> <td>Apr&nbsp;09 02:56</td> <td>GBP</td> <td style="text-align: right;"><b>4</b></td> <td>Amex 1234</td> </tr> <tr> <td colspan="6" style="color:red; text-align: center; border-bottom: 1pt solid red; border-top: 1pt solid red;"> ^ New Charges Since You Last checked ^ </td> </tr> <tr style="background-color: #def;"> <td>Charge</td> <td>PiHut</td> <td>Apr&nbsp;09 02:40</td> <td>USD</td> <td style="text-align: right;"><b>5</b></td> <td>Amex 1234</td> </tr> </table>""" expected_message = ("Subject: Spending Digest\n" + MAIL_HDR + expected_payload + "\n\n-----NOTIFICATION_BOUNDARY-5678") digest_inbox_proxy = Mock() digest_inbox_proxy.delete_previous_message.side_effect = stub((call(), True)) digest_inbox_proxy.append.side_effect = stub((call(expected_message), True)) digester.new_charge_summary = PIMORONI_CHARGE digester.notification_boundary_rand = "5678" digester.rewrite_digest_emails(digest_inbox_proxy, True, False, "<EMAIL>") self.assertEqual(digest_inbox_proxy.mock_calls, [call.delete_previous_message(), call.append(expected_message)]) calls = store_writer.mock_calls self.assertEqual(calls, [ call.get_from_binary('charges'), call.store_as_binary('charges', { 'charges': PIHUT_AND_PIMORONI_CHARGE_WITH_WHEN_STR, 'most_recent_seen': 1460184000 }) ]) if __name__ == '__main__': unittest.main()
python
[ { "Id": "1099968", "ThreadId": "459424", "Html": "Hi.....My Self I Am Karthikeyan, I Am New To PHPExcel, I Have One Problem In My Project, I Want To Get The Excel File Detail According To The Username,Can u Help me.... <br />\n", "PostedDate": "2013-09-27T00:15:02.507-07:00", "UserRole": null, "MarkedAsAnswerDate": null }, { "Id": "1100067", "ThreadId": "459424", "Html": "What details do you want to get? If it comes to the properties in the workbook, $objExcel-&gt;GetProperties()) returns a PHPExcel_DocumentProperties object that puts at disposal methods such as getCreator(), getLastModifiedBy(), etc.<br />\n", "PostedDate": "2013-09-27T04:40:07.627-07:00", "UserRole": null, "MarkedAsAnswerDate": null }, { "Id": "1101239", "ThreadId": "459424", "Html": "Hi...Thanks For Your Reply To My Post, See My Problem Is In My Project I Have a 10 User. For Each User They Have a Separate Excel File,According To The Username or User Id I Want Display The Excel Sheet,Can You Give Any Examples For My Project, It Will Useful For me....<br />\n", "PostedDate": "2013-10-01T02:20:48.547-07:00", "UserRole": null, "MarkedAsAnswerDate": null }, { "Id": "1102562", "ThreadId": "459424", "Html": "An example from the documentation, showing a reading of data from an Excel file and the display in a table.<br />\n<pre><code>&lt;?php\n/** Include PHPExcel */\nrequire_once '../Classes/PHPExcel.php'; //change path if needed\n\n$objReader = PHPExcel_IOFactory::createReader('Excel2007');\n$objReader-&gt;setReadDataOnly(true);\n\n$objPHPExcel = $objReader-&gt;load(&quot;test.xlsx&quot;);\n$objWorksheet = $objPHPExcel-&gt;getActiveSheet();\n\n$highestRow = $objWorksheet-&gt;getHighestRow(); // e.g. 10\n$highestColumn = $objWorksheet-&gt;getHighestColumn(); // e.g 'F'\n\n$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5\n\necho '&lt;table&gt;' . &quot;\\n&quot;;\nfor ($row = 1; $row &lt;= $highestRow; ++$row) {\n echo '&lt;tr&gt;' . &quot;\\n&quot;;\n\n for ($col = 0; $col &lt;= $highestColumnIndex; ++$col) {\n echo '&lt;td&gt;' . $objWorksheet-&gt;getCellByColumnAndRow($col, $row)-&gt;getValue() . '&lt;/td&gt;' . &quot;\\n&quot;;\n }\n\n echo '&lt;/tr&gt;' . &quot;\\n&quot;;\n}\necho '&lt;/table&gt;' . &quot;\\n&quot;;\n?&gt;\n</code></pre>\n\n", "PostedDate": "2013-10-01T23:20:07.373-07:00", "UserRole": null, "MarkedAsAnswerDate": null } ]
json
<filename>20211SVAC/G38/interfaz/styles/styleIde.css textarea#txtEntradaXML{ background: url(http://i.imgur.com/2cOaJ.png); background-attachment: local; background-repeat: no-repeat; padding-left: 35px; padding-top: 10px; border-color:#ccc; } textarea#txtEntradaXPath{ background: url(http://i.imgur.com/2cOaJ.png); background-attachment: local; background-repeat: no-repeat; padding-left: 35px; padding-top: 10px; border-color:#ccc; } .button { cursor: pointer; margin: 0px; width: 150px; padding: 10px; color: #fff; text-align: center; border: 1px solid hsl(0, 0%, 0%); text-shadow: 1px 1px 0px hsl(0, 0%, 12%); -webkit-box-shadow: inset 0px 1px 0px hsl(0, 0%, 40%), inset 0px -10px 20px hsl(0, 0%, 22%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); -moz-box-shadow: inset 0px 1px 0px hsl(0, 0%, 40%), inset 0px -10px 20px hsl(0, 0%, 22%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); box-shadow: inset 0px 1px 0px hsl(0, 0%, 40%), inset 0px -10px 20px hsl(0, 0%, 22%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); background: hsl(0, 0%, 27%); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .button:hover { -webkit-box-shadow: inset 0px 1px 0px hsl(0, 0%, 53%), inset 0px -10px 20px hsl(0, 0%, 35%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); -moz-box-shadow: inset 0px 1px 0px hsl(0, 0%, 53%), inset 0px -10px 20px hsl(0, 0%, 35%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); box-shadow: inset 0px 1px 0px hsl(0, 0%, 53%), inset 0px -10px 20px hsl(0, 0%, 35%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); background: hsl(0, 0%, 40%); } .button:active { -webkit-box-shadow: inset 0px 1px 0px hsl(0, 0%, 30%), inset 0px -10px 20px hsl(0, 0%, 19%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); -moz-box-shadow: inset 0px 1px 0px hsl(0, 0%, 30%), inset 0px -10px 20px hsl(0, 0%, 19%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); box-shadow: inset 0px 1px 0px hsl(0, 0%, 30%), inset 0px -10px 20px hsl(0, 0%, 19%), 0px 2px 10px hsla(0, 0%, 0%, 0.4); background: hsl(0, 0%, 25%); }
css
<reponame>padajuan/taiga-deployer<filename>ansible/roles/taiga-frontend/templates/conf.json { "api": "http://{{ host_fqdn }}:{{ taiga_port }}/api/v1/", "eventsUrl": "ws://{{ host_fqdn }}:{{ taiga_port }}/events", "debug": "true", "publicRegisterEnabled": true, "feedbackEnabled": true, "privacyPolicyUrl": null, "termsOfServiceUrl": null, "maxUploadFileSize": null, "contribPlugins": [] }
json
Virat Kohli’s love affair with Bengaluru’s M. Chinnaswamy Stadium continued on Saturday when the crowd cheered themselves hoarse in his support in India’s second Test against Sri Lanka. Kohli, who is a Royal Challengers Bangalore player, having captained them till last season, played to the crowd as they rained down adulations on him. The insane amount of support was present from the first ball as the crowd chanted Kohli’s name as India won the toss and came down to bat first. In a bizarre moment in the match, the partisan crowd even cheered the dismissal of Rohit Sharma as the next batter down was Kohli. As soon as he made his way down the field towards the pitch, the noise was deafening. Even though Kohli failed to register a big score, having being dismissed by Dhananjaya de Silva at 23, the support refused to die down. The cheers continued as India came out to field after getting all out for 252. As chants of “Kohli, Kohli” rang around the stadium, the man himself turned around and flashed a heart sign towards the galleries. In another instance, when the crowd started chanting for RCB, Kohli pulled up his India shirt to reveal a red coloured apparel below it. The fans were even chanting for the recently retired AB de Villiers, who is a hot favourite among the RCB fans and Kohli obliged by mimicking a famous ABD shot. Shreyas Iyer was out on 92 off 98 deliveries while Jasprit Bumrah remained not out without scoring. The dinner break was taken once Iyer was dismissed. Wicketkeeper-batter Rishabh Pant was the next highest contributor for India with a 26-ball 39 while Hanuma Vihari made 31. Virat Kohli was out for 23 just before the tea break while captain Rohit Sharma scored 15. For Sri Lanka, Lasith Embuldeniya and Praveen Jayawickrama took three wickets apiece while Dhananjaya de Silva got two.
english
{ "id": 472, "title": [ "[Upper Trollfang]" ], "description": [ "The narrow road ends here in the courtyard of a rambling structure that appears to be a prosperous inn. The thanot door keeps the guests safe from the dangers of weather and creature. The footprints that mark the dirt don't look like they were made by anyone you'd care to meet on a moonlit stroll, making the inn a welcome haven." ], "paths": [ "Obvious paths: southwest" ], "location": "the Upper Trollfang", "wayto": { "6830": "go bushes", "471": "southwest", "6854": "go door" }, "timeto": { "6830": 0.2, "471": 0.2, "6854": 0.2 }, "image": "wl-gates-1264234799.png", "image_coords": [ 925, 731, 935, 741 ], "tags": [ "some sovyn clove", "some acantha leaf", "fennel bulb", "bright red teaberry", "some angelica root", "ginger root", "ironfern root", "orris root", "pepperthorn root", "sprig of lavender", "some ambrominas leaf" ] }
json
// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. package language // NumCompactTags is the number of common tags. The maximum tag is // NumCompactTags-1. const NumCompactTags = 752 var specialTags = []Tag{ // 2 elements 0: {lang: 0xd5, region: 0x6d, script: 0x0, pVariant: 0x5, pExt: 0xe, str: "ca-ES-valencia"}, 1: {lang: 0x134, region: 0x134, script: 0x0, pVariant: 0x5, pExt: 0x5, str: "en-US-u-va-posix"}, } // Size: 72 bytes var coreTags = map[uint32]uint16{ 0x0: 0, // und 0x01500000: 3, // af 0x015000d1: 4, // af-NA 0x01500160: 5, // af-ZA 0x01b00000: 6, // agq 0x01b00051: 7, // agq-CM 0x02000000: 8, // ak 0x0200007f: 9, // ak-GH 0x02600000: 10, // am 0x0260006e: 11, // am-ET 0x03900000: 12, // ar 0x03900001: 13, // ar-001 0x03900022: 14, // ar-AE 0x03900038: 15, // ar-BH 0x03900061: 16, // ar-DJ 0x03900066: 17, // ar-DZ 0x0390006a: 18, // ar-EG 0x0390006b: 19, // ar-EH 0x0390006c: 20, // ar-ER 0x03900096: 21, // ar-IL 0x0390009a: 22, // ar-IQ 0x039000a0: 23, // ar-JO 0x039000a7: 24, // ar-KM 0x039000ab: 25, // ar-KW 0x039000af: 26, // ar-LB 0x039000b8: 27, // ar-LY 0x039000b9: 28, // ar-MA 0x039000c8: 29, // ar-MR 0x039000e0: 30, // ar-OM 0x039000ec: 31, // ar-PS 0x039000f2: 32, // ar-QA 0x03900107: 33, // ar-SA 0x0390010a: 34, // ar-SD 0x03900114: 35, // ar-SO 0x03900116: 36, // ar-SS 0x0390011b: 37, // ar-SY 0x0390011f: 38, // ar-TD 0x03900127: 39, // ar-TN 0x0390015d: 40, // ar-YE 0x03f00000: 41, // ars 0x04200000: 42, // as 0x04200098: 43, // as-IN 0x04300000: 44, // asa 0x0430012e: 45, // asa-TZ 0x04700000: 46, // ast 0x0470006d: 47, // ast-ES 0x05700000: 48, // az 0x0571e000: 49, // az-Cyrl 0x0571e031: 50, // az-Cyrl-AZ 0x05752000: 51, // az-Latn 0x05752031: 52, // az-Latn-AZ 0x05d00000: 53, // bas 0x05d00051: 54, // bas-CM 0x07000000: 55, // be 0x07000046: 56, // be-BY 0x07400000: 57, // bem 0x07400161: 58, // bem-ZM 0x07800000: 59, // bez 0x0780012e: 60, // bez-TZ 0x07d00000: 61, // bg 0x07d00037: 62, // bg-BG 0x08100000: 63, // bh 0x09e00000: 64, // bm 0x09e000c2: 65, // bm-ML 0x0a300000: 66, // bn 0x0a300034: 67, // bn-BD 0x0a300098: 68, // bn-IN 0x0a700000: 69, // bo 0x0a700052: 70, // bo-CN 0x0a700098: 71, // bo-IN 0x0b000000: 72, // br 0x0b000077: 73, // br-FR 0x0b300000: 74, // brx 0x0b300098: 75, // brx-IN 0x0b500000: 76, // bs 0x0b51e000: 77, // bs-Cyrl 0x0b51e032: 78, // bs-Cyrl-BA 0x0b552000: 79, // bs-Latn 0x0b552032: 80, // bs-Latn-BA 0x0d500000: 81, // ca 0x0d500021: 82, // ca-AD 0x0d50006d: 83, // ca-ES 0x0d500077: 84, // ca-FR 0x0d50009d: 85, // ca-IT 0x0da00000: 86, // ce 0x0da00105: 87, // ce-RU 0x0dd00000: 88, // cgg 0x0dd00130: 89, // cgg-UG 0x0e300000: 90, // chr 0x0e300134: 91, // chr-US 0x0e700000: 92, // ckb 0x0e70009a: 93, // ckb-IQ 0x0e70009b: 94, // ckb-IR 0x0f600000: 95, // cs 0x0f60005d: 96, // cs-CZ 0x0fa00000: 97, // cu 0x0fa00105: 98, // cu-RU 0x0fc00000: 99, // cy 0x0fc0007a: 100, // cy-GB 0x0fd00000: 101, // da 0x0fd00062: 102, // da-DK 0x0fd00081: 103, // da-GL 0x10400000: 104, // dav 0x104000a3: 105, // dav-KE 0x10900000: 106, // de 0x1090002d: 107, // de-AT 0x10900035: 108, // de-BE 0x1090004d: 109, // de-CH 0x1090005f: 110, // de-DE 0x1090009d: 111, // de-IT 0x109000b1: 112, // de-LI 0x109000b6: 113, // de-LU 0x11300000: 114, // dje 0x113000d3: 115, // dje-NE 0x11b00000: 116, // dsb 0x11b0005f: 117, // dsb-DE 0x12000000: 118, // dua 0x12000051: 119, // dua-CM 0x12400000: 120, // dv 0x12700000: 121, // dyo 0x12700113: 122, // dyo-SN 0x12900000: 123, // dz 0x12900042: 124, // dz-BT 0x12b00000: 125, // ebu 0x12b000a3: 126, // ebu-KE 0x12c00000: 127, // ee 0x12c0007f: 128, // ee-GH 0x12c00121: 129, // ee-TG 0x13100000: 130, // el 0x1310005c: 131, // el-CY 0x13100086: 132, // el-GR 0x13400000: 133, // en 0x13400001: 134, // en-001 0x1340001a: 135, // en-150 0x13400024: 136, // en-AG 0x13400025: 137, // en-AI 0x1340002c: 138, // en-AS 0x1340002d: 139, // en-AT 0x1340002e: 140, // en-AU 0x13400033: 141, // en-BB 0x13400035: 142, // en-BE 0x13400039: 143, // en-BI 0x1340003c: 144, // en-BM 0x13400041: 145, // en-BS 0x13400045: 146, // en-BW 0x13400047: 147, // en-BZ 0x13400048: 148, // en-CA 0x13400049: 149, // en-CC 0x1340004d: 150, // en-CH 0x1340004f: 151, // en-CK 0x13400051: 152, // en-CM 0x1340005b: 153, // en-CX 0x1340005c: 154, // en-CY 0x1340005f: 155, // en-DE 0x13400060: 156, // en-DG 0x13400062: 157, // en-DK 0x13400063: 158, // en-DM 0x1340006c: 159, // en-ER 0x13400071: 160, // en-FI 0x13400072: 161, // en-FJ 0x13400073: 162, // en-FK 0x13400074: 163, // en-FM 0x1340007a: 164, // en-GB 0x1340007b: 165, // en-GD 0x1340007e: 166, // en-GG 0x1340007f: 167, // en-GH 0x13400080: 168, // en-GI 0x13400082: 169, // en-GM 0x13400089: 170, // en-GU 0x1340008b: 171, // en-GY 0x1340008c: 172, // en-HK 0x13400095: 173, // en-IE 0x13400096: 174, // en-IL 0x13400097: 175, // en-IM 0x13400098: 176, // en-IN 0x13400099: 177, // en-IO 0x1340009e: 178, // en-JE 0x1340009f: 179, // en-JM 0x134000a3: 180, // en-KE 0x134000a6: 181, // en-KI 0x134000a8: 182, // en-KN 0x134000ac: 183, // en-KY 0x134000b0: 184, // en-LC 0x134000b3: 185, // en-LR 0x134000b4: 186, // en-LS 0x134000be: 187, // en-MG 0x134000bf: 188, // en-MH 0x134000c5: 189, // en-MO 0x134000c6: 190, // en-MP 0x134000c9: 191, // en-MS 0x134000ca: 192, // en-MT 0x134000cb: 193, // en-MU 0x134000cd: 194, // en-MW 0x134000cf: 195, // en-MY 0x134000d1: 196, // en-NA 0x134000d4: 197, // en-NF 0x134000d5: 198, // en-NG 0x134000d8: 199, // en-NL 0x134000dc: 200, // en-NR 0x134000de: 201, // en-NU 0x134000df: 202, // en-NZ 0x134000e5: 203, // en-PG 0x134000e6: 204, // en-PH 0x134000e7: 205, // en-PK 0x134000ea: 206, // en-PN 0x134000eb: 207, // en-PR 0x134000ef: 208, // en-PW 0x13400106: 209, // en-RW 0x13400108: 210, // en-SB 0x13400109: 211, // en-SC 0x1340010a: 212, // en-SD 0x1340010b: 213, // en-SE 0x1340010c: 214, // en-SG 0x1340010d: 215, // en-SH 0x1340010e: 216, // en-SI 0x13400111: 217, // en-SL 0x13400116: 218, // en-SS 0x1340011a: 219, // en-SX 0x1340011c: 220, // en-SZ 0x1340011e: 221, // en-TC 0x13400124: 222, // en-TK 0x13400128: 223, // en-TO 0x1340012b: 224, // en-TT 0x1340012c: 225, // en-TV 0x1340012e: 226, // en-TZ 0x13400130: 227, // en-UG 0x13400132: 228, // en-UM 0x13400134: 229, // en-US 0x13400138: 230, // en-VC 0x1340013b: 231, // en-VG 0x1340013c: 232, // en-VI 0x1340013e: 233, // en-VU 0x13400141: 234, // en-WS 0x13400160: 235, // en-ZA 0x13400161: 236, // en-ZM 0x13400163: 237, // en-ZW 0x13700000: 238, // eo 0x13700001: 239, // eo-001 0x13900000: 240, // es 0x1390001e: 241, // es-419 0x1390002b: 242, // es-AR 0x1390003e: 243, // es-BO 0x13900040: 244, // es-BR 0x13900050: 245, // es-CL 0x13900053: 246, // es-CO 0x13900055: 247, // es-CR 0x13900058: 248, // es-CU 0x13900064: 249, // es-DO 0x13900067: 250, // es-EA 0x13900068: 251, // es-EC 0x1390006d: 252, // es-ES 0x13900085: 253, // es-GQ 0x13900088: 254, // es-GT 0x1390008e: 255, // es-HN 0x13900093: 256, // es-IC 0x139000ce: 257, // es-MX 0x139000d7: 258, // es-NI 0x139000e1: 259, // es-PA 0x139000e3: 260, // es-PE 0x139000e6: 261, // es-PH 0x139000eb: 262, // es-PR 0x139000f0: 263, // es-PY 0x13900119: 264, // es-SV 0x13900134: 265, // es-US 0x13900135: 266, // es-UY 0x1390013a: 267, // es-VE 0x13b00000: 268, // et 0x13b00069: 269, // et-EE 0x14000000: 270, // eu 0x1400006d: 271, // eu-ES 0x14100000: 272, // ewo 0x14100051: 273, // ewo-CM 0x14300000: 274, // fa 0x14300023: 275, // fa-AF 0x1430009b: 276, // fa-IR 0x14900000: 277, // ff 0x14900051: 278, // ff-CM 0x14900083: 279, // ff-GN 0x149000c8: 280, // ff-MR 0x14900113: 281, // ff-SN 0x14c00000: 282, // fi 0x14c00071: 283, // fi-FI 0x14e00000: 284, // fil 0x14e000e6: 285, // fil-PH 0x15300000: 286, // fo 0x15300062: 287, // fo-DK 0x15300075: 288, // fo-FO 0x15900000: 289, // fr 0x15900035: 290, // fr-BE 0x15900036: 291, // fr-BF 0x15900039: 292, // fr-BI 0x1590003a: 293, // fr-BJ 0x1590003b: 294, // fr-BL 0x15900048: 295, // fr-CA 0x1590004a: 296, // fr-CD 0x1590004b: 297, // fr-CF 0x1590004c: 298, // fr-CG 0x1590004d: 299, // fr-CH 0x1590004e: 300, // fr-CI 0x15900051: 301, // fr-CM 0x15900061: 302, // fr-DJ 0x15900066: 303, // fr-DZ 0x15900077: 304, // fr-FR 0x15900079: 305, // fr-GA 0x1590007d: 306, // fr-GF 0x15900083: 307, // fr-GN 0x15900084: 308, // fr-GP 0x15900085: 309, // fr-GQ 0x15900090: 310, // fr-HT 0x159000a7: 311, // fr-KM 0x159000b6: 312, // fr-LU 0x159000b9: 313, // fr-MA 0x159000ba: 314, // fr-MC 0x159000bd: 315, // fr-MF 0x159000be: 316, // fr-MG 0x159000c2: 317, // fr-ML 0x159000c7: 318, // fr-MQ 0x159000c8: 319, // fr-MR 0x159000cb: 320, // fr-MU 0x159000d2: 321, // fr-NC 0x159000d3: 322, // fr-NE 0x159000e4: 323, // fr-PF 0x159000e9: 324, // fr-PM 0x15900101: 325, // fr-RE 0x15900106: 326, // fr-RW 0x15900109: 327, // fr-SC 0x15900113: 328, // fr-SN 0x1590011b: 329, // fr-SY 0x1590011f: 330, // fr-TD 0x15900121: 331, // fr-TG 0x15900127: 332, // fr-TN 0x1590013e: 333, // fr-VU 0x1590013f: 334, // fr-WF 0x1590015e: 335, // fr-YT 0x16400000: 336, // fur 0x1640009d: 337, // fur-IT 0x16800000: 338, // fy 0x168000d8: 339, // fy-NL 0x16900000: 340, // ga 0x16900095: 341, // ga-IE 0x17800000: 342, // gd 0x1780007a: 343, // gd-GB 0x18a00000: 344, // gl 0x18a0006d: 345, // gl-ES 0x19c00000: 346, // gsw 0x19c0004d: 347, // gsw-CH 0x19c00077: 348, // gsw-FR 0x19c000b1: 349, // gsw-LI 0x19d00000: 350, // gu 0x19d00098: 351, // gu-IN 0x1a200000: 352, // guw 0x1a400000: 353, // guz 0x1a4000a3: 354, // guz-KE 0x1a500000: 355, // gv 0x1a500097: 356, // gv-IM 0x1ad00000: 357, // ha 0x1ad0007f: 358, // ha-GH 0x1ad000d3: 359, // ha-NE 0x1ad000d5: 360, // ha-NG 0x1b100000: 361, // haw 0x1b100134: 362, // haw-US 0x1b500000: 363, // he 0x1b500096: 364, // he-IL 0x1b700000: 365, // hi 0x1b700098: 366, // hi-IN 0x1ca00000: 367, // hr 0x1ca00032: 368, // hr-BA 0x1ca0008f: 369, // hr-HR 0x1cb00000: 370, // hsb 0x1cb0005f: 371, // hsb-DE 0x1ce00000: 372, // hu 0x1ce00091: 373, // hu-HU 0x1d000000: 374, // hy 0x1d000027: 375, // hy-AM 0x1da00000: 376, // id 0x1da00094: 377, // id-ID 0x1df00000: 378, // ig 0x1df000d5: 379, // ig-NG 0x1e200000: 380, // ii 0x1e200052: 381, // ii-CN 0x1f000000: 382, // is 0x1f00009c: 383, // is-IS 0x1f100000: 384, // it 0x1f10004d: 385, // it-CH 0x1f10009d: 386, // it-IT 0x1f100112: 387, // it-SM 0x1f200000: 388, // iu 0x1f800000: 389, // ja 0x1f8000a1: 390, // ja-JP 0x1fb00000: 391, // jbo 0x1ff00000: 392, // jgo 0x1ff00051: 393, // jgo-CM 0x20200000: 394, // jmc 0x2020012e: 395, // jmc-TZ 0x20600000: 396, // jv 0x20800000: 397, // ka 0x2080007c: 398, // ka-GE 0x20a00000: 399, // kab 0x20a00066: 400, // kab-DZ 0x20e00000: 401, // kaj 0x20f00000: 402, // kam 0x20f000a3: 403, // kam-KE 0x21700000: 404, // kcg 0x21b00000: 405, // kde 0x21b0012e: 406, // kde-TZ 0x21f00000: 407, // kea 0x21f00059: 408, // kea-CV 0x22c00000: 409, // khq 0x22c000c2: 410, // khq-ML 0x23100000: 411, // ki 0x231000a3: 412, // ki-KE 0x23a00000: 413, // kk 0x23a000ad: 414, // kk-KZ 0x23c00000: 415, // kkj 0x23c00051: 416, // kkj-CM 0x23d00000: 417, // kl 0x23d00081: 418, // kl-GL 0x23e00000: 419, // kln 0x23e000a3: 420, // kln-KE 0x24200000: 421, // km 0x242000a5: 422, // km-KH 0x24900000: 423, // kn 0x24900098: 424, // kn-IN 0x24b00000: 425, // ko 0x24b000a9: 426, // ko-KP 0x24b000aa: 427, // ko-KR 0x24d00000: 428, // kok 0x24d00098: 429, // kok-IN 0x26100000: 430, // ks 0x26100098: 431, // ks-IN 0x26200000: 432, // ksb 0x2620012e: 433, // ksb-TZ 0x26400000: 434, // ksf 0x26400051: 435, // ksf-CM 0x26500000: 436, // ksh 0x2650005f: 437, // ksh-DE 0x26b00000: 438, // ku 0x27800000: 439, // kw 0x2780007a: 440, // kw-GB 0x28100000: 441, // ky 0x281000a4: 442, // ky-KG 0x28800000: 443, // lag 0x2880012e: 444, // lag-TZ 0x28c00000: 445, // lb 0x28c000b6: 446, // lb-LU 0x29a00000: 447, // lg 0x29a00130: 448, // lg-UG 0x2a600000: 449, // lkt 0x2a600134: 450, // lkt-US 0x2ac00000: 451, // ln 0x2ac00029: 452, // ln-AO 0x2ac0004a: 453, // ln-CD 0x2ac0004b: 454, // ln-CF 0x2ac0004c: 455, // ln-CG 0x2af00000: 456, // lo 0x2af000ae: 457, // lo-LA 0x2b600000: 458, // lrc 0x2b60009a: 459, // lrc-IQ 0x2b60009b: 460, // lrc-IR 0x2b700000: 461, // lt 0x2b7000b5: 462, // lt-LT 0x2b900000: 463, // lu 0x2b90004a: 464, // lu-CD 0x2bb00000: 465, // luo 0x2bb000a3: 466, // luo-KE 0x2bc00000: 467, // luy 0x2bc000a3: 468, // luy-KE 0x2be00000: 469, // lv 0x2be000b7: 470, // lv-LV 0x2c800000: 471, // mas 0x2c8000a3: 472, // mas-KE 0x2c80012e: 473, // mas-TZ 0x2e000000: 474, // mer 0x2e0000a3: 475, // mer-KE 0x2e400000: 476, // mfe 0x2e4000cb: 477, // mfe-MU 0x2e800000: 478, // mg 0x2e8000be: 479, // mg-MG 0x2e900000: 480, // mgh 0x2e9000d0: 481, // mgh-MZ 0x2eb00000: 482, // mgo 0x2eb00051: 483, // mgo-CM 0x2f600000: 484, // mk 0x2f6000c1: 485, // mk-MK 0x2fb00000: 486, // ml 0x2fb00098: 487, // ml-IN 0x30200000: 488, // mn 0x302000c4: 489, // mn-MN 0x31200000: 490, // mr 0x31200098: 491, // mr-IN 0x31600000: 492, // ms 0x3160003d: 493, // ms-BN 0x316000cf: 494, // ms-MY 0x3160010c: 495, // ms-SG 0x31700000: 496, // mt 0x317000ca: 497, // mt-MT 0x31c00000: 498, // mua 0x31c00051: 499, // mua-CM 0x32800000: 500, // my 0x328000c3: 501, // my-MM 0x33100000: 502, // mzn 0x3310009b: 503, // mzn-IR 0x33800000: 504, // nah 0x33c00000: 505, // naq 0x33c000d1: 506, // naq-NA 0x33e00000: 507, // nb 0x33e000d9: 508, // nb-NO 0x33e0010f: 509, // nb-SJ 0x34500000: 510, // nd 0x34500163: 511, // nd-ZW 0x34700000: 512, // nds 0x3470005f: 513, // nds-DE 0x347000d8: 514, // nds-NL 0x34800000: 515, // ne 0x34800098: 516, // ne-IN 0x348000da: 517, // ne-NP 0x35e00000: 518, // nl 0x35e0002f: 519, // nl-AW 0x35e00035: 520, // nl-BE 0x35e0003f: 521, // nl-BQ 0x35e0005a: 522, // nl-CW 0x35e000d8: 523, // nl-NL 0x35e00115: 524, // nl-SR 0x35e0011a: 525, // nl-SX 0x35f00000: 526, // nmg 0x35f00051: 527, // nmg-CM 0x36100000: 528, // nn 0x361000d9: 529, // nn-NO 0x36300000: 530, // nnh 0x36300051: 531, // nnh-CM 0x36600000: 532, // no 0x36c00000: 533, // nqo 0x36d00000: 534, // nr 0x37100000: 535, // nso 0x37700000: 536, // nus 0x37700116: 537, // nus-SS 0x37e00000: 538, // ny 0x38000000: 539, // nyn 0x38000130: 540, // nyn-UG 0x38700000: 541, // om 0x3870006e: 542, // om-ET 0x387000a3: 543, // om-KE 0x38c00000: 544, // or 0x38c00098: 545, // or-IN 0x38f00000: 546, // os 0x38f0007c: 547, // os-GE 0x38f00105: 548, // os-RU 0x39400000: 549, // pa 0x39405000: 550, // pa-Arab 0x394050e7: 551, // pa-Arab-PK 0x3942f000: 552, // pa-Guru 0x3942f098: 553, // pa-Guru-IN 0x39800000: 554, // pap 0x3aa00000: 555, // pl 0x3aa000e8: 556, // pl-PL 0x3b400000: 557, // prg 0x3b400001: 558, // prg-001 0x3b500000: 559, // ps 0x3b500023: 560, // ps-AF 0x3b700000: 561, // pt 0x3b700029: 562, // pt-AO 0x3b700040: 563, // pt-BR 0x3b70004d: 564, // pt-CH 0x3b700059: 565, // pt-CV 0x3b700085: 566, // pt-GQ 0x3b70008a: 567, // pt-GW 0x3b7000b6: 568, // pt-LU 0x3b7000c5: 569, // pt-MO 0x3b7000d0: 570, // pt-MZ 0x3b7000ed: 571, // pt-PT 0x3b700117: 572, // pt-ST 0x3b700125: 573, // pt-TL 0x3bb00000: 574, // qu 0x3bb0003e: 575, // qu-BO 0x3bb00068: 576, // qu-EC 0x3bb000e3: 577, // qu-PE 0x3cb00000: 578, // rm 0x3cb0004d: 579, // rm-CH 0x3d000000: 580, // rn 0x3d000039: 581, // rn-BI 0x3d300000: 582, // ro 0x3d3000bb: 583, // ro-MD 0x3d300103: 584, // ro-RO 0x3d500000: 585, // rof 0x3d50012e: 586, // rof-TZ 0x3d900000: 587, // ru 0x3d900046: 588, // ru-BY 0x3d9000a4: 589, // ru-KG 0x3d9000ad: 590, // ru-KZ 0x3d9000bb: 591, // ru-MD 0x3d900105: 592, // ru-RU 0x3d90012f: 593, // ru-UA 0x3dc00000: 594, // rw 0x3dc00106: 595, // rw-RW 0x3dd00000: 596, // rwk 0x3dd0012e: 597, // rwk-TZ 0x3e200000: 598, // sah 0x3e200105: 599, // sah-RU 0x3e300000: 600, // saq 0x3e3000a3: 601, // saq-KE 0x3e900000: 602, // sbp 0x3e90012e: 603, // sbp-TZ 0x3f200000: 604, // sdh 0x3f300000: 605, // se 0x3f300071: 606, // se-FI 0x3f3000d9: 607, // se-NO 0x3f30010b: 608, // se-SE 0x3f500000: 609, // seh 0x3f5000d0: 610, // seh-MZ 0x3f700000: 611, // ses 0x3f7000c2: 612, // ses-ML 0x3f800000: 613, // sg 0x3f80004b: 614, // sg-CF 0x3fe00000: 615, // shi 0x3fe52000: 616, // shi-Latn 0x3fe520b9: 617, // shi-Latn-MA 0x3fed2000: 618, // shi-Tfng 0x3fed20b9: 619, // shi-Tfng-MA 0x40200000: 620, // si 0x402000b2: 621, // si-LK 0x40800000: 622, // sk 0x40800110: 623, // sk-SK 0x40c00000: 624, // sl 0x40c0010e: 625, // sl-SI 0x41200000: 626, // sma 0x41300000: 627, // smi 0x41400000: 628, // smj 0x41500000: 629, // smn 0x41500071: 630, // smn-FI 0x41800000: 631, // sms 0x41900000: 632, // sn 0x41900163: 633, // sn-ZW 0x41f00000: 634, // so 0x41f00061: 635, // so-DJ 0x41f0006e: 636, // so-ET 0x41f000a3: 637, // so-KE 0x41f00114: 638, // so-SO 0x42700000: 639, // sq 0x42700026: 640, // sq-AL 0x427000c1: 641, // sq-MK 0x4270014c: 642, // sq-XK 0x42800000: 643, // sr 0x4281e000: 644, // sr-Cyrl 0x4281e032: 645, // sr-Cyrl-BA 0x4281e0bc: 646, // sr-Cyrl-ME 0x4281e104: 647, // sr-Cyrl-RS 0x4281e14c: 648, // sr-Cyrl-XK 0x42852000: 649, // sr-Latn 0x42852032: 650, // sr-Latn-BA 0x428520bc: 651, // sr-Latn-ME 0x42852104: 652, // sr-Latn-RS 0x4285214c: 653, // sr-Latn-XK 0x42d00000: 654, // ss 0x43000000: 655, // ssy 0x43100000: 656, // st 0x43a00000: 657, // sv 0x43a00030: 658, // sv-AX 0x43a00071: 659, // sv-FI 0x43a0010b: 660, // sv-SE 0x43b00000: 661, // sw 0x43b0004a: 662, // sw-CD 0x43b000a3: 663, // sw-KE 0x43b0012e: 664, // sw-TZ 0x43b00130: 665, // sw-UG 0x44400000: 666, // syr 0x44600000: 667, // ta 0x44600098: 668, // ta-IN 0x446000b2: 669, // ta-LK 0x446000cf: 670, // ta-MY 0x4460010c: 671, // ta-SG 0x45700000: 672, // te 0x45700098: 673, // te-IN 0x45a00000: 674, // teo 0x45a000a3: 675, // teo-KE 0x45a00130: 676, // teo-UG 0x46100000: 677, // th 0x46100122: 678, // th-TH 0x46500000: 679, // ti 0x4650006c: 680, // ti-ER 0x4650006e: 681, // ti-ET 0x46700000: 682, // tig 0x46c00000: 683, // tk 0x46c00126: 684, // tk-TM 0x47600000: 685, // tn 0x47800000: 686, // to 0x47800128: 687, // to-TO 0x48000000: 688, // tr 0x4800005c: 689, // tr-CY 0x4800012a: 690, // tr-TR 0x48400000: 691, // ts 0x49a00000: 692, // twq 0x49a000d3: 693, // twq-NE 0x49f00000: 694, // tzm 0x49f000b9: 695, // tzm-MA 0x4a200000: 696, // ug 0x4a200052: 697, // ug-CN 0x4a400000: 698, // uk 0x4a40012f: 699, // uk-UA 0x4aa00000: 700, // ur 0x4aa00098: 701, // ur-IN 0x4aa000e7: 702, // ur-PK 0x4b200000: 703, // uz 0x4b205000: 704, // uz-Arab 0x4b205023: 705, // uz-Arab-AF 0x4b21e000: 706, // uz-Cyrl 0x4b21e136: 707, // uz-Cyrl-UZ 0x4b252000: 708, // uz-Latn 0x4b252136: 709, // uz-Latn-UZ 0x4b400000: 710, // vai 0x4b452000: 711, // vai-Latn 0x4b4520b3: 712, // vai-Latn-LR 0x4b4d9000: 713, // vai-Vaii 0x4b4d90b3: 714, // vai-Vaii-LR 0x4b600000: 715, // ve 0x4b900000: 716, // vi 0x4b90013d: 717, // vi-VN 0x4bf00000: 718, // vo 0x4bf00001: 719, // vo-001 0x4c200000: 720, // vun 0x4c20012e: 721, // vun-TZ 0x4c400000: 722, // wa 0x4c500000: 723, // wae 0x4c50004d: 724, // wae-CH 0x4db00000: 725, // wo 0x4e800000: 726, // xh 0x4f100000: 727, // xog 0x4f100130: 728, // xog-UG 0x4ff00000: 729, // yav 0x4ff00051: 730, // yav-CM 0x50800000: 731, // yi 0x50800001: 732, // yi-001 0x50e00000: 733, // yo 0x50e0003a: 734, // yo-BJ 0x50e000d5: 735, // yo-NG 0x51500000: 736, // yue 0x5150008c: 737, // yue-HK 0x51e00000: 738, // zgh 0x51e000b9: 739, // zgh-MA 0x51f00000: 740, // zh 0x51f34000: 741, // zh-Hans 0x51f34052: 742, // zh-Hans-CN 0x51f3408c: 743, // zh-Hans-HK 0x51f340c5: 744, // zh-Hans-MO 0x51f3410c: 745, // zh-Hans-SG 0x51f35000: 746, // zh-Hant 0x51f3508c: 747, // zh-Hant-HK 0x51f350c5: 748, // zh-Hant-MO 0x51f3512d: 749, // zh-Hant-TW 0x52400000: 750, // zu 0x52400160: 751, // zu-ZA } // Total table size 4580 bytes (4KiB); checksum: A7F72A2A
go
{"type":"AvailableStorageSystemsV2","members":[{"availableNetworks":[{"name":"FC_Network_A","uri":"/rest/fc-networks/2d19d40b-d348-49da-9510-421acb0598af"}],"storageSystemUri":"/rest/storage-systems/TXQ1000307","storageSystemName":"ThreePAR7200-4310","volumes":[{"volumeName":"vol1","volumeUri":"/rest/storage-volumes/9A05C0A1-09B1-46E4-ADA3-49199BF5EE05","poolName":"ScaleTestingDomain_CPG_1","poolUri":"/rest/storage-pools/FA60DB08-3C0D-4B95-9D75-0434B927E52F","raidLevel":"RAID1","isShareable":false,"capacityBytes":"10737418240","provisionType":"Thin"}]}],"start":0,"total":1,"count":1}
json
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { PostResponse } from '../models/interfaces/post'; const POSTS_BASE_URL = 'post'; const DEFAULT_HEADERS = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('BEARER_TOKEN')}`, }), }; @Injectable({ providedIn: 'root', }) export class PostsService { constructor(private http: HttpClient) {} getAllPosts(): Observable<PostResponse[]> { let requestUrl = `${environment.apiBaseUrl}${POSTS_BASE_URL}/admin/all`; return this.http.get<PostResponse[]>(requestUrl, DEFAULT_HEADERS); } deletePost(postId: string) { let requestUrl = `${environment.apiBaseUrl}${POSTS_BASE_URL}/admin/${postId}`; return this.http.delete(requestUrl, DEFAULT_HEADERS); } }
typescript
<reponame>PyLadiesBerlin/advent_twitter_bot<filename>src/notifications.py from loguru import logger from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import * logger = logger.bind(name="PyLadiesAdvent") def send_email(e, tweet_text, SENDGRID_API_KEY, NOTIFY_EMAIL, subject="unknown"): """ Create the body of the message (a plain-text and an HTML version). text is your plain-text email html is your html version of the email if the reciever is able to view html emails then only the html email will be displayed """ text = """ Hi!\nHow are you?\nPlease check on the Advent project, something has gone wrong! """ html = """\n <html> <head></head> <body> Hi!<br> How are you? <p>Something went wrong in the PyLadies Advent project:</p> <p><b>%s</b></p> <p> Do not freak out, everything is gona be ok. :)</p> <p> Please sen the tweet for today manually </p> <p>%s</p> <br> Hugs!<br> you </body> </html> """ % ( e, tweet_text ) sg = SendGridAPIClient(api_key=SENDGRID_API_KEY) from_email = Email(NOTIFY_EMAIL) to_email = To(NOTIFY_EMAIL) subject = "Issue in PyLadies Advent project: " + subject content = Mail( from_email, to_email, subject, plain_text_content=PlainTextContent(text), html_content=HtmlContent(html), ) try: response = sg.send(message=content) if response.status_code == 202: logger.info("Error email sent") else: logger.info( f"Not sure if email was sent, but no exception raised: {response.status_code}" ) except Exception as e: raise Exception("Error sending email:", e)
python
const Discord = require("discord.js"); const ms = require("ms"); var fs = require('fs'); //FileSystem let conf = JSON.parse(fs.readFileSync("./config.json", "utf8")); //Config file module.exports.run = async (client, message, args) => { let log = client.channels.get('588742451255050243') // Logging channel if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send({ embed: { "title": "You don't have permissions, baby", "color": 0xff2222 } }).then(msg => { if (conf[message.guild.id].delete == 'true') { msg.delete(conf[message.guild.id].deleteTime); } }); let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0])); if (!tomute) return message.channel.send({ embed: { "title": "Couldn't find user :anguished: ", "color": 0xff2222 } }).then(msg => { if (conf[message.guild.id].delete == 'true') { msg.delete(conf[message.guild.id].deleteTime); } }); if (tomute.hasPermission("MANAGE_MESSAGES")) return message.channel.send({ embed: { "title": "The user you are trying to mute is either the same, or higher role than you", "color": 0xff2222 } }).then(msg => { if (conf[message.guild.id].delete == 'true') { msg.delete(conf[message.guild.id].deleteTime); } }); let muterole = message.guild.roles.find(`name`, "With Dick In Mouth"); if (!muterole) { try { muterole = await message.guild.createRole({ name: "With Dick In Mouth", color: "#000000", permissions: [] }) message.guild.channels.forEach(async (channel, id) => { await channel.overwritePermissions(muterole, { SEND_MESSAGES: false, ADD_REACTIONS: false }); }); } catch (e) { console.log(e.stack); } } let mutetime = args[1]; if (!mutetime) return message.channel.send({ embed: { "title": "You didn't specify a time!", "color": 0xff2222 } }).then(msg => { if (conf[message.guild.id].delete == 'true') { msg.delete(conf[message.guild.id].deleteTime); } }); await (tomute.addRole(muterole.id)); message.channel.send({ embed: { "title": "Muted", "description": `<@${tomute.id}> has been muted for ${ms(ms(mutetime))} seconds by <@${message.author.id}>`, "color": 0xf47742 } }).then(msg => { if (conf[message.guild.id].delete == 'true') { msg.delete(conf[message.guild.id].deleteTime); } }); setTimeout(function() { if (!tomute.roles.has(muterole.id)) return; tomute.removeRole(muterole.id); message.channel.send({ embed: { "description": `<@${tomute.id}> has been unmuted!`, "color": 0x22ff22, "title": "Unmuted" } }).then(msg => { if (conf[message.guild.id].delete == 'true') { msg.delete(conf[message.guild.id].deleteTime); } }); }, ms(mutetime)); }
javascript
As per the information furnished by respective nodal Ministries, Government plans to complete the following rail, air and road projects in the North Eastern States to strengthen the connectivity in the region: A total of 19 railway infrastructure projects, falling fully / partly in North Eastern States, covering a total length of 1909 km at a cost of Rs.81,941 crore have been undertaken and are at different stages of planning/approval/execution. Out of these, 482 km length has been commissioned and an expenditure of Rs.37,713 crore has been incurred upto March,2023. Ministry of Civil Aviation has launched regional connectivity scheme (RCS)-UDAN (Ude Desh ka Aam Nagrik) on 21.10.2016 to enhance regional connectivity across the country from unserved and under-served regions in the country and making air travel affordable to masses. Airport at Rupsi, Tezu, Tezpur, Pasighat, Jorhat, Lilabari, Shillong, Pakyong, Itanagar and Dimapur involving 64 routes have been operationalized under UDAN in the North Eastern Region. There were nine operational airports in 2014 in the North Eastern Region. Presently, there are 16 operational airports in the North Eastern Region. Additionally, Advanced Landing Ground at Ziro has also been operationalized. Further, 13 major infrastructure works worth Rs.1543.70 crore are under implementation in the States of Arunachal Pradesh, Assam, Manipur, Meghalaya and Tripura. A total of 261 road projects under different Schemes of MoRTH with a total sanctioned cost of Rs.1,02,594 crore are under implementation through National Highways Authority of India (NHAI), National Highways & Infrastructure Development Corporation Ltd. (NHIDCL) and State Public Works Departments (PWDs) in the North Eastern States. In addition, the Ministry of Development of North Eastern Region, under the erstwhile North East Road Sector Development Scheme (NERSDS) and the present North East Special Infrastructure Development Scheme (NESIDS) has sanctioned a total of 77 road projects amounting to Rs.3372.58 crore. - Moreover, under North Eastern Council (NEC) 51 projects worth Rs.4345.16 crore under Schemes of NEC has been sanctioned in connection with improving rail, air and road connectivity in the North Eastern Region. Department of Expenditure, Ministry Finance, under the Scheme for Special Assistance to States for Capital Investment for 2022-23 and 2023-24 has released funds to the North-Eastern States as detailed below: (Rs. In crore) Sl. No. The necessary Environment Impact Assessment (EIA) is done before starting the new projects. The requisite Environment & Forest clearance is also obtained by the concerned Agencies of Ministry/Departments/State Government, as per law. This information was given by Union Minister for Ministry of Development of North Eastern Region Shri G. Kishan Reddy in a written reply in Lok Sabha today.
english
The jokes about “dumb blondes” are, well, just jokes! Researchers have found that the average IQ of blondes may actually be slightly higher than those with other hair colours. While jokes about blondes may seem harmless to some, they can have real-world implications, said study author Jay Zagorsky from The Ohio State University in the US. “Research shows that stereotypes often have an impact on hiring, promotions and other social experiences,” Zagorsky said. “This study provides compelling evidence that there shouldn’t be any discrimination against blondes based on their intelligence,” Zagorsky pointed out. The study involved 10,878 US women. Data from the study came from the US National Longitudinal Survey of Youth 1979 (NLSY79), a national survey of people who were between 14 and 21 years old when they were first interviewed in 1979. In 1980, participants in the NLSY79 took the Armed Forces Qualification Test, or AFQT, which is used by the Pentagon to determine the intelligence of all recruits. The overall AFQT score is based on word knowledge, paragraph comprehension, math knowledge and arithmetic reasoning. The resulting findings showed that blonde-haired White women had an average IQ of 103. 2, compared to 102. 7 for those with brown hair, 101. 2 for those with red hair and 100. 5 for those with black hair. Blonde women were slightly more likely to be in the highest IQ category than those with other hair colours, and slightly less likely to be in the lowest IQ category, the findings showed. The study, published in the journal Economics Bulletin, could not say whether there are any genetic relationships between hair colour and intelligence, but Zagorsky did find one fact that could at least partially explain why blondes showed slightly higher intelligence — they grew up in homes with more reading material than did those with any other hair colour. “If blondes have any slight advantage, it may simply be that they were more likely to grow up in homes with more intellectual stimulation,” he said. “I don’t think you can say with certainty that blondes are smarter than others, but you can definitely say they are not any dumber,” Zagorsky pointed out.
english
Hundreds of Afghans protested outside a bank in Kabul on Saturday and others formed long lines at cash machines as a UN agency warned that a worsening drought could leave millions in need of humanitarian aid. At the Kabul airport, thousands are still gathering in hope of fleeing the country, even after a suicide attack on Thursday killed 169 Afghans and 13 US service members and amid warnings of more attacks. The massive US-led airlift is winding down, with many Western nations having completed their own evacuation efforts ahead of Tuesday’s deadline. The economic crisis, which predates the Taliban takeover earlier this month, could give Western nations leverage as they urge Afghanistan’s new rulers to form a moderate, inclusive government and allow people to leave after the planned withdrawal of US forces on August 31. Afghanistan is heavily dependent on international aid, which covered around 75% of the Western-backed government’s budget. The Taliban have said they want good relations with the international community and have promised a more moderate form of Islamic rule than when they last governed the country, but many Afghans are deeply skeptical. The protesters at New Kabul Bank included many civil servants demanding their salaries, which they said had not been paid for the past three to six months. They said even though banks reopened three days ago no one has been able to withdraw cash. ATM machines are still operating, but withdrawals are limited to around $200 every 24 hours, contributing to the formation of long lines. A UN agency meanwhile warned that a worsening drought threatens the livelihoods of more than 7 million people. The Rome-based Food and Agriculture Organization said Afghans are also suffering from the coronavirus pandemic and displacement from the recent fighting. Earlier this month, the UN World Food Programme estimated that some 14 million people — roughly one out of every three Afghans — urgently need food assistance. The FAO said that crucial help is needed ahead of the winter wheat planting season, which begins in a month in many areas. So far, funding would cover assistance to only 110,000 families of farmers, while some 1. 5 million need help, the agency said, adding that the current harvest is expected to be 20% below last year’s. President Joe Biden has said he will adhere to a self-imposed August 31 deadline for withdrawing all US forces. The Taliban, who control nearly the entire country outside Kabul’s airport, have rejected any extension. Italy said its final evacuation flight had landed in Rome but that it would work with the United Nations and countries bordering Afghanistan to continue helping Afghans who had worked with its military contingent to leave the country. “Our imperative must be to not abandon the Afghan people,” especially women and children, Italian Foreign Minister Luigi Di Maio said Saturday. He said 4,890 Afghans were evacuated by Italy’s air force on 87 flights, but did not say how many others were still eligible. The Taliban have encouraged Afghans to stay in the country, pledging amnesty even to those who fought against them. They have said commercial flights will resume after the US withdrawal, but it’s unclear if airlines will be willing to offer service. The US and its allies have said they will continue providing humanitarian aid through the UN and other partners, but any broader engagement — including development assistance — is likely to hinge on whether the Taliban deliver on their promises of more moderate rule. When the Taliban last governed Afghanistan, from 1996 until the US-led invasion in 2001, they imposed a harsh interpretation of Islamic law. Women were largely confined to their homes, television and music were banned, and suspected criminals were maimed or executed in public. But even as the group’s top leadership has struck a more moderate tone, there have been reports of human rights abuses in areas under Taliban control. It’s unclear whether fighters are acting under orders or on their own. Taliban fighters beat up a cameraman for the private broadcaster Tolo TV earlier this week in Kabul. Saad Mohseni, the CEO of the group that owns the channel, said the Taliban have been in touch with the station’s management about the incident. He said the fighter has been identified, but it’s unclear if he has faced any disciplinary action. There was no comment from the Taliban.
english
Vinita and Vishal rest for a while and decide to go back to the corner of the villa. And this time the two will be together in the villa so that what happened to Sandhya yesterday does not happen to Vinita. Vinita and Vishal first decide to go to the left wing of the villa where Sandhya went to investigate and was found unconscious in the room in the left wing. According to her, she saw three ghosts there. The composition of Vasantavila was something like this. Enter through the main gate and there was a paved road of about 500 meters. And there was a garden on the side of the road. Which was now covered with bushes. It can be estimated that there was a grand garden in one era. There was a paved road to enter the house between the two gardens. And a temple was built in a side garden. Vishal and Vinita had cleared some bushes from around the temple and lit the lamps in front of the idols after cleaning the temple. Out of which one idol was of the Pandit clan's clan goddess and the other idol was of Mahadev, the god of gods. Beyond the main entrance was the main entrance to the building. Beyond that was the foyer. Crossing the foyer was a large living room and in the middle of the living room was a large staircase. which went upwards and had wings falling to its left and right. To the left were five rooms. And on the right side there were six rooms. Similarly, the rooms were situated upwards. The living room had elegant furniture made of old-fashioned teak and cedar wood. Which showed the past glory of Vasantvilla. A tiger was kept in the living room. A deer's head was kept in the wall. On one wall were oil paintings of ancestors. And a shield and sword were mounted on one wall. The living room was cleaned yesterday. Because Siddhidevi had performed havan and rituals there yesterday and had cleaned the two rooms on the right side. Siddhidevi and her family were to stay in one and Sandhya and Vishal in the other. All the other rooms were covered with the dust of months. If one looks into the darkness of the living room of the night, the burning eyes of the tiger will be blinded. Vasantvilla was completely closed for the last five years. Only electricity and water connections were on. Lokesh used to pay the electricity corporation bill. And his staff used to go and clean Vasantvilla once a year. Before that, a care taker lived during the day. But the body of that caretaker was found in the swimming pool behind Vasantvilla in a very horrible condition. All the blood was drained from his body. No local person was willing to work there after this incident. Hence, Lokesh assigned his Dehradun staff to go and maintain Vasantavila once a year. If a buyer is found for the villa, he will be freed from the hassle of property. And property money can rise. Cleaning was not done for the last six months. Yesterday, Siddhidevi and family came and did the necessary cleaning. So Vinita and Vishal didn't have any problem today. Vinita and Vishal started checking in the room on the left side. As soon as they entered the first room on the left side, they got a general confined smell like the room had been closed for a long time and it was open. The room was cobwebbed and dusty. The room was furnished with elegant old style furniture. Both looked at the furniture and room and wondered how glorious their past must have been. Vinita also saw the magnificence of the villa and if it is proved that there is no ghost in this villa, then the deal of this villa is said to be very cheap. And Siddha Devi's guru should also be called once in this villa if there is a solution to drive away the ghost, then that should also be done. They stayed in that room for a while but there was no movement in that room so both of them went to the adjoining room. There also did not seem to be any presence. Thus they did not feel any ghost in the four rooms of the left wing. It was around ten o'clock in the night, both of them came to the last and fifth room of the left wing where Sandhya experienced the ghost. Vishal entered the room. But Vinita hesitated going into the room and remembered the video recording she had seen in the morning. But she went into the room behind Vishal. Upon entering the room, they both felt the same confined and uninhabitable smell that they had experienced in the four rooms before them. Apart from that, no one felt that anyone was present there. Even after spending almost half an hour in that room, nothing seemed strange. So Vinita said, I have heard that ghosts also have a certain time to come. This experience may have occurred in the early evening between three and four o'clock in the morning. We will come back to this room after two o'clock tonight because it may be the time of ghosts. Now that we are resting in the cleaned room, the ghosts come at midnight. So we will rest now and check the right wing after twelve o'clock and come back to this room after two o'clock. Vishal agrees with her. And both go back to the cleaned room to relax. Meanwhile, Sandhya has taken the hotel car and left for Vasantvilla to give holy water. She suddenly remembers. In her haste, she forgets to give Rachna and Bharat the number of Pratap Singh Thakur, Vishal's uncle. If any of the three do not return to the hotel by noon, contact them and give them all the details. So he calls Rachna. But Rachna does not receive the call. So she messages Rachna and Bharat on WhatsApp. "If we will not come to hotel by tomorrow evening kindly contact Mr. Pratapsinh Thakur uncle of vishal Thakur his contact No is : 98xxxxxx10 “It is not certain when the weather will turn bad in the hills. Today there was more fog. It was difficult to see even at a distance of five feet, but Sandhya was slowly moving towards Vasantvilla. On the other hand, Vishal and Vinita woke up hearing the alarm of Vishal's cell phone at midnight. Both of them first looked in all the rooms of the right wing and finally decided to go to the last room of the left wing. All the remaining rooms of the right wing were retaken, but there was no strange feeling in any of the rooms. All the rooms felt a sense of unease. The rooms looked like they had not been cleaned for months. They had another experience. They walked around all the rooms for about two and a half hours. As much time had passed. There was absolute peace in the villa. The soft hooting of an owl could be heard from the forest behind the villa. The barking of some jackal was heard. Apart from that there was silence. Vinita and Vishal Sandhya saw the ghost in the room. He comes into the room. He cleans the necessary chair in the room and decides to spend the night sitting on it. Both of them are sitting on the chair talking and almost an hour has passed. Suddenly the lights of the villa start going on and off. And suddenly the light goes off. Vishal switches on the torch he has. And the torch light is thrown on Vinita's face. So Vinita gets scared and screams. Vishal explains to her that he is Vishal himself and has lit your side with a torch to check if you are safe or not. Suddenly something sounds in the next room. So Vishal and Vinita rush towards that room.
english
Auli - budget and hotels if you have been there, also please mention the number of days you stayed there. You can get cheap hotels and homestays at MMT and Goibibo. I have been planning to visit this month as well. Upvote (1) Hi Mayank You can look for hotels or homestays on goibibo/airbnb/booking.com. Also if you go by bus then it should cost you around 5k for 3 days. Upvote (1) Upvote (1) for affordable options. Hi, I have attached some budget options for you in Auli, you can click on the cards to check them out, you can also use the same link to book them. TRH Joshimath (Old) You can find lot of budget properties in Airbnb for Auli. Earn credits when your answers are upvoted by others. Do you know Indochina? And Have you been there? Hey guys, I am planning a trip to auli, Uttrakhand in the month of mid-February. what will be the required budget ? And can you please tell how many days it is required to visit Auli? And what are the nearby places to visit after Auli in Uttrakhand.
english
<gh_stars>1-10 (function() { "use strict"; angular.module("spa.subjects") .component("sdImageSelector", { templateUrl: imageSelectorTemplateUrl, controller: ImageSelectorController, bindings: { authz: "<" }, }) .component("sdImageEditor", { templateUrl: imageEditorTemplateUrl, controller: ImageEditorController, bindings: { authz: "<" }, require: { imagesAuthz: "^sdImagesAuthz" } }); imageSelectorTemplateUrl.$inject = ["spa.config.APP_CONFIG"]; function imageSelectorTemplateUrl(APP_CONFIG) { return APP_CONFIG.image_selector_html; } imageEditorTemplateUrl.$inject = ["spa.config.APP_CONFIG"]; function imageEditorTemplateUrl(APP_CONFIG) { return APP_CONFIG.image_editor_html; } ImageSelectorController.$inject = ["$scope", "$stateParams", "spa.authz.Authz", "spa.subjects.Image"]; function ImageSelectorController($scope, $stateParams, Authz, Image) { var vm = this; vm.$onInit = function() { $scope.$watch(function() { return Authz.getAuthorizedUserId(); }, function() { if (!$stateParams.id) { vm.items = Image.query(); } }); } return; } ImageEditorController.$inject = ["$scope", "$q", "$state", "$stateParams", "spa.authz.Authz", "spa.layout.DataUtils", "spa.subjects.Image", "spa.subjects.ImageThing", "spa.subjects.ImageLinkableThing", "spa.geoloc.geocoder"]; function ImageEditorController($scope, $q, $state, $stateParams, Authz, DataUtils, Image, ImageThing, ImageLinkableThing, geocoder) { var vm = this; vm.selected_linkables = []; vm.create = create; vm.clear = clear; vm.update = update; vm.remove = remove; vm.linkThings = linkThings; vm.setImageContent = setImageContent; vm.locationByAddress = locationByAddress; vm.$onInit = function() { $scope.$watch(function() { return Authz.getAuthorizedUserId(); }, function() { if ($stateParams.id) { reload($stateParams.id); } else { newResource(); } }); } return; function newResource() { vm.item = new Image(); vm.imagesAuthz.newItem(vm.item); return vm.item; } function reload(imageId) { var itemId = imageId ? imageId : vm.item.id; vm.item = Image.get({ id: itemId }); vm.things = ImageThing.query({ image_id: itemId }); vm.linkable_things = ImageLinkableThing.query({ image_id: itemId }); vm.imagesAuthz.newItem(vm.item); $q.all([vm.item.$promise, vm.things.$promise]).catch(handleError); vm.item.$promise.then(function(image) { vm.location = geocoder.getLocationByPosition(image.position); }); } function clear() { if (!vm.item.id) { $state.reload(); } else { $state.go(".", { id: null }); } } function setImageContent(dataUri) { vm.item.image_content = DataUtils.getContentFromDataUri(dataUri); } function create() { vm.item.$save().then(function() { $state.go(".", { id: vm.item.id }); }, handleError); } function update() { vm.item.errors = null; var update = vm.item.$update(); linkThings(update); } function linkThings(parentPromise) { var promises = []; if (parentPromise) { promises.push(parentPromise); } angular.forEach(vm.selected_linkables, function(linkable) { var resource = ImageThing.save({ image_id: vm.item.id }, { thing_id: linkable }); promises.push(resource.$promise); }); vm.selected_linkables = []; $q.all(promises).then(function(response) { $scope.imageform.$setPristine(); reload(); }, handleError); } function remove() { vm.item.errors = null; vm.item.$delete().then(function() { clear(); }, handleError); } function locationByAddress(address) { geocoder.getLocationByAddress(address).$promise.then(function(location) { vm.location = location; vm.item.position = location.position; }); } function handleError(response) { console.log("error", response); if (response.data) { vm.item["errors"] = response.data.errors; } if (!vm.item.errors) { vm.item["errors"] = {} vm.item["errors"]["full_messages"] = [response]; } $scope.imageform.$setPristine(); } } })();
javascript
<filename>src/components/Table/index.js<gh_stars>0 /* * @Description: * @Author: * @Date: 2020-01-09 18:16:18 */ import Table from './Table' Table.install = function (Vue) { Vue.component('Table', Table) } export default Table
javascript
<filename>src/api/flashbots.rs //! `Flashbots` namespace use serde_json::json; use crate::{ api::Namespace, helpers::{self, CallFuture}, types::{BlockNumber, Bytes, CallBundleResponse, H256}, Transport, }; /// `Flashbots` namespace: *must be used with a proper flashbots provider* #[derive(Debug, Clone)] pub struct Flashbots<T> { transport: T, } impl<T: Transport> Namespace<T> for Flashbots<T> { fn new(transport: T) -> Self where Self: Sized, { Flashbots { transport } } fn transport(&self) -> &T { &self.transport } } impl<T: Transport> Flashbots<T> { /// Call bundle pub fn call_bundle( &self, signed_txs: &[Bytes], target_block: BlockNumber, state_block: BlockNumber, timestamp: Option<u64>, ) -> CallFuture<CallBundleResponse, T::Out> { let signed_txs = helpers::serialize(&signed_txs); let target_block = helpers::serialize(&target_block); let state_block = helpers::serialize(&state_block); let timestamp = helpers::serialize(&timestamp); CallFuture::new(self.transport.execute( "eth_callBundle", vec![json!({ "txs": signed_txs, "blockNumber": target_block, "stateBlockNumber": state_block, "timestamp": timestamp })], )) } /// Send bundle pub fn send_bundle( &self, signed_txs: &[Bytes], block: BlockNumber, min_timestamp: Option<u64>, max_timestamp: Option<u64>, reverting_tx_hashes: Option<Vec<H256>>, ) -> CallFuture<(), T::Out> { let signed_txs = helpers::serialize(&signed_txs); let block = helpers::serialize(&block); let min_timestamp = helpers::serialize(&min_timestamp); let max_timestamp = helpers::serialize(&max_timestamp); let reverting_tx_hashes = helpers::serialize(&reverting_tx_hashes); CallFuture::new(self.transport.execute( "eth_sendBundle", vec![json!({ "txs": signed_txs, "blockNumber": block, "minTimestamp": min_timestamp, "maxTimestamp": max_timestamp, "revertingTxHashes": reverting_tx_hashes, })], )) } }
rust
package com.birthstone.core.helper; import com.birthstone.core.constant.SplitString; /// <summary> /// </summary> public class StringToArray { public static String[] stringConvertArray(String str) { String[] array = new String[6]; array[0] = "Empty"; if (str != null) { array=str.replace(SplitString.Sep1, "!").split("!"); } return array; } }
java
<filename>src/main/resources/data/fabric/tags/items/shovels.json<gh_stars>1-10 { "replace": false, "values": [ "minecraft:emerald_shovel", "minecraft:redstone_shovel", "minecraft:lapis_shovel", "minecraft:copper_shovel", "minecraft:amethyst_shovel" ] }
json
<reponame>CristianNajeraL/fairmotion<filename>fairmotion/tasks/motion_prediction/metrics.py # Copyright (c) Facebook, Inc. and its affiliates. import numpy as np from fairmotion.ops import conversions def euler_diff(predictions, targets): """ Computes the Euler angle error as in previous work, following https://github.com/una-dinosauria/human-motion-prediction/blob/master/src/translate.py#L207 Args: predictions: np array of predicted joint angles represented as rotation matrices, i.e. in shape (..., n_joints, 3, 3) targets: np array of same shape as `predictions` Returns: The Euler angle error an np array of shape (..., ) """ assert predictions.shape[-1] == 3 and predictions.shape[-2] == 3 assert targets.shape[-1] == 3 and targets.shape[-2] == 3 n_joints = predictions.shape[-3] ori_shape = predictions.shape[:-3] preds = np.reshape(predictions, [-1, 3, 3]) targs = np.reshape(targets, [-1, 3, 3]) euler_preds = conversions.R2E(preds) # (N, 3) euler_targs = conversions.R2E(targs) # (N, 3) # reshape to (-1, n_joints*3) to be consistent with previous work euler_preds = np.reshape(euler_preds, [-1, n_joints * 3]) euler_targs = np.reshape(euler_targs, [-1, n_joints * 3]) # l2 error on euler angles idx_to_use = np.where(np.std(euler_targs, 0) > 1e-4)[0] euc_error = np.power( euler_targs[:, idx_to_use] - euler_preds[:, idx_to_use], 2, ) euc_error = np.sqrt(np.sum(euc_error, axis=1)) # (-1, ...) # reshape to original return np.reshape(euc_error, ori_shape)
python
<filename>src/pyglue/DocStrings/ExceptionMissingFile.py class ExceptionMissingFile: """ An exception class for errors detected at runtime, thrown when OCIO cannot find a file that is expected to exist. This is provided as a custom type to distinguish cases where one wants to continue looking for missing files, but wants to properly fail for other error conditions. """ def __init__(self): pass
python
<filename>website/static/css/custom.css<gh_stars>1-10 /** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* your custom css */ .button { font-weight: 600; border-width: 2px; transition: 0.2s all; } .logo { height: 400px; } .homeWrapper { padding-top: 40px; display: flex; align-items: center; justify-content: flex-start; flex-direction: row; min-height: 500px; padding: 20px; } .homeWrapper .title { text-align: left; color: white; font-weight: 100; font-size: 40px; } .homeWrapper .title h1 { margin: 0px; margin-bottom: 20px; font-size: 60px; } .homeWrapper .button { color: white; border-color: white; } .homeWrapper .button:hover { background-color: transparent; opacity: 0.5; } .homeContainer { background: radial-gradient(#1565c0 20%, #1145a1); } .fixedHeaderContainer { background-color: white; color: #1145a1; border-bottom: 3px solid #1145a1; } .fixedHeaderContainer a { color: #1145a1 !important; } .fixedHeaderContainer .slidingNav ul li { margin-right: 10px; } .fixedHeaderContainer li a { border-radius: 4px; font-weight: 600; } .fixedHeaderContainer .slidingNav ul li a:hover { color: #37474f; background-color: #cfd8dc; } .fixedHeaderContainer .slidingNav ul li a:focus { color: #37474f; background-color: #cfd8dc; } .fixedHeaderContainer .slidingNav ul li.siteNavItemActive a, .fixedHeaderContainer .slidingNav ul li.siteNavGroupActive a { background-color: #cfd8dc; } .buttons { display: inline-flex; } .buttons a { margin-right: 15px; } .about h2 { font-size: 40px; margin-bottom: 40px; margin-top: 0px; } .about ul { font-size: 20px; font-weight: 300; width: 80%; padding-left: 25px; } .about ul li { margin-bottom: 30px; } .about .logo { height: 200px; } .features h1 { font-size: 60px; margin-top: 0px; font-weight: 900; } .features h2 { font-size: 40px; margin-top: 0px; } .features p { width: 80%; font-size: 20px; font-weight: 100; margin-bottom: 0px !important; } .startProject h2 { font-size: 60px; margin-top: 0px; } .startProject p { margin-bottom: 0px !important; } .startProject .code { width: 100%; } .sitemap { text-align: center; } .sitemap h4 { color: white; font-size: 18px; margin-top: 0px; } .darkBackground { background-color: #1145a1; } .mainContainer .container:first-child { margin-top: -40px; } .mainContainer .container:last-child { margin-bottom: -40px; } .command-snippet { background-color: #041627; padding: 12px; margin: 32px 0; font-size: 24px; color: #abb2bf; border-radius: 8px; box-shadow: -8px 12px 12px -8px rgba(0, 0, 0, 0.7); } .command-snippet__header { display: flex; margin-bottom: 16px; align-items: center; } .command-snippet__header__icon { display: inline-flex; background-color: #ddd; width: 16px; height: 16px; border-radius: 8px; margin-right: 8px; } .command-snippet__header__icon.red { background-color: #f55f56; } .command-snippet__header__icon.yellow { background-color: #f8bc2f; } .command-snippet__header__icon.green { background-color: #38c93f; } .command-snippet__snippet { display: flex; flex-wrap: wrap; } @media only screen and (min-device-width: 360px) and (max-device-width: 736px) { .homeWrapper { flex-direction: column; } .headerTitleWithLogo { display: initial !important; } .fixedHeaderContainer header { justify-content: center; } .fixedHeaderContainer .navigationSlider .slidingNav ul { background: white; padding: 5px; box-sizing: border-box; height: 50px; } .fixedHeaderContainer .navigationSlider .slidingNav ul li a { padding: 5px; height: 35px; } } @media only screen and (min-width: 1024px) { } @media only screen and (max-width: 1023px) { .homeWrapper { flex-direction: column; } .headerTitleWithLogo { display: initial !important; } .fixedHeaderContainer header { justify-content: center; } .fixedHeaderContainer .navigationSlider .slidingNav ul { background: white; padding: 5px; box-sizing: border-box; height: 50px; } .fixedHeaderContainer .navigationSlider .slidingNav ul li a { padding: 5px; height: 35px; } } @media only screen and (min-width: 1400px) { } @media only screen and (min-width: 1500px) { }
css
<reponame>evfox9/minimal-mistakes --- title: 1-3. Shallow Neural Networks tags: AI Deep_Learning Coursera Deep_Learning_Specialization --- ## Shallow Neural Network ### Neural Network Representation ![](https://raw.githubusercontent.com/evfox9/blog/master/deeplearning/dl1301.png) We call the layers with input features $x_1, x_2, x_3$ as **input layer**. Layer in the middle are called **hidden layer**. Layer on the right with only one node is called **output layer**. We don't count the input layer, so the neural network above is a 2-layer NN. ### Computing a Neural Network's Output ![](https://raw.githubusercontent.com/evfox9/blog/master/deeplearning/dl1302.png) $z^{[1]} = \begin{bmatrix} {w_1}^{[1]T} \\\ {w_2}^{[1]T} \\\ {w_3}^{[1]T} \\\ {w_4}^{[1]T} \end{bmatrix} \begin{bmatrix} x_1 \\\ x_2 \\\ x_3 \end{bmatrix} + \begin{bmatrix} {b_1}^{[1]} \\\ {b_2}^{[1]} \\\ {b_3}^{[1]} \\\ {b_4}^{[1]} \end{bmatrix} = \begin{bmatrix} {w_1}^{[1]T} x + {b_1}^{[1]} \\\ {w_2}^{[1]T} x + {b_2}^{[1]} \\\ {w_3}^{[1]T} x + {b_3}^{[1]} \\\ {w_4}^{[1]T} x + {b_4}^{[1]} \end{bmatrix} = \begin{bmatrix} {z_1}^{[1]} \\\ {z_2}^{[1]} \\\ {z_3}^{[1]} \\\ {z_4}^{[1]} \end{bmatrix}$ In short, $z^{[1]} = W^{[1]} x + b^{[1]},\ a^{[1]} = \sigma(z^{[1]})$. For $z^{[i]}$ which $i \geq 2$, $z^{[i]} = W^{[i]} a^{[i-1]}+ b^{[i]},\ a^{[i]} = \sigma(z^{[i]})$. ### Activation Functions **Activation function** is the function that defines the output of that node. Here are some examples of activation functions. #### Sigmoid ![](https://raw.githubusercontent.com/evfox9/blog/master/deeplearning/dl1303.png) $$a = \frac{1}{1 + e^{-z}}$$ #### Hyperbolic tangent (tanh) ![](https://raw.githubusercontent.com/evfox9/blog/master/deeplearning/dl1304.png) $$a = \tanh{z} = \frac{e^z - e^{-z}}{e^z + e^{-z}}$$ #### Rectified Linear Unit (ReLU) ![](https://raw.githubusercontent.com/evfox9/blog/master/deeplearning/dl1305.png) $$a = \max (0,z)$$ #### Leaky ReLU ![](https://raw.githubusercontent.com/evfox9/blog/master/deeplearning/dl1306.png) $$a = \max (0.01z,z)$$ * can replace 0.01 to other number #### Why non-linear activation functions? Functions above are all non-linear functions. Activation functions should be non-linear because no matter how much you compose linear functions it will still be linear functions, so having many hidden layers won't have any meanings. Having non-linear function as activation function makes the model more expressive. ### Derivative of Activation functions #### Sigmoid $$g'(z) = g(z) (1 - g(z))$$ $$0 < g'(z) \leq \frac{1}{4}$$ #### Hyperbolic tangent (tanh) $$g'(z) = 1 - {\tanh{z}}^2$$ $$0 < g'(z) < 1$$ #### Rectified Linear Unit (ReLU) $$g'(z) = \begin{cases} 0 \ \text{if} \ z < 0 \\ 1 \ \text{if} \ z > 0 \end{cases} $$ #### Leaky ReLU $$g'(z) = \begin{cases} 0.01 \ \text{if} \ z < 0 \\ 1 \ \text{if} \ z > 0 \end{cases} $$ ### Gradient descent for Neural Networks #### Forward Propagation $z^{[1]} = W^{[1]} x + b^{[1]}$ $a^{[1]} = \sigma(z^{[1]})$. $z^{[2]} = W^{[2]} a^{[1]}+ b^{[2]}$ $a^{[2]} = \sigma(z^{[2]})$. #### Backward Propagation $d z^{[2]} = A^{[2]} - Y$ $d w^{[2]} = \frac{1}{m} d z^{[2]} A^{[1]T}$ $d b^{[2]} = \frac{1}{m}$ `np.sum`($d z^{[2]}$, axis=1, keepdims=True) $d z^{[1]} = w^{[2]T} d z^{[2]} \times g^{[1]'} z^{[1]}$ $d W^{[1]} = \frac{1}{m} d Z^{[1]} X^{[T]}$ $d b^{[1]} = \frac{1}{m}$ `np.sum`($d z^{[1]}$, axis=1, keepdims=True) To keep the dimension of the matrix after sum operation, you should set the `keepdims` parameter to true. ## Programming Assignment [Planar_data_classification_with_onehidden_layer](https://github.com/evfox9/Coursera/blob/master/Deep_Learning/Neural_Networks_and_Deep_Learning/Planar_data_classification_with_onehidden_layer.ipynb) --- ## References [Neural Networks and Deep Learning](https://www.coursera.org/learn/neural-networks-deep-learning)
markdown
<filename>BohFoundation.WebApi/AngularApp/ApplicationEvaluator/EvaluateApplicants/RatingSummaries/Services/RatingSummariesService.ts module BohFoundation.ApplicationEvaluator.EvaluateApplicants.RatingSummaries.Services { export interface IRatingSummariesService { getRatingSummariesFromServer(): ng.resource.IResource<any>; resolveGetRatingSummariesFromServer(serverResponse: Common.Models.ServerResponseModel): void; getTop5Applicants(): Array<Dtos.ApplicationEvaluator.RatingSummary.TopApplicantRatingSummaryModel>; gotoApplicant(index: number): void; } export class RatingSummariesService implements IRatingSummariesService { private apiEndpoint = "/api/applicationevaluator/evaluatingapplicants/ratingSummaries"; private typeOfData = "applicant's average ratings"; private top5ApplicantsModel: Dtos.ApplicationEvaluator.RatingSummary.Top5ApplicantsModel; static $inject = ['AuthRequiredRepository', 'GenericResolver', '$location']; constructor( private authRequiredRepository: Common.Repositories.IAuthRequiredRepository, private genericResolver: Common.Services.Resolvers.IGenericResolver, private $location: ng.ILocationService) { } getRatingSummariesFromServer(): ng.resource.IResource<any> { return this.authRequiredRepository.get(this.apiEndpoint); } resolveGetRatingSummariesFromServer(serverResponse: Common.Models.ServerResponseModel): void { this.top5ApplicantsModel = this.genericResolver.genericGetResolver(this.typeOfData, serverResponse); } getTop5Applicants(): Array<Dtos.ApplicationEvaluator.RatingSummary.TopApplicantRatingSummaryModel> { if (this.top5ApplicantsModel == undefined) { return []; } return this.top5ApplicantsModel.topApplicants; } gotoApplicant(index: number): void { this.$location.path("/ApplicationEvaluator/ReviewApplicant/" + this.top5ApplicantsModel.topApplicants[index].applicantsGuid); } } } module BohFoundation.Main { Register.ApplicationEvaluator.service("RatingSummariesService", ApplicationEvaluator.EvaluateApplicants.RatingSummaries.Services.RatingSummariesService); }
typescript
<filename>src/main/com/mithril/flares/event/FetchComplete.java package com.mithril.flares.event; import org.skk.tide.Event; public class FetchComplete extends Event { public Event withData(String s) { AllGameData allGameData = new AllGameData(s); return withData(allGameData); } }
java
from typing import * from .. import tensor as T from ..stochastic import StochasticTensor from ..typing_ import * from .base import Distribution from .utils import copy_distribution, check_tensor_arg_types __all__ = ['BaseCategorical', 'Categorical', 'OneHotCategorical'] class BaseCategorical(Distribution): continuous = False reparameterized = False _logits: Optional[T.Tensor] """Logits of the probabilities of being each class.""" _probs: Optional[T.Tensor] """The probabilities of being each class.""" n_classes: int """The number of categorical classes.""" epsilon: float """The infinitesimal constant, used for computing `logits`.""" _mutual_params: Dict[str, Any] """Dict that stores the original `logits` or `probs` constructor argument.""" def __init__(self, *, logits: Optional[TensorOrData], probs: Optional[TensorOrData], dtype: str, event_ndims: int, epsilon: float = T.EPSILON, device: Optional[str] = None, validate_tensors: Optional[bool] = None): (logits, probs), = check_tensor_arg_types([('logits', logits), ('probs', probs)], device=device) if logits is not None: param_shape = T.shape(logits) mutual_params = {'logits': logits} device = device or T.get_device(logits) else: param_shape = T.shape(probs) mutual_params = {'probs': probs} device = device or T.get_device(probs) epsilon = float(epsilon) if len(param_shape) < 1: for param_key in mutual_params: raise ValueError(f'`{param_key}` must be at least 1d: ' f'got shape {param_shape}.') value_shape = (param_shape if self.min_event_ndims == 1 else param_shape[:-1]) n_classes = param_shape[-1] super().__init__( dtype=dtype, value_shape=value_shape, event_ndims=event_ndims, device=device, validate_tensors=validate_tensors, ) for k, v in mutual_params.items(): mutual_params[k] = self._assert_finite(v, k) self._logits = logits self._probs = probs self.n_classes = n_classes self.epsilon = epsilon self._mutual_params = mutual_params @property def logits(self) -> T.Tensor: """Logits of the probabilities of being each class.""" if self._logits is None: self._logits = T.random.categorical_probs_to_logits(self._probs, self.epsilon) return self._logits @property def probs(self) -> T.Tensor: """The probabilities of being each class.""" if self._probs is None: self._probs = T.random.categorical_logits_to_probs(self._logits) return self._probs def to_indexed(self, dtype: str = T.categorical_dtype) -> 'Categorical': """ Get a :class:`Categorical` object according to this distribution. Args: dtype: The dtype of the returned distribution. Returns: The current distribution itself, if this is already an instance of :class:`Categorical`, and its dtype equals to `dtype`. Otherwise returns a new :class:`Categorical` instance. """ raise NotImplementedError() def to_one_hot(self, dtype: str = T.int32) -> 'OneHotCategorical': """ Get a :class:`OneHotCategorical` object according to this distribution. Args: dtype: The dtype of the returned distribution. Returns: The current distribution itself, if this is already an instance of :class:`OneHotCategorical`, and its dtype equals to `dtype`. Otherwise returns a new :class:`OneHotCategorical` instance. """ raise NotImplementedError() def copy(self, **overrided_params): return copy_distribution( cls=self.__class__, base=self, attrs=('dtype', 'event_ndims', 'epsilon', 'device', 'validate_tensors'), mutual_attrs=(('logits', 'probs'),), compute_deps={'logits': ('epsilon',)}, original_mutual_params=self._mutual_params, overrided_params=overrided_params, ) class Categorical(BaseCategorical): """ Categorical distribution. A categorical random variable is a discrete random variable being one of `1` to `n_classes - 1`. The probability of being each possible value is specified via the `probs`, or the `logits` of the probs. """ min_event_ndims = 0 def __init__(self, *, logits: Optional[TensorOrData] = None, probs: Optional[TensorOrData] = None, dtype: str = T.categorical_dtype, event_ndims: int = 0, epsilon: float = T.EPSILON, device: Optional[str] = None, validate_tensors: Optional[bool] = None): """ Construct a new :class:`Categorical` distribution object. Args: logits: The logits of the probabilities of being each possible value. ``logits = log(p)``. Either `logits` or `probs` must be specified, but not both. probs: The probability `p` of being each possible value. ``p = softmax(logits)``. dtype: The dtype of the samples. event_ndims: The number of dimensions in the samples to be considered as an event. epsilon: The infinitesimal constant, used for computing `logits`. validate_tensors: Whether or not to check the numerical issues? Defaults to ``settings.validate_tensors``. """ super().__init__( logits=logits, probs=probs, dtype=dtype, event_ndims=event_ndims, epsilon=epsilon, device=device, validate_tensors=validate_tensors, ) def _sample(self, n_samples: Optional[int], group_ndims: int, reduce_ndims: int, reparameterized: bool) -> StochasticTensor: samples = T.random.categorical( probs=self.probs, n_samples=n_samples, dtype=self.dtype) return StochasticTensor( distribution=self, tensor=samples, n_samples=n_samples, group_ndims=group_ndims, reparameterized=reparameterized, ) def _log_prob(self, given: T.Tensor, group_ndims: int, reduce_ndims: int) -> T.Tensor: return T.random.categorical_log_prob( given=given, logits=self.logits, group_ndims=reduce_ndims) def to_indexed(self, dtype: str = T.categorical_dtype) -> 'Categorical': return self if dtype == self.dtype else self.copy(dtype=dtype) def to_one_hot(self, dtype: str = T.int32) -> 'OneHotCategorical': return copy_distribution( cls=OneHotCategorical, base=self, attrs=('dtype', 'event_ndims', 'epsilon', 'device', 'validate_tensors'), mutual_attrs=(('logits', 'probs'),), compute_deps={'logits': ('epsilon',)}, original_mutual_params=self._mutual_params, overrided_params={'dtype': dtype, 'event_ndims': self.event_ndims + 1} ) class OneHotCategorical(BaseCategorical): """ One-hot categorical distribution. A one-hot categorical random variable is a `n_classes` binary vector, with only one element being 1 and all remaining elements being 0. The probability of each element being 1 is specified via thevia the `probs`, or the `logits` of the probs. """ min_event_ndims = 1 def __init__(self, *, logits: Optional[TensorOrData] = None, probs: Optional[TensorOrData] = None, dtype: str = T.int32, event_ndims: int = 1, epsilon: float = T.EPSILON, device: Optional[str] = None, validate_tensors: Optional[bool] = None): """ Construct a new :class:`OneHotCategorical` distribution object. Args: logits: The logits of the probabilities of being each possible value. ``logits = log(p)``. Either `logits` or `probs` must be specified, but not both. probs: The probability `p` of being each possible value. ``p = softmax(logits)``. dtype: The dtype of the samples. device: The device where to place new tensors and variables. event_ndims: The number of dimensions in the samples to be considered as an event. epsilon: The infinitesimal constant, used for computing `logits`. validate_tensors: Whether or not to check the numerical issues? Defaults to ``settings.validate_tensors``. """ super().__init__( logits=logits, probs=probs, dtype=dtype, event_ndims=event_ndims, epsilon=epsilon, device=device, validate_tensors=validate_tensors, ) def _sample(self, n_samples: Optional[int], group_ndims: int, reduce_ndims: int, reparameterized: bool) -> StochasticTensor: samples = T.random.one_hot_categorical( probs=self.probs, n_samples=n_samples, dtype=self.dtype) return StochasticTensor( distribution=self, tensor=samples, n_samples=n_samples, group_ndims=group_ndims, reparameterized=reparameterized, ) def _log_prob(self, given: T.Tensor, group_ndims: int, reduce_ndims: int) -> T.Tensor: return T.random.one_hot_categorical_log_prob( given=given, logits=self.logits, group_ndims=reduce_ndims) def to_indexed(self, dtype: str = T.categorical_dtype) -> 'Categorical': return copy_distribution( cls=Categorical, base=self, attrs=('dtype', 'event_ndims', 'epsilon', 'device', 'validate_tensors'), mutual_attrs=(('logits', 'probs'),), compute_deps={'logits': ('epsilon',)}, original_mutual_params=self._mutual_params, overrided_params={'dtype': dtype, 'event_ndims': self.event_ndims - 1} ) def to_one_hot(self, dtype: str = T.int32) -> 'OneHotCategorical': return self if dtype == self.dtype else self.copy(dtype=dtype)
python
#include <bits/stdc++.h> typedef long long ll; using namespace std; ll N, K; ll dp[105][105]; ll cal(ll sum, ll len){ if(sum == N && len == K){ return 1; } else if(sum > N){ return 0; } if(len > K){ return 0; } if(dp[sum][len] != -1){ return dp[sum][len]; } ll ans = 0; for(ll i = sum; i <= N; i++){ ans += cal(sum+i,len+1); } return dp[sum][len] = ans; } int main(){ while(cin>>N>>K && N+K){ memset(dp, -1, sizeof dp); cout<<cal(0,0)<<"\n"; } }
cpp
package com.github.vole.passport.common.handler; import com.github.vole.passport.common.auth.PassportAuthentication; import com.github.vole.passport.common.contants.PassportConstants; import com.github.vole.passport.common.details.DetailsConvertPassportAuth; import com.github.vole.passport.common.details.PassportUserDetails; import com.github.vole.passport.common.token.DefaultPassportToken; import com.github.vole.passport.common.token.PassportToken; import com.github.vole.passport.common.tokenstore.PassportTokenStore; import com.github.vole.passport.common.utils.IpHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.security.core.Authentication; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class PassportTokenProcessingHandle implements AuthenticationSuccessHandler { protected final Log logger = LogFactory.getLog(this.getClass()); private String serviceParamName; private String targetParamName; private String tokenParamName; private PassportTokenStore passportTokenStore; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); public void setTargetParamName(String targetParamName) { this.targetParamName = targetParamName; } public void setServiceParamName(String serviceParamName) { this.serviceParamName = serviceParamName; } public void setTokenParamName(String tokenParamName) { this.tokenParamName = tokenParamName; } public void setPassportTokenStore(PassportTokenStore passportTokenStore) { this.passportTokenStore = passportTokenStore; } protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { logger.debug("Passport Server Success Authentication"); String redirect = obtainRedirect(request); if(StringUtils.isEmpty(redirect)){ logger.error("Error redirectURL is null for Passport Server"); response.sendError(HttpStatus.UNAUTHORIZED.value(), "Error redirectURL For Passport Server"); return; } String target = obtainTarget(request); DefaultPassportToken token = new DefaultPassportToken(); String ip = IpHelper.getIpAddr(request); token.setIp(ip); PassportAuthentication passportAuthentication = DetailsConvertPassportAuth.convert ((PassportUserDetails) authentication.getPrincipal()); token.setValue(passportAuthentication); PassportToken pt = passportTokenStore.storeToken(token); String tokenKey = pt.getKey(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(redirect); if (!StringUtils.isEmpty(target)) { builder.queryParam(getTargetParamName(), target); } builder.queryParam(getTokenParamName(), tokenKey); redirectStrategy.sendRedirect(request, response, builder.encode().toUriString()); } protected String obtainRedirect(HttpServletRequest request) { return request.getParameter(getServiceParamName()); } protected String obtainTarget(HttpServletRequest request) { return request.getParameter(getTargetParamName()); } protected String getTargetParamName() { return !StringUtils.isEmpty(targetParamName) ? targetParamName : PassportConstants.DEFAULT_TARGET_PARAM; } protected String getServiceParamName() { return !StringUtils.isEmpty(serviceParamName) ? serviceParamName : PassportConstants.DEFAULT_SERVICE_PARAM; } protected String getTokenParamName() { return !StringUtils.isEmpty(tokenParamName) ? tokenParamName : PassportConstants.DEFAULT_TOKEN_PARAM; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { handle(request,response,authentication); } }
java
<gh_stars>10-100 ["generate-appveyor","generate-assemblefile","generate-babelrc","generate-coc","generate-collections","generate-contributing","generate-data","generate-defaults","generate-dest","generate-editorconfig","generate-engine","generate-eslint","generate-example","generate-file","generate-generator","generate-git","generate-gitattributes","generate-gitignore","generate-install","generate-license","generate-log","generate-mocha","generate-node","generate-npmrc","generate-package","generate-project","generate-readme","generate-robots","generate-scaffold","generate-slack","generate-slush","generate-snippet","generate-travis","generate-updatefile","generate-updater","generate-verbfile","generate-webtask","updater-verb","verb-generate-readme","verb-trees"]
json
<gh_stars>0 {"gender":"male","name":{"title":"Mr","first":"Kirk","last":"Stewart"},"email":"<EMAIL>","login":{"username":"silverrabbit355","uuid":"ZxPvmu4tREaM5b2RMaNxDw==","isloggedin":false},"picture":{"large":"https://randomuser.me/api/portraits/men/94.jpg","medium":"https://randomuser.me/api/portraits/med/men/94.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/men/94.jpg"},"location":{"street":{"number":1379,"name":"<NAME> Dr"},"city":"Maitland","state":"Western Australia","country":"Australia","postcode":1785,"coordinates":{"latitude":-16.6819,"longitude":74.3747},"timezone":{"offset":"+9:30","description":"Adelaide, Darwin"}},"isactive":false}
json
<gh_stars>1-10 { "title": "Mars Panorama from Curiosity", "credit": "NASA, JPL-Caltech, MSSS", "explanation": "The Mars Rover named Curiosity recorded high-resolution, 360 degree views of its location on Mars late last year. The panoramic scene was stitched from over 1,000 images from Curiosity's Mast camera or Mastcam. In this version, captured with Mastcam's medium angle lens, the rover's deck and robotic arm are in the foreground, stretched and distorted by the extreme wide perspective. Just beyond the rover are regions of clay rich rock, evidence for an ancient watery environment, with a clear view toward more distant martian ridges and buttes. Gale crater wall runs across the center (toward the north) in the background over 30 kilometers in the distance. The upper reaches of Mt. Sharp are at the far right. Images to construct the panorama were recorded over 4 consecutive sols between local noon and 2pm to provide consistent lighting. Zoom in to the panoramic scene and you can easily spot the shadow casting sundial mounted on rover's deck (right). In July NASA plans to launch a new rover to Mars named Perseverance.", "date": "2020-03-06", "hdurl": "https://apod.nasa.gov/apod/image/2003/PIA23623_fig1.jpg", "service_version": "v1", "media_type": "image", "url": "https://apod.nasa.gov/apod/image/2003/PIA23623_fig1_600v.jpg" }
json
<gh_stars>0 package com.organization.Giscle.giscle_app; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.organization.Giscle.giscle_app.giscle_socket.*; import com.organization.Giscle.giscle_app.Authentication.Login; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Intent i = new Intent(MainActivity.this, UserDashboard.class); //startActivity(i); } }
java
(userdocs:getting_started:single_example)= # Simulating a regular spiking Izhikevich neuron In this section, we wish to simulate a single regular spiking Izhikevich neuron ({cite}`Izhikevich2007`) and record/visualise its membrane potential (as shown in the figure below): ```{figure} ../Userdocs/NML2_examples/example-single-izhikevich2007cell-sim-v.png :alt: Membrane potential for neuron recorded from the simulation :align: center Membrane potential of the simulated regular spiking Izhikevich neuron. ``` This plot, saved as `example-single-izhikevich2007cell-sim-v.png`, is generated using the following Python NeuroML script: ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python ---- ``` (userdocs:getting_started:single_example:declaring)= ## Declaring the model in NeuroML ```{admonition} Python is the suggested programming language to use for working with NeuroML. The Python NeuroML tools and libraries provide a convenient, easy to use interface to use NeuroML. ``` Let us step through the different sections of the Python script. To start writing a model in NeuroML, we first create a `NeuroMLDocument`. This document is the top level container for everything that the model should contain. ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 21, 22 ---- ``` Next, all entities that we want to use in the model must be defined. The {ref}`NeuroML specification <userdocs:neuromlv2>` includes many standard entities, and it is possible to also define new entities that may not already be included in the NeuroML specification. We will look at the pre-defined entities, and how NeuroML may be extended later when we look at the {ref}`NeuroML standard <userdocs:specification>` in detail. For now, we limit ourselves to defining a new `Izhikevich2007Cell` (definition of this {ref}`here <schema:izhikevich2007Cell>`). The Izhikevich neuron model can take sets of parameters to show different types of spiking behaviour. Here, we define an instance of the general Izhikevich cell using parameters that exhibit regular spiking. ```{admonition} Units in NeuroML NeuroML defines a {ref}`standard set of units <schema:neuromlcoredimensions_>` that can be used in models. Learn more about units and dimensions in NeuroML and LEMS {ref}`here <userdocs:unitsanddimensions>`. ``` Once defined, we add this to our `NeuroMLDocument`. ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 24-28 ---- ``` Now that the neuron has been defined, we declare a {ref}`network <schema:network>` with a {ref}`population <schema:population>` of these neurons to create a network. Here, our model includes one network which includes only one population, which in turn only consists of a single neuron. Once the network, its populations, and their neurons have been declared, we again them to our model: ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 30-37 ---- ``` To record the membrane potential of the neuron, we must give it some external input that makes it spike. As with the neuron, we create and add a {ref}`pulse generator <schema:pulsegenerator>` to our network. We then connect it to our neuron, the `target` using an {ref}`explicit input <schema:explicitinput>`. ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 39-46 ---- ``` This completes our model. It includes a single network, with one population of one neuron that is driven by one pulse generator. At this point, we can save our model to a file and validate it to check if it conforms to the NeuroML schema (more on this {ref}`later <userdocs:validating_models>`). ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 48-54 ---- ``` (userdocs:getting_started:single_example:declaring:model)= ### The generated NeuroML model We have now defined our model in NeuroML. Let us investigate the generated NeuroML file: ```{literalinclude} ./NML2_examples/izhikevich2007_single_cell_network.nml ---- language: xml ``` NeuroML files are written in XML. So, they consist of tags and attributes and can be processed by general purpose XML tools. Each entity between chevrons is a *tag*: `<..>`, and each tag may have multiple *attributes* that are defined using the `name=value` format. For example `<neuroml ..>` is a tag, that contains the `id` attribute with value `NML2_SimpleIonChannel`. ```{admonition} XML Tutorial For details on XML, have a look through [this tutorial](https://www.w3schools.com/xml/). ``` ```{admonition} Is this XML well-formed? :class: tip A NeuroML file needs to be both 1) well-formed, as in complies with the general rules of the XML language syntax, and 2) valid, i.e. contains the expected NeuroML specific tags/attributes. Is the XML shown above well-formed? See for yourself. Copy the NeuroML file listed above and check it using an [online XML syntax checker](https://www.w3schools.com/xml/xml_validator.asp). ``` Let us step through this file to understand the different constructs used in it. The first segment introduces the `neuroml` tag that includes information on the specification that this NeuroML file adheres to. ```{literalinclude} ./NML2_examples/izhikevich2007_single_cell_network.nml ---- language: xml lines: 1-1 ---- ``` The first attribute, `xmlns` defines the XML *namespace*. All the tags that are defined for use in NeuroML are defined for use in the NeuroML namespace. This prevents conflicts with other XML schemas that may use the same tags. Read more on XML namespaces [here](https://en.wikipedia.org/wiki/XML_namespace). The remaining lines in this snippet refer to the *XML Schema* that is defined for NeuroML. XML itself does not define any tags, so any tags can be used in a general XML document. Here is an example of a valid XML document, a simple HTML snippet: ```{code-block} xml <html> <head> <title>A title</title> </head> </html> ``` NeuroML, however, does not use these tags. It defines its own set of standard tags using an [XML Schema](http://www.w3.org/2001/XMLSchema-instance). In other words, the NeuroML XML schema defines the structure and contents of a valid NeuroML document. Various tools can then compare NeuroML documents to the NeuroML Schema to validate them. ```{admonition} Purpose of the NeuroML schema The NeuroML Schema defines the structure and contents of a valid NeuroML document. ``` The `xmlns:xi` attribute documents that NeuroML has a defined XML Schema. The next attribute, `xsi:schemaLocation` tells us the locations of the NeuroML Schema. Here, two locations are provided: - the Web URL: [http://www.neuroml.org/schema/neuroml2](http://www.neuroml.org/schema/neuroml2), - and the location of the Schema Definition file (an `xsd` file) relative to this example file in the GitHub repository. We will look at the NeuroML schema in detail in later sections. All NeuroML files must include the `neuroml` tag, and the attributes related to the NeuroML Schema. The last attribute, `id` is the identification (or the name) of this particular NeuroML document. The remaining part of the file is the *declaration* of the model and its dynamics: ```{literalinclude} ./NML2_examples/izhikevich2007_single_cell_network.nml ---- language: xml lines: 2-7 ---- ``` The cell, is defined in the `izhikevich2007Cell` tag, which has a number of attributes (see {ref}`here <schema:izhikevich2007Cell>` for more): - `id`: the name that we want to give to this cell. To refer to it later, for example, - `v0`: the initial membrane potential for the cell, - `C`: the leak conductance, - `k`: conductance per voltage, - `vr`: the membrane potential after a spike, - `vt`: the threshold membrane potential, to detect a spike, - `vpeak`: the peak membrane potential, - `a`, `b`, `c`, and `d`: are parameters of the Izhikevich neuron model. Similarly, the `pulseGenerator` is also defined, and the `network` tag includes the `population` and `explicitInput`. We observe that even though we have declared the entities, and the values for parameters that govern them, we do not state what and how these parameters are used. This is because NeuroML is a [declarative language](https://en.wikipedia.org/wiki/Declarative_programming) that defines the structure of models. We do not need to define how the dynamics of the different parts of the model are implemented. As we will see further below, these are already defined in NeuroML. ```{admonition} NeuroML is a declarative language. Users describe the various components of the model but do not need to worry about how they are implemented. ``` We have seen how an Izhikevich cell can be declared in NeuroML, with all its parameters. However, given that NeuroML develops a standard and defines what tags and attributes can be used, let us see how these are defined for the Izhikevich cell. The Izhikevich cell is defined in version 2 of the NeuroML schema [here](https://github.com/NeuroML/NeuroML2/blob/master/Schemas/NeuroML2/NeuroML_v2.0.xsd#L1422): ```{code-block} xml <xs:complexType name="Izhikevich2007Cell"> <xs:complexContent> <xs:extension base="BaseCellMembPotCap"> <xs:attribute name="v0" type="Nml2Quantity_voltage" use="required"/> <xs:attribute name="k" type="Nml2Quantity_conductancePerVoltage" use="required"/> <xs:attribute name="vr" type="Nml2Quantity_voltage" use="required"/> <xs:attribute name="vt" type="Nml2Quantity_voltage" use="required"/> <xs:attribute name="vpeak" type="Nml2Quantity_voltage" use="required"/> <xs:attribute name="a" type="Nml2Quantity_pertime" use="required"/> <xs:attribute name="b" type="Nml2Quantity_conductance" use="required"/> <xs:attribute name="c" type="Nml2Quantity_voltage" use="required"/> <xs:attribute name="d" type="Nml2Quantity_current" use="required"/> </xs:extension> </xs:complexContent> </xs:complexType> ``` The `xs:` prefix indicates that these are all part of an XML Schema. The Izhikevich cell and all its parameters are defined in the schema. As we saw before, parameters of the model are defined as attributes in NeuroML files. So, here in the schema, they are also defined as `attributes` of the `complexType` that the schema describes. The schema also specifies which of the parameters are necessary, and what their dimensions (units) are using the `use` and `type` properties. This schema gives us all the information we need to describe an Izhikevich cell in NeuroML. Using the specification in the Schema, any number of Izhikevich cells can be defined in a NeuroML file with the necessary parameter sets to create networks of Izhikevich cells. As is evident, XML files are excellent for storing structured data, but may not be easy to write by hand. However, NeuroML users *are not expected* to write in XML. They should use the Python tools as demonstrated here. (userdocs:getting_started:single_example:simulating)= ## Simulating the model Until now, we have just declared the model. We have not, however, included any information related to the simulation of this model. The same model may be instantiated many times with different random seeds and so on to give rise to different simulations and behaviours. In NeuroML, the information required to simulate the model is provided using {ref}`LEMS <userdocs:specification:lemsdefs>`. We will not go into the details of LEMS just yet. We will limit ourselves to the bits necessary to simulate our Izhikevich neuron only. The following lines of code instantiate a new simulation with certain simulation parameters: `duration`, `dt`, `simulation_seed`. Additionally, they also define what information is being recorded from the simulation. In this case, we create an output file, and then add a new column to record the membrane potential `v` from our one neuron in the one population in it. You can read more about recording from NeuroML simulations {ref}`here <userdocs:quantitiesandrecording>`. Finally, like we had saved our NeuroML model to a file, we also save our LEMS document to a file. ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 60-75 ---- ``` The generated LEMS file is shown below: ```{literalinclude} ./NML2_examples/LEMS_example-single-izhikevich2007cell-sim.xml ---- language: xml ---- ``` Similar to NeuroML, LEMS also has a well defined schema. I.e., a set of valid tags define a LEMS file. We observe that whereas the NeuroML tags were related to the modelling parameters, the LEMS tags are related to simulation. We also note that our NeuroML model has been "included" in the LEMS file, so that all entities defined there are now known to the LEMS simulation also. Like NeuroML, *users are not expected to write the LEMS XML component by hand*. They should continue to use the NeuroML Python tools. Finally, {ref}`pyNeuroML <pyNeuroML>` also includes functions that allow you to run the simulation from the Python script itself: ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 77-80 ---- ``` Here, we are running our simulation using the {ref}`jNeuroML <jNeuroML>` simulator, which is bundled with {ref}`pyNeuroML <pyNeuroML>`. Since NeuroML is a well defined standard, models defined in NeuroML can also be run using other {ref}`supported simulators <userdocs:simulators>`. (userdocs:getting_started:single_example:plotting)= ## Plotting the recorded membrane potential Once we have simulated our model and the data has been collected in the specified file, we can analyse the data. pyNeuroML also includes some helpful functions to quickly plot various recorded variables. The last few lines of code shows how the membrane potential plot at the top of the page is generated. ```{literalinclude} ./NML2_examples/izhikevich-single-neuron.py ---- language: python lines: 82-90 ---- ``` The next section is an interactive Jupyter notebook where you can play with this example. Click the "launch" button in the top right hand corner to run the notebook in a configured service. *You do not need to install any software on your computer to run these notebooks.*
markdown
RIM releases two BlackBerry 7 OS handsets for Sprint. One is Sprint's thinnest BlackBerry and one is Sprint's first full touch-screen BlackBerry. RIM has been busy today, with not only the release of three new BlackBerry 7 OS devices for AT&T, but two more for Sprint. They are the RIM BlackBerry Bold 9930 and the BlackBerry Torch 9850. Both phones boast the latest BlackBerry 7 OS that promises better performance, plus a 1.2GHz processor and 5-megapixel cameras. Both devices also feature RIM's new "Liquid Graphics" technology that promises to deliver faster speeds and a better touch-screen experience. Other features include voice-activated universal search, augmented-reality experiences with BBM 6, and a list of preinstalled apps that include BBM, BlackBerry App World, BlackBerry Balance, BlackBerry Protect, and more. The Bold 9930 is essentially the Sprint version of the Bold 9900 that was announced for AT&T, except that it had a dual-mode GSM/CDMA chipset and is world phone compatible. Like the Bold 9900, the Bold 9930 is the thinnest BlackBerry yet at only 10.5mm (less than half an inch) thick. It has a 2.8-inch capacitive touch-screen display, which is a first for Bold handsets. It also has the widest QWERTY keyboard available on a BlackBerry, plus the usual optical trackpad. The Torch 9850 is the first full touch-screen BlackBerry available for Sprint, and it is the Sprint version of the Torch 9860 for AT&T. Like the Bold 9930, it has a dual-mode GSM/CDMA chipset for world travelers, plus a 3.7-inch display.
english
<reponame>ryoheinan/e-shoku-webapp<filename>.vscode/extensions.json { "recommendations": [ "ms-vscode-remote.vscode-remote-extensionpack", "redhat.vscode-yaml", "mikestead.dotenv", "saikou9901.evilinspector", "dbaeumer.vscode-eslint", "wix.vscode-import-cost", "zignd.html-css-class-completion", "esbenp.prettier-vscode", "github.vscode-pull-request-github", "formulahendry.auto-close-tag", "formulahendry.auto-rename-tag" ] }
json
<reponame>Juniper/gohan_webui /* global $ _ confirm*/ import Backbone from 'backbone'; import 'backbone-forms'; import ObjectListEditor from './objectListEditor'; Backbone.Form.editors.List = class List extends Backbone.Form.editors.Base { get events() { return { 'click [data-action="add"]': event => { event.stopPropagation(); event.preventDefault(); this.addItem(this.schema.default, true); }, 'click span.tab-delete': event => { event.stopPropagation(); event.preventDefault(); const item = _.findWhere(this.items, {cid: $(event.target).data('cid')}); if (item) { this.removeItem(item); } } }; } static template() { return _.template( '<div>' + ' <div data-items></div>' + ' <button type="button" data-action="add">Add</button>' + '</div>', Backbone.Form.templateSettings)(); } static objectTemplate() { return _.template( '<div class="object-list-container">' + ' <a class="add-item" data-action="add"><span class="fa fa-plus-circle"></span> Add Item</a>' + ' <ul class="nav nav-tabs object-list-tabs" role="tablist" data-tabs></ul>' + ' <div class="tab-content" data-items></div>' + '</div>', Backbone.Form.templateSettings)(); } constructor(options) { super(options); const editors = Backbone.Form.editors; const type = this.schema.itemType; if (!this.schema) { throw new Error('Missing required option \'schema\''); } // Default to Text if (!type) { this.Editor = editors.Text; } else if (editors.List[type]) { this.Editor = editors.List[type]; } else { this.Editor = editors[type]; } this.isObjectType = (type === 'Object'); this.items = []; } render() { const value = this.value || []; const $el = (this.isObjectType) ? $($.trim(List.objectTemplate())) : $($.trim(List.template())); this.$list = $el.is('[data-items]') ? $el : $el.find('[data-items]'); if (this.isObjectType) { this.$tab = $el.find('[data-tabs]'); } if (value.length) { value.forEach(itemValue => { this.addItem(itemValue); }); } if (this.isObjectType) { this.$tab.find('a[href="#tab-' + this.items[0].cid + '"]').tab('show'); this.items[0].$el.addClass('active in'); } this.setElement($el); this.$el.attr('id', this.id); this.$el.attr('name', this.key); if (this.hasFocus) this.trigger('blur', this); return this; } /** * Add a new item to the list * @param {Mixed} [value] Value for the new item editor * @param {Boolean} [userInitiated] If the item was added by the user clicking 'add' */ addItem(value, userInitiated) { const editors = Backbone.Form.editors; // Create the item const item = new editors.List.Item({ list: this, form: this.form, schema: this.schema, value, Editor: this.Editor, key: this.key }).render(); const tab = _.template( '<li role="presentation" class="object-list-tab">' + ' <a href="#tab-<%= cid %>" class="tab-link" aria-controls="tab-<%= cid %>" role="tab" data-toggle="tab">' + ' <span class="tab-title">Item</span>' + ' <span class="tab-delete fa fa-times-circle" data-cid="<%= cid %>"></span>' + ' </a>' + '</li>', Backbone.Form.templateSettings)({cid: item.cid}); const _addItem = () => { this.items.push(item); this.$list.append(item.el); if (this.isObjectType) { this.$tab.append(tab); this.$tab.find('a[href="#tab-' + item.cid + '"]').tab('show'); } item.editor.on('all', event => { if (event === 'change') return; // args = ["key:change", itemEditor, fieldEditor] var args = _.toArray(arguments); args[0] = 'item:' + event; args.splice(1, 0, this); // args = ["item:key:change", this=listEditor, itemEditor, fieldEditor] editors.List.prototype.trigger.apply(this, args); }, this); item.editor.on('change', function () { if (!item.addEventTriggered) { item.addEventTriggered = true; this.trigger('add', this, item.editor); } this.trigger('item:change', this, item.editor); this.trigger('change', this); }, this); item.editor.on('focus', function () { if (this.hasFocus) return; this.trigger('focus', this); }, this); item.editor.on('blur', () => { if (!this.hasFocus) return; setTimeout(() => { if (_.find(this.items, item => { return item.editor.hasFocus; })) return; this.trigger('blur', this); }, 0); }, this); if (userInitiated || value) { item.addEventTriggered = true; } if (userInitiated) { this.trigger('add', this, item.editor); this.trigger('change', this); } }; // Check if we need to wait for the item to complete before adding to the list if (this.Editor.isAsync) { item.editor.on('readyToAdd', _addItem, this); } else { // Most editors can be added automatically _addItem(); item.editor.focus(); } return item; } /** * Remove an item from the list * @param {List.Item} item */ removeItem(item) { // Confirm delete const confirmMsg = this.schema.confirmDelete; if (confirmMsg && !confirm(confirmMsg)) { // eslint-disable-line no-alert return; } const index = _.indexOf(this.items, item); this.items[index].remove(); this.items.splice(index, 1); if (this.isObjectType) { let prev = (index - 1 < 0) ? 0 : index - 1; this.$tab.children().eq(index).remove(); if (this.items.length > 0) { this.$tab.find('a[href="#tab-' + this.items[prev].cid + '"]').tab('show'); } } if (item.addEventTriggered) { this.trigger('remove', this, item.editor); this.trigger('change', this); } } /** * Move an item in the list * @param {List.Item} item * @param {String} direction */ moveItem(item, direction) { const index = _.indexOf(this.items, item); const $currentPane = this.$list.children().eq(index); let moveIndex = index - 1; if (direction === 'left') { $currentPane.insertBefore($currentPane.prev()); } else if (direction === 'right') { $currentPane.insertAfter($currentPane.next()); moveIndex++; } if (this.isObjectType) { const $currentTab = this.$tab.children().eq(index); if (direction === 'left') { $currentTab.insertBefore($currentTab.prev()); } else if (direction === 'right') { $currentTab.insertAfter($currentTab.next()); } } this.items.splice(moveIndex, 2, this.items[moveIndex + 1], this.items[moveIndex]); } getValue() { const values = _.map(this.items, function (item) { return item.getValue(); }); // Filter empty items return _.without(values, undefined, ''); } setValue(value) { this.value = value; this.render(); } focus() { if (this.hasFocus) return; if (this.items[0]) this.items[0].editor.focus(); } blur() { if (!this.hasFocus) return; var focusedItem = _.find(this.items, function (item) { return item.editor.hasFocus; }); if (focusedItem) focusedItem.editor.blur(); } /** * Override default remove function in order to remove item views */ remove() { _.invoke(this.items, 'remove'); Backbone.Form.editors.Base.prototype.remove.call(this); } /** * Run validation * * @return {Object|Null} */ validate() { if (!this.validators) return null; // Collect errors const errors = _.map(this.items, function (item) { return item.validate(); }); // Check if any item has errors const hasErrors = Boolean(_.compact(errors).length); if (!hasErrors) return null; // If so create a shared error var fieldError = { type: 'list', message: 'Some of the items in the list failed validation', errors }; return fieldError; } }; /** * A single item in the list * * @param {editors.List} options.list The List editor instance this item belongs to * @param {Function} options.Editor Editor constructor function * @param {String} options.key Model key * @param {Mixed} options.value Value * @param {Object} options.schema Field schema */ Backbone.Form.editors.List.Item = class ListItem extends Backbone.Form.editors.Base { get events() { return { 'click [data-action="remove"]': event => { event.stopPropagation(); event.preventDefault(); this.list.removeItem(this); }, 'click [data-action="move-left"]': event => { event.stopPropagation(); event.preventDefault(); this.list.moveItem(this, 'left'); }, 'click [data-action="move-right"]': event => { event.stopPropagation(); event.preventDefault(); this.list.moveItem(this, 'right'); }, 'keydown input[type=text]': event => { if (event.keyCode !== 13) return; event.stopPropagation(); event.preventDefault(); this.list.addItem(); this.list.$list.find('> li:last input').focus(); } }; } static template() { return _.template( '<div style="margin-bottom: 5px">' + ' <span data-editor></span>' + ' <button type="button" data-action="move-left">&and; up</button>' + ' <button type="button" data-action="move-right">&or; down</button>' + ' <button type="button" data-action="remove">&times; delete</button>' + '</div>', Backbone.Form.templateSettings)(); } static objectTemplate(data) { return _.template( '<div role="tabpanel" class="list-tab-pane tab-pane fade" id="tab-<%= cid %>">' + ' <div class="object-list-tab-pane">' + ' <div class="tab-pane-action">' + ' <a class="tab-pane-move-left" data-action="move-left">' + ' <span class="fa fa-angle-left"></span> Move Left' + ' </a>' + ' <a class="tab-pane-move-right" data-action="move-right">' + ' Move Right <span class="fa fa-angle-right"></span>' + ' </a>' + ' </div>' + ' <span data-editor></span>' + ' </div>' + '</div>', Backbone.Form.templateSettings)(data); } static errorClassName() { return 'error'; } constructor(options) { super(options); this.list = options.list; this.schema = options.schema || this.list.schema; this.value = options.value; this.Editor = options.Editor || Backbone.Form.editors.Text; this.key = options.key; this.template = options.template || this.schema.itemTemplate || this.constructor.template; this.errorClassName = options.errorClassName || this.constructor.errorClassName; this.form = options.form; } render() { // Create editor this.editor = new this.Editor({ key: this.key, schema: this.schema, value: this.value, list: this.list, item: this, form: this.form }).render(); // Create main element const $el = (this.list.isObjectType) ? $($.trim(this.constructor.objectTemplate({cid: this.cid}))) : $($.trim(this.template())); $el.find('[data-editor]').append(this.editor.el); // Replace the entire element so there isn't a wrapper tag this.setElement($el); return this; } getValue() { return this.editor.getValue(); } setValue(value) { this.editor.setValue(value); } focus() { this.editor.focus(); } blur() { this.editor.blur(); } remove() { this.editor.remove(); Backbone.View.prototype.remove.call(this); } validate() { const value = this.getValue(); const formValues = this.list.form ? this.list.form.getValue() : {}; const validators = this.schema.validators; const getValidator = this.getValidator; if (!validators) return null; // Run through validators until an error is found let error = null; _.every(validators, function (validator) { error = getValidator(validator)(value, formValues); return !error; }); // Show/hide error if (error) { this.setError(error); } else { this.clearError(); } // Return error to be aggregated by list return error ? error : null; } /** * Show a validation error */ setError(err) { this.$el.addClass(this.errorClassName); this.$el.attr('title', err.message); } /** * Hide validation errors */ clearError() { this.$el.removeClass(this.errorClassName); this.$el.attr('title', null); } }; Backbone.Form.editors.List.Object = ObjectListEditor;
javascript
<gh_stars>0 package frc.robot; import java.util.ArrayList; import com.ctre.phoenix.motorcontrol.can.TalonFX; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.Button; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.commands.*; import frc.robot.subsystems.*; import frc.robot.QAIModes.*; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final XboxController controller2; private final Joystick leftJoystick; private final Joystick rightJoystick; // private final MusicSubsystem musicSubsystem1; // private final MusicSubsystem musicSubsystem2; // private final MusicSubsystem musicSubsystem3; // private final MusicSubsystem musicSubsystem4; // private final MusicSubsystem musicSubsystem5; // private final MusicSubsystem musicSubsystem6; private final AMDB5Subsystem driveTrain; private final SkyHookSubsystem climb; private final ShakenNotStirredSubsystem intake; private final GoldenPP7Subsystem shooter; private final MoonRakerSubsystem vision; //private final Command m_autoCommand; SendableChooser<Command> qChooser = new SendableChooser<>(); // Add commands to the autonomous command chooser // The robot's subsystems and commands are defined here... /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { this.leftJoystick = new Joystick(0); this.rightJoystick = new Joystick(1); this.controller2 = new XboxController(2); // var instruments1 = new ArrayList<TalonFX>(); // instruments1.add(new TalonFX(5)); // var instruments2 = new ArrayList<TalonFX>(); // instruments2.add(new TalonFX(4)); // var instruments3 = new ArrayList<TalonFX>(); // instruments3.add(new TalonFX(3)); // var instruments4 = new ArrayList<TalonFX>(); // instruments4.add(new TalonFX(2)); // var instruments5 = new ArrayList<TalonFX>(); // instruments5.add(new TalonFX(30)); // var instruments6 = new ArrayList<TalonFX>(); // instruments6.add(new TalonFX(40)); // this.musicSubsystem1 = new MusicSubsystem(instruments1); // this.musicSubsystem1.load("songwii.chrp"); // this.musicSubsystem2 = new MusicSubsystem(instruments2); // this.musicSubsystem2.load("songwii.chrp"); // this.musicSubsystem3 = new MusicSubsystem(instruments3); // this.musicSubsystem3.load("songwii.chrp"); // this.musicSubsystem4 = new MusicSubsystem(instruments4); // this.musicSubsystem4.load("songwii.chrp"); // this.musicSubsystem5 = new MusicSubsystem(instruments5); // this.musicSubsystem5.load("songwii.chrp"); // this.musicSubsystem6 = new MusicSubsystem(instruments5); // this.musicSubsystem6.load("songwii.chrp"); // Button musicButton1 = new JoystickButton(controller2, XboxController.Button.kA.value); // musicButton1 // .whenPressed(() -> this.musicSubsystem1.play()); // Button musicButton2 = new JoystickButton(controller2, XboxController.Button.kA.value); // musicButton2 // .whenPressed(() -> this.musicSubsystem2.play()); // Button musicButton3 = new JoystickButton(controller2, XboxController.Button.kA.value); // musicButton3 // .whenPressed(() -> this.musicSubsystem3.play()); // Button musicButton4 = new JoystickButton(controller2, XboxController.Button.kA.value); // musicButton4 // .whenPressed(() -> this.musicSubsystem4.play()); // Button musicButton5 = new JoystickButton(controller2, XboxController.Button.kA.value); // musicButton5 // .whenPressed(() -> this.musicSubsystem5.play()); // Button musicButton6 = new JoystickButton(controller2, XboxController.Button.kA.value); // musicButton6 // .whenPressed(() -> this.musicSubsystem6.play()); this.driveTrain = new AMDB5Subsystem(); this.climb = new SkyHookSubsystem(); this.intake = new ShakenNotStirredSubsystem(); this.vision = new MoonRakerSubsystem(); this.shooter = new GoldenPP7Subsystem(); Command regular = new QAIRegular(driveTrain, intake, vision, shooter); Command shortauton = new QAIShort(driveTrain, intake, vision, shooter); Command threeball = new QAI3Ball(driveTrain, shooter, vision, intake); driveTrain.setDefaultCommand(new AMDB5Command(driveTrain,leftJoystick,rightJoystick, controller2)); climb.setDefaultCommand(new SkyHookCommand(climb, rightJoystick, controller2)); intake.setDefaultCommand(new ShakenNotStirredCommand(intake, leftJoystick, rightJoystick, controller2)); shooter.setDefaultCommand(new GoldenPP7Command(shooter, leftJoystick, rightJoystick, controller2, vision)); configureButtonBindings(); qChooser.setDefaultOption("Regular Auton", regular); qChooser.addOption("Short Auton (for the wall)", shortauton); qChooser.addOption("3 Balls Auton", threeball); // Put the chooser on the dashboard SmartDashboard.putData(qChooser); } /** * Use this method to define your button->command mappings. Buttons can be created by * instantiating a {@link GenericHID} or one of its subclasses ({@link * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link * edu.wpi.first.wpilibj2.command.button.JoystickButton}. */ private void configureButtonBindings() { // Button visionButton = new JoystickButton(controller1, XboxController.Button.kBack.value); // visionButton // .whenPressed(new QSpikeFanOnCommand(shooter, vision)); } /** * Use this to pass the autonomous command to the main {@link Robot} class. * * @return the command to run in autonomous */ public Command getAutonomousCommand() { // An ExampleCommand will run in autonomous return qChooser.getSelected(); } }
java
<reponame>salahgapr5/snif package keeper import ( "fmt" "github.com/Sifchain/sifnode/x/faucet/types" "github.com/cosmos/cosmos-sdk/store/prefix" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) // Keeper of the faucet store type Keeper struct { storeKey sdk.StoreKey cdc *codec.Codec supplyKeeper types.SupplyKeeper bankKeeper types.BankKeeper } // NewKeeper creates a faucet keeper func NewKeeper(supplyKeeper types.SupplyKeeper, cdc *codec.Codec, key sdk.StoreKey, bankKeeper types.BankKeeper) Keeper { keeper := Keeper{ supplyKeeper: supplyKeeper, bankKeeper: bankKeeper, storeKey: key, cdc: cdc, // paramspace: paramspace.WithKeyTable(types.ParamKeyTable()), } return keeper } // Logger returns a module-specific logger. func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } func (k Keeper) GetBankKeeper() types.BankKeeper { return k.bankKeeper } func (k Keeper) GetSupplyKeeper() types.SupplyKeeper { return k.supplyKeeper } // GetWithdrawnAmountInEpoch validates if a user has utilized faucet functionality within the last 4 hours // If a withdrawal action has occurred the module will block withdraws until the timer is reset func (k Keeper) GetWithdrawnAmountInEpoch(ctx sdk.Context, user string, token string) (sdk.Int, error) { faucetTracker := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.FaucetPrefix)) ok := faucetTracker.Has(types.GetBalanceKey(user, token)) if !ok { return sdk.ZeroInt(), nil } amount := faucetTracker.Get(types.GetBalanceKey(user, token)) var am sdk.Int err := k.cdc.UnmarshalBinaryBare(amount, &am) if err != nil { return sdk.ZeroInt(), err } return am, nil } func (k Keeper) SetWithdrawnAmountInEpoch(ctx sdk.Context, user string, amount sdk.Int, token string) error { faucetTracker := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.FaucetPrefix)) withdrawnAmount, err := k.GetWithdrawnAmountInEpoch(ctx, user, token) if err != nil { return err } totalAmountInEpoch := withdrawnAmount.Add(amount) bz, err := k.cdc.MarshalBinaryBare(&totalAmountInEpoch) if err != nil { return err } faucetTracker.Set(types.GetBalanceKey(user, token), bz) return nil } func (k Keeper) StartNextEpoch(ctx sdk.Context) { faucetTracker := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(faucetTracker, types.KeyPrefix(types.FaucetPrefix)) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { faucetTracker.Delete(iterator.Key()) } } func (k Keeper) CanRequest(ctx sdk.Context, user string, coins sdk.Coins) (bool, error) { alreadyWithraw, err := k.GetWithdrawnAmountInEpoch(ctx, user, types.FaucetToken) if err != nil { return false, err } maxAllowedWithdraw, ok := sdk.NewIntFromString(types.MaxWithdrawAmountPerEpoch) if !ok { return false, nil } amount := coins.AmountOf(types.FaucetToken) if alreadyWithraw.Add(amount).GT(maxAllowedWithdraw) { return false, types.ErrInvalid } return true, nil } func (k Keeper) ExecuteRequest(ctx sdk.Context, user string, coins sdk.Coins) (bool, error) { amount := coins.AmountOf(types.FaucetToken) err := k.SetWithdrawnAmountInEpoch(ctx, user, amount, types.FaucetToken) if err != nil { return false, err } return true, nil }
go
New Delhi: India's rainfed agriculture region is set to receive above normal rainfall this monsoon season, the weather office said on Tuesday raising hopes for a bumper farm output and reining in inflation. "The average rainfall this monsoon season is expected to be 103% of the long period average," India Meteorological Department Director General Mrutyunjay Mohapatra told reporters here. In April, the IMD had said the country would receive normal rainfall -- 99 per cent of the long period average (LPA), which is the mean rainfall received over a 50-year-period from 1971-2020. The LPA for the entire country is 87 cm. The monsoon core zone - states ranging from Gujarat to Odisha that are dependent on rainfall for agriculture - is set to experience above normal rainfall at more than 106 per cent of the long period average, Mohapatra said. He said central India and south peninsula are set to receive above normal rainfall, while north-east and north-west regions are likely to get normal rains. This is the fourth consecutive year that India is likely to experience a normal monsoon. Earlier, India had witnessed normal monsoon from 2005-08 and 2010-13. Mohapatra said in the near future, India could witness normal monsoons as the decadal epoch of below normal rains was nearing its end. "We are now moving towards a normal monsoon epoch," he said. Asked about the criticism faced by IMD for "hasty" declaration of monsoon onset over Kerala, Mohapatra said the weather office followed a scientific process to announce the onset and progress of monsoon. He asserted that 70 per cent of the weather stations in Kerala had reported fairly widespread rainfall and other parameters related to strong westerly winds and cloud formation over the region were fulfilled. Mohapatra said the prevailing La Nina conditions, which refer to the cooling of the equatorial Pacific region, were expected to continue till August and augur well for the monsoon rains in India. However, the possibility of development of negative Indian Ocean Dipole, which refers to cooler than normal sea surface temperatures in the western Indian Ocean, could lead to below normal rainfall in extreme southwestern peninsula that includes Kerala.
english
<reponame>vincentbin/DesignPattern-Java<gh_stars>1-10 package interfaces; public interface Invocation { /** * 调用 * @return */ Object invoke(); }
java
Braun Strowman vs Roman Reigns for the Universal Championship is set to happen at the WWE's upcoming pay-per-view - Hell in a Cell. Many speculations have been made about the winner of this match, and there are many things WWE could do to make this match more interesting. However, WWE has already done many things in this feud including Strowman's heel turn, and there are some things they should avoid at any cost in this rivalry. The pay-per-view is just a few days away and there is still one episode of Raw and SmackDown remaining. Today, we will take a look at 2 things the WWE should avoid during Braun Strowman vs Roman Reigns at Hell in a Cell, and 1 they should do. WWE is doing everything they can do to make Reigns 'the fan favorite' wrestler. They let him defeat The UnderTaker, turned Strowman and Lesnar heel, and even gave him the Universal Title. However, none of these seemed to work, and at Hell in a Cell we might see something the fans will never wish to see. Recently on Raw, Strowman turned heel against Reigns in a tag team match, and since then has been playing a heel character. At the upcoming pay-per-view, Reigns' winning chances are higher than Strowman winning the title. Reigns' victory will definitely make the fans angry as Strowman will then lose his Money in the Bank briefcase. They already did this last year with Corbin, and now they shouldn't repeat it again. For the past few weeks, The Shield and the current Raw tag team champions have been playing a major role in building this feud. Last week, during a Raw segment, Rollins got legitimately injured after breaking a Police Van window. Fans will definitely expect more from the WWE rather than just a classic encounter between Reigns and Strowman. An outside interference from The Shield or the Tag Team Champions will not disappoint the fans, and it will only make this match more interesting to see. This interference can also lead to a future match between The Shield and the trio of Strowman, Ziggler, and McIntyre at Survivor Series, where Ziggler and McIntyre will defend their titles, whereas Strowman will fight for the Universal Championship. For the past weeks, Monday Night Raw has been revolving around the Reigns vs Strowman rivalry, and after weeks of strong build-up, a clean ending to the match will not be a good idea. WWE should avoid this. To make this match much more interesting, they could end this match in a controversy. We already saw a classic rivalry between these two wrestlers, and now the WWE have to do something else to make the match more interesting. A heel turn from Ambrose will not hurt the fans, especially if he turns against Reigns. This will add more heat to this match than ever before, and it will surely increase Raw's ratings.
english
Nokia has a wide range of offerings across different price points. This year, the company came up with the flagship Nokia 9 PureView, which is a flagship device with a penta-lens camera setup. Apart from this, even the Nokia X71, Nokia 4. 2 and Nokia 3. 2 smartphones went official this year. Now, it looks like the company is in plans to unveil an upper mid-range smartphone. Going by a recent report from MySmartPrice, this upcoming smartphone could be the Nokia 8. 2. The report touts that the device in the making might feature a 32MP selfie camera housed within a pop-up mechanism. The report adds that the Nokia 8. 2 could be preloaded with Android Q, which is the latest iteration of the OS that might be rolled out commercially in August. Given that the Nokia smartphones launched to date belong to the Android One program, we can expect this new offering to also be launched under this program. The other aspect that is known is that the Nokia 8. 2 might feature 8GB RAM and 256GB of storage space. As of now, there are no other details regarding this device. Given that its predecessor, the Nokia 8. 1 comes with a Snapdragon 710 processor and dual rear cameras, we can expect this one to be launched with a Snapdragon 730 or 730G or 735 processor. Apart from these few details, the report does not reveal the possible design or renders of the upcoming Nokia smartphone. The latest Snapdragon 700 series smartphones support the next-generation network making it an affordable 5G smartphone. Moreover, the Nokia 8. 1 features a premium build quality and a notch display. And, this makes us believe that its successor could also be launched with the same build quality. Though the report speculates about the Nokia 8. 2, there is no confirmation regarding the same from the company. Maybe it could be the global variant of the Nokia X71. Also, there are speculations regarding the Nokia 6. 2, so there is a possibility for it to also be launched this year.
english
The fiancée of Texas men's basketball head coach Chris Beard said that he didn't strangle her in an alleged domestic violence encounter that led to his arrest and suspension last week. In a statement released Friday through her attorney, the woman apologized for the situation and said she initiated a physical confrontation with Beard, whom she said acted in self-defense. She also said she told law enforcement that he did not strangle her that night. The full statement: "Chris and I are deeply saddened that we have brought negative attention upon our family, friends, and the University of Texas, among others. As Chris' fiancé and biggest supporter, I apologize for the role I played in this unfortunate event. I realize that my frustration, when breaking his glasses, initiated a physical struggle between Chris and myself. Chris did not strangle me, and I told that to law enforcement that evening. Chris has stated that he was acting in self-defense, and I do not refute that. I do not believe Chris was trying to intentionally harm me in any way. It was never my intent to have him arrested or prosecuted. We appreciate everyone's support and prayers during this difficult time." Asked to respond to the statement from Beard's accuser, Beard's attorney, Perry Minton, told Yahoo Sports on Saturday morning that she's "a smart and independent woman." Neither Minton nor the woman's attorney, Randy Leavitt, responded when asked by Yahoo Sports if she or Beard have been in contact with the Austin police department or the University of Texas since she requested that the charge be dropped. Beard was arrested in the early morning of Dec. 12 and charged with third-degree assault on a family or household member/impeding breath circulation. He was later released on $10,000 bail with the condition that he not go within 200 yards of the alleged victim or the home they reportedly shared. An Austin police spokesperson told Yahoo Sports that they received a 911 call at 12:15 a.m. on Dec. 12. They immediately dispatched officers to a home on the 1900 block of Vista Lane in Tarrytown, an upscale Austin neighborhood near the UT campus. According to first obtained by the , a woman answered the door and identified herself as Beard's fiancee. She said that she and Beard had been arguing and that Beard “just snapped” and “became super violent." Beard, the woman told officers the night of the incident, "choked me, threw me off the bed, bit me, bruises all over my leg, throwing me around, and going nuts." She said Beard choked her from behind for “like 5 seconds” hard enough that she couldn’t breathe. Texas suspended Beard indefinitely shortly before its game Dec. 12 and has since won three games without him. The team has been playing with associate head coach Rodney Terry as its acting head coach. Yahoo Sports' Jeff Eisenberg contributed to this report.
english
<filename>src/scripts/build.js const debug = require('debug')('frans:build'); const { isNil, is, has, prop, propIs } = require('ramda'); const { promisify } = require('util'); const rimraf = promisify(require('rimraf')); const runScript = require('../utils/run-script'); const { resolveBin, hasFile, hasPkgProp, reformatFlags, fromRoot, } = require('../utils'); function build(configPath) { if (isNil(configPath) || !is(String, configPath)) { throw new Error( `You must specify a default config path (as string) to command build`, ); } return async args => { debug('Setup script build'); const hasArg = p => has(p, args); const getArg = p => prop(p, args); const argIsString = p => propIs(String, p, args); const useBuiltinConfig = !hasArg('presets') && !hasFile('.babelrc') && !hasPkgProp('babel'); debug(`Use builtin config: ${useBuiltinConfig}`); const useBuiltinIgnore = !hasArg('ignore'); debug(`Use builtin ignore: ${useBuiltinIgnore}`); const useBuiltinOutDir = !hasArg('out-dir') || !argIsString('out-dir'); debug(`Use builtin out dir: ${useBuiltinOutDir}`); const useBuiltinCopy = !hasArg('copy-files') || getArg('copy-files'); debug(`Use builtin copy: ${useBuiltinCopy}`); const useBuiltinClean = !hasArg('clean') || getArg('clean'); debug(`Use builtin clean: ${useBuiltinClean}`); const config = useBuiltinConfig ? ['--presets', configPath] : hasArg('presets') && argIsString('presets') ? ['--presets', getArg('presets')] : []; const ignore = useBuiltinIgnore ? ['--ignore', '__tests__,__mocks__,*.test.js,*.spec.js'] : hasArg('ignore') && argIsString('ignore') ? ['--ignore', getArg('ignore')] : []; const outDir = useBuiltinOutDir ? ['--out-dir', 'dist'] : ['--out-dir', getArg('out-dir')]; const copyFiles = useBuiltinCopy ? ['--copy-files'] : []; const flags = reformatFlags(args, [ 'presets', 'ignore', 'out-dir', 'copy-files', 'clean', 'debug', ]); const bin = resolveBin('babel-cli', { executable: 'babel' }); const commandArgs = [ 'src', ...outDir, ...config, ...ignore, ...copyFiles, ...flags, ]; const out = fromRoot(outDir[1]); if (useBuiltinClean) await rimraf(out); return runScript(bin, commandArgs); }; } module.exports = build;
javascript
[{"transactionDate":"103.04.26","produceNumber":"70","produceName":"\u5c0f\u756a\u8304-\u5176\u4ed6","marketNumber":"338","marketName":"\u6843\u5712\u7e23","topPrice":"15","middlePrice":"13","lowPrice":"10","averagePrice":"13","transactionAmount":"272","number":"70","main_category":"fruit","sub_category":""},{"transactionDate":"103.04.26","produceNumber":"I4","produceName":"\u6728\u74dc-\u9752\u6728\u74dc","marketNumber":"338","marketName":"\u6843\u5712\u7e23","topPrice":"13","middlePrice":"13","lowPrice":"13","averagePrice":"13","transactionAmount":"24","number":"I4","main_category":"fruit","sub_category":""},{"transactionDate":"103.04.26","produceNumber":"B2","produceName":"\u9cf3\u68a8-\u91d1\u947d\u9cf3\u68a8","marketNumber":"338","marketName":"\u6843\u5712\u7e23","topPrice":"35","middlePrice":"35","lowPrice":"35","averagePrice":"35","transactionAmount":"48","number":"B2","main_category":"fruit","sub_category":""},{"transactionDate":"103.04.26","produceNumber":"72","produceName":"\u5c0f\u756a\u8304-\u8056\u5973","marketNumber":"338","marketName":"\u6843\u5712\u7e23","topPrice":"76.3","middlePrice":"37","lowPrice":"10.3","averagePrice":"37","transactionAmount":"429","number":"72","main_category":"fruit","sub_category":""},{"transactionDate":"103.04.26","produceNumber":"F1","produceName":"\u6ab8\u6aac-\u6ab8\u6aac","marketNumber":"338","marketName":"\u6843\u5712\u7e23","topPrice":"69","middlePrice":"69","lowPrice":"69","averagePrice":"69","transactionAmount":"10","number":"F1","main_category":"fruit","sub_category":""}]
json
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. console.log("Hello world"); const testChannelId = 164; const testProgramId = 2023; const testEpisodeId = 1738930; const client = new SrApiClient(); client.getChannels( Format.Json, undefined, undefined, undefined, undefined, undefined ).then(response => { console.log("*** Got " + response.channels.length + " channels."); for (let i = 0; i < response.channels.length; i++) { const channel = response.channels[i]; console.log(); console.log("id: " + channel.id); console.log("name: " + channel.name); console.log("channeltype: " + channel.channeltype); console.log("color: " + channel.color); console.log("image: " + channel.image); console.log("imagetemplate: " + channel.imagetemplate); console.log("liveaudio.id: " + channel.liveaudio?.id); console.log("liveaudio.statkey: " + channel.liveaudio?.statkey); console.log("liveaudio.url: " + channel.liveaudio?.url); console.log("scheduleurl: " + channel.scheduleurl); console.log("siteurl: " + channel.siteurl); console.log("tagline: " + channel.tagline); console.log("xmltvid: " + channel.xmltvid); } console.log("Requesting single channel " + response.channels[0].id); client.getChannel( Format.Json, response.channels[0].id, undefined, undefined ).then(response => { console.log("*** Got single channel response."); const channel = response.channel; console.log(); console.log("id: " + channel.id); console.log("name: " + channel.name); console.log("channeltype: " + channel.channeltype); console.log("color: " + channel.color); console.log("image: " + channel.image); console.log("imagetemplate: " + channel.imagetemplate); console.log("liveaudio.id: " + channel.liveaudio?.id); console.log("liveaudio.statkey: " + channel.liveaudio?.statkey); console.log("liveaudio.url: " + channel.liveaudio?.url); console.log("scheduleurl: " + channel.scheduleurl); console.log("siteurl: " + channel.siteurl); console.log("tagline: " + channel.tagline); console.log("xmltvid: " + channel.xmltvid); }); }); client.getProgramCategories( Format.Json, undefined, undefined ).then(response => { console.log("*** Got " + response.programcategories.length + " program categories."); for (let i = 0; i < response.programcategories.length; i++) { const category = response.programcategories[i]; console.log(); console.log("id: " + category.id); console.log("name: " + category.name); } console.log("Requesting single category " + response.programcategories[0].id); client.getProgramCategory( Format.Json, response.programcategories[0].id ).then(response => { console.log("*** Got single program category response."); const category = response.programcategory; console.log(); console.log("id: " + category.id); console.log("name: " + category.name); }); }); client.getPrograms( Format.Json, undefined, undefined, undefined, undefined ).then(response => { console.log("*** Got " + response.programs.length + " programs."); for (let i = 0; i < response.programs.length; i++) { const program = response.programs[i]; console.log(); console.log("id: " + program.id); console.log("name: " + program.name); console.log("archived: " + program.archived); console.log("broadcastinfo: " + program.broadcastinfo); console.log("channel.id: " + program.channel?.id); console.log("channel.name: " + program.channel?.name); console.log("description: " + program.description); console.log("email: " + program.email); console.log("hasondemand: " + program.hasondemand); console.log("haspod: " + program.haspod); console.log("payoff: " + program.payoff); console.log("phone: " + program.phone); console.log("programcategory.id: " + program.programcategory?.id); console.log("programcategory.name: " + program.programcategory?.name); console.log("programimage: " + program.programimage); console.log("programimagetemplate: " + program.programimagetemplate); console.log("programimagetemplatewide: " + program.programimagetemplatewide); console.log("programimagewide: " + program.programimagewide); console.log("programslug: " + program.programslug); console.log("programurl: " + program.programurl); console.log("responsibleeditor: " + program.responsibleeditor); console.log("socialimage: " + program.socialimage); console.log("socialimagetemplate: " + program.socialimagetemplate); console.log("socialmediaplatforms: " + program.socialmediaplatforms); } console.log("Requesting single program " + response.programs[0].id); client.getProgram( Format.Json, response.programs[0].id ).then(response => { console.log("*** Got single program response."); const program = response.program; console.log(); console.log("id: " + program.id); console.log("name: " + program.name); }); }); client.getEpisodes( Format.Json, undefined, undefined, testProgramId, undefined, undefined, undefined ).then(response => { console.log("*** Got " + response.episodes.length + " episodes."); for (let i = 0; i < response.episodes.length; i++) { const program = response.episodes[i]; console.log(); console.log("id: " + program.id); console.log("title: " + program.title); console.log("audiopreference: " + program.audiopreference); console.log("audiopresentation: " + program.audiopresentation); console.log("audiopriority: " + program.audiopriority); console.log("program.broadcast.availablestoputc: " + program.broadcast?.availablestoputc); console.log("broadcasttime?.starttimeutc: " + program.broadcasttime?.starttimeutc); console.log("broadcasttime?.endtimeutc: " + program.broadcasttime?.endtimeutc); console.log("channelid: " + program.channelid); console.log("description: " + program.description); console.log("imageurl: " + program.imageurl); console.log("imageurltemplate: " + program.imageurltemplate); console.log("program.id: " + program.program?.id); console.log("program.name: " + program.program?.name); console.log("publishdateutc: " + program.publishdateutc); console.log("url: " + program.url); console.log("downloadpodfile.availablefromutc: " + program.downloadpodfile?.availablefromutc); console.log("listenpodfile.availablefromutc: " + program.listenpodfile?.availablefromutc); } console.log("Requesting single episode " + response.episodes[0].id); client.getEpisode( Format.Json, response.episodes[0].id, undefined ).then(response => { console.log("*** Got single episode response."); const program = response.episode; console.log(); console.log("id: " + program.id); console.log("title: " + program.title); }); }); client.searchEpisodes( Format.Json, undefined, undefined, "sport", undefined ).then(response => { console.log("*** Got " + response.episodes.length + " episodes."); for (let i = 0; i < response.episodes.length; i++) { const program = response.episodes[i]; console.log(); console.log("id: " + program.id); console.log("title: " + program.title); console.log("audiopreference: " + program.audiopreference); console.log("audiopresentation: " + program.audiopresentation); console.log("audiopriority: " + program.audiopriority); console.log("program.broadcast.availablestoputc: " + program.broadcast?.availablestoputc); console.log("broadcasttime?.starttimeutc: " + program.broadcasttime?.starttimeutc); console.log("broadcasttime?.endtimeutc: " + program.broadcasttime?.endtimeutc); console.log("channelid: " + program.channelid); console.log("description: " + program.description); console.log("imageurl: " + program.imageurl); console.log("imageurltemplate: " + program.imageurltemplate); console.log("program.id: " + program.program?.id); console.log("program.name: " + program.program?.name); console.log("publishdateutc: " + program.publishdateutc); console.log("url: " + program.url); console.log("downloadpodfile.availablefromutc: " + program.downloadpodfile?.availablefromutc); console.log("listenpodfile.availablefromutc: " + program.listenpodfile?.availablefromutc); } }); client.getPlaylistRightNow( Format.Json, testChannelId ).then(response => { console.log("*** Got right now playlist."); const playlist = response.playlist; console.log(); console.log("channel.id: " + playlist.channel?.id); console.log("channel.name: " + playlist.channel?.name); console.log("previoussong.albumname " + playlist.previoussong?.albumname); console.log("previoussong.artist: " + playlist.previoussong?.artist); console.log("previoussong.composer: " + playlist.previoussong?.composer); console.log("previoussong.conductor: " + playlist.previoussong?.conductor); console.log("previoussong.description: " + playlist.previoussong?.description); console.log("previoussong.lyricist: " + playlist.previoussong?.lyricist); console.log("previoussong.producer: " + playlist.previoussong?.producer); console.log("previoussong.recordlabel: " + playlist.previoussong?.recordlabel); console.log("previoussong.starttimeutc: " + playlist.previoussong?.starttimeutc); console.log("previoussong.stoptimeutc: " + playlist.previoussong?.stoptimeutc); console.log("previoussong.title: " + playlist.previoussong?.title); console.log("song.albumname " + playlist.song?.albumname); console.log("song.artist: " + playlist.song?.artist); console.log("song.composer: " + playlist.song?.composer); console.log("song.conductor: " + playlist.song?.conductor); console.log("song.description: " + playlist.song?.description); console.log("song.lyricist: " + playlist.song?.lyricist); console.log("song.producer: " + playlist.song?.producer); console.log("song.recordlabel: " + playlist.song?.recordlabel); console.log("song.starttimeutc: " + playlist.song?.starttimeutc); console.log("song.stoptimeutc: " + playlist.song?.stoptimeutc); console.log("nextsong.title: " + playlist.nextsong?.title); console.log("nextsong.albumname " + playlist.nextsong?.albumname); console.log("nextsong.artist: " + playlist.nextsong?.artist); console.log("nextsong.composer: " + playlist.nextsong?.composer); console.log("nextsong.conductor: " + playlist.nextsong?.conductor); console.log("nextsong.description: " + playlist.nextsong?.description); console.log("nextsong.lyricist: " + playlist.nextsong?.lyricist); console.log("nextsong.producer: " + playlist.nextsong?.producer); console.log("nextsong.recordlabel: " + playlist.nextsong?.recordlabel); console.log("nextsong.starttimeutc: " + playlist.nextsong?.starttimeutc); console.log("nextsong.stoptimeutc: " + playlist.nextsong?.stoptimeutc); console.log("nextsong.title: " + playlist.nextsong?.title); }); client.getPlaylistByChannel( Format.Json, undefined, testChannelId, undefined, undefined ).then(response => { console.log("*** Got " + response.song.length + " songs for channel " + testChannelId + "."); for (let i = 0; i < response.song.length; i++) { const song = response.song[i]; console.log(); console.log("song.albumname " + song.albumname); console.log("song.artist: " + song.artist); console.log("song.composer: " + song.composer); console.log("song.conductor: " + song.conductor); console.log("song.description: " + song.description); console.log("song.lyricist: " + song.lyricist); console.log("song.producer: " + song.producer); console.log("song.recordlabel: " + song.recordlabel); console.log("song.starttimeutc: " + song.starttimeutc); console.log("song.stoptimeutc: " + song.stoptimeutc); } }); client.getPlaylistByProgram( Format.Json, undefined, testProgramId, undefined, undefined ).then(response => { console.log("*** Got " + response.song.length + " songs for program " + testProgramId + "."); for (let i = 0; i < response.song.length; i++) { const song = response.song[i]; console.log(); console.log("song.albumname " + song.albumname); console.log("song.artist: " + song.artist); console.log("song.composer: " + song.composer); console.log("song.conductor: " + song.conductor); console.log("song.description: " + song.description); console.log("song.lyricist: " + song.lyricist); console.log("song.producer: " + song.producer); console.log("song.recordlabel: " + song.recordlabel); console.log("song.starttimeutc: " + song.starttimeutc); console.log("song.stoptimeutc: " + song.stoptimeutc); } }); client.getPlaylistByEpisode( Format.Json, testEpisodeId ).then(response => { console.log("*** Got " + response.song.length + " songs for episode " + testEpisodeId + "."); for (let i = 0; i < response.song.length; i++) { const song = response.song[i]; console.log(); console.log("song.albumname " + song.albumname); console.log("song.artist: " + song.artist); console.log("song.composer: " + song.composer); console.log("song.conductor: " + song.conductor); console.log("song.description: " + song.description); console.log("song.lyricist: " + song.lyricist); console.log("song.producer: " + song.producer); console.log("song.recordlabel: " + song.recordlabel); console.log("song.starttimeutc: " + song.starttimeutc); console.log("song.stoptimeutc: " + song.stoptimeutc); } }); client.getNewsPrograms( Format.Json ).then(response => { console.log("*** Got " + response.programs.length + " news programs."); for (let i = 0; i < response.programs.length; i++) { const program = response.programs[i]; console.log(); console.log("id: " + program.id); console.log("name: " + program.name); console.log("archived: " + program.archived); console.log("channel.id: " + program.channel?.id); console.log("channel.name: " + program.channel?.name); console.log("hasondemand: " + program.hasondemand); console.log("haspod: " + program.haspod); console.log("programcategory.id: " + program.programcategory?.id); console.log("programcategory.name: " + program.programcategory?.name); console.log("programimage: " + program.programimage); console.log("programimagetemplate: " + program.programimagetemplate); console.log("programimagetemplatewide: " + program.programimagetemplatewide); console.log("programimagewide: " + program.programimagewide); console.log("programslug: " + program.programslug); console.log("programurl: " + program.programurl); console.log("responsibleeditor: " + program.responsibleeditor); console.log("socialimage: " + program.socialimage); console.log("socialimagetemplate: " + program.socialimagetemplate); console.log("socialmediaplatforms: " + program.socialmediaplatforms); } }); client.getNewsEpisodes( Format.Json, undefined ).then(response => { console.log("*** Got " + response.episodes.length + " episodes."); for (let i = 0; i < response.episodes.length; i++) { const program = response.episodes[i]; console.log(); console.log("id: " + program.id); console.log("title: " + program.title); console.log("audiopreference: " + program.audiopreference); console.log("audiopresentation: " + program.audiopresentation); console.log("audiopriority: " + program.audiopriority); console.log("program.broadcast.availablestoputc: " + program.broadcast?.availablestoputc); console.log("broadcasttime?.starttimeutc: " + program.broadcasttime?.starttimeutc); console.log("broadcasttime?.endtimeutc: " + program.broadcasttime?.endtimeutc); console.log("channelid: " + program.channelid); console.log("description: " + program.description); console.log("imageurl: " + program.imageurl); console.log("imageurltemplate: " + program.imageurltemplate); console.log("program.id: " + program.program?.id); console.log("program.name: " + program.program?.name); console.log("publishdateutc: " + program.publishdateutc); console.log("url: " + program.url); console.log("downloadpodfile.url: " + program.downloadpodfile?.url); console.log("listenpodfile.url: " + program.listenpodfile?.url); } }); client.getExtraBroadcasts( Format.Json, undefined, undefined ).then(response => { console.log("*** Got " + response.broadcasts.length + " broadcasts."); for (let i = 0; i < response.broadcasts.length; i++) { const program = response.broadcasts[i]; console.log(); console.log("id: " + program.id); console.log("channel.id: " + program.channel?.id); console.log("channel.name: " + program.channel?.name); console.log("description: " + program.description); console.log("liveaudio.url: " + program.liveaudio?.url); console.log("liveaudio.statkey: " + program.liveaudio?.statkey); console.log("localstarttime: " + program.localstarttime); console.log("localstoptime: " + program.localstoptime); console.log("mobileliveaudio.url: " + program.mobileliveaudio?.url); console.log("mobileliveaudio.statkey: " + program.mobileliveaudio?.statkey); console.log("name: " + program.name); console.log("publisher.id: " + program.publisher?.id); console.log("publisher.name: " + program.publisher?.name); console.log("sport: " + program.sport); } }); client.getScheduledEpisodesForChannel( Format.Json, undefined, undefined, testChannelId, undefined ).then(response => { console.log("*** Got " + response.schedule.length + " schedule."); for (let i = 0; i < response.schedule.length; i++) { const scheduledEpisode = response.schedule[i]; console.log(); console.log("episodeid: " + scheduledEpisode.episodeid); console.log("channel.id: " + scheduledEpisode.channel?.id); console.log("channel.name: " + scheduledEpisode.channel?.name); console.log("description: " + scheduledEpisode.description); console.log("endtimeutc: " + scheduledEpisode.endtimeutc); console.log("imageurl: " + scheduledEpisode.imageurl); console.log("imageurltemplate: " + scheduledEpisode.imageurltemplate); console.log("program.id: " + scheduledEpisode.program?.id); console.log("program.name: " + scheduledEpisode.program?.name); console.log("starttimeutc: " + scheduledEpisode.starttimeutc); console.log("title: " + scheduledEpisode.title); } }); client.getScheduledEpisodesForProgram( Format.Json, undefined, undefined, testProgramId, new Date(2020, 1, 1), new Date(2021, 1, 1) ).then(response => { console.log("*** Got " + response.schedule.length + " schedule."); for (let i = 0; i < response.schedule.length; i++) { const scheduledEpisode = response.schedule[i]; console.log(); console.log("episodeid: " + scheduledEpisode.episodeid); console.log("channel.id: " + scheduledEpisode.channel?.id); console.log("channel.name: " + scheduledEpisode.channel?.name); console.log("description: " + scheduledEpisode.description); console.log("endtimeutc: " + scheduledEpisode.endtimeutc); console.log("imageurl: " + scheduledEpisode.imageurl); console.log("imageurltemplate: " + scheduledEpisode.imageurltemplate); console.log("program.id: " + scheduledEpisode.program?.id); console.log("program.name: " + scheduledEpisode.program?.name); console.log("starttimeutc: " + scheduledEpisode.starttimeutc); console.log("title: " + scheduledEpisode.title); } }); client.getEpisodesRightNowAllChannels( Format.Json, undefined, undefined ).then(response => { console.log("*** Got " + response.channels.length + " channels."); for (let i = 0; i < response.channels.length; i++) { const channel = response.channels[i]; console.log(); console.log("id: " + channel.id); console.log("name: " + channel.name); console.log("previousscheduledepisode.description: " + channel.previousscheduledepisode?.description); console.log("previousscheduledepisode.endtimeutc: " + channel.previousscheduledepisode?.endtimeutc); console.log("previousscheduledepisode.episodeid;: " + channel.previousscheduledepisode?.episodeid); console.log("previousscheduledepisode.program.id: " + channel.previousscheduledepisode?.program?.id); console.log("previousscheduledepisode.program.name: " + channel.previousscheduledepisode?.program?.name); console.log("previousscheduledepisode.socialimage: " + channel.previousscheduledepisode?.socialimage); console.log("previousscheduledepisode.starttimeut: " + channel.previousscheduledepisode?.starttimeutc); console.log("previousscheduledepisode.title: " + channel.previousscheduledepisode?.title); console.log("currentscheduledepisode.description: " + channel.currentscheduledepisode?.description); console.log("currentscheduledepisode.endtimeutc: " + channel.currentscheduledepisode?.endtimeutc); console.log("currentscheduledepisode.episodeid;: " + channel.currentscheduledepisode?.episodeid); console.log("currentscheduledepisode.program.id: " + channel.currentscheduledepisode?.program?.id); console.log("currentscheduledepisode.program.name: " + channel.currentscheduledepisode?.program?.name); console.log("currentscheduledepisode.socialimage: " + channel.currentscheduledepisode?.socialimage); console.log("currentscheduledepisode.starttimeut: " + channel.currentscheduledepisode?.starttimeutc); console.log("currentscheduledepisode.title: " + channel.currentscheduledepisode?.title); console.log("nextscheduledepisode.description: " + channel.nextscheduledepisode?.description); console.log("nextscheduledepisode.endtimeutc: " + channel.nextscheduledepisode?.endtimeutc); console.log("nextscheduledepisode.episodeid;: " + channel.nextscheduledepisode?.episodeid); console.log("nextscheduledepisode.program.id: " + channel.nextscheduledepisode?.program?.id); console.log("nextscheduledepisode.program.name: " + channel.nextscheduledepisode?.program?.name); console.log("nextscheduledepisode.socialimage: " + channel.nextscheduledepisode?.socialimage); console.log("nextscheduledepisode.starttimeut: " + channel.nextscheduledepisode?.starttimeutc); console.log("nextscheduledepisode.title: " + channel.nextscheduledepisode?.title); } }); client.getEpisodesRightNowForChannel( Format.Json, testChannelId ).then(response => { const channel = response.channel; console.log(); console.log("id: " + channel.id); console.log("name: " + channel.name); console.log("previousscheduledepisode.description: " + channel.previousscheduledepisode?.description); console.log("previousscheduledepisode.endtimeutc: " + channel.previousscheduledepisode?.endtimeutc); console.log("previousscheduledepisode.episodeid;: " + channel.previousscheduledepisode?.episodeid); console.log("previousscheduledepisode.program.id: " + channel.previousscheduledepisode?.program?.id); console.log("previousscheduledepisode.program.name: " + channel.previousscheduledepisode?.program?.name); console.log("previousscheduledepisode.socialimage: " + channel.previousscheduledepisode?.socialimage); console.log("previousscheduledepisode.starttimeut: " + channel.previousscheduledepisode?.starttimeutc); console.log("previousscheduledepisode.title: " + channel.previousscheduledepisode?.title); console.log("currentscheduledepisode.description: " + channel.currentscheduledepisode?.description); console.log("currentscheduledepisode.endtimeutc: " + channel.currentscheduledepisode?.endtimeutc); console.log("currentscheduledepisode.episodeid;: " + channel.currentscheduledepisode?.episodeid); console.log("currentscheduledepisode.program.id: " + channel.currentscheduledepisode?.program?.id); console.log("currentscheduledepisode.program.name: " + channel.currentscheduledepisode?.program?.name); console.log("currentscheduledepisode.socialimage: " + channel.currentscheduledepisode?.socialimage); console.log("currentscheduledepisode.starttimeut: " + channel.currentscheduledepisode?.starttimeutc); console.log("currentscheduledepisode.title: " + channel.currentscheduledepisode?.title); console.log("nextscheduledepisode.description: " + channel.nextscheduledepisode?.description); console.log("nextscheduledepisode.endtimeutc: " + channel.nextscheduledepisode?.endtimeutc); console.log("nextscheduledepisode.episodeid;: " + channel.nextscheduledepisode?.episodeid); console.log("nextscheduledepisode.program.id: " + channel.nextscheduledepisode?.program?.id); console.log("nextscheduledepisode.program.name: " + channel.nextscheduledepisode?.program?.name); console.log("nextscheduledepisode.socialimage: " + channel.nextscheduledepisode?.socialimage); console.log("nextscheduledepisode.starttimeut: " + channel.nextscheduledepisode?.starttimeutc); console.log("nextscheduledepisode.title: " + channel.nextscheduledepisode?.title); }); client.getLastPublishedShows( Format.Json, undefined, undefined, undefined ).then(response => { console.log("*** Got " + response.shows.length + " shows."); for (let i = 0; i < response.shows.length; i++) { const show = response.shows[i]; console.log(); console.log("id: " + show.id); console.log("name: " + show.title); console.log("broadcast.availablestoputc: " + show.broadcast?.availablestoputc); console.log("broadcast.broadcastfiles.length: " + show.broadcast?.broadcastfiles?.length); console.log("broadcast.playlist.duration: " + show.broadcast?.playlist?.duration); console.log("broadcast.playlist.id: " + show.broadcast?.playlist?.id); console.log("broadcast.playlist.publishdateutc: " + show.broadcast?.playlist?.publishdateutc); console.log("broadcast.playlist.statkey: " + show.broadcast?.playlist?.statkey); console.log("broadcast.playlist.url: " + show.broadcast?.playlist?.url); console.log("description: " + show.description); console.log("endtimeutc: " + show.endtimeutc); console.log("imageurl: " + show.imageurl); console.log("imageurltemplate: " + show.imageurltemplate); console.log("program.id: " + show.program?.id); console.log("program.name: " + show.program?.name); console.log("starttimeutc: " + show.starttimeutc); } }); client.getImportantMessages( Format.Json, ).then(response => { console.log("*** Got " + response.messages.length + " messages."); for (let i = 0; i < response.messages.length; i++) { const message = response.messages[i]; console.log(); console.log("id: " + message.id); console.log("name: " + message.title); console.log("date: " + message.date); console.log("description: " + message.description); console.log("url: " + message.url); } }); client.getTrafficAreas( Format.Json, undefined, undefined ).then(response => { console.log("*** Got " + response.areas.length + " area."); for (let i = 0; i < response.areas.length; i++) { const area = response.areas[i]; console.log(); console.log("name: " + area.name); console.log("radius: " + area.radius); console.log("trafficdepartmentunitid: " + area.trafficdepartmentunitid); console.log("zoom: " + area.zoom); } }); client.getTrafficArea( Format.Json, 3.123, -78.5345 ).then(response => { const area = response.area; console.log(); console.log("name: " + area.name); console.log("radius: " + area.radius); console.log("trafficdepartmentunitid: " + area.trafficdepartmentunitid); console.log("zoom: " + area.zoom); }); client.getTrafficMessages( Format.Json, undefined, undefined, undefined ).then(response => { console.log("*** Got " + response.messages.length + " area."); for (let i = 0; i < response.messages.length; i++) { const area = response.messages[i]; console.log(); console.log("id: " + area.id); console.log("title: " + area.title); console.log("category: " + area.category); console.log("createddate: " + area.createddate); console.log("description: " + area.description); console.log("exactlocation: " + area.exactlocation); console.log("latitude: " + area.latitude); console.log("longitude: " + area.longitude); console.log("priority: " + area.priority); console.log("subcategory: " + area.subcategory); } });
typescript
Challenger to Gary Kasparov's throne of 'Chess Dynasty', Russia's Vladimir Kramnik resisted all the advances by the wizard in a Ruy Lopez to draw their third round game of BrainGames World Chess Championship in London on Friday night. Kramnik, who earned a point cushion with a second round win, repeated the Berlin Defence which proved so successful in game one and drew in 53 moves to lead 2-1 in their 16-round match. Kasparov, however, cannot be counted out as he is known to strike when the going gets tough. World number one Kasparov, finding Kramnik opting for Berlin defence again, castled his White king and rook on the fourth move and waited for his opponent to reveal his plans. Kramnik accounted for Kasparov's 'e' pawn with a knight though White regained the advantage of the better pawn struture. Black, however, had two bishops and a solid position. Kasparov tried variety with Rad1 on the 12th move - a textbook move used by the Spanish Grandmaster Alexei Shirov. Kramnik had evidently prepared an improved answer than 12.a5 as he played 'b6'. But this intense play put Kramnik half an hour behind Kasparov on the clock. This was the first time in the match that Kasparov appeared to have come out of the opening with the initiative both in position and on the clock. Kasparov's knight perched on d5 gave threatening moments to the Black and the White looked well set to let his kingside pawns in motion. White knight on d5 was the apparent key to Kasparov holding on to his domination. With time advantage still on his side, Kasparov put Kramnik in a corner with seemingly little chance to draw level on strength. Black took a major decision by wrecking his pawn structure in exchange for pieces activity and in turn ate 10 minutes from Kasparov's clock. Nevertheless Kramnik was left with only half an hour thinking time left to make 20 moves while Kasparov looked heading for a clear plan of doubling rooks on the d-file and invading on d8. The challenger went for mass liquidation and appeared to gain some respite with a classically well chalked out defence. Though still having majority of pawns on the kingside, White could not be happy with Black's queenside pawns doubled. This let Kramnik to gain some solid ground as his pieces were left well-anchored on the light squares. Kasparov tried to realign his pieces to attack Black's pawn on h6, but Kramnik stirred up the trouble on the other flank by pushing his pawn to a4 as both players had 15 minutes left for 10 moves. After a quiet strategic struggle, Kramnik's 31st move caused the board to erupt in flames. Retreat of the White rook seemed to create a highly dangerous passed pawn. The game went into an amazing position with six passed pawns on the board with a theoritical advantage to White. But as the first time control was passed, Kramnik withstood all the pressure before the two GMs agreed to split the point.
english
The early reviews for the much-awaited sequel film Spider-Man: Across the Spider-Verse are here and critics are hailing it as one of the best-animated films ever made. The plot of the film picks up right after the events of the 2018-released film Spider-Man: Into the Spider-Verse with Hailee Steinfeld, Shameik Moore, and Jason Schwartzman voicing the lead animated characters. Just like the last film, the sequel is also set against the backdrop of a shared multiverse, with a brand new adventurous mission. The first reactions indicate that people haven’t only fallen in love with the enigmatic animated graphics but also the emotional touch the plot brings in. Check out the early reviews of ‘Spider-Man: Across the Spider-Verse’ below: For Seon O’ Connel, the Managing Editor at CinemaBlend, it was one step above any masterpiece with its artwork deserving to be hung in a museum. Daniel Baptista, the creator, producer, and host of The Movie Podcast, called it a revolutionary creation in the world of animation while also hailing it as one of the best Spider-Man movies ever made. Shahbaz, also the host of The Movie Podcast, hinted that the movie’s groundbreaking plot has multiple jaw-dropping surprises in store for fans. A critic called it a cultural experience that is sure to leave people teary-eyed. Meanwhile, many appreciated the performances of the lead characters. “Hailee Steinfeld really comes into her own as Gwen Stacy and her scenes with Shea Whigham’s Captain Stacy are truly special. It’s darker and sadder than I expected, but necessary,” said Brain Davids, a writer at The Hollywood Reporter. The movie is helmed by Joaquim Dos Santos, Kemp Powers and Justin K. Thompson. Shameik Moore voices Miles Morales aka Spider-Man, while Hailee Steinfeld is the Spider-Woman. Jason Schwartzman’s voice takes the place of the supervillain spot. The movie is set to release on June 2.
english
<filename>src/main/java/tech/qvanphong/arkdc/views/arkdelegatorcalculator/CalculatorView.java package tech.qvanphong.arkdc.views.arkdelegatorcalculator; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.checkbox.Checkbox; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.page.Viewport; import com.vaadin.flow.component.template.Id; import com.vaadin.flow.component.textfield.NumberField; import com.vaadin.flow.dom.Element; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.PWA; import com.vaadin.flow.templatemodel.TemplateModel; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.polymertemplate.PolymerTemplate; import org.springframework.beans.factory.annotation.Autowired; import tech.qvanphong.arkdc.services.ArkDelegatesService; /** * A Designer generated component for the calculator-view template. * <p> * Designer will add and remove fields with @Id mappings but * does not overwrite or otherwise change this file. */ @Tag("calculator-view") @JsModule("./views/calculator/calculator-view.js") @Route("") @PageTitle("ARK Delegate Calculator") @Viewport("width=device-width, initial-scale=1.0") @PWA(display = "standalone", name = "ARK Delegate Calculator", shortName = "ARK Delegate", iconPath = "icons/favicon.png") public class CalculatorView extends PolymerTemplate<CalculatorView.CalculatorViewModel> { private ArkDelegatesService delegatesService; @Id("switch-mode-button") private Button switchModeButton; @Id("switch-mode-button-mobile") private Button switchModeMobileButton; @Id("is-voted") private Checkbox isVoted; @Id("ark-balance") private NumberField arkBalance; private final AllDelegate allDelegate; private final SingleDelegateCalculator singleDelegateCalculator; private final String SW_TABLE_STR = "Switch to table mode"; private final String SW_SINGLE_STR = "Switch to single mode"; @Autowired public CalculatorView(ArkDelegatesService delegatesService) { this.delegatesService = delegatesService; this.allDelegate = new AllDelegate(delegatesService); this.singleDelegateCalculator = new SingleDelegateCalculator(delegatesService); this.arkBalance.addValueChangeListener(e -> valueChangedListener()); this.isVoted.addValueChangeListener(e -> valueChangedListener()); switchModeButton.setIcon(VaadinIcon.REFRESH.create()); switchModeMobileButton.setIcon(VaadinIcon.REFRESH.create()); switchModeButton.addClickListener(e -> switchModeListener()); switchModeMobileButton.addClickListener(e -> switchModeListener()); Element element = allDelegate.getElement(); getElement().appendChild(element); } private void valueChangedListener() { allDelegate.setArkBalance(arkBalance.getValue()); allDelegate.setVoted(isVoted.getValue()); singleDelegateCalculator.setArkBalance(arkBalance.getValue()); singleDelegateCalculator.setVoted(isVoted.getValue()); if (getElement().getChild(0).equals(allDelegate.getElement())) { allDelegate.refreshOnValueChange(); } else { singleDelegateCalculator.updateCalculateResult(); } } private void switchModeListener() { Element elementToReplace; if (getElement().getChild(0).equals(allDelegate.getElement())) { elementToReplace = singleDelegateCalculator.getElement(); switchModeButton.setText(SW_TABLE_STR); switchModeMobileButton.setText(SW_TABLE_STR); } else { elementToReplace = allDelegate.getElement(); switchModeButton.setText(SW_SINGLE_STR); switchModeMobileButton.setText(SW_SINGLE_STR); } valueChangedListener(); getElement().removeAllChildren(); getElement().appendChild(elementToReplace); } public interface CalculatorViewModel extends TemplateModel { } }
java
<filename>stellar-dotnet-sdk-test/testdata/effects/effectTrade.json { "_links": { "operation": { "href": "http://horizon-testnet.stellar.org/operations/33788507721730" }, "succeeds": { "href": "http://horizon-testnet.stellar.org/effects?order=desc&cursor=33788507721730-2" }, "precedes": { "href": "http://horizon-testnet.stellar.org/effects?order=asc&cursor=33788507721730-2" } }, "id": "0000033788507721730-0000000002", "paging_token": "<PASSWORD>", "account": "<KEY>", "type": "trade", "type_i": 33, "seller": "<KEY>", "seller_muxed": "MAAAAAABGFQ36FMUQEJBVEBWVMPXIZAKSJYCLOECKPNZ4CFKSDCEWV75TR3C55HR2FJ24", "seller_muxed_id": 5123456789, "offer_id": "1", "sold_amount": "1000.0", "sold_asset_type": "credit_alphanum4", "sold_asset_code": "EUR", "sold_asset_issuer": "<KEY>", "bought_amount": "60.0", "bought_asset_type": "credit_alphanum12", "bought_asset_code": "TESTTEST", "bought_asset_issuer": "<KEY>" }
json
<reponame>pellizzetti/pulumi-oci-dev // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package core import ( "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // This data source provides the list of Peer Region For Remote Peerings in Oracle Cloud Infrastructure Core service. // // Lists the regions that support remote VCN peering (which is peering across regions). // For more information, see [VCN Peering](https://docs.cloud.oracle.com/iaas/Content/Network/Tasks/VCNpeering.htm). // // ## Example Usage // // ```go // package main // // import ( // "github.com/pulumi/pulumi-oci/sdk/go/oci/core" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // _, err := core.GetPeerRegionForRemotePeerings(ctx, nil, nil) // if err != nil { // return err // } // return nil // }) // } // ``` func GetPeerRegionForRemotePeerings(ctx *pulumi.Context, args *GetPeerRegionForRemotePeeringsArgs, opts ...pulumi.InvokeOption) (*GetPeerRegionForRemotePeeringsResult, error) { var rv GetPeerRegionForRemotePeeringsResult err := ctx.Invoke("oci:core/getPeerRegionForRemotePeerings:getPeerRegionForRemotePeerings", args, &rv, opts...) if err != nil { return nil, err } return &rv, nil } // A collection of arguments for invoking getPeerRegionForRemotePeerings. type GetPeerRegionForRemotePeeringsArgs struct { Filters []GetPeerRegionForRemotePeeringsFilter `pulumi:"filters"` } // A collection of values returned by getPeerRegionForRemotePeerings. type GetPeerRegionForRemotePeeringsResult struct { Filters []GetPeerRegionForRemotePeeringsFilter `pulumi:"filters"` // The provider-assigned unique ID for this managed resource. Id string `pulumi:"id"` // The list of peer_region_for_remote_peerings. PeerRegionForRemotePeerings []GetPeerRegionForRemotePeeringsPeerRegionForRemotePeering `pulumi:"peerRegionForRemotePeerings"` }
go
{"artist_id":"ARGCVZG1187B9B916F","artist_latitude":null,"artist_location":"","artist_longitude":null,"artist_name":"<NAME>","duration":250.67057,"num_songs":1,"song_id":"SOIOQNE12A58A7CBB7","title":"Sabbath Bloody Sabbath","year":2010}
json
'Wonder Woman 1984' is currently in theaters in India. 'Wonder Woman 1984' is currently in theaters in India. The iPhone 11, iPhone 11 Pro, iPhone 11 Pro Max and Apple Watch Series 5 are now available for pre-order in India. Instead of a regular September event, Apple is expected to unveil new iPhones and iPads at an event in October. Cupertino tech giant is going to launch the upcoming iPhones with a USB Type-C port and ditch the lightning port in the future iPhone models. Apple has topped the Indian premium smartphone market for the second consecutive quarter. Realme GT 2 Pro will be available for purchase on Flipkart and Realme's official website from 12 PM. Apple's newly-released battery cases for the iPhone 11, iPhone 11 Pro and iPhone 11 Pro Max all include a dedicated camera button that can launch the Camera app, take a photo or record a quick video. In addition to 'Velma', HBO Max has also ordered 'Clone High', 'Fired On Mars', and picked up two more seasons of 'Close Enough Max'. This new hybrid Mac Studio might be the new high-end Mac mini's replacement, as well as a viable alternative for people who cannot or will not be able to afford the highly-priced Mac Pro. Wait, why didn't Apple say something about this before? The South Korean tech giant announced the Samsung Galaxy Book 2 Pro and Galaxy Book 2 Pro 360 laptops today during the 'MWC 2022' event. The bug which was causing the issue with iPhone hearing devices connectivity is also fixed with the update.
english
According to state BJP President VD Sharma, those who resigned as MLAs are strong contenders for the tickets in by-elections as they had ‘sacrificed’ a lot and are thus strong contenders for being fielded. Bharatiya Janata Party (BJP) is likely to allocate tickets for the forthcoming Madhya Pradesh Assembly by-polls to a majority of former Congress members of the House who helped the party wrest power from Kamal Nath. According to state BJP President VD Sharma, those who resigned as MLAs are strong contenders for the tickets in by-elections as they had “sacrificed” a lot and are thus strong contenders for being fielded. “These are people had left their ministerial berths and posts as MLAs to save Madhya Pradesh from corruption and poor administration. I would not be wrong in saying that these people had sacrificed themselves and their posts for the state. So, for this reason, all of them are in consideration for the candidature,” the state BJP President told ANI. The by-polls have been necessitated as seats fell vacant after the sitting MLAs resigned. The party is already gearing up for by-elections in 24 assembly constituencies. MLAs considered close to Jyotiraditya Scindia had resigned and later crossed over to the BJP resulting in the fall of Kamal Nath government in the state. The nomination for tickets for the by-elections will be approved by the Central leadership of the party, he added. Despite lockdown, the party has begun preparations for these by-polls. According to Sharma, online meetings in all constituencies are being conducted. Present in these meeting were 20-25 people including former candidates, district, mandal level leaders and other prominent leaders in every constituency. “We have strengthened the organisation online. Shakti kendra and booth level meetings have begun. We work round the year. We will reach people through online mediums and door to door campaign will be done by keeping physical distancing and following other health measures,” said Sharma. The by-polls are expected to take place in September. Sharma praised BJP workers in the state and called them Corona warriors. “I take pride in saying that BJP workers are not less than any Corona warriors. They have served people while endangering their lives. One of our corporator from Ujjain contracted and died while serving people. We have ensured that migrants reaching or crossing over the state will get food and essentials,” claimed Sharma. On the announcement of his new team in the state, Sharma said, “ it will be announced soon. It got delayed as we all are busy with COVID-19 relief work. It may get announced by the end of this month. ” (ANI)
english
<reponame>LoomDev/Loom-API<filename>src/main/java/org/loomdev/api/village/VillagerVariant.java package org.loomdev.api.village; import org.jetbrains.annotations.Nullable; import org.loomdev.api.Loom; import org.loomdev.api.util.registry.Keyed; import org.loomdev.api.world.biome.BiomeType; public interface VillagerVariant extends Keyed { // region :: VillagerVariants VillagerVariant DESERT = getById("minecraft:desert"); VillagerVariant JUNGLE = getById("minecraft:jungle"); VillagerVariant PLAINS = getById("minecraft:plains"); VillagerVariant SAVANNA = getById("minecraft:savanna"); VillagerVariant SNOW = getById("minecraft:snow"); VillagerVariant SWAMP = getById("minecraft:swamp"); VillagerVariant TAIGA = getById("minecraft:taiga"); // endregion :: VillagerVariants static VillagerVariant getById(String id) { return Loom.getRegistry().getWrapped(VillagerVariant.class, id); } @Nullable static VillagerVariant getByBiome(BiomeType biomeType) { return biomeType.getVillagerVariant(); } }
java
<gh_stars>100-1000 import json import pytest from indy import did, error @pytest.mark.asyncio async def test_list_my_dids_works(wallet_handle, seed_my1, did_my1, verkey_my1, metadata): await did.create_and_store_my_did(wallet_handle, json.dumps({'seed': seed_my1})) await did.set_did_metadata(wallet_handle, did_my1, metadata) res_json = await did.list_my_dids_with_meta(wallet_handle) res = json.loads(res_json) assert len(res) == 1 assert res[0]["did"] == did_my1 assert res[0]["metadata"] == metadata assert res[0]["verkey"] == verkey_my1 @pytest.mark.asyncio async def test_list_my_dids_works_for_invalid_handle(wallet_handle): with pytest.raises(error.WalletInvalidHandle): await did.list_my_dids_with_meta(wallet_handle + 1)
python
Impossible Foods, which makes plant-based nuggets, burgers and patties, is reportedly laying off 20% of its staff, Bloomberg reported first. According to the story, the 12-year-old company currently employs about 700 workers, which could then affect over 100 employees. This comes as the company made a 6% reduction in its workforce last October. Impossible Foods did not respond to a request for a comment about the layoffs. Months before that, CEO Peter McGuinness said in an interview with Bloomberg Technology that the company had a strong balance sheet, good cash flow and growth of between 65% and 70%. In total, Impossible raised $1.9 billion in venture capital, according to Crunchbase data. The last time the company raised capital was a $500 million Series H round in November 2021, and it was at that time that the company was valued at $7 billion. Founder Pat Brown spoke at the TC Sessions: Climate event last June and said that his vision for the company was to be the conduit that helps the world be less reliant on animals for food. Even though Impossible and other plant-based companies have tried to go mainstream via grocery stores and restaurant partnerships, like Impossible’s with Burger King, plant-based meat remains quite a niche industry as a Yahoo article pointed out last week. My colleague Tim De Chant also noted that when meat prices rose during the global pandemic, the gap between traditional meat and meat alternatives was closing. However, that changed with the recent inflation. And the scale still isn’t there as Stray Dog Capital’s Lisa Feria explained to TechCrunch. Impossible is not the only plant-based meat alternative company to make layoffs in recent months. In a regulatory filing made last October, Beyond Meat said it planned to lay off about 200 employees, or 19% of its workforce, as part of cost-saving measures as sales were slumping.
english
<filename>basic_code/load.py from __future__ import print_function import torch print(torch.__version__) import torch.utils.data import torchvision.transforms as transforms from basic_code import data_generator cate2label = {'CK+':{0: 'Happy', 1: 'Angry', 2: 'Disgust', 3: 'Fear', 4: 'Sad', 5: 'Contempt', 6: 'Surprise', 'Angry': 1,'Disgust': 2,'Fear': 3,'Happy': 0,'Contempt': 5,'Sad': 4,'Surprise': 6}, 'AFEW':{0: 'Happy',1: 'Angry',2: 'Disgust',3: 'Fear',4: 'Sad',5: 'Neutral',6: 'Surprise', 'Angry': 1,'Disgust': 2,'Fear': 3,'Happy': 0,'Neutral': 5,'Sad': 4,'Surprise': 6}} def ckplus_faces_baseline(video_root, video_list, fold, batchsize_train, batchsize_eval): train_dataset = data_generator.TenFold_VideoDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), fold=fold, run_type='train' ) val_dataset = data_generator.TenFold_VideoDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), fold=fold, run_type='test' ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8,pin_memory=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def ckplus_faces_fan(video_root, video_list, fold, batchsize_train, batchsize_eval): train_dataset = data_generator.TenFold_TripleImageDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([ transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), fold=fold, run_type='train', ) val_dataset = data_generator.TenFold_VideoDataset( video_root=video_root, video_list=video_list, rectify_label=cate2label['CK+'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), fold=fold, run_type='test' ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8,pin_memory=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def afew_faces_baseline(root_train, list_train, batchsize_train, root_eval, list_eval, batchsize_eval): train_dataset = data_generator.VideoDataset( video_root=root_train, video_list=list_train, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), ) val_dataset = data_generator.VideoDataset( video_root=root_eval, video_list=list_eval, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), csv=False) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8, pin_memory=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def afew_faces_fan(root_train, list_train, batchsize_train, root_eval, list_eval, batchsize_eval): train_dataset = data_generator.TripleImageDataset( video_root=root_train, video_list=list_train, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]), ) val_dataset = data_generator.VideoDataset( video_root=root_eval, video_list=list_eval, rectify_label=cate2label['AFEW'], transform=transforms.Compose([transforms.Resize(224), transforms.ToTensor()]), csv=False) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batchsize_train, shuffle=True, num_workers=8, pin_memory=True, drop_last=True) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=batchsize_eval, shuffle=False, num_workers=8, pin_memory=True) return train_loader, val_loader def model_parameters(_structure, _parameterDir): checkpoint = torch.load(_parameterDir) pretrained_state_dict = checkpoint['state_dict'] model_state_dict = _structure.state_dict() for key in pretrained_state_dict: if ((key == 'module.fc.weight') | (key == 'module.fc.bias')): pass else: model_state_dict[key.replace('module.', '')] = pretrained_state_dict[key] _structure.load_state_dict(model_state_dict) model = torch.nn.DataParallel(_structure).cuda() return model
python
{"remainingRequest":"E:\\XiangMu\\ant-design-pro-vue\\node_modules\\thread-loader\\dist\\cjs.js!E:\\XiangMu\\ant-design-pro-vue\\node_modules\\babel-loader\\lib\\index.js!E:\\XiangMu\\ant-design-pro-vue\\node_modules\\cache-loader\\dist\\cjs.js??ref--0-0!E:\\XiangMu\\ant-design-pro-vue\\node_modules\\vue-loader\\lib\\index.js??vue-loader-options!E:\\XiangMu\\ant-design-pro-vue\\src\\components\\FooterToolbar\\FooterToolBar.vue?vue&type=script&lang=js&","dependencies":[{"path":"E:\\XiangMu\\ant-design-pro-vue\\src\\components\\FooterToolbar\\FooterToolBar.vue","mtime":1562294713035},{"path":"E:\\XiangMu\\ant-design-pro-vue\\node_modules\\cache-loader\\dist\\cjs.js","mtime":499162500000},{"path":"E:\\XiangMu\\ant-design-pro-vue\\node_modules\\thread-loader\\dist\\cjs.js","mtime":499162500000},{"path":"E:\\XiangMu\\ant-design-pro-vue\\node_modules\\babel-loader\\lib\\index.js","mtime":499162500000},{"path":"E:\\XiangMu\\ant-design-pro-vue\\node_modules\\cache-loader\\dist\\cjs.js","mtime":499162500000},{"path":"E:\\XiangMu\\ant-design-pro-vue\\node_modules\\vue-loader\\lib\\index.js","mtime":499162500000}],"contextDependencies":[],"result":["//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\nexport default {\n name: 'FooterToolBar',\n props: {\n prefixCls: {\n type: String,\n default: 'ant-pro-footer-toolbar'\n },\n extra: {\n type: [String, Object],\n default: ''\n }\n }\n};",null]}
json
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.Contacts; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.testng.Assert.assertEquals; public class DeleteContactTest extends TestBase { @BeforeMethod public void ensurePreconditions(){ if (app.db().contacts().size() == 0) { ContactData contactData = new ContactData().withFirstName("Jane").withLastName("Smith") .withAddress("743 Evergreen Terrace, Springfield, Anytown").withHomephone("555-55-55") .withMobilephone("81234567890").withWorkphone("33 34 33").withEmail("<EMAIL>");//.withGroup("test1"); app.contact().create(contactData); app.goTo().homePage(); } } @Test public void testDeleteContact() { Contacts before = app.db().contacts(); ContactData deletedContact = before.iterator().next(); app.contact().delete(deletedContact); app.goTo().homePage(); Contacts after = app.db().contacts(); assertEquals(after.size(), before.size() - 1); assertThat(after, equalTo(before.without(deletedContact))); verifyContactListInUI(); } }
java
Two stalwarts of Indian women's badminton, PV Sindhu and Saina Nehwal, suffered contrasting fates at the Malaysia Open Super 750. Two stalwarts of Indian women's badminton, PV Sindhu and Saina Nehwal, suffered contrasting fates at the Malaysia Open Super 750 tournament with the former progressing to the second round and the latter bowing out after losing her opener here on Wednesday. If Sindhu, a former world champion, dished out a fine performance to outwit Thailand's world number 10 Pornpawee Chochuwong 21-13, 21-17, London Olympics bronze medallist Saina went down fighting against American Iris Wang, ranked 33rd in the world, 11-21, 17-21 in 37 minutes. Former Commonwealth Games champion Parupalli Kashyap also made a positive return from injury as he prevailed 21-12, 21-17 over Korea's Heo Kwang Hee to advance to the second round in men's singles. Sindhu, seeded seventh, set up a clash with Phittayaporn Chaiwan, a 21-year-old from Thailand, who held the number one ranking in world junior ranking and also was part of the bronze medal-winning team at the Uber Cup in Bangkok. Kashyap, ranked world number 39, will meet Thailand's Kunlavut Vitidsarn, who had won the German Open Super 300 in March. B Sumeeth Reddy and Ashwini Ponnappa, who will be leading India's charge at the Commonwealth Games, couldn't get past world number 21 pairing of Robin Tabeling and Selena Piek of the Netherlands. The Indian duo lost 15-21, 21-19, 17-21 after a 52-minute battle. Sindhu enjoys a 5-3 head-to-head record against Chochuwong, having won the last time they met, at the 2021 World Championship, and the Indian looked in good touch against the Thai, who struggled with her lengths and finishing strokes. The match started with the duo playing at a good pace but it was Sindhu who dictated terms with her better court coverage. Chochuwong matched Sindhu in the rallies but faltered in her finishing. The result was Sindhu led throughout the first game after securing a 4-1 advantage early on. A tight net shot earned her a four-point cushion at the break. Sindhu's front court play was more polished than her rival and she used the smashes and attacking returns to good effect whenever there was an opportunity. Sindhu extended her lead to 16-11 before producing an over-the-head return to grab seven game points and converted it with a smash. After the change of sides, Chochuwong started with two net errors before pouncing on some weak returns from Sindhu to lead 4-2. The Thai player kept gathering points with Sindhu also committing errors at the net or going wide. It was one such long return from Sindhu which handed Chochuwong a three-point advantage at the break. Chochuwong quickly moved to 16-10 with the help of two precise returns on both sides and Sindhu also miscued her shots. But the Indian then scripted a phenomenal recovery with a five-point burst with her rival falling into a heap of unforced errors. With the Thai going long again, Sindhu levelled the score at 17-17 and then moved to the lead with yet another shot from Chochuwong getting buried at the nets. With the shuttle sailing out twice again, Sindhu grabbed three match points and sealed it comfortably.
english
<gh_stars>1-10 # epydoc -- Command line interface # # Copyright (C) 2005 <NAME> # Author: <NAME> <<EMAIL>> # URL: <http://epydoc.sf.net> # # $Id: cli.py 1196 2006-04-09 18:15:55Z edloper $ """ Command-line interface for epydoc. Abbreviated Usage:: epydoc [options] NAMES... NAMES... The Python modules to document. --html Generate HTML output (default). --latex Generate LaTeX output. --pdf Generate pdf output, via LaTeX. -o DIR, --output DIR The output directory. --inheritance STYLE The format for showing inherited objects. -V, --version Print the version of epydoc. -h, --help Display a usage message. Run \"epydoc --help\" for a complete option list. See the epydoc(1) man page for more information. Config Files ============ Configuration files can be specified with the C{--config} option. These files are read using U{ConfigParser <http://docs.python.org/lib/module-ConfigParser.html>}. Configuration files may set options or add names of modules to document. Option names are (usually) identical to the long names of command line options. To specify names to document, use any of the following option names:: module modules value values object objects A simple example of a config file is:: [epydoc] modules: sys, os, os.path, re name: Example graph: classtree introspect: no Verbosity Levels ================ The C{-v} and C{-q} options increase and decrease verbosity, respectively. The default verbosity level is zero. The verbosity levels are currently defined as follows:: Progress Markup warnings Warnings Errors -3 none no no no -2 none no no yes -1 none no yes yes 0 (default) bar no yes yes 1 bar yes yes yes 2 list yes yes yes """ __docformat__ = 'epytext en' import sys, os, time, re, pstats from glob import glob from optparse import OptionParser, OptionGroup import epydoc from epydoc import log from epydoc.util import wordwrap, run_subprocess, RunSubprocessError from epydoc.apidoc import UNKNOWN import ConfigParser INHERITANCE_STYLES = ('grouped', 'listed', 'included') GRAPH_TYPES = ('classtree', 'callgraph', 'umlclasstree') ACTIONS = ('html', 'text', 'latex', 'dvi', 'ps', 'pdf', 'check') DEFAULT_DOCFORMAT = 'epytext' ###################################################################### #{ Argument & Config File Parsing ###################################################################### def parse_arguments(): # Construct the option parser. usage = '%prog ACTION [options] NAMES...' version = "Epydoc, version %s" % epydoc.__version__ optparser = OptionParser(usage=usage, version=version) action_group = OptionGroup(optparser, 'Actions') options_group = OptionGroup(optparser, 'Options') # Add options -- Actions action_group.add_option( # --html "--html", action="store_const", dest="action", const="html", help="Write HTML output.") action_group.add_option( # --latex "--text", action="store_const", dest="action", const="text", help="Write plaintext output. (not implemented yet)") action_group.add_option( # --latex "--latex", action="store_const", dest="action", const="latex", help="Write LaTeX output.") action_group.add_option( # --dvi "--dvi", action="store_const", dest="action", const="dvi", help="Write DVI output.") action_group.add_option( # --ps "--ps", action="store_const", dest="action", const="ps", help="Write Postscript output.") action_group.add_option( # --pdf "--pdf", action="store_const", dest="action", const="pdf", help="Write PDF output.") action_group.add_option( # --check "--check", action="store_const", dest="action", const="check", help="Check completeness of docs.") # Add options -- Options options_group.add_option( # --output "--output", "-o", dest="target", metavar="PATH", help="The output directory. If PATH does not exist, then " "it will be created.") options_group.add_option( # --show-imports "--inheritance", dest="inheritance", metavar="STYLE", help="The format for showing inheritance objects. STYLE " "should be one of: %s." % ', '.join(INHERITANCE_STYLES)) options_group.add_option( # --output "--docformat", dest="docformat", metavar="NAME", help="The default markup language for docstrings. Defaults " "to \"%s\"." % DEFAULT_DOCFORMAT) options_group.add_option( # --css "--css", dest="css", metavar="STYLESHEET", help="The CSS stylesheet. STYLESHEET can be either a " "builtin stylesheet or the name of a CSS file.") options_group.add_option( # --name "--name", dest="prj_name", metavar="NAME", help="The documented project's name (for the navigation bar).") options_group.add_option( # --url "--url", dest="prj_url", metavar="URL", help="The documented project's URL (for the navigation bar).") options_group.add_option( # --navlink "--navlink", dest="prj_link", metavar="HTML", help="HTML code for a navigation link to place in the " "navigation bar.") options_group.add_option( # --top "--top", dest="top_page", metavar="PAGE", help="The \"top\" page for the HTML documentation. PAGE can " "be a URL, the name of a module or class, or one of the " "special names \"trees.html\", \"indices.html\", or \"help.html\"") options_group.add_option( # --help-file "--help-file", dest="help_file", metavar="FILE", help="An alternate help file. FILE should contain the body " "of an HTML file -- navigation bars will be added to it.") options_group.add_option( # --frames "--show-frames", action="store_true", dest="show_frames", help="Include frames in the HTML output. (default)") options_group.add_option( # --no-frames "--no-frames", action="store_false", dest="show_frames", help="Do not include frames in the HTML output.") options_group.add_option( # --private "--show-private", action="store_true", dest="show_private", help="Include private variables in the output. (default)") options_group.add_option( # --no-private "--no-private", action="store_false", dest="show_private", help="Do not include private variables in the output.") options_group.add_option( # --show-imports "--show-imports", action="store_true", dest="show_imports", help="List each module's imports.") options_group.add_option( # --show-imports "--no-imports", action="store_false", dest="show_imports", help="Do not list each module's imports. (default)") options_group.add_option( # --quiet "--quiet", "-q", action="count", dest="quiet", help="Decrease the verbosity.") options_group.add_option( # --verbose "--verbose", "-v", action="count", dest="verbose", help="Increase the verbosity.") options_group.add_option( # --debug "--debug", action="store_true", dest="debug", help="Show full tracebacks for internal errors.") options_group.add_option( # --parse-only "--parse-only", action="store_false", dest="introspect", help="Get all information from parsing (don't introspect)") options_group.add_option( # --introspect-only "--introspect-only", action="store_false", dest="parse", help="Get all information from introspecting (don't parse)") if epydoc.DEBUG: # this option is for developers, not users. options_group.add_option( "--profile-epydoc", action="store_true", dest="profile", help="Run the profiler. Output will be written to profile.out") options_group.add_option( "--dotpath", dest="dotpath", metavar='PATH', help="The path to the Graphviz 'dot' executable.") options_group.add_option( '--config', action='append', dest="configfiles", metavar='FILE', help=("A configuration file, specifying additional OPTIONS " "and/or NAMES. This option may be repeated.")) options_group.add_option( '--graph', action='append', dest='graphs', metavar='GRAPHTYPE', help=("Include graphs of type GRAPHTYPE in the generated output. " "Graphs are generated using the Graphviz dot executable. " "If this executable is not on the path, then use --dotpath " "to specify its location. This option may be repeated to " "include multiple graph types in the output. GRAPHTYPE " "should be one of: all, %s." % ', '.join(GRAPH_TYPES))) options_group.add_option( '--separate-classes', action='store_true', dest='list_classes_separately', help=("When generating LaTeX or PDF output, list each class in " "its own section, instead of listing them under their " "containing module.")) options_group.add_option( '--show-sourcecode', action='store_true', dest='include_source_code', help=("Include source code with syntax highlighting in the " "HTML output.")) options_group.add_option( '--no-sourcecode', action='store_false', dest='include_source_code', help=("Do not include source code with syntax highlighting in the " "HTML output.")) options_group.add_option( '--pstat', action='append', dest='pstat_files', metavar='FILE', help="A pstat output file, to be used in generating call graphs.") # Add the option groups. optparser.add_option_group(action_group) optparser.add_option_group(options_group) # Set the option parser's defaults. optparser.set_defaults(action="html", show_frames=True, docformat=DEFAULT_DOCFORMAT, show_private=True, show_imports=False, inheritance="listed", verbose=0, quiet=0, parse=True, introspect=True, debug=epydoc.DEBUG, profile=False, graphs=[], list_classes_separately=False, include_source_code=True, pstat_files=[]) # Parse the arguments. options, names = optparser.parse_args() # Process any config files. if options.configfiles: try: parse_configfiles(options.configfiles, options, names) except (KeyboardInterrupt,SystemExit): raise except Exception, e: optparser.error('Error reading config file:\n %s' % e) # Check to make sure all options are valid. if len(names) == 0: optparser.error("No names specified.") # perform shell expansion. for i, name in enumerate(names[:]): if '?' in name or '*' in name: names[i:i+1] = glob(name) if options.inheritance not in INHERITANCE_STYLES: optparser.error("Bad inheritance style. Valid options are " + ",".join(INHERITANCE_STYLES)) if not options.parse and not options.introspect: optparser.error("Invalid option combination: --parse-only " "and --introspect-only.") if options.action == 'text' and len(names) > 1: optparser.error("--text option takes only one name.") # Check the list of requested graph types to make sure they're # acceptable. options.graphs = [graph_type.lower() for graph_type in options.graphs] for graph_type in options.graphs: if graph_type == 'callgraph' and not options.pstat_files: optparser.error('"callgraph" graph type may only be used if ' 'one or more pstat files are specified.') # If it's 'all', then add everything (but don't add callgraph if # we don't have any profiling info to base them on). if graph_type == 'all': if options.pstat_files: options.graphs = GRAPH_TYPES else: options.graphs = [g for g in GRAPH_TYPES if g != 'callgraph'] break elif graph_type not in GRAPH_TYPES: optparser.error("Invalid graph type %s." % graph_type) # Calculate verbosity. options.verbosity = options.verbose - options.quiet # The target default depends on the action. if options.target is None: options.target = options.action # Return parsed args. return options, names def parse_configfiles(configfiles, options, names): configparser = ConfigParser.ConfigParser() # ConfigParser.read() silently ignores errors, so open the files # manually (since we want to notify the user of any errors). for configfile in configfiles: fp = open(configfile, 'r') # may raise IOError. configparser.readfp(fp, configfile) fp.close() for optname in configparser.options('epydoc'): val = configparser.get('epydoc', optname).strip() optname = optname.lower().strip() if optname in ('modules', 'objects', 'values', 'module', 'object', 'value'): names.extend(val.replace(',', ' ').split()) elif optname == 'output': if optname not in ACTIONS: raise ValueError('"%s" expected one of: %s' % (optname, ', '.join(ACTIONS))) options.action = action elif optname == 'target': options.target = val elif optname == 'inheritance': if val.lower() not in INHERITANCE_STYLES: raise ValueError('"%s" expected one of: %s.' % (optname, ', '.join(INHERITANCE_STYLES))) options.inerhitance = val.lower() elif optname == 'docformat': options.docformat = val elif optname == 'css': options.css = val elif optname == 'name': options.prj_name = val elif optname == 'url': options.prj_url = val elif optname == 'link': options.prj_link = val elif optname == 'top': options.top_page = val elif optname == 'help': options.help_file = val elif optname =='frames': options.frames = _str_to_bool(val, optname) elif optname =='private': options.private = _str_to_bool(val, optname) elif optname =='imports': options.imports = _str_to_bool(val, optname) elif optname == 'verbosity': try: options.verbosity = int(val) except ValueError: raise ValueError('"%s" expected an int' % optname) elif optname == 'parse': options.parse = _str_to_bool(val, optname) elif optname == 'introspect': options.introspect = _str_to_bool(val, optname) elif optname == 'dotpath': options.dotpath = val elif optname == 'graph': graphtypes = val.replace(',', '').split() for graphtype in graphtypes: if graphtype not in GRAPH_TYPES: raise ValueError('"%s" expected one of: %s.' % (optname, ', '.join(GRAPH_TYPES))) options.graphs.extend(graphtypes) elif optname in ('separate-classes', 'separate_classes'): options.list_classes_separately = _str_to_bool(val, optname) elif optname == 'sourcecode': options.include_source_code = _str_to_bool(val, optname) elif optname == 'pstat': options.pstat_files.extend(val.replace(',', ' ').split()) else: raise ValueError('Unknown option %s' % optname) def _str_to_bool(val, optname): if val.lower() in ('0', 'no', 'false', 'n', 'f', 'hide'): return False elif val.lower() in ('1', 'yes', 'true', 'y', 't', 'show'): return True else: raise ValueError('"%s" option expected a boolean' % optname) ###################################################################### #{ Interface ###################################################################### def main(options, names): if options.action == 'text': if options.parse and options.introspect: options.parse = False # Set up the logger if options.action == 'text': logger = None # no logger for text output. elif options.verbosity > 1: logger = ConsoleLogger(options.verbosity) log.register_logger(logger) else: # Each number is a rough approximation of how long we spend on # that task, used to divide up the unified progress bar. stages = [40, # Building documentation 7, # Merging parsed & introspected information 1, # Linking imported variables 3, # Indexing documentation 30, # Parsing Docstrings 1, # Inheriting documentation 2] # Sorting & Grouping if options.action == 'html': stages += [100] elif options.action == 'text': stages += [30] elif options.action == 'latex': stages += [60] elif options.action == 'dvi': stages += [60,30] elif options.action == 'ps': stages += [60,40] elif options.action == 'pdf': stages += [60,50] elif options.action == 'check': stages += [10] else: raise ValueError, '%r not supported' % options.action if options.parse and not options.introspect: del stages[1] # no merging if options.introspect and not options.parse: del stages[1:3] # no merging or linking logger = UnifiedProgressConsoleLogger(options.verbosity, stages) log.register_logger(logger) # check the output directory. if options.action != 'text': if os.path.exists(options.target): if not os.path.isdir(options.target): return log.error("%s is not a directory" % options.target) # Set the default docformat from epydoc import docstringparser docstringparser.DEFAULT_DOCFORMAT = options.docformat # Set the dot path if options.dotpath: from epydoc import dotgraph dotgraph.DOT_PATH = options.dotpath # Build docs for the named values. from epydoc.docbuilder import build_doc_index docindex = build_doc_index(names, options.introspect, options.parse, add_submodules=(options.action!='text')) if docindex is None: return # docbuilder already logged an error. # Load profile information, if it was given. if options.pstat_files: try: profile_stats = pstats.Stats(options.pstat_files[0]) for filename in options.pstat_files[1:]: profile_stats.add(filename) except KeyboardInterrupt: raise except Exception, e: log.error("Error reading pstat file: %s" % e) profile_stats = None if profile_stats is not None: docindex.read_profiling_info(profile_stats) # Perform the specified action. if options.action == 'html': write_html(docindex, options) elif options.action in ('latex', 'dvi', 'ps', 'pdf'): write_latex(docindex, options, options.action) elif options.action == 'text': write_text(docindex, options) elif options.action == 'check': check_docs(docindex, options) else: print >>sys.stderr, '\nUnsupported action %s!' % options.action # If we supressed docstring warnings, then let the user know. if logger is not None and logger.supressed_docstring_warning: if logger.supressed_docstring_warning == 1: prefix = '1 markup error was found' else: prefix = ('%d markup errors were found' % logger.supressed_docstring_warning) log.warning("%s while processing docstrings. Use the verbose " "switch (-v) to display markup errors." % prefix) # Basic timing breakdown: if options.verbosity >= 2 and logger is not None: logger.print_times() def write_html(docindex, options): from epydoc.docwriter.html import HTMLWriter html_writer = HTMLWriter(docindex, **options.__dict__) if options.verbose > 0: log.start_progress('Writing HTML docs to %r' % options.target) else: log.start_progress('Writing HTML docs') html_writer.write(options.target) log.end_progress() _RERUN_LATEX_RE = re.compile(r'(?im)^LaTeX\s+Warning:\s+Label\(s\)\s+may' r'\s+have\s+changed.\s+Rerun') def write_latex(docindex, options, format): from epydoc.docwriter.latex import LatexWriter latex_writer = LatexWriter(docindex, **options.__dict__) log.start_progress('Writing LaTeX docs') latex_writer.write(options.target) log.end_progress() # If we're just generating the latex, and not any output format, # then we're done. if format == 'latex': return if format == 'dvi': steps = 4 elif format == 'ps': steps = 5 elif format == 'pdf': steps = 6 log.start_progress('Processing LaTeX docs') oldpath = os.path.abspath(os.curdir) running = None # keep track of what we're doing. try: try: os.chdir(options.target) # Clear any old files out of the way. for ext in 'tex aux log out idx ilg toc ind'.split(): if os.path.exists('apidoc.%s' % ext): os.remove('apidoc.%s' % ext) # The first pass generates index files. running = 'latex' log.progress(0./steps, 'LaTeX: First pass') run_subprocess('latex api.tex') # Build the index. running = 'makeindex' log.progress(1./steps, 'LaTeX: Build index') run_subprocess('makeindex api.idx') # The second pass generates our output. running = 'latex' log.progress(2./steps, 'LaTeX: Second pass') out, err = run_subprocess('latex api.tex') # The third pass is only necessary if the second pass # changed what page some things are on. running = 'latex' if _RERUN_LATEX_RE.match(out): log.progress(3./steps, 'LaTeX: Third pass') out, err = run_subprocess('latex api.tex') # A fourth path should (almost?) never be necessary. running = 'latex' if _RERUN_LATEX_RE.match(out): log.progress(3./steps, 'LaTeX: Fourth pass') run_subprocess('latex api.tex') # If requested, convert to postscript. if format in ('ps', 'pdf'): running = 'dvips' log.progress(4./steps, 'dvips') run_subprocess('dvips api.dvi -o api.ps -G0 -Ppdf') # If requested, convert to pdf. if format in ('pdf'): running = 'ps2pdf' log.progress(5./steps, 'ps2pdf') run_subprocess( 'ps2pdf -sPAPERSIZE=letter -dMaxSubsetPct=100 ' '-dSubsetFonts=true -dCompatibilityLevel=1.2 ' '-dEmbedAllFonts=true api.ps api.pdf') except RunSubprocessError, e: if running == 'latex': e.out = re.sub(r'(?sm)\A.*?!( LaTeX Error:)?', r'', e.out) e.out = re.sub(r'(?sm)\s*Type X to quit.*', '', e.out) e.out = re.sub(r'(?sm)^! Emergency stop.*', '', e.out) log.error("%s failed: %s" % (running, (e.out+e.err).lstrip())) except OSError, e: log.error("%s failed: %s" % (running, e)) finally: os.chdir(oldpath) log.end_progress() def write_text(docindex, options): log.start_progress('Writing output') from epydoc.docwriter.plaintext import PlaintextWriter plaintext_writer = PlaintextWriter() s = '' for apidoc in docindex.root: s += plaintext_writer.write(apidoc) log.end_progress() if isinstance(s, unicode): s = s.encode('ascii', 'backslashreplace') print s def check_docs(docindex, options): from epydoc.checker import DocChecker DocChecker(docindex).check() def cli(): # Parse command-line arguments. options, names = parse_arguments() try: if options.profile: _profile() else: main(options, names) except KeyboardInterrupt: print '\n\n' print >>sys.stderr, 'Keyboard interrupt.' except: if options.debug: raise print '\n\n' exc_info = sys.exc_info() if isinstance(exc_info[0], basestring): e = exc_info[0] else: e = exc_info[1] print >>sys.stderr, ('\nUNEXPECTED ERROR:\n' '%s\n' % (str(e) or e.__class__.__name__)) print >>sys.stderr, 'Use --debug to see trace information.' def _profile(): import profile, pstats try: prof = profile.Profile() prof = prof.runctx('main(*parse_arguments())', globals(), {}) except SystemExit: pass prof.dump_stats('profile.out') return # Use the pstats statistical browser. This is made unnecessarily # difficult because the whole browser is wrapped in an # if __name__=='__main__' clause. try: pstats_pyfile = os.path.splitext(pstats.__file__)[0]+'.py' sys.argv = ['pstats.py', 'profile.out'] print execfile(pstats_pyfile, {'__name__':'__main__'}) except: print 'Could not run the pstats browser' print 'Profiling output is in "profile.out"' ###################################################################### #{ Logging ###################################################################### class TerminalController: """ A class that can be used to portably generate formatted output to a terminal. See U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116} for documentation. (This is a somewhat stripped-down version.) """ BOL = '' #: Move the cursor to the beginning of the line UP = '' #: Move the cursor up one line DOWN = '' #: Move the cursor down one line LEFT = '' #: Move the cursor left one char RIGHT = '' #: Move the cursor right one char CLEAR_EOL = '' #: Clear to the end of the line. CLEAR_LINE = '' #: Clear the current line; cursor to BOL. BOLD = '' #: Turn on bold mode NORMAL = '' #: Turn off all modes COLS = 75 #: Width of the terminal (default to 75) BLACK = BLUE = GREEN = CYAN = RED = MAGENTA = YELLOW = WHITE = '' _STRING_CAPABILITIES = """ BOL=cr UP=cuu1 DOWN=cud1 LEFT=cub1 RIGHT=cuf1 CLEAR_EOL=el BOLD=bold UNDERLINE=smul NORMAL=sgr0""".split() _COLORS = """BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE""".split() _ANSICOLORS = "BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE".split() def __init__(self, term_stream=sys.stdout): # If the stream isn't a tty, then assume it has no capabilities. if not term_stream.isatty(): return # Curses isn't available on all platforms try: import curses except: # If it's not available, then try faking enough to get a # simple progress bar. self.BOL = '\r' self.CLEAR_LINE = '\r' + ' '*self.COLS + '\r' # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return # Look up numeric capabilities. self.COLS = curses.tigetnum('cols') # Look up string capabilities. for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, self._tigetstr(cap_name) or '') if self.BOL and self.CLEAR_EOL: self.CLEAR_LINE = self.BOL+self.CLEAR_EOL # Colors set_fg = self._tigetstr('setf') if set_fg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, curses.tparm(set_fg, i) or '') set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, curses.tparm(set_fg_ansi, i) or '') def _tigetstr(self, cap_name): # String capabilities can include "delays" of the form "$<2>". # For any modern terminal, we should be able to just ignore # these, so strip them out. import curses cap = curses.tigetstr(cap_name) or '' return re.sub(r'\$<\d+>[/*]?', '', cap) class ConsoleLogger(log.Logger): def __init__(self, verbosity): self._verbosity = verbosity self._progress = None self._message_blocks = [] # For ETA display: self._progress_start_time = None # For per-task times: self._task_times = [] self._progress_header = None self.supressed_docstring_warning = 0 """This variable will be incremented once every time a docstring warning is reported tothe logger, but the verbosity level is too low for it to be displayed.""" self.term = TerminalController() # Set the progress bar mode. if verbosity >= 2: self._progress_mode = 'list' elif verbosity >= 0: if self.term.COLS < 15: self._progress_mode = 'simple-bar' if self.term.BOL and self.term.CLEAR_EOL and self.term.UP: self._progress_mode = 'multiline-bar' elif self.term.BOL and self.term.CLEAR_LINE: self._progress_mode = 'bar' else: self._progress_mode = 'simple-bar' else: self._progress_mode = 'hide' def start_block(self, header): self._message_blocks.append( (header, []) ) def end_block(self): header, messages = self._message_blocks.pop() if messages: width = self.term.COLS - 5 - 2*len(self._message_blocks) prefix = self.term.CYAN+self.term.BOLD+'| '+self.term.NORMAL divider = (self.term.CYAN+self.term.BOLD+'+'+'-'*(width-1)+ self.term.NORMAL) # Mark up the header: header = wordwrap(header, right=width-2, splitchars='\\/').rstrip() header = '\n'.join([prefix+self.term.CYAN+l+self.term.NORMAL for l in header.split('\n')]) # Construct the body: body = '' for message in messages: if message.endswith('\n'): body += message else: body += message+'\n' # Indent the body: body = '\n'.join([prefix+' '+l for l in body.split('\n')]) # Put it all together: message = divider + '\n' + header + '\n' + body + '\n' self._report(message) def _format(self, prefix, message, color): """ Rewrap the message; but preserve newlines, and don't touch any lines that begin with spaces. """ lines = message.split('\n') startindex = indent = len(prefix) for i in range(len(lines)): if lines[i].startswith(' '): lines[i] = ' '*(indent-startindex) + lines[i] + '\n' else: width = self.term.COLS - 5 - 4*len(self._message_blocks) lines[i] = wordwrap(lines[i], indent, width, startindex, '\\/') startindex = 0 return color+prefix+self.term.NORMAL+''.join(lines) def log(self, level, message): if self._verbosity >= -2 and level >= log.ERROR: message = self._format(' Error: ', message, self.term.RED) elif self._verbosity >= -1 and level >= log.WARNING: message = self._format('Warning: ', message, self.term.YELLOW) elif self._verbosity >= 1 and level >= log.DOCSTRING_WARNING: message = self._format('Warning: ', message, self.term.YELLOW) elif self._verbosity >= 3 and level >= log.INFO: message = self._format(' Info: ', message, self.term.NORMAL) elif epydoc.DEBUG and level == log.DEBUG: message = self._format(' Debug: ', message, self.term.CYAN) else: if level >= log.DOCSTRING_WARNING: self.supressed_docstring_warning += 1 return self._report(message) def _report(self, message): if not message.endswith('\n'): message += '\n' if self._message_blocks: self._message_blocks[-1][-1].append(message) else: # If we're in the middle of displaying a progress bar, # then make room for the message. if self._progress_mode == 'simple-bar': if self._progress is not None: print self._progress = None if self._progress_mode == 'bar': sys.stdout.write(self.term.CLEAR_LINE) if self._progress_mode == 'multiline-bar': sys.stdout.write((self.term.CLEAR_EOL + '\n')*2 + self.term.CLEAR_EOL + self.term.UP*2) # Display the message message. sys.stdout.write(message) sys.stdout.flush() def progress(self, percent, message=''): percent = min(1.0, percent) message = '%s' % message if self._progress_mode == 'list': if message: print '[%3d%%] %s' % (100*percent, message) sys.stdout.flush() elif self._progress_mode == 'bar': dots = int((self.term.COLS/2-8)*percent) background = '-'*(self.term.COLS/2-8) if len(message) > self.term.COLS/2: message = message[:self.term.COLS/2-3]+'...' sys.stdout.write(self.term.CLEAR_LINE + '%3d%% '%(100*percent) + self.term.GREEN + '[' + self.term.BOLD + '='*dots + background[dots:] + self.term.NORMAL + self.term.GREEN + '] ' + self.term.NORMAL + message + self.term.BOL) sys.stdout.flush() self._progress = percent elif self._progress_mode == 'multiline-bar': dots = int((self.term.COLS-10)*percent) background = '-'*(self.term.COLS-10) if len(message) > self.term.COLS-10: message = message[:self.term.COLS-10-3]+'...' else: message = message.center(self.term.COLS-10) time_elapsed = time.time()-self._progress_start_time if percent > 0: time_remain = (time_elapsed / percent) * (1-percent) else: time_remain = 0 sys.stdout.write( # Line 1: self.term.CLEAR_EOL + ' ' + '%-8s' % self._timestr(time_elapsed) + self.term.BOLD + 'Progress:'.center(self.term.COLS-26) + self.term.NORMAL + '%8s' % self._timestr(time_remain) + '\n' + # Line 2: self.term.CLEAR_EOL + ('%3d%% ' % (100*percent)) + self.term.GREEN + '[' + self.term.BOLD + '='*dots + background[dots:] + self.term.NORMAL + self.term.GREEN + ']' + self.term.NORMAL + '\n' + # Line 3: self.term.CLEAR_EOL + ' ' + message + self.term.BOL + self.term.UP + self.term.UP) sys.stdout.flush() self._progress = percent elif self._progress_mode == 'simple-bar': if self._progress is None: sys.stdout.write(' [') self._progress = 0.0 dots = int((self.term.COLS-2)*percent) progress_dots = int((self.term.COLS-2)*self._progress) if dots > progress_dots: sys.stdout.write('.'*(dots-progress_dots)) sys.stdout.flush() self._progress = percent def _timestr(self, dt): dt = int(dt) if dt >= 3600: return '%d:%02d:%02d' % (dt/3600, dt%3600/60, dt%60) else: return '%02d:%02d' % (dt/60, dt%60) def start_progress(self, header=None): if self._progress is not None: raise ValueError self._progress = None self._progress_start_time = time.time() self._progress_header = header if self._progress_mode != 'hide' and header: print self.term.BOLD + header + self.term.NORMAL def end_progress(self): self.progress(1.) if self._progress_mode == 'bar': sys.stdout.write(self.term.CLEAR_LINE) if self._progress_mode == 'multiline-bar': sys.stdout.write((self.term.CLEAR_EOL + '\n')*2 + self.term.CLEAR_EOL + self.term.UP*2) if self._progress_mode == 'simple-bar': print ']' self._progress = None self._task_times.append( (time.time()-self._progress_start_time, self._progress_header) ) def print_times(self): print print 'Timing summary:' total = sum([time for (time, task) in self._task_times]) max_t = max([time for (time, task) in self._task_times]) for (time, task) in self._task_times: task = task[:31] print ' %s%s %7.1fs' % (task, '.'*(35-len(task)), time), if self.term.COLS > 55: print '|'+'=' * int((self.term.COLS-53) * time / max_t) else: print print class UnifiedProgressConsoleLogger(ConsoleLogger): def __init__(self, verbosity, stages): self.stage = 0 self.stages = stages self.task = None ConsoleLogger.__init__(self, verbosity) def progress(self, percent, message=''): #p = float(self.stage-1+percent)/self.stages i = self.stage-1 p = ((sum(self.stages[:i]) + percent*self.stages[i]) / float(sum(self.stages))) if message == UNKNOWN: message = None if message: message = '%s: %s' % (self.task, message) ConsoleLogger.progress(self, p, message) def start_progress(self, header=None): self.task = header if self.stage == 0: ConsoleLogger.start_progress(self) self.stage += 1 def end_progress(self): if self.stage == len(self.stages): ConsoleLogger.end_progress(self) def print_times(self): pass ###################################################################### ## main ###################################################################### if __name__ == '__main__': try: cli() except: print '\n\n' raise
python
Dominic Thiem's US Open quarterfinal defeat to Rafael Nadal is one that will stick in his mind "forever". Thiem produced a stunning first-set performance to take the opener without losing a game but fell victim to a Nadal fightback. The Austrian was able to force a decider after dropping sets two and three, but a tight tie-break went the way of Nadal, the defending champion moving on to a semifinal with Juan Martin del Potro courtesy of a 0-6 6-4 7-5 6-7 (4-7) 7-6 (7-5) triumph. Nadal holds an 8-3 record in his head to head with Thiem, having also prevailed in the pair's meeting at Roland Garros as the Spaniard claimed an 11th French Open title. While that encounter was settled in straight sets, Thiem was agonisingly close to his first major victory over Nadal on this occasion, and seeing the opportunity slip from his grasp is something that he says will never leave him. Thiem told a post-match media conference: "It's going to be stuck in my mind forever. Forever I'm going to remember this match, for sure. "It's cruel sometimes tennis, because I think this match didn't really deserve a loser. But there has to be one. And I would say if we skip the first set, it was a really open match from the beginning to the end. The way it ended up in the fifth set tiebreaker, there it's 50-50. He made one more point than me. "I would say [this is] the first really epic match I played. I played some good ones before, but not that long, not that long against the great guys on the grand slam stage. "I'm happy that I did this for the first time, even if it went the wrong way. Of course, now I'm devastated a little bit. But in few days I will look back and will remember how great it was to play in front of a packed Arthur Ashe this great match." Nadal had said he was sorry to defeat Thiem, who joked: "I don't think he's really sorry. "He's a great guy. I don't want to lose against anybody. But now I wish him the title the most, that's for sure. I think we almost all the time have great matches. I hope that we have many more in the future with a different end." Though the match was played in the night session, allowing Nadal and Thiem to avoid the searing daytime temperatures that have had a significant impact on the tournament, the ninth seed still felt the conditions played their part. "I already played under worse conditions. It's nicer to play [at] night than under the full sun. The only thing which was uncomfortable was the sweating I couldn't run any more in the fourth set because the shoes were completely wet," Thiem said. "Also changing the clothes doesn't really make sense because after three, four points anyway you're completely wet again."
english
Round: Fourth round (Round of 16) The last American alive in the men’s draw - Frances Tiafoe - will take on last year’s runner-up Daniil Medvedev in the fourth round of the 2020 US Open. This is as tough a test as it can get for the young Tiafoe, given that the third-seed Russian is playing some of his best tennis this week. That said, the American will be buoyed by his magnificent victory against Marton Fucsovics on Saturday. Frances Tiafoe displayed some exemplary attacking skills to get the better of the Hungarian, whom he had never beaten before. Tiafoe's serve and groundstrokes were clicking in a big way, and he’ll be hoping for more of the same against Medvedev. Daniil Medvedev will go into this match-up as the fresher player of the two. The Russian has spent just under six hours on the court, which is a full three hours less than the time spent by Tiafoe. That said, this will no doubt be Medvedev’s toughest challenge yet too at this year’s US Open. If on song, Tiafoe’s serve and forehand - aided by the faster surfaces this year - will greatly test Medvedev’s defensive skills. A foray into the second week of the US Open is already a big achievement for Tiafoe, considering he recently recuperated from COVID-19. Daniil Medvedev leads Frances Tiafoe by a margin of 2-0 in the head-to-head. Their most recent encounter was in the opening round of this year’s Australian Open, which Medvedev won in four sets. Frances Tiafoe’s natural game is to attack his opponents with his flat and depth-heavy groundstrokes, especially off his forehand wing. But that won’t be easy against Daniil Medvedev, who excels at returning from the back-end of the court. The Russian has been positioning himself further behind the baseline than usual to deal with the extra pace of the surface. As such, Tiafoe will not find it easy to penetrate Medvedev's defense despite his powerful game. Medvedev will be more than prepared for the American’s hard-hitting style, so Tiafoe could look to bring in some variety into his game - especially in the forecourt area. The American had struggled at the net when the pair met earlier in the year at Melbourne, and will look to improve on that. Taking the pace off the ball and going cross-court more often are a couple of avenues that Tiafoe can explore if he’s to make serious inroads. Apart from that, he will also have to keep his errors to a minimum as Medvedev will not give him any freebies. Courtesy of his form and pedigree, Danill Medvedev should be expected to win this one. But it wouldn't be a surprise if he gets stretched to his limit by the American. Prediction: Daniil Medvedev to win in four or five sets.
english
module.exports.handler = async (event, context) => { // Every Lambda function invoked by API Gateway should return an object like this. // https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format return { statusCode: 200, // You need to manually enable CORS. headers: { 'Access-Control-Allow-Origin': '*' }, // Body must always be a string. body: JSON.stringify({ event, context }), }; };
javascript
<filename>lib-core/src/main/java/com/gzq/lib_core/http/cache/RoomCacheEntity.java /* * Copyright 2016 jeasonlzy(廖子尧) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gzq.lib_core.http.cache; import android.arch.persistence.room.Entity; import android.arch.persistence.room.Ignore; import android.arch.persistence.room.PrimaryKey; import android.arch.persistence.room.TypeConverters; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.Serializable; import okhttp3.Headers; import okhttp3.Protocol; import okhttp3.internal.http.HttpHeaders; @Entity(tableName = "RoomCache") public class RoomCacheEntity implements Serializable { @Ignore private static final long serialVersionUID = -4337711009801627866L; @Ignore public static final long CACHE_NEVER_EXPIRE = -1; //缓存永不过期 //表中的字段 @Ignore public static final String KEY = "key"; @Ignore public static final String LOCAL_EXPIRE = "localExpire"; @Ignore public static final String HEAD = "head"; @Ignore public static final String DATA = "data"; @PrimaryKey @NonNull private String key; // 缓存key private long localExpire; // 缓存过期时间 private String protocol; @Nullable private Headers responseHeaders; // 缓存的响应头 @Nullable private String data; // 缓存的实体数据 private boolean isExpire; //缓存是否过期该变量不必保存到数据库,程序运行起来后会动态计算 public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Headers getResponseHeaders() { return responseHeaders; } public void setResponseHeaders(Headers responseHeaders) { this.responseHeaders = responseHeaders; } public String getData() { return data; } public void setData(String data) { this.data = data; } public long getLocalExpire() { return localExpire; } public void setLocalExpire(long localExpire) { this.localExpire = localExpire; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public boolean isExpire() { return isExpire; } public void setExpire(boolean expire) { isExpire = expire; } /** * @param cacheTime 允许的缓存时间 * @param baseTime 基准时间,小于当前时间视为过期 * @return 是否过期 */ @Ignore public boolean checkExpire(String cacheMode, long cacheTime, long baseTime) { //304的默认缓存模式,设置缓存时间无效,需要依靠服务端的响应头控制 if (cacheMode.equals(CacheMode.DEFAULT)) return getLocalExpire() < baseTime; if (cacheTime == CACHE_NEVER_EXPIRE) return false; return getLocalExpire() + cacheTime < baseTime; } }
java
#include "Alignment/ReferenceTrajectories/interface/DualBzeroReferenceTrajectory.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "DataFormats/TrajectoryState/interface/LocalTrajectoryParameters.h" #include "Alignment/ReferenceTrajectories/interface/BzeroReferenceTrajectory.h" DualBzeroReferenceTrajectory::DualBzeroReferenceTrajectory(const TrajectoryStateOnSurface& tsos, const ConstRecHitContainer& forwardRecHits, const ConstRecHitContainer& backwardRecHits, const MagneticField* magField, const reco::BeamSpot& beamSpot, const ReferenceTrajectoryBase::Config& config) : DualReferenceTrajectory(tsos.localParameters().mixedFormatVector().kSize - 1, numberOfUsedRecHits(forwardRecHits) + numberOfUsedRecHits(backwardRecHits) - 1, config), theMomentumEstimate(config.momentumEstimate) { theValidityFlag = construct(tsos, forwardRecHits, backwardRecHits, magField, beamSpot); } ReferenceTrajectory* DualBzeroReferenceTrajectory::construct(const TrajectoryStateOnSurface &referenceTsos, const ConstRecHitContainer &recHits, double mass, MaterialEffects materialEffects, const PropagationDirection propDir, const MagneticField *magField, bool useBeamSpot, const reco::BeamSpot &beamSpot) const { if (materialEffects >= breakPoints) throw cms::Exception("BadConfig") << "[DualBzeroReferenceTrajectory::construct] Wrong MaterialEffects: " << materialEffects; ReferenceTrajectoryBase::Config config(materialEffects, propDir, mass, theMomentumEstimate); config.useBeamSpot = useBeamSpot; config.hitsAreReverse = false; return new BzeroReferenceTrajectory(referenceTsos, recHits, magField, beamSpot, config); } AlgebraicVector DualBzeroReferenceTrajectory::extractParameters(const TrajectoryStateOnSurface &referenceTsos) const { AlgebraicVector param = asHepVector<5>( referenceTsos.localParameters().mixedFormatVector() ); return param.sub( 2, 5 ); }
cpp
{"id":"00082","group":"easy-ham-2","checksum":{"type":"MD5","value":"b0ca31a7482b5c60906aa29a9fa6e9df"},"text":"From <EMAIL> Mon Jul 22 18:12:06 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy@<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 228D9440C8\n\tfor <jm@localhost>; Mon, 22 Jul 2002 13:12:05 -0400 (EDT)\nReceived: from dogma.slashnull.org [212.17.35.15]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 22 Jul 2002 18:12:05 +0100 (IST)\nReceived: from webnote.net (mail.webnote.net [192.168.3.1119]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g6MFGu901745 for\n <<EMAIL>>; Mon, 22 Jul 2002 16:16:56 +0100\nReceived: from lugh.tuatha.org (<EMAIL> [194.125.145.45]) by\n webnote.net (8.9.3/8.9.3) with ESMTP id PAA32428 for <<EMAIL>>;\n Mon, 22 Jul 2002 15:27:11 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id PAA30448; Mon, 22 Jul 2002 15:26:08 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from apollo.dit.ie (apollo.dit.ie [172.16.17.3221]) by\n lugh.tuatha.org (8.9.3/8.9.3) with ESMTP id PAA30415 for <<EMAIL>>;\n Mon, 22 Jul 2002 15:26:01 +0100\nReceived: from jupiter.dit.ie (jupiter.dit.ie [147.252.1.77]) by\n apollo.dit.ie (8.11.6/8.11.6) with ESMTP id g6MEDaW19243 for\n <<EMAIL>>; Mon, 22 Jul 2002 15:13:36 +0100\nReceived: from holger ([147.252.132.189]) by mail.dit.ie (PMDF V6.1\n #30532) with SMTP id <<EMAIL>> for <EMAIL>;\n Mon, 22 Jul 2002 15:23:56 +0100 (WET-DST)\nDate: Mon, 22 Jul 2002 15:26:00 +0100\nFrom: <NAME> <<EMAIL>>\nTo: ilug <<EMAIL>.ie>\nMessage-Id: <ECTQGOIA9WQGBIHXR63DBGDIGZU42LH.3d3c15f8@holger>\nOrganization: DIT Kevin Street\nMIME-Version: 1.0\nX-Mailer: Opera 6.01 build 1041\nContent-Type: text/plain; charset=windows-1252\nContent-Transfer-Encoding: 7BIT\nX-Priority: 3 (Normal)\nSubject: [ILUG] Dell Inspiron 2650 X problem\nSender: ilug-admin<EMAIL>\nErrors-To: ilug-admin<EMAIL>\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: ilug@linux.ie\n\nHowdy all, \n\nI have a friend with the problem outlined below, suggestions anyone?\n\n\n\"I have a dell inspirion 2650 laptop, with a P4 1.6GHz proc., an Nvidia Geforce II graphics card (8Mb) and am trying to \ninstall redhat 7.3 .\nThe installation goes nicely until the Xwindows setup. My graphics card IS detected but not the monitor. I have \nrandomly chosen various LCD laptop display monitors but none seem to work, problem is that when i test a particular \nmonitor the screen doesn't default back to the nice clear picture i have become acustomed to but remains fuzzy and \nflashy so it is impossible to test another monitor type. rebooting allows me to run in text mode where i try to configure X \nagain with Xconfigurator but i run into the same problem again.\n\nVery annoying...\"\n\nTa very, \n\nR\n\n----------------------------------------\n<NAME>,\nSchool of Computing\nDublin Institute of Technology\nKevin Street, Dublin 8\nIreland\n\nOffice : \t+353 1 402 4682\nMobile : \t+353 87 618 1793\nEmail : \<EMAIL>, \n \<EMAIL>\n\n \n\n\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>.ie\n\n\n"}
json
<filename>src/types.ts import { camelCase, startCase, set, get } from 'lodash'; import { readFileSync } from 'fs'; import { Logger } from 'log4js'; export class App { _id: string | undefined; description: string | undefined; appCenterStyle: AppCenterStyle | undefined; logo: Logo | undefined; users: Array<string> | undefined; groups: Array<string> | undefined; constructor(data?: App) { this._id = data?._id; this.description = data?.description; this.appCenterStyle = data?.appCenterStyle; this.logo = data?.logo; this.users = data?.users; this.groups = data?.groups; } } export class AppCenterStyle { theme: string | undefined; bannerColor: string | undefined; primaryColor: string | undefined; textColor: string | undefined; constructor(data?: AppCenterStyle) { this.theme = data?.theme; this.bannerColor = data?.bannerColor; this.primaryColor = data?.primaryColor; this.textColor = data?.textColor; } } export class Logo { full: string | undefined; thumbnail: string | undefined; constructor(data?: Logo) { this.full = data?.full; this.thumbnail = data?.thumbnail; } } export class UserDetails { _id: string | undefined; basicDetails: BasicDetails | undefined; enableSessionRefresh: boolean | undefined; username: string | undefined; sessionTime: number | undefined; accessControl: AccessControl | undefined; description: string | undefined; apps: App[] | undefined; token: string | undefined; rToken: string | undefined; expiresIn: number | undefined; serverTime: number | undefined; auth: Auth | undefined; isSuperAdmin: boolean | undefined; rbacBotTokenDuration: number | undefined; rbacHbInterval: number | undefined; rbacUserCloseWindowToLogout: boolean | undefined; rbacUserToSingleSession: boolean | undefined; rbacUserTokenDuration: number | undefined; rbacUserTokenRefresh: boolean | undefined; googleApiKey: string | undefined; uuid: string | undefined; lastLogin: any | undefined; bot: boolean | undefined; defaultTimezone: string | undefined; b2BEnable: boolean | undefined; constructor(data?: UserDetails) { this._id = data?._id; this.basicDetails = data?.basicDetails; this.enableSessionRefresh = data?.enableSessionRefresh; this.username = data?.username; this.sessionTime = data?.sessionTime; this.accessControl = data?.accessControl; this.description = data?.description; this.apps = data?.apps; this.token = data?.token; this.rToken = data?.rToken; this.expiresIn = data?.expiresIn; this.serverTime = data?.serverTime; this.auth = data?.auth; this.isSuperAdmin = data?.isSuperAdmin; this.rbacBotTokenDuration = data?.rbacBotTokenDuration; this.rbacHbInterval = data?.rbacHbInterval; this.rbacUserCloseWindowToLogout = data?.rbacUserCloseWindowToLogout; this.rbacUserToSingleSession = data?.rbacUserToSingleSession; this.rbacUserTokenDuration = data?.rbacUserTokenDuration; this.rbacUserTokenRefresh = data?.rbacUserTokenRefresh; this.googleApiKey = data?.googleApiKey; this.uuid = data?.uuid; this.lastLogin = data?.lastLogin; this.bot = data?.bot; this.defaultTimezone = data?.defaultTimezone; this.b2BEnable = data?.b2BEnable; } } export class Auth { isLdap: boolean | undefined; dn: string | undefined; authType: string | undefined; constructor(data?: Auth) { this.isLdap = data?.isLdap; this.dn = data?.dn; this.authType = data?.authType; } } export class AccessControl { apps: App[] | undefined; accessLevel: string | undefined; constructor(data?: AccessControl) { this.apps = data?.apps; this.accessLevel = data?.accessLevel; } } export class BasicDetails { name: string | undefined; email: string | undefined; phone: string | undefined; constructor(data?: BasicDetails) { this.name = data?.name; this.email = data?.email; this.phone = data?.phone; } } export class Credentials { host?: string | undefined; /** * @description Username or Client ID */ username: string | undefined; /** * @description Password or API Key */ password: string | undefined; /** * @description Available Authentication Token */ token?: string | undefined; /** * @description Enable trace logging */ trace?: boolean; /** * @description Provide a custom logger. */ logger?: Logger; constructor(data?: Credentials) { this.host = data?.host || process.env.DATA_STACK_HOST; this.username = data?.username || process.env.DATA_STACK_USERNAME; this.password = data?.password || process.env.DATA_STACK_PASSWORD; this.token = data?.token || process.env.DATA_STACK_TOKEN; } } export class ListOptions { select: string | undefined; sort: string | undefined; page: number | undefined; count: number | undefined; filter: any | undefined; expand: boolean; constructor(data?: ListOptions) { this.select = data?.select; this.sort = data?.sort; this.page = data?.page; this.count = data?.count || 30; this.filter = data?.filter || {}; this.expand = data?.expand || false; } } export class DataService { _id: string | undefined; name: string | undefined; description: string | undefined; api: string | undefined; definition: Array<SchemaField>; status: string | undefined; preHooks: Array<WebHook>; webHooks: Array<WebHook>; workflowHooks: { postHooks: { approve: Array<WebHook>; discard: Array<WebHook>; reject: Array<WebHook>; rework: Array<WebHook>; submit: Array<WebHook>; } }; role: { fields: { [key: string]: { _t: string, _p: { [key: string]: string } } }, roles: Array<RoleBlock> } draftVersion?: number | undefined; version?: number; constructor(data?: DataService) { this._id = data?._id; this.name = data?.name; this.description = data?.description; this.api = data?.api; this.definition = []; this.preHooks = []; this.webHooks = []; this.workflowHooks = data?.workflowHooks || { postHooks: { approve: [], discard: [], reject: [], rework: [], submit: [] } }; if (data?.definition) { this.definition = data?.definition.map(e => new SchemaField(e)); } if (data?.preHooks) { this.preHooks = data?.preHooks.map(e => new WebHook(e)); } if (data?.webHooks) { this.webHooks = data?.webHooks.map(e => new WebHook(e)); } if (data?.workflowHooks?.postHooks?.approve) { this.workflowHooks.postHooks.approve = data?.workflowHooks?.postHooks?.approve.map(e => new WebHook(e)); } if (data?.workflowHooks?.postHooks?.discard) { this.workflowHooks.postHooks.discard = data?.workflowHooks?.postHooks?.discard.map(e => new WebHook(e)); } if (data?.workflowHooks?.postHooks?.reject) { this.workflowHooks.postHooks.reject = data?.workflowHooks?.postHooks?.reject.map(e => new WebHook(e)); } if (data?.workflowHooks?.postHooks?.rework) { this.workflowHooks.postHooks.rework = data?.workflowHooks?.postHooks?.rework.map(e => new WebHook(e)); } if (data?.workflowHooks?.postHooks?.submit) { this.workflowHooks.postHooks.submit = data?.workflowHooks?.postHooks?.submit.map(e => new WebHook(e)); } this.role = data?.role || { fields: {}, roles: [new RoleBlock()] }; this.draftVersion = data?.draftVersion; this.version = data?.version || 1; } public HasDraft(): boolean { try { if (typeof this.draftVersion === 'number') { return true; } return false; } catch (err: any) { console.error('[ERROR] [Start]', err); throw new ErrorResponse(err.response); } } } export class RoleBlock { id: string; name: string | undefined; description: string | undefined; manageRole: boolean; viewRole: boolean; skipReviewRole: boolean; operations: Array<{ method: RoleMethods }> constructor(data?: RoleBlock) { this.id = data?.id || 'P' + Math.ceil(Math.random() * 10000000000); this.name = data?.name; this.description = data?.description; this.manageRole = data?.manageRole || false; this.viewRole = data?.viewRole || false; this.skipReviewRole = data?.skipReviewRole || false; this.operations = data?.operations || [{ method: RoleMethods.GET }]; } setName(name: string): void { this.name = name; } setDescription(description: string | undefined): void { this.description = description; } enableCreate(): RoleBlock { this.operations.push({ method: RoleMethods.POST }); return this; } disableCreate(): RoleBlock { const index = this.operations.findIndex(e => e.method === RoleMethods.POST); this.operations.splice(index, 1); return this; } enableEdit(): RoleBlock { this.operations.push({ method: RoleMethods.PUT }); return this; } disableEdit(): RoleBlock { const index = this.operations.findIndex(e => e.method === RoleMethods.PUT); this.operations.splice(index, 1); return this; } enableDelete(): RoleBlock { this.operations.push({ method: RoleMethods.DELETE }); return this; } disableDelete(): RoleBlock { const index = this.operations.findIndex(e => e.method === RoleMethods.DELETE); this.operations.splice(index, 1); return this; } enableReview(): RoleBlock { this.operations.push({ method: RoleMethods.REVIEW }); return this; } disableReview(): RoleBlock { const index = this.operations.findIndex(e => e.method === RoleMethods.REVIEW); this.operations.splice(index, 1); return this; } enableSkipReview(): RoleBlock { this.operations.push({ method: RoleMethods.SKIP_REVIEW }); return this; } disableSkipReview(): RoleBlock { const index = this.operations.findIndex(e => e.method === RoleMethods.SKIP_REVIEW); this.operations.splice(index, 1); return this; } } export enum RoleMethods { GET = 'GET', PUT = 'PUT', POST = 'POST', DELETE = 'DELETE', REVIEW = 'REVIEW', SKIP_REVIEW = 'SKIP_REVIEW' } export class ErrorResponse { statusCode?: number; body?: object; message?: string; constructor(data: ErrorResponse | any) { if (typeof data === 'string') { this.statusCode = 500; this.body = { message: data }; this.message = 'Internal Error'; } else { this.statusCode = data?.statusCode; this.body = data?.body; this.message = data?.statusMessage; } } } export class SuccessResponse { message: string; [key: string]: any; constructor(data: SuccessResponse | any) { this.message = data?.message; } } export class FileUploadResponse { _id: string | undefined; length: number | undefined; chunkSize: number | undefined; uploadDate: string | undefined; filename: string | undefined; md5: string | undefined; contentType: string | undefined; metadata: { filename: string | undefined; } | undefined; constructor(data: any) { Object.assign(this, data); } } export class DataStackDocument { _id: number | undefined; _metadata: Metadata | undefined; [key: string]: FileUploadResponse | any; constructor(data?: any) { if (data) { Object.assign(this, data); this._id = data?._id; this._metadata = new Metadata(data?._metadata); } } setValue(path: string, value: any) { set(this, path, value); } getValue(path: string) { return get(this, path); } } export class Metadata { deleted: boolean; lastUpdated: Date | undefined; lastUpdatedBy: string; createdAt: Date | undefined; version: { document: number, release: string; } | undefined; constructor(data: Metadata) { this.deleted = data?.deleted || false; this.lastUpdated = data?.lastUpdated ? new Date(data?.lastUpdated) : undefined; this.lastUpdatedBy = data?.lastUpdatedBy || ''; this.createdAt = data?.createdAt ? new Date(data?.createdAt) : undefined; this.version = data?.version; } } export class WebHook { name: string; url: string; failMessage: string; constructor(data: WebHook) { this.name = data.name; this.url = data.url; this.failMessage = data.failMessage; } } export class SchemaField { private key: string | undefined; private type: SchemaFieldTypes; private properties: SchemaFieldProperties; private definition: SchemaField[]; constructor(data?: SchemaField) { this.key = data?.key; this.type = data?.type || SchemaFieldTypes.STRING; this.properties = new SchemaFieldProperties(data?.properties); this.definition = []; if (data?.definition) { this.definition = data?.definition.map(e => new SchemaField(e)); } } newField(data?: SchemaField) { return new SchemaField(data); } getName() { return this.properties.getName(); } setName(name: string): void { this.properties.setName(name); this.key = camelCase(name); } getKey() { return this.key; } setKey(key: string): void { this.key = key; this.setName(startCase(key)); } getType() { return this.type; } setType(type: SchemaFieldTypes): SchemaField { this.type = type; if (this.type === SchemaFieldTypes.ARRAY) { const childField = new SchemaField(); childField.setKey('_self'); return childField; } else { return this; } } addChildField(data: SchemaField) { this.type = SchemaFieldTypes.OBJECT; this.definition.push(data); return this; } removeChildField(name: string) { const index = this.definition.findIndex(e => e.getName() === name); this.definition.splice(index, 1); return this; } getProperties() { return this.properties; } } export enum SchemaFieldTypes { STRING = 'String', NUMBER = 'Number', BOOLEAN = 'Boolean', DATA = 'Data', OBJECT = 'Object', ARRAY = 'Array', RELATION = 'Relation', SCHEMA = 'Global', LOCATION = 'Geojson', } export class SchemaFieldProperties { private name: string | undefined; private required: boolean; private unique: boolean; private createOnly: boolean; private email: boolean; private password: boolean; private enum: string[]; private tokens: string[]; private maxLength: number | undefined; private minLength: number | undefined; private max: number | undefined; private min: number | undefined; private pattern: string | undefined; private default: string | undefined; private relatedTo: string | undefined; private schema: string | undefined; private dateType: string | undefined; constructor(data?: SchemaFieldProperties) { this.name = data?.name; this.required = data?.required || false; this.unique = data?.unique || false; this.createOnly = data?.createOnly || false; this.email = data?.email || false; this.password = data?.password || false; this.enum = data?.enum || []; this.tokens = data?.tokens || []; this.maxLength = data?.maxLength; this.minLength = data?.minLength; this.max = data?.max; this.min = data?.min; this.pattern = data?.pattern; this.default = data?.default; this.relatedTo = data?.relatedTo; this.schema = data?.schema; this.dateType = data?.dateType; } public getName(): string | undefined { return this.name; } public setName(name: string): void { this.name = name; } public isRequired(): boolean { return this.required; } public setRequired(required: boolean): void { this.required = required; } public isUnique(): boolean { return this.unique; } public setUnique(unique: boolean): void { this.unique = unique; } public isCreateOnly(): boolean { return this.createOnly; } public setCreateOnly(createOnly: boolean): void { this.createOnly = createOnly; } public isEmail(): boolean { return this.email; } public setEmail(email: boolean): void { this.email = email; } public isPassword(): boolean { return this.password; } public setPassword(password: boolean): void { this.password = password; } public getMaxLength(): number | undefined { return this.maxLength; } public setMaxLength(maxLength: number): void { this.maxLength = maxLength; } public getMinLength(): number | undefined { return this.minLength; } public setMinLength(minLength: number): void { this.minLength = minLength; } public getMax(): number | undefined { return this.max; } public setMax(max: number): void { this.max = max; } public getMin(): number | undefined { return this.min; } public setMin(min: number): void { this.min = min; } public getPattern(): string | undefined { return this.pattern; } public setPattern(pattern: string): void { this.pattern = pattern; } public getDefault(): string | undefined { return this.default; } public setDefault(value: string): void { this.default = value; } public getRelatedTo(): string | undefined { return this.relatedTo; } public setRelatedTo(relatedTo: string): void { this.relatedTo = relatedTo; } public getSchema(): string | undefined { return this.schema; } public setSchema(schema: string): void { this.schema = schema; } } export enum WorkflowActions { DISCARD = 'Discard', SUBMIT = 'Submit', REWORK = 'Rework', APPROVE = 'Approve', REJECT = 'Reject' } export class WorkflowRespond { private remarks: string | null; private attachments: Array<File>; constructor(data?: any) { this.remarks = data?.remarks; this.attachments = data?.attachments || []; } // public AddFileFromBuffer(data: any): WorkflowRespond { // return this; // } public AddFileFromPath(filePath: string): WorkflowRespond { readFileSync(filePath) return this; } public RemoveFile(name: string): WorkflowRespond { const index = this.attachments.findIndex(e => e.name === name); if (index > -1) { this.attachments.splice(index, 1); } return this; } public SetRemarks(text: string | null): WorkflowRespond { this.remarks = text; return this; } public CreatePayload(): any { return { remarks: this.remarks, attachments: this.attachments }; } }
typescript
Former India cricketer Kris Srikkanth has said he is a huge fan and believer of MS Dhoni and added that he would like to see the wicket-keeper batsman as a part of the Indian T20 World Cup squad. The T20 World Cup is slated to be played in Australia in October-November this year. Dhoni was slated to return to the cricket field on March 29 in the IPL's opening match between CSK and Mumbai Indians. However, the tournament has been suspended indefinitely as a precautionary measure against coronavirus. If the IPL does not take place this year, then it would really put Dhoni's selection in doubt as the cricketer has not played since July last year. Talking about Dhoni's future, Srikkanth told : "Dhoni has done a lot for Indian cricket, but the last ball of yesterday is all history, you start from scratch the next day, if he plays the T20 World Cup, there will be a microscope on him. We have freedom of speech so anybody can give an opinion, I am not Sunil Joshi (national selector) so I cannot decide. I am a fan of Dhoni so I would like to see him in the squad, but it is not my call". However, saying this, Srikkanth also said that if the IPL does not take place, it would really be difficult for Dhoni to make a comeback as he does not have any cricket behind him for almost a year. The former cricketer also said that KL Rahul and Rishabh Pant now have significant white-ball cricket experience behind them and they can very well edge out Dhoni when it comes to selection for the T20 World Cup. "I would say I am lucky that I am not a selector. The world knows that Dhoni last played during the 2019 World Cup. By the looks of it, it looks like IPL would not be happening soon. If there is no IPL and if India directly goes into T20 World Cup in Australia, how will selectors choose Dhoni? The only thing that could come in his favour is that he has played a lot for the country, but this looks highly improbable according to me," Srikkanth said. "Both Rahul and Pant have been a regular part of white-ball squad so that this can go in their favour. The odds are stacked up against Dhoni, but he can spring a surprise. The dilemma is with the spectators, it will be a huge challenge. It would be a tough call, personally I think it is stacked against Dhoni. It is a monumental task, knowing the sentiments of cricket followers in the country, it would be difficult for the selectors. If the selectors stick their neck out for Dhoni and if he doesn't perform and we do not win the World Cup, it can bring a lot of criticism towards the team and selectors," he added. Thirty-eight-year-old Dhoni has been currently enjoying some time away from the game. He last played competitive cricket during the 2019 World Cup. Dhoni had to face criticism for his slow batting approach during India's matches in the high-profile tournament. Earlier this year, Dhoni did not find a place for himself in the BCCI's centrally contracted players list. The board had released the list of central contract list of players for the period from October 2019 to September 2020. Dhoni is the only captain to win all major ICC trophies (50-over World Cup, T20 World Cup, and Champions Trophy). Under his leadership, India also managed to attain the number one ranking in Test cricket. ( With inputs from ANI )
english
{ "countries": [ "Australia", "Liechtenstein", "Monaco", "Switzerland", "Japan", "Norway" ], "topics": [ "UNFCCC and Kyoto Protocol Functioning", "Flexibility Mechanisms", "Extension of the Kyoto protocol" ], "section_title": "CMP Decision", "enb_start_date": "26-Nov-12", "enb_short_title": "COP 18", "subtype": "", "actors": [ "European Union" ], "sentences": [ "In its decision (FCCC/KP/CMP/2012/L.9), the CMP adopts the amendment to the Kyoto Protocol.", "The amendment, set out in Annex I, contains a new Annex B, setting out the quantified emission limitation and reduction commitment (QELRC) for each Annex I party for the second commitment period.", "The list of covered greenhouse gases in Protocol Annex A was amended by adding nitrogen trifluoride (NF3).", "Amendments were also adopted to Protocol Article 3.1, including the objective of reducing overall emissions by Annex I parties of the covered greenhouse gases by at least 18% below 1990 levels in the commitment period from 2013 to 2020.", "A new provision was added to Article 3.1 whereby a party included in Annex B may propose an adjustment to decrease its QELRC listed in Annex B, and this proposal shall be considered adopted by the CMP unless more than three-quarters of the parties present and voting object to its adoption.", "The CMP decision: recognizes that parties may provisionally apply the amendment pending its entry into force; and decides that each Annex I party will revisit its second commitment period QELRC by 2014 at the latest, and may increase the ambition of this QELRC in line with an aggregate reduction of GHG emissions of at least 25-40% below 1990 levels by 2020.", "Regarding eligibility to participate in the flexibility mechanisms, the CMP clarifies that all Annex I parties can continue to participate in ongoing and new CDM projects, but only parties with second commitment period QELRCs can transfer and acquire CERs in the second commitment period.", "It further decides, with respect to JI eligibility requirements for participating in emissions trading, only parties with second commitment period QELRCs can transfer and acquire CERs, AAUs, emission reduction units (ERUs) and removal units (RMUs) valid for emissions trading in the second commitment period.", "On the share of proceeds, the CMP extends the 2% share of proceeds levy to assist vulnerable developing countries to meet the costs of adaptation to emissions trading and JI.", "Regarding the carry-over of surplus AAUs, the CMP: - requires Annex I parties with second commitment period QELRCs to establish previous period surplus reserves ; - decides that CERs or ERUs in the national registry of an Annex I party that have not been cancelled or retired may be carried over to the subsequent commitment period up to a maximum for each unit type of 2.5% of the party s assigned amount; - decides that AAUs in a party s national registry that have not been retired or cancelled may be added to the party s second commitment period assigned amount and transferred to its previous period surplus reserve account; - such a party with surplus CERs, ERUs or AAUs can use this excess to fulfill its commitment, if its emissions exceed its assigned amount; and - allows parties to acquire units from other parties previous surplus reserve accounts into their own such accounts, up to 2% of their first commitment period assigned amounts.", "Annex II of the CMP decision contains political declarations on surplus AAUs, where Australia, the EU and its member states, Japan, Liechtenstein, Monaco, Norway and Switzerland declare that they will not purchase/use surplus AAUs carried over from the first commitment period.", "The CMP concludes by deciding that the AWG-KP has fulfilled its mandate and has concluded its work." ], "enb_url": "http://www.iisd.ca/vol12/enb12567e.html", "enb_long_title": "Doha Climate Change Conference - November 2012", "type": "", "id": "enb12567e_42", "enb_end_date": "08-Dec-12" }
json
With every passing day, Bungie finds itself in hot water with respect to Destiny 2. Over the past few seasons, the game has been riddled with problems, and many fans have complained about not being able to play the game. From basic server issues and game-breaking bugs to cheaters, players have had to face many problems on a regular basis. Ever since Destiny 2 Lightfall went live, it looks like the servers went for a toss. Moreover, players believe the campaign itself is mediocre, considering that Bungie fails to explain some major plot points that are important to the lore. The latest cause of outrage comes after the developer had to disable some mods in the title due to a game-breaking bug. The glitch in question was detected by a popular Destiny 2 content creator known as Cheese Forever. According to them, if players keep switching between armor with Focusing Strike, Bolstering Detonation, Impact Induction, and Momentum Transfer mods, they would instantly get their Supers and melee energy back. Although there's a certain skill curve associated with this, there's still a large number of players who would be able to do it without breaking a sweat. Players took to Twitter to express their disappointment with the bug. Some said it ruins the overall game experience. Others stated that Bungie could do with some new management, considering so many issues were cropping up. Many players also believe that Bungie is more concerned about speed rather than doing a proper QA check of the patches it puts out with respect to Destiny 2. What's more interesting is the fact that the four mods that Bungie has disabled can be found in almost every meta-build in Destiny 2 (for all three subclasses). Disabling them does hamper the efficacy of a build, especially in activities like Grandmaster Nightfalls and Raids. Considering that these are important mods, Bungie might employ a fix sooner than later. However, the fact that the developer had to disable the mods in the first place is somewhat disappointing to see. If this is how the servers and the game is going to behave in the coming days, Bungie might have a hard time convincing players to purchase The Final Shape, which is the final expansion in the Light vs Darkness saga. While everyone is excited about the upcoming expansion, there's a sentiment of distrust brewing among players. Bungie hyped up Destiny 2 Lightfall a lot but failed to deliver on the campaign. Fans can only hope that the developer has a plan to fix all the issues before the final campaign goes live.
english
import numpy as np def ornstein_uhlenbeck(input, theta=0.1, sigma=0.2): """Ornstein-Uhlembeck perturbation. Using Gaussian Wiener process.""" noise_perturb = -theta*input + sigma*np.random.normal() return input + noise_perturb noise = 0 for _ in range(20): noise = ornstein_uhlenbeck(noise) print(noise/(np.pi))
python
Former England allrounder Ravi Bopara produced a match-winning all-round performance to help Essex Eagles to their first Vitality T20 Blast Finals Day appearance in 2013, taking two wickets and then scoring 39 not out from 18 balls as Lancashire Lightning were defeated by six wickets at Durham’s Riverside ground. Put into bat, Lancashire made 159/5 with one-time England wicketkeeper-batsman Alex Davies top-scoring with 80* from 55 balls and the captain Dane Vilas getting 41 off 36. No other Lancashire batsman topped 14 and Glenn Maxwell was the only other to make it to double-digits. Bopara (2/28) and Aaron Beard (2/31) helped check Lancashire’s progress. Chasing 160, Essex lost wickets but Cameron Delport‘s 44 off 30 balls kept runs flowing until Bopara and skipper Ryan ten Doeschate (45* off 31) put on 60 to complete the game with four deliveries left.
english
<reponame>kyzoon/kaggle_titanic<filename>titanic2.py #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'preston.zhu' import numpy as np import pandas as pd import re import operator from sklearn.ensemble import RandomForestClassifier, ExtraTreesRegressor import pdb def get_title(name): # 正则表达式搜索,搜索到如' Mr.'的字符串 title_search = re.search(' ([A-Za-z]+)\.', name) # 搜索到则非空 if title_search: # group()返回一个字符串,字符串[0]为空格,故从[1]开始读取 return title_search.group(1) return "" family_id_mapping = {} def get_family_id(row): last_name = row['Name'].split(',')[0] family_id = "{0}{1}".format(last_name, row['FamilySize']) if family_id not in family_id_mapping: if len(family_id_mapping) == 0: current_id = 1 else: # operator.itemgetter(1)即取出对象第一个域的内容 # dict.items(): dict所有元素成都表示成元组,然后展开成list # max()函数按key参数比较大小,取出第一个列表中最大的对象 current_id = (max(family_id_mapping.items(), key=operator.itemgetter(1))[1] + 1) # 姓氏名映射成数值家庭号 family_id_mapping[family_id] = current_id return family_id_mapping[family_id] # 函数根据年龄和性别分成三类 def get_person(passenger): age, sex = passenger if age < 14: # child age define 14 return 'child' elif sex == 'female': return 'female_adult' else: return 'male_adult' # 获取家族名称 def process_surname(nm): return nm.split(',')[0].lower() perishing_female_surnames = [] def perishing_mother_wife(passenger): surname, Pclass, person = passenger # 筛选“成年女性,过逝的,有同行家庭成员的”,并返回1,否则返回0 return 1.0 if (surname in perishing_female_surnames) else 0.0 surviving_male_surnames = [] def surviving_father_husband(passenger): surname, Pclass, person = passenger return 1.0 if (surname in surviving_male_surnames) else 0.0 """ 特征工程: 采用将训练集与测试集的数据拼接在一起,然后进行回归,再补充'Age'的缺失值,这是一个很好的方法; 移除掉'Ticket'特征 'Embarked'特征采用众数'S'补充缺失值 'Fare'采用中间值补充缺件值 增加'TitleCat'特征:从名称中抽取表示个人身份地位的称为来表示 增加'CabinCat'特征:先将缺件值补充字符'0',然后提取第一个字符做为其分类。缺失值太多,另作为一个分类 增加'EmbarkedCat'特征:由'Cabin'特征转换成数值分类表示 增加'Sex_male'和'Sex_female'两个特征:由'Sex'特征仿拟(dummy) 增加'FamilySize'特征:由'SibSp'和'Parch'两个特征之各,表示同行家人数量 增加'NameLength'特征:由名称字符数量表示。 增加'FamilyId'特征:先提取'Name'特征中的姓氏,并按字母排序编号得出。另外,同行家人少于3人的,'FamilyId'统一 归于-1类 增加'person'特征:由'Age'和'Sex'特征,小于14岁定义为儿童'child',大于14岁的女性定义为成年女性 'female_adult',大于14岁的男性定义为成年男性'male_adult' 增加'persion_child', 'person_female_adult', 'person_male_adult'三个特征:由'person'特征仿拟(dummy) 增加'surname'特征:由'Name'特征提取出姓氏部分 增加'perishing_mother_wife'特征:过逝的母亲或妻子,对家人的存活影响会比较大 增加‘surviving_father_husband'特征:存活的父亲或丈夫,对家人的存活影响也会比较大 最后选择进行训练的特征为: 'Age', 'Fare', 'Parch', 'Pclass', 'SibSp','male_adult', 'female_adult', 'child', 'perishing_mother_wife', 'surviving_father_husband', 'TitleCat', 'CabinCat', 'Sex_female', 'Sex_male', 'EmbarkedCat', 'FamilySize', 'NameLength', 'FamilyId' 由于经过拼接,所以需要对训练集与测试集进行拆分,前891个实例为训练集,后418个实例为测试集 """ def features(): train_data = pd.read_csv("input/train.csv", dtype={"Age": np.float64}) test_data = pd.read_csv("input/test.csv", dtype={"Age": np.float64}) # 按列方向连接两个DataFrame,test_data排在train_data之后 combined2 = pd.concat([train_data, test_data], axis=0) # 去掉'Ticket'特征,axis=1表示每行,inplace=True表示直接作用于本身 combined2.drop(['Ticket'], axis=1, inplace=True) # Embarked特征使用众数补充缺失值 # inplace参数为True,函数作用于当前变量之上 combined2.Embarked.fillna('S', inplace=True) # Fare特征使用中间值补充缺失值 combined2.Fare.fillna(combined2.Fare[combined2.Fare.notnull()].median(), inplace=True) # 新建'Title'特征,从'Name'特征中提取称谓来表示 # Series.apply(func)对Series中每一个元素都调用一次func函数 combined2['Title'] = combined2["Name"].apply(get_title) title_mapping = { "Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Dr": 5, "Rev": 6, "Major": 7, "Col": 7, "Mlle": 8, "Mme": 8, "Don": 7, "Dona": 10, "Lady": 10, "Countess": 10, "Jonkheer": 10, "Sir": 7, "Capt": 7, "Ms": 2 } # 新建'TitleCat'特征,则'Title'映射成数值 # map()函数使用dict对'Title'每个元素都进行映射 combined2["TitleCat"] = combined2.loc[:, 'Title'].map(title_mapping) # 新建'CabinCat'特征。缺失值补充为0,其它项取第一个字母 # Categorical先统计数组中有多少个不同项,按升序排列,然后用数值表示各个分类 combined2["CabinCat"] = pd.Categorical(combined2.Cabin.fillna('0').apply(lambda x: x[0])).codes # Cabin特征缺失值为'0'填充 combined2.Cabin.fillna('0', inplace=True) # 以数值表示'Embarked'各个分类 combined2['EmbarkedCat'] = pd.Categorical(combined2.Embarked).codes # 延行方向进行连接,创建新DataFrame;增加两个性别相关列,并将'Survived'特征移动至最后一列 # pandas.get_dummies()将'Sex'特征重构成'Sex_male'和'Sex_female'两列, # 'Sex_male'列中,male表示为1,female表示为0. 'Sex_female'则相反 full_data = pd.concat([ combined2.drop(['Survived'], axis=1), pd.get_dummies(combined2.Sex, prefix='Sex'), combined2.Survived ], axis=1) # 新建'FamilySize'特征,使用'SibSp'和'Parch'两个家庭成员特征求和得出 full_data['FamilySize'] = full_data['SibSp'] + full_data['Parch'] # 新建'NameLength'特征,使用名称长度表示 full_data['NameLength'] = full_data.Name.apply(lambda x: len(x)) family_ids = full_data.apply(get_family_id, axis=1) # 将所有家庭成员人数小于3个的设置成-1类,归成一类 family_ids[full_data['FamilySize'] < 3] = -1 # 新建'FamilyId'特征 full_data['FamilyId'] = family_ids # 追加'person'特征列,'person'特征由年龄和性别划分成child, femal_adult, male_adult full_data = pd.concat([ full_data, pd.DataFrame(full_data[['Age', 'Sex']].apply(get_person, axis=1), columns=['person']) ], axis=1) # dummies person dummies = pd.get_dummies(full_data['person']) # 追加'persion_child', 'person_female_adult', 'person_male_adult'三个特征 full_data = pd.concat([full_data, dummies], axis=1) # 新建姓氏名称'surname'特征 full_data['surname'] = full_data['Name'].apply(process_surname) # 筛选“成年女性,过逝的,有同行家庭成员的”,去重 perishing_female_surnames = list(set(full_data[ (full_data.female_adult == 1.0) & (full_data.Survived == 0.0) & ((full_data.Parch > 0) | (full_data.SibSp > 0))]['surname'].values)) # 新建'perishing_mother_wife'特征,如果是“已过逝且有同行家人的成年女性”为1,否则为0 full_data['perishing_mother_wife'] \ = full_data[['surname', 'Pclass', 'person']].apply(perishing_mother_wife, axis=1) # 筛选“成年男性,存活的,有同行家人了”,去重 surviving_male_surnames = list(set(full_data[ (full_data.male_adult == 1.0) & (full_data.Survived == 1.0) & ((full_data.Parch > 0) | (full_data.SibSp > 0))]['surname'])) full_data['surviving_father_husband'] \ = full_data[['surname', 'Pclass', 'person']].apply(surviving_father_husband, axis=1) # 定义筛选器 classers = [ 'Fare', 'Parch', 'Pclass', 'SibSp', 'TitleCat', 'CabinCat', 'Sex_female', 'Sex_male', 'EmbarkedCat', 'FamilySize', 'NameLength', 'FamilyId' ] # ExtraTreesRegressor模型,用带'Age'特征的数据回归出'Age'特征缺失的值 age_et = ExtraTreesRegressor(n_estimators=200) # 筛选'Age'不为空的数据作为训练集 X_train = full_data.loc[full_data.Age.notnull(), classers] # 筛选'Age'不为空的数据的'Age'特征作为训练集的结果标签 Y_train = full_data.loc[full_data.Age.notnull(), ['Age']] # 'Age'为空即为测试集 X_test = full_data.loc[full_data.Age.isnull(), classers] # np.ravel()转换为np.array age_et.fit(X_train, np.ravel(Y_train)) age_preds = age_et.predict(X_test) # 将回归预测的结果,填充到原数据集中 full_data.loc[full_data.Age.isnull(), ['Age']] = age_preds # 定义筛选器 model_dummys = [ 'Age', 'Fare', 'Parch', 'Pclass', 'SibSp','male_adult', 'female_adult', 'child', 'perishing_mother_wife', 'surviving_father_husband', 'TitleCat', 'CabinCat', 'Sex_female', 'Sex_male', 'EmbarkedCat', 'FamilySize', 'NameLength', 'FamilyId' ] # 筛选出训练集,测试集 X_data = full_data.iloc[:891, :] X_train = X_data.loc[:, model_dummys] Y_data = full_data.iloc[:891, :] y_train = Y_data.loc[:, ['Survived']] X_t_data = full_data.iloc[891:, :] X_test = X_t_data.loc[:, model_dummys] test_PassengerId = X_t_data.PassengerId.as_matrix() return X_train, y_train, X_test, test_PassengerId def titanic(): print('Preparing Data...') X_train, y_train, X_test, test_PassengerId = features() print('Train RandomForestClassifier Model...') # 随机森林模型 model_rf = RandomForestClassifier(n_estimators=300, min_samples_leaf=4, class_weight={0:0.745,1:0.255}) # 训练 model_rf.fit(X_train, np.ravel(y_train)) print('Predictings...') model_results = model_rf.predict(X_test) print('Generate Submission File...') submission = pd.DataFrame({ 'PassengerId': test_PassengerId, 'Survived': model_results.astype(np.int32) }) submission.to_csv('prediction7.csv', index=False) print('Done.') if __name__ == '__main__': titanic()
python
from .embedded import EmbeddedStorage from .inmemory import InMemoryStorage from .mongo import MongoStorage from .sqlite import SQLiteStorage
python
NewZNew (Chandigarh) : Fortis Hospital, Mohali organized a session on ‘Self Esteem’ by Dr Savita Malhotra, Consultant, Psychiatry to the students of Class X at the Bhavan Vidyalaya-27 today. The students listened in rapt attention as the world-renowned expert in child and adolescent psychiatry addressed & explained them on topics like self-improvement, pursuit of happiness, individualism and personal well-being and effectiveness. Dr Malhotra, former Dean and Head of Psychiatry Department at PGIMER, recently joined Fortis Mohali. She has over 40 years of experience of patient care, teaching and research and is trained in Child Psychiatry in UK and USA. Talking about why high self-esteem is important, she said it leads to positive self-image, confidence and ability to make friends easily. “Those with high self-esteem feel more comfortable around new people, find it easier to seek help and are proud of their achievements,” Dr Malhotra added. In contrast, those with poor self-esteem are fearful of making mistakes and failing, are generally under-achievers and unsure about their decisions. “Without generalizing, we can safely can that they are also shy & quiet, insecure, unhappy & angry. As a result, they suffer from depression, have poor self-image, lack confidence and also harbor suicidal thoughts,” the doctor said. The most common signs of children suffering from poor self-esteem are that they start avoiding, become shy, withdraw into a shell, quit and give up easily. “When help is not available, children with low self-esteem resort to bullying, cheating, aggression, rowdy behavior, substance abuse and can fall victim to psychiatric disorders like anorexia, bulimia, anxiety, dissociation and attention-seeking behavior,” she warned. Advising teachers to avoid criticism, ridicule and public shaming, Dr Malhotra said passing judgmental statements often causes children to clamp up. “Instead of focusing on the problem child, focus on his/her behavior,” she suggested. Positive parenting also goes a long way into developing high self-esteem, the Fortis doctor said, advising parents to use praise, good communication, reasoning and healthy discussion as tools. “Be fair, firm and friendly,” she strongly recommended.
english