text
stringlengths 1
1.04M
| language
stringclasses 25
values |
---|---|
{
"siteTitle": "Defend Crypto",
"googleAnalyticsId": "UA-123898108-17",
"matomoSiteId": "",
"donateUrl": "https://donate.fightforthefuture.org/",
"mapboxToken": "",
"isArchived": false
}
| json |
.component{
padding-left: 35px;
padding-bottom: 15px;
margin-bottom: 25px;
border-color: #408BC9;
}
.clusterHeader{
color: white;
text-align: center;
font-size: larger;
font-weight: bolder;
padding: 20px;
background-color: #35558e;
margin: 0;
}
.running{
color: #085208;
font-weight: bold;
background-color: #d3f9d3;
padding: 5px;
text-transform: capitalize;
}
.shutting-down{
color: #a00505;
font-weight: bold;
background-color: #e89e9e;
padding: 5px;
text-transform: capitalize;
}
.terminated{
color: #bb7205;
font-weight: bold;
background-color: #daa4539e;
padding: 5px;
text-transform: capitalize;
}
| css |
package input
import (
"github.com/galaco/tinygametools"
"github.com/go-gl/glfw/v3.3/glfw"
)
type mouse struct {
window *tinygametools.Window
mouse *tinygametools.Mouse
xOld, yOld float64
}
func (m *mouse) LockMousePosition() {
m.window.Handle().SetInputMode(glfw.CursorMode, glfw.CursorDisabled)
}
func (m *mouse) UnlockMousePosition() {
m.window.Handle().SetInputMode(glfw.CursorMode, glfw.CursorNormal)
}
func (m *mouse) SetBoundWindow(win *tinygametools.Window) {
m.window = win
}
func (m *mouse) RegisterExternalMousePositionCallback(callback func(x, y float64)) {
m.mouse.AddMousePosCallback(func(window *glfw.Window, xpos float64, ypos float64) {
if m.xOld == 0 {
m.xOld = xpos
}
if m.yOld == 0 {
m.yOld = ypos
}
callback(xpos-m.xOld, ypos-m.yOld)
m.xOld = xpos
m.yOld = ypos
})
}
| go |
Houston Texans defensive end DeMarcus Walker added to the defense’s ability to score in the third and final preseason game.
Against the Tampa Bay Buccaneers at NRG Stadium Saturday night, Walker fell on quarterback Blaine Gabbert, who was attempting to recover a bad snap in the end zone. Walker got a safety for the Texans, who trailed 13-2 late in the second quarter.
Walker told reporters on Aug. 19 that one of his favorite aspects of playing in the Texans’ defense was the ability to just play and not overthink.
The Texans trailed 16-2 at halftime.
| english |
Punjab Health minister Balbir Singh Sidhu who recently shared the stage with Congress leader Rahul Gandhi tested positive for coronavirus on Tuesday, a health officer said. He has mild fever and a sore throat, Mohali civil surgeon Manjit Singh said.
The minister is stable and in isolation at home. People who have come in contact with him will also be tested, the doctor said. Sidhu was in Sangrur on Monday for Kheti Bachao Yatra, taking part in a protest against the new farm laws.
The event was also attended by Rahul Gandhi, Chief Minister Amarinder Singh and other senior Congress leaders. Gandhi led a series of tractor rallies in the state for three days against the new laws. On Tuesday afternoon, he entered neighbouring Haryana to continue with the protests. (This story has not been edited by News18 staff and is published from a syndicated news agency feed - PTI) | english |
On Friday, July 14, authorities released documents that revealed how they came to arrest Rex Heuermann, an architect who has been accused of being the Gilgo Beach serial killer. Heuermann has been charged with six counts of murder, with investigators connecting the architect to 11 sets of human remains that were found along Gilgo beach in 2010 and 2011.
He has pleaded not guilty to the charges of first-degree murder.
Trigger warning: This article concerns references to violence and child abuse. Readers' discretion is advised.
Authorities said that they began to suspect Heuermann after probing his search history, which included searches for sadistic, torture-related p*rnography and child abuse-related material.
In response to the shocking revelations, many netizens noted the horrifying fact that Rex Heuermann was a seemingly normal family man with children.
How did Rex Heuermann's google searches lead authorities to him?
As per Suffolk County and New York State authorities, authorities began to suspect Rex Heuermann after they probed his cellphone records. It was then revealed that the architect's phone was tied to several burner numbers, which had reportedly been used to communicate with the victims who were discovered on Gilgo Beach.
The victims were Melissa Barthelemy, 24, Amber Costello, 27, and Megan Waterman, 22. Heuermann is also a suspect in the murder of Maureen Brainard-Barnes, but has not been charged.
Upon discovering that the burners were potentially connected to Heuermann, New York authorities began exploring the suspected serial killer's search history. They discovered that he appeared to be obsessively searching up details of the murder investigation.
As reported by Fox, the searches included "why hasn’t the long island serial killer been caught," and "why could law enforcement not trace the calls made by the long island serial killer. " Additionally, he reportedly searched up the victim's children and relatives.
Suffolk County District Attorney Raymond Tierney said that Heuermann was also looking up violent and graphic online material:
"[Heuermann] was compulsively searching pictures of the victims. But not only pictures of the victims: Pictures of their relatives, their sisters, their children. And he was trying to locate those individuals. "
Netizens were particularly stunned by the nature of the man's internet searches, as they wondered how a family man could look up child abuse. Some also expressed their condolences for the victims' families:
Many netizens took to social media to post their reactions after reading the man's browsing history and going through his court documents:
According to neighbors, Rex Heuermann was always considered strange and intimidating. One neighbor, Barry Auslander, told Newsweek that during Halloween, children were urged to stay away from his home.
Another neighbor, who remained unidentified, said that Heuermann was a quiet neighbor who could occasionally be seen washing his car or doing other chores.
As the allegations against Rex Heuermann came to light, netizens also searched through all online traces of the suspect. As someone who was well known for architectural work, he appeared for an interview on Bonjour Realty, where he discussed his career. | english |
#!usr/bin/env python
#coding:utf8
from nltk.tokenize import TweetTokenizer
from nltk.stem.cistem import Cistem
from nltk.corpus import stopwords
import nltk
from sklearn.feature_extraction.text import CountVectorizer
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from pathlib import Path
from sklearn.cluster import KMeans
from sklearn.manifold import TSNE
nltk.download('stopwords')
tknzr= TweetTokenizer()
stemmer = Cistem(True)
file_in = open("../data/postillon.txt", "r")
file_out = open("../build/preprocessed/postillon_stem.txt", "w")
for line in file_in:
tokenized = tknzr.tokenize(line)
for word in tokenized:
if word in stopwords.words('german'):
tokenized.remove(word)
word = stemmer.stem(word)
token_text = " ".join(tokenized)
file_out.write(token_text+'\n')
file_in.close()
file_out.close()
data = open("../build/preprocessed/postillon_stem.txt", "r")
vectorizer = CountVectorizer(max_features=1000, ngram_range=(1, 3))
X = vectorizer.fit_transform(data).toarray()
#print(vectorizer.get_feature_names())
#print(X)
contents = Path("../build/preprocessed/postillon_stem.txt").read_text()
wordcloud = WordCloud(background_color='white',
width=1920,
height=1080
).generate(contents)
plt.imshow(wordcloud)
plt.axis('off')
plt.savefig("../build/plots/postillonWordcloud.pdf")
plt.clf()
X_embedded = TSNE(n_components=2).fit_transform(X)
kmeans = KMeans(n_clusters=12)
kmeans.fit(X_embedded)
#print(kmeans.labels_)
plt.scatter(X_embedded[:, 0], X_embedded[:, 1], c=kmeans.labels_, cmap='rainbow')
plt.scatter(kmeans.cluster_centers_[:, 0],
kmeans.cluster_centers_[:, 1], color='black')
plt.savefig("../build/plots/tSNE_kNN_postillon.pdf")
| python |
<reponame>1224500506/NCME-Web
package com.hys.qiantai.struts.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.hys.auth.util.DateUtils;
import com.hys.auth.util.ParamUtils;
import com.hys.auth.util.StrutsUtil;
import com.hys.exam.common.util.DateUtil;
import com.hys.exam.common.util.LogicUtil;
import com.hys.exam.common.util.StringUtil;
import com.hys.exam.constants.Constants;
import com.hys.exam.model.CVSet;
import com.hys.exam.model.ExamHospital;
import com.hys.exam.model.ExamProp;
import com.hys.exam.model.ExpertInfo;
import com.hys.exam.model.SystemUser;
import com.hys.exam.service.local.CVSetEntityManage;
import com.hys.exam.service.local.CVSetManage;
import com.hys.exam.service.local.SystemUserManage;
import com.hys.exam.sessionfacade.local.ExamPropValFacade;
import com.hys.exam.utils.PageList;
import com.hys.exam.utils.PageUtil;
import com.hys.framework.web.action.BaseAction;
import com.hys.qiantai.model.LogStudyCvSet;
import com.hys.qiantai.model.MyStudyInfo;
import com.hys.qiantai.model.StudyRecordInfo;
public class StudyRecordManageAction extends BaseAction {
CVSetEntityManage localCVSetEntity;
private ExamPropValFacade localExamPropValFacade;
CVSetManage localCVSetManage;
public ExamPropValFacade getLocalExamPropValFacade() {
return localExamPropValFacade;
}
public void setLocalExamPropValFacade(ExamPropValFacade localExamPropValFacade) {
this.localExamPropValFacade = localExamPropValFacade;
}
public CVSetManage getLocalCVSetManage() {
return localCVSetManage;
}
public void setLocalCVSetManage(CVSetManage localCVSetManage) {
this.localCVSetManage = localCVSetManage;
}
public CVSetEntityManage getLocalCVSetEntity() {
return localCVSetEntity;
}
public void setLocalCVSetEntity(CVSetEntityManage localCVSetEntity) {
this.localCVSetEntity = localCVSetEntity;
}
protected String actionExecute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
SystemUser user = LogicUtil.getSystemUser(request);
if(user == null)
{
return "fail";
}
LogStudyCvSet info = new LogStudyCvSet();
List<MyStudyInfo> list = new ArrayList<MyStudyInfo>();
int year = ParamUtils.getIntParameter(request, "year", 0);
int month = ParamUtils.getIntParameter(request, "month", 0);
// 没选择年,不用月 2017-01-12 han
if (year == 0)
month = 0;
info.setsYear(year);
info.setsMonth(month);
info.setSystem_user_id(user.getUserId());
PageList<LogStudyCvSet> page = new PageList<LogStudyCvSet>();
int currentPage = PageUtil.getPageIndex(request);
int pageSize = PageUtil.getPageSize(request);
page.setObjectsPerPage(pageSize);
page.setPageNumber(currentPage);
localCVSetEntity.getLogCVSetListFromUser(info, page);
/* //Get My Job
ExamProp myJobClass = new ExamProp();
myJobClass.setType(9);
List<ExamProp> myJobClassList = localExamPropValFacade.getPropListByType(myJobClass);
Integer workExtType = 0;
for(ExamProp examProp: myJobClassList) {
String userJobId = user.getJob_Id();
if(userJobId != null)
{
String eId = String.valueOf(examProp.getId());
if(!userJobId.equals(eId)) {
continue;
}
workExtType = examProp.getExt_type();
myJobClass.setExt_type(workExtType);
myJobClassList = localExamPropValFacade.getPropListByType(myJobClass);
request.setAttribute("myJobList", myJobClassList);
}
}
//Hospital
ExamHospital host = new ExamHospital();
if(user.getWork_unit_id() != null)
{
String userWorkID = String.valueOf(user.getWork_unit_id());
host.setId(Long.valueOf(userWorkID));
List<ExamHospital> list2 = localExamPropValFacade.getHospitalList(host);
request.setAttribute("hospital", list2);
}*/
request.setAttribute("userInfo", user);
request.setAttribute("pageStudyRecord", page);
request.setAttribute("year", year);
request.setAttribute("month", month);
request.setAttribute("data", list);
return "success";
}
} | java |
<filename>server.js
var express = require('express');
var fs = require('fs');
var app = express();
var PORT = process.env.PORT || 5000;
app.use(express.static(__dirname));
// how to handle the receiving end. this just pipes the data
// it receives into a file on disk. Alternatively transcode it and
// send the result back to the client.
app.post('/convert', function(req, res, next) {
console.log('receiving');
var outStream = fs.createWriteStream('./output.wav');
outStream.on('close', function() {
console.log('all good');
res.status(200).end('OK')
});
outStream.on('error', function(err) {
console.error(err);
res.status(500).end(err.message);
});
req.pipe(outStream);
});
app.listen(PORT, function() {console.log('on http://localhost:' + PORT)});
| javascript |
<reponame>hskang9/monkey-rust
use crate::token::*;
#[derive(Debug, Clone)]
pub struct Lexer {
/// input string of code
pub input: String,
/// current read position of lexer
pub position: usize,
/// position to read in string
pub read_position: usize,
/// next character to read
pub ch: char,
}
impl Lexer {
pub fn new(input: String) -> Lexer {
let mut l = Lexer {
input,
position: 0,
read_position: 0,
ch: ' ',
};
l.read_char();
return l;
}
pub fn peek_char(&mut self) -> char {
if self.read_position >= self.input.len() {
'\0'
} else {
self.input.chars().nth(self.read_position).unwrap()
}
}
pub fn read_char(&mut self) {
if self.read_position >= self.input.len() {
self.ch = '\0';
} else {
self.ch = self.input.chars().nth(self.read_position).unwrap();
}
self.position = self.read_position;
self.read_position += 1;
}
pub fn new_token(&mut self, r#type: TokenType, literal: String) -> Token {
Token { r#type, literal }
}
pub fn next_token(&mut self) -> Token {
self.skip_whitespace();
let ch: char = self.ch.clone();
let tok = match ch {
'=' => {
if self.peek_char() == '=' {
self.read_char();
let token_literal = [ch.clone().to_string(), ch.clone().to_string()].concat();
self.new_token(EQ, token_literal)
} else {
self.new_token(ASSIGN, self.ch.to_string())
}
}
';' => self.new_token(SEMICOLON, self.ch.to_string()),
'(' => self.new_token(LPAREN, self.ch.to_string()),
')' => self.new_token(RPAREN, self.ch.to_string()),
',' => self.new_token(COMMA, self.ch.to_string()),
'+' => self.new_token(PLUS, self.ch.to_string()),
'-' => self.new_token(MINUS, self.ch.to_string()),
'!' => {
if self.peek_char() == '=' {
self.read_char();
let token_literal = [ch.clone().to_string(), '='.to_string()].concat();
self.new_token(NOT_EQ, token_literal)
} else {
self.new_token(BANG, self.ch.to_string())
}
}
'/' => self.new_token(SLASH, self.ch.to_string()),
'*' => self.new_token(ASTERISK, self.ch.to_string()),
'<' => self.new_token(LT, self.ch.to_string()),
'>' => self.new_token(GT, self.ch.to_string()),
'{' => self.new_token(LBRACE, self.ch.to_string()),
'}' => self.new_token(RBRACE, self.ch.to_string()),
'\0' => self.new_token(EOF, self.ch.to_string()),
_ => {
if is_letter(ch.clone()) {
let token_literal = self.read_identifier().to_string();
self.position += token_literal.len();
return self.new_token(lookup_ident(&token_literal), token_literal);
} else if is_digit(ch.clone()) {
let token_literal = self.read_number().to_string();
return self.new_token(INT, token_literal);
} else {
self.read_char();
return self.new_token(ILLEGAL, ch.to_string());
}
}
};
self.read_char();
return tok;
}
pub fn read_identifier(&mut self) -> &str {
let position = self.position;
while is_letter(self.ch) {
self.read_char()
}
return &self.input[position..self.position];
}
pub fn read_number(&mut self) -> &str {
let position = self.position;
while is_digit(self.ch) {
self.read_char()
}
&self.input[position..self.position]
}
pub fn skip_whitespace(&mut self) {
loop {
if self.ch == ' ' || self.ch == '\t' || self.ch == '\n' || self.ch == '\r' {
self.read_char();
} else {
break;
}
}
}
}
pub fn is_letter(ch: char) -> bool {
'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_'
}
pub fn is_digit(ch: char) -> bool {
'0' <= ch && ch <= '9'
}
| rust |
import mongoose from "mongoose";
export type UserDocument = mongoose.Document & {
_id: mongoose.Types.ObjectId,
firstName: string,
lastName: string,
email: string,
password: string,
}
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
lowercase: true,
},
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
});
export const User = mongoose.model<UserDocument>("User", userSchema);
| typescript |
import * as utils from 'tns-core-modules/utils/utils';
import { android as androidApp } from "tns-core-modules/application";
import { CardBrand, CardCommon, CreditCardViewBase, PaymentMethodCommon, StripePaymentIntentCommon, StripePaymentIntentStatus, Token } from './stripe.common';
export class Stripe {
private _stripe: com.stripe.android.Stripe;
private _apiKey: string;
constructor(apiKey: string) {
this._apiKey = apiKey;
this._stripe = new com.stripe.android.Stripe(
utils.ad.getApplicationContext(),
apiKey
);
}
setStripeAccount(accountId: string) {
this._stripe.setStripeAccount(accountId);
}
createToken(card: CardCommon, cb: (error: Error, token: Token) => void): void {
if (!card) {
if (typeof cb === 'function') {
cb(new Error('Invalid card'), null);
}
return;
}
this._stripe.createToken(
card.native,
new com.stripe.android.TokenCallback({
onSuccess: function (token) {
if (typeof cb === 'function') {
const newToken: Token = {
id: token.getId(),
bankAccount: token.getBankAccount(),
card: Card.fromNative(token.getCard()),
created: new Date(token.getCreated().toString()),
livemode: token.getLivemode(),
android: token,
ios: null
};
cb(null, newToken);
}
},
onError: function (error) {
if (typeof cb === 'function') {
cb(new Error(error.getLocalizedMessage()), null);
}
}
})
);
}
createPaymentMethod(card: CardCommon, cb: (error: Error, pm: PaymentMethod) => void): void {
if (!card) {
if (typeof cb === 'function') {
cb(new Error('Invalid card'), null);
}
return;
}
const cardParams = new com.stripe.android.model.PaymentMethodCreateParams.Card.Builder();
if (card.cvc) cardParams.setCvc(card.cvc);
if (card.expMonth) cardParams.setExpiryMonth(new java.lang.Integer(card.expMonth));
if (card.expYear) cardParams.setExpiryYear(new java.lang.Integer(card.expYear));
if (card.number) cardParams.setNumber(card.number);
const billing = new com.stripe.android.model.PaymentMethod.BillingDetails.Builder();
const addr = new com.stripe.android.model.Address.Builder();
if (card.addressLine1) addr.setLine1(card.addressLine1);
if (card.addressLine2) addr.setLine2(card.addressLine2);
if (card.addressCity) addr.setCity(card.addressCity);
if (card.addressState) addr.setState(card.addressState);
if (card.addressZip) addr.setPostalCode(card.addressZip);
if (card.addressCountry) addr.setCountry(card.addressCountry);
billing.setAddress(addr.build());
const params = com.stripe.android.model.PaymentMethodCreateParams.create(cardParams.build(), billing.build());
try {
const apiResultCallback = new com.stripe.android.ApiResultCallback<com.stripe.android.model.PaymentMethod>({
onSuccess: (result: any) => {
cb(null, PaymentMethod.fromNative(result));
},
onError: (error: any) => {
cb(new Error(error.localizedDescription), null);
}
});
this._stripe.createPaymentMethod(params, apiResultCallback, this._apiKey, null);
} catch (error) {
if (typeof cb === 'function') {
cb(new Error(error.localizedDescription), null);
}
}
}
retrievePaymentIntent(clientSecret: string, cb: (error: Error, pm: StripePaymentIntent) => void): void {
try {
const pi = this._stripe.retrievePaymentIntentSynchronous(clientSecret);
cb(null, StripePaymentIntent.fromNative(pi));
} catch (error) {
cb(new Error(error.localizedDescription), null);
}
}
confirmSetupIntent(paymentMethodId: string, clientSecret: string, cb: (error: Error, pm: StripeSetupIntent) => void): void {
try {
const activity = androidApp.foregroundActivity;
const resultCb = new com.stripe.android.ApiResultCallback<com.stripe.android.SetupIntentResult>({
onSuccess: (result: com.stripe.android.SetupIntentResult) => {
cb(null, StripeSetupIntent.fromNative(result.getIntent()));
},
onError: (error: any) => {
cb(new Error(error.localizedDescription), null);
}
});
activity.onActivityResult = (requestCode, resultCode, data) => {
this._stripe.onSetupResult(requestCode, data, resultCb);
};
this._stripe.confirmSetupIntent(activity, new StripeSetupIntentParams(paymentMethodId, clientSecret).native);
} catch (error) {
cb(new Error(error.localizedDescription), null);
}
}
authenticateSetupIntent(clientSecret: string, returnUrl: string, cb: (error: Error, pm: StripeSetupIntent) => void): void {
const activity = androidApp.foregroundActivity;
const resultCb = new com.stripe.android.ApiResultCallback<com.stripe.android.SetupIntentResult>({
onSuccess: (result: com.stripe.android.SetupIntentResult) => {
cb(null, StripeSetupIntent.fromNative(result.getIntent()));
},
onError: (error: any) => {
cb(new Error(error.localizedDescription), null);
}
});
activity.onActivityResult = (requestCode, resultCode, data) => {
this._stripe.onSetupResult(requestCode, data, resultCb);
};
this._stripe.authenticateSetup(activity, clientSecret);
}
confirmPaymentIntent(piParams: StripePaymentIntentParams, cb: (error: Error, pm: StripePaymentIntent) => void): void {
try {
const activity = androidApp.foregroundActivity;
const resultCb = new com.stripe.android.ApiResultCallback<com.stripe.android.PaymentIntentResult>({
onSuccess: (result: com.stripe.android.PaymentIntentResult) => {
cb(null, StripePaymentIntent.fromNative(result.getIntent()));
},
onError: (error: any) => {
cb(new Error(error.localizedDescription), null);
}
});
activity.onActivityResult = (requestCode, resultCode, data) => {
this._stripe.onPaymentResult(requestCode, data, resultCb);
};
this._stripe.confirmPayment(activity, piParams.native);
} catch (error) {
cb(new Error(error.localizedDescription), null);
}
}
// Manual confirmation flow https://stripe.com/docs/payments/payment-intents/ios#manual-confirmation-ios
authenticatePaymentIntent(clientSecret: string, returnUrl: string, cb: (error: Error, pm: StripePaymentIntent) => void): void {
const activity = androidApp.foregroundActivity;
const resultCb = new com.stripe.android.ApiResultCallback<com.stripe.android.PaymentIntentResult>({
onSuccess: (result: com.stripe.android.PaymentIntentResult) => {
cb(null, StripePaymentIntent.fromNative(result.getIntent()));
},
onError: (error: any) => {
cb(new Error(error.localizedDescription), null);
}
});
activity.onActivityResult = (requestCode, resultCode, data) => {
this._stripe.onPaymentResult(requestCode, data, resultCb);
};
this._stripe.authenticatePayment(activity, clientSecret);
}
}
export class Card implements CardCommon {
private _cardBuilder: com.stripe.android.model.Card.Builder;
private _brand: CardBrand;
private _last4: string;
constructor(
cardNumber: string,
cardExpMonth: number,
cardExpYear: number,
cardCVC: string
) {
if (cardNumber && cardExpMonth && cardExpYear && cardCVC) {
this._cardBuilder = new com.stripe.android.model.Card.Builder(
cardNumber,
new java.lang.Integer(cardExpMonth),
new java.lang.Integer(cardExpYear),
cardCVC
);
}
}
public static fromNative(card: com.stripe.android.model.Card): Card {
const newCard = new Card(null, null, null, null);
newCard._cardBuilder = card.toBuilder();
return newCard;
}
public static fromNativePaymentMethod(pm: com.stripe.android.model.PaymentMethod): Card {
const newCard = new Card(null, null, null, null);
newCard._last4 = pm.card.last4;
newCard._brand = <CardBrand>pm.card.brand;
newCard._cardBuilder = new com.stripe.android.model.Card.Builder(null, pm.card.expiryMonth, pm.card.expiryYear, null).country(pm.card.country);
return newCard;
}
get native(): com.stripe.android.model.Card {
return this._cardBuilder.build();
}
validateNumber(): boolean {
return this.native.validateNumber();
}
validateCVC(): boolean {
return this.native.validateCVC();
}
validateCard(): boolean {
return this.native.validateCard();
}
validateExpMonth(): boolean {
return this.native.validateExpMonth();
}
validateExpiryDate(): boolean {
return this.native.validateExpiryDate();
}
get number(): string {
return this.native.getNumber();
}
get cvc(): string {
return this.native.getCVC();
}
get expMonth(): number {
return this.native.getExpMonth().intValue();
}
get expYear(): number {
return this.native.getExpYear().intValue();
}
get name(): string {
return this.native.getName();
}
set name(value: string) {
this._cardBuilder.name(value);
}
get addressLine1(): string {
return this.native.getAddressLine1();
}
set addressLine1(value: string) {
this._cardBuilder.addressLine1(value);
}
get addressLine2(): string {
return this.native.getAddressLine2();
}
set addressLine2(value: string) {
this._cardBuilder.addressLine2(value);
}
get addressCity(): string {
return this.native.getAddressCity();
}
set addressCity(value: string) {
this._cardBuilder.addressCity(value);
}
get addressZip(): string {
return this.native.getAddressZip();
}
set addressZip(value: string) {
this._cardBuilder.addressZip(value);
}
get addressState(): string {
return this.native.getAddressState();
}
set addressState(value: string) {
this._cardBuilder.addressState(value);
}
get addressCountry(): string {
return this.native.getAddressCountry();
}
set addressCountry(value: string) {
this._cardBuilder.addressCountry(value);
}
get currency(): string {
return this.native.getCurrency();
}
set currency(value: string) {
this._cardBuilder.currency(value);
}
get last4(): string {
if (!this._last4) this._last4 = this.native.getLast4();
return this._last4;
}
get brand(): CardBrand {
if (!this._brand) this._brand = <CardBrand>this.native.getBrand();
return this._brand;
}
get fingerprint(): string {
return this.native.getFingerprint();
}
get funding(): string {
return this.native.getFunding();
}
get country(): string {
return this.native.getCountry();
}
}
export class CreditCardView extends CreditCardViewBase {
private _widget: com.stripe.android.view.CardInputWidget;
get android(): com.stripe.android.view.CardInputWidget {
return this._widget;
}
public createNativeView(): com.stripe.android.view.CardInputWidget {
this._widget = new com.stripe.android.view.CardInputWidget(this._context);
return this._widget;
}
get card(): Card {
const card = this._widget.getCard();
if (card) {
return new Card(
card.getNumber(),
card.getExpMonth().intValue(),
card.getExpYear().intValue(),
card.getCVC()
);
} else {
return null;
}
}
}
export class PaymentMethod implements PaymentMethodCommon {
native: com.stripe.android.model.PaymentMethod;
static fromNative(native: com.stripe.android.model.PaymentMethod): PaymentMethod {
const pm = new PaymentMethod();
pm.native = native;
return pm;
}
get id(): string { return this.native.id; }
get created(): Date { return new Date(this.native.created.longValue()); }
get type(): "card" { return this.native.type as "card"; }
get billingDetails(): object { return this.native.billingDetails; }
get card(): CardCommon { return Card.fromNativePaymentMethod(this.native); }
get customerId(): string { return this.native.customerId; }
get metadata(): object { return this.native.metadata; }
}
class StripeIntent {
native: com.stripe.android.model.PaymentIntent | com.stripe.android.model.SetupIntent;
get id(): string { return this.native.getId(); }
get clientSecret(): string { return this.native.getClientSecret(); }
get description(): string { return this.native.getDescription(); }
get status(): StripePaymentIntentStatus {
switch (this.native.getStatus()) {
case com.stripe.android.model.StripeIntent.Status.Canceled:
return StripePaymentIntentStatus.Canceled;
case com.stripe.android.model.StripeIntent.Status.Processing:
return StripePaymentIntentStatus.Processing;
case com.stripe.android.model.StripeIntent.Status.RequiresAction:
return StripePaymentIntentStatus.RequiresAction;
case com.stripe.android.model.StripeIntent.Status.RequiresCapture:
return StripePaymentIntentStatus.RequiresCapture;
case com.stripe.android.model.StripeIntent.Status.RequiresConfirmation:
return StripePaymentIntentStatus.RequiresConfirmation;
case com.stripe.android.model.StripeIntent.Status.RequiresPaymentMethod:
return StripePaymentIntentStatus.RequiresPaymentMethod;
case com.stripe.android.model.StripeIntent.Status.Succeeded:
return StripePaymentIntentStatus.Succeeded;
}
return null;
}
get requiresAction(): boolean {
return this.status === StripePaymentIntentStatus.RequiresAction;
}
get isSuccess(): boolean { return this.status === StripePaymentIntentStatus.Succeeded; }
get requiresConfirmation(): boolean { return this.status === StripePaymentIntentStatus.RequiresConfirmation; }
get requiresCapture(): boolean { return this.status === StripePaymentIntentStatus.RequiresCapture; }
}
export class StripePaymentIntent extends StripeIntent implements StripePaymentIntentCommon {
native: com.stripe.android.model.PaymentIntent;
static fromNative(native: com.stripe.android.model.PaymentIntent): StripePaymentIntent {
const pi = new StripePaymentIntent();
pi.native = native;
return pi;
}
static fromApi(json: any): StripePaymentIntent {
const native = com.stripe.android.model.PaymentIntent.fromJson(json);
return StripePaymentIntent.fromNative(native);
}
get amount(): number { return this.native.getAmount().longValue(); }
get created(): Date { return new Date(this.native.getCreated().longValue()); }
get currency(): string { return this.native.getCurrency(); }
get captureMethod(): "manual" | "automatic" { return this.native.getCaptureMethod() as "manual" | "automatic"; }
}
export class StripePaymentIntentParams {
clientSecret: any;
paymentMethodId: string;
sourceId: string;
returnURL: string; // a URL that opens your app
get native(): com.stripe.android.model.ConfirmPaymentIntentParams {
if (this.sourceId) {
return com.stripe.android.model.ConfirmPaymentIntentParams.createWithSourceId(this.sourceId, this.clientSecret, this.returnURL);
} else if (this.paymentMethodId) {
return com.stripe.android.model.ConfirmPaymentIntentParams.createWithPaymentMethodId(this.paymentMethodId, this.clientSecret, this.returnURL);
} else {
return com.stripe.android.model.ConfirmPaymentIntentParams.create(this.clientSecret);
}
}
}
export class StripeSetupIntentParams {
native: com.stripe.android.model.ConfirmSetupIntentParams;
constructor(paymentMethodId: string, clientSecret: string) {
this.native = com.stripe.android.model.ConfirmSetupIntentParams.create(paymentMethodId, clientSecret);
}
}
export class StripeSetupIntent extends StripeIntent {
native: com.stripe.android.model.SetupIntent;
static fromNative(native: com.stripe.android.model.SetupIntent): StripeSetupIntent {
const si = new StripeSetupIntent();
si.native = native;
return si;
}
get paymentMethodId(): string { return this.native.getPaymentMethodId(); }
}
| typescript |
{"sweet-alert.css":"<KEY>,"sweet-alert.js":"<KEY>,"sweet-alert.min.css":"<KEY>,"sweet-alert.min.js":"<KEY>} | json |
I first became aware of Mesut Ozil when I watched Werder Bremen's German Cup (DFB-Pokal) semi-final against Martin Jol's Hamburg in 2009. He caught my eye with his twisting runs and left-footed delivery, and went on to score the only goal in the final of that competition. He also scored and was named man of the match in another final that summer, against England at the Under-21 European Championship.
Ozil has a wide range of midfield qualities: he can pass, he runs well with the ball and he can score. He also has the advantage of being left-footed. An elusive midfielder with a licence to break forward and seek space towards the touchlines in high positions, he roves behind Miroslav Klose with Bastian Schweinsteiger and Sami Khedira providing insurance behind him, in case he loses the ball.
England will need to squeeze the space between the back line and central midfield to restrict his room to receive the ball and manoeuvre. Gareth Barry, in all probability, is going to be vital. He must stay close to Ozil, tracking and closing him down. But Barry must be clever, too — he must not be drawn towards high, wide positions, far away from his base in the centre. Instead, when Ozil goes wide the full-back on that side will need to cope.
This might mean that Ashley Cole and Glen Johnson must curb their instinct to surge forwards. The German is clever enough to exploit the space vacated when either full-back goes on the attack, and can damage his opponents as soon as the ball changes hands. At least until the first goal of the game, Cole and Johnson will have to be cautious. Otherwise, John Terry and Matthew Upson will be pulled out towards the touchlines to cover, with potentially disastrous consequences in front of goal.
Another feature of Ozil's game is his quick shooting in front of goal. England's defenders have proved beyond question their determination to block shots with brave challenges, but they must be wary: Ozil has mastered the “dummy” kick, where he pretends to shoot and works a fresh angle. The defenders must not fall for that.
Ozil is not quite a Maradona or a Messi, but he can certainly be a thorn in England's side if they do not get close and make him hurry his game. | english |
//inserts title code
module.exports = function(yfm) {
var title = yfm['title'];
return '<script>document.getElementById("header-title").innerHTML="' + title + '";</script>';
};
| javascript |
<gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package patrones;
import java.util.Date;
/**
*
* @author erisi
*/
public class ArticuloTecnologico {
protected float precio;
protected int numeroS;
protected String nombreComercial;
protected String locacion;
protected boolean presentaFalla;
protected Date garantia;
public ArticuloTecnologico(float precio, int numeroS, String nombreComercial, String locacion, boolean presentaFalla, Date garantia) {
this.precio = precio;
this.numeroS = numeroS;
this.nombreComercial = nombreComercial;
this.locacion = locacion;
this.presentaFalla = presentaFalla;
this.garantia = garantia;
}
}
| java |
<filename>package.json<gh_stars>0
{
"name": "repeater-scope",
"version": "1.3.0",
"description": "The utils for repeated item scope event handlers in Velo by Wix",
"type": "module",
"source": "src/index.js",
"main": "dist/index.cjs",
"module": "dist/index.js",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "rollup -c",
"lint": "eslint 'src/**/*.js'"
},
"devDependencies": {
"@babel/core": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"@rollup/plugin-babel": "^5.3.0",
"corvid-types": "^0.2.31",
"eslint": "^8.0.1",
"rollup": "^2.58.0",
"simple-git-hooks": "^2.6.1"
},
"simple-git-hooks": {
"pre-commit": "npm run lint && npm run build"
},
"sideEffects": false,
"keywords": [
"wix",
"wixcode",
"editorx",
"velo"
],
"files": [
"dist",
"LICENSE",
"package.json",
"README.md"
],
"author": {
"name": "<NAME>",
"email": "<EMAIL>",
"url": "https://twitter.com/_shoonia"
},
"repository": {
"type": "git",
"url": "git+https://github.com/shoonia/repeater-scope.git"
},
"bugs": {
"url": "https://github.com/shoonia/repeater-scope/issues"
},
"homepage": "https://github.com/shoonia/repeater-scope#readme",
"license": "MIT"
}
| json |
import country from '../interfaces/country'
import { minMax } from '../utility/math'
import { lands } from './lands'
export default class World {
countries: country[];
constructor() {
this.countries = [];
this.addData();
}
addData(): void {
this.countries = lands.map(name => {
return {
name,
co2: minMax(1000, 9000),
electroUse: minMax(),
meatConsumption: minMax(10, 100)
}
});
}
};
| typescript |
<filename>catalog/books/a-matter-of-importance-by-murray-leinster.json
{"title": "Matter of Importance", "description": "The importance of a matter is almost entirely a matter of your attitude. And whether you call something \"a riot\" or \"a war\" ... well, there is a difference, but what is it? Someone steals a space ship? The local police know how to handle that. A broken down freighter in a far distant solar system? That's their normal job too. A bunch of idiots want to start a war? Just another days' work for the boys in blue. The twisted mind of Murray Leinster takes on an Earth empire of thousands of planets and that has moved beyond armies or navies. No need for 'em any more when you have an experienced police force, eh? They've seen it all and everything is routine to the guys and gals of the Empire Police. - Summary by <NAME>", "duration": 5928, "language": "English", "authors": [{"id": "479", "name": "<NAME>"}], "coverArt": "https://archive.org/download/amattetofimportance_2008_librivox/matter_importance_2008.jpg", "copyright_year": "0", "genres": ["Science Fiction"], "supporters": [{"role": "Read by", "name": "<NAME>"}, {"role": "Book Coordinator", "name": "<NAME>"}, {"role": "Meta Coordinator", "name": "<NAME>"}, {"role": "Proof Listener", "name": "<NAME>"}], "sections": [{"section": 1, "title": "Part 1", "readers": [5717], "path": "https://www.archive.org/download/amattetofimportance_2008_librivox/amatterofimportance_01_leinster_64kb.mp3", "duration": 1502}, {"section": 2, "title": "Part 2", "readers": [5717], "path": "https://www.archive.org/download/amattetofimportance_2008_librivox/amatterofimportance_02_leinster_64kb.mp3", "duration": 1430}, {"section": 3, "title": "Part 3", "readers": [5717], "path": "https://www.archive.org/download/amattetofimportance_2008_librivox/amatterofimportance_03_leinster_64kb.mp3", "duration": 1470}, {"section": 4, "title": "Part 4", "readers": [5717], "path": "https://www.archive.org/download/amattetofimportance_2008_librivox/amatterofimportance_04_leinster_64kb.mp3", "duration": 1526}]} | json |
<gh_stars>0
const displayProductNutrient = () => {
const productNutrient = `<div class="productNutrient" id="productNutrient" >
<span class="nutrientCloseBtn" onclick="closeProductNutrient()">X</span>
<img src="../images/recipe6.jpg" />
<p class="productName text-align-center">Deli pizza</p>
<div class="nutrients">
<div class="row">
<div class="nutrient">Protein</div>
<div class="unit">20g</div>
</div>
<div class="row">
<div class="nutrient">Vitamin A</div>
<div class="unit">10g</div>
</div>
<div class="row">
<div class="nutrient">Vitamin b</div>
<div class="unit">1g</div>
</div>
<div class="row">
<div class="nutrient">Fat</div>
<div class="unit">10g</div>
</div>
</div>
</div>`
const bacdrop = document.getElementById("backdrop");
bacdrop.classList.remove('backdropHide');
bacdrop.classList.add('backdropShow');
const root = document.getElementById('root');
root.insertAdjacentHTML("beforeend", productNutrient);
}
const closeProductNutrient = () => {
const bacdrop = document.getElementById("backdrop");
bacdrop.classList.remove('backdropShow');
bacdrop.classList.add('backdropHide');
const root = document.getElementById('root');
root.removeChild(root.lastChild);
}
export {
closeProductNutrient,
displayProductNutrient
} | javascript |
---
layout: post
category: research
subcategory: "Wireless Technologies"
title: "Wireless Linear LAN for Interstate 81 (Salem District)"
date: 2012-05-22 16:25:06 -0700
sponsor: Virginia Department of Transportion (VDOT)
award: $593,603
dates: 2003-2005
role: PI
website: ""
report: ""
report2: ""
report3: ""
report4: ""
report5: ""
report6: ""
media1: ""
media2: ""
media3: ""
media1title: ""
media2title: ""
media3title: ""
comments: true
ordinal: 1
---
Based on successful preliminary analysis of the US460 installation (see below), VDOT provided funding for a 10 mile section of Interstate 81 around Roanoke to covered with an 802.11 wireless spine, 9 digital cameras, and a series of digital traffic counters and weather stations. This project is being used as both a ‘further proof of concept’ and as a test-case for adjusting how DOTs procure operational IT systems (which are traditionally used for 15-30 year planning cycles).
| markdown |
Lizelle Lee scored the third highest individual score by a South African batswoman in ODIs as SA cruised to an easy win.
Opening batswoman Lizelle Lee smashed the third highest score by a South African batswoman as they cruised to a 6 run win by the DLS method in the third ODI at the Ekana Stadium in Lucknow.
Being put into bat, the Women in Blue lost an early wicket for third time in a row as the right-handed Jemimah Rodrigues was sent back for a duck in the very first over by Shabnim Ismail.
Joining Smriti Mandhana (25) in the middle, Punam Raut started off with a flurry of boundaries as the duo stitched a 64 run partnership in no time before Mandhana was sent back by Tumi Sekhukhune. Almost all the Indian batters got some good starts but none other than Raut (77) managed to convert it into something substantial as they were restricted to 248-5 in their 50 overs.
Shabnim Ismail was the star bowler for the South African Women with figures of 2-46 in her quota of 10 overs while Anne Bosch, Sekhukhune and Marizanne Kapp all finished with a wicket apiece.
While 248 looked more than enough at the halfway stage, considering the batting performance by both the teams in the first two matches, but Lizelle Lee had other ideas.
Opening the innings for South Africa, Lee completely demolished the Indian bowlers with her aggressive approach as she struck a near-perfect 132* off 131 deliveries to win the match by six runs via DLS method.
Even though Lee lost her opening partner and stand-in-skipper Wolvaardt cheaply she kept going while the rest of the team batted around her as South Africa piled up 223/4 in 46.3 overs before the rain interruption.
Going into the break South Africa were six runs ahead of India in DLS method and this eventually proved the fate of the match as the rain refused to subside.
For the Indian women, Jhulan Goswami once again stood up with her figures of 2-20 in 9 overs while Deepti Sharma and Rajeshwari Gayakwad chipped in with one wicket each.
| english |
{
"configOverwrite": {
"disableInviteFunctions": true,
"disableDeepLinking": true,
"doNotStoreRoom": true,
"remoteVideoMenu": {
"disableKick": true
},
"makeJsonParserHappy": "even if last key had a trailing comma",
"prejoinConfig": {
"enabled": false
},
"connectionIndicators": {
"autoHide": true,
"autoHideTimeout": 1000,
"disabled": true
},
"toolbarConfig": {
"initialTimeout": 3000,
"alwaysVisible": true,
"timeout": 3000
},
"defaultLocalDisplayName": "me",
"disableModeratorIndicator": true,
"defaultRemoteDisplayName": "",
"toolbarButtons ": []
},
"interfaceConfigOverwrite": {
"DEFAULT_BACKGROUND": "#00759f",
"DISABLE_VIDEO_BACKGROUND": false,
"LIVE_STREAMING_HELP_LINK": " ",
"SHOW_JITSI_WATERMARK": false,
"SHOW_BRAND_WATERMARK": false,
"JITSI_WATERMARK_LINK": "",
"BRAND_WATERMARK_LINK": "",
"SHOW_POWERED_BY": false,
"DISABLE_JOIN_LEAVE_NOTIFICATIONS": true,
"DISABLE_RINGING": true,
"DISABLE_TRANSCRIPTION_SUBTITLES": true,
"DISABLE_PRESENCE_STATUS": true,
"ENABLE_FEEDBACK_ANIMATION": false,
"HIDE_INVITE_MORE_HEADER": true,
"SHOW_DEEP_LINKING_IMAGE": false,
"GENERATE_ROOMNAMES_ON_WELCOME_PAGE": true,
"DISPLAY_WELCOME_PAGE_CONTENT": false,
"SHOW_CHROME_EXTENSION_BANNER": false,
"DISPLAY_WELCOME_PAGE_TOOLBAR_ADDITIONAL_CONTENT": false,
"APP_NAME": " ",
"NATIVE_APP_NAME": " ",
"PROVIDER_NAME": " ",
"LANG_DETECTION": true,
"RECENT_LIST_ENABLED": false,
"SETTINGS_SECTIONS": [],
"VIDEO_LAYOUT_FIT": "both",
"VERTICAL_FILMSTRIP": true,
"CLOSE_PAGE_GUEST_HINT": false,
"SHOW_PROMOTIONAL_CLOSE_PAGE": false,
"FILM_STRIP_MAX_HEIGHT": 120,
"DISABLE_DOMINANT_SPEAKER_INDICATOR": false,
"AUDIO_LEVEL_PRIMARY_COLOR": "rgba(255,255,255,0.4)",
"AUDIO_LEVEL_SECONDARY_COLOR": "rgba(255,255,255,0.2)",
"POLICY_LOGO": null,
"LOCAL_THUMBNAIL_RATIO": "16 / 9",
"REMOTE_THUMBNAIL_RATIO": 1,
"MOBILE_APP_PROMO": true,
"MAXIMUM_ZOOMING_COEFFICIENT": 1.3,
"SUPPORT_URL": " ",
"VIDEO_QUALITY_LABEL_DISABLED": true,
"OPTIMAL_BROWSERS": [
"chrome",
"chromium",
"firefox",
"nwjs",
"electron"
],
"UNSUPPORTED_BROWSERS": [],
"AUTO_PIN_LATEST_SCREEN_SHARE": "remote-only"
},
"jitsiDomain": "meet-dev1.livecontract.de",
"secret": "<KEY>",
"aud": "lc.dev.jitsi-meet",
"iss": "lc.dev.jitsi-meet",
"sub": "meet"
} | json |
{"vendor":"liberica","filename":"bellsoft-jre8u265+1-macos-amd64.zip","release_type":"ga","version":"8u265+1","java_version":"8u265+1","jvm_impl":"hotspot","os":"macosx","architecture":"x86_64","file_type":"zip","image_type":"jre","features":[],"url":"https://github.com/bell-sw/Liberica/releases/download/8u265+1/bellsoft-jre8u265+1-macos-amd64.zip","md5":"e0455425e39422387d89f7b1ffaf31b7","md5_file":"bellsoft-jre8u265+1-macos-amd64.zip.md5","sha1":"7b5c0e3743ff604e1f5f2f76bc16cc479e837ae2","sha1_file":"bellsoft-jre8u265+1-macos-amd64.zip.sha1","sha256":"dfb0284ac316a1c87f3ad011f2be8eac7877d13a71cd7b6e9ab9f0a622c09d9a","sha256_file":"bellsoft-jre8u265+1-macos-amd64.zip.sha256","sha512":"c931088953984ecd01af6a136e02afae5a45e6fea95d9af2679ec4695f554e1e12b1a622c208537b014783c07f2d77a73075aaae19f51fdf9349e78cd1133b85","sha512_file":"bellsoft-jre8u265+1-macos-amd64.zip.sha512","size":38916504}
| json |
After whitewashing New Zealand 5-0 in the T20I series, India's fortune took a nosedive as they lost matches one after another. First, the ODI series was lost 3-0 and then getting outplayed in the two-match Test series by 2-0, India's performance has made everyone to think how could a world-class team suddenly lose the plot all of a sudden.
In the Test series, India had a batting disaster in the first Test at Wellington and lost the match by 10 wickets, exposing their batsmen's weakness in facing swinging deliveries. The scene did not change much in the second Test at Christchurch as India, despite gaining a slender lead in the first innings and getting a chance to save the match as well as the series in the second innings, threw it away with another batting collapse and handed the hosts a 7-wicket victory.
India, who are currently at the top of the ICC World Test Championship points table, failed to live up to their reputation in the two-match Test series against the Black Caps. While the overall performance of the team was below-par, there were several decisions which did not pay off for India in the series and here are 3 such decisions.
KL Rahul was in the form of his life in the limited over formats in New Zealand. His versatility to play the role of both opener and finisher made his case stronger for his comeback into the Test squad. And looking at his purple patch on New Zealand soil, Rahul was expected to open in Tests after Rohit Sharma's unavailability.
However, India preferred Prithvi Shaw as Mayank Agarwal's opening partner for the Test series over KL Rahul. It was never going to easy to bat in swinging conditions in New Zealand wickets and the pair of Shaw and Agarwal had the tough task of providing India a good start in such challenging situations. But unfortunately, India's new opening pair failed to survive for long in front of the New Zealand fast bowlers. Although both the batsmen scored a fifty each in the Test series, their opening pair could not survive even 10 overs in a single innings, exposing the middle order to the Kiwi bowlers too early.
The Shaw-Agarwal pair played only 19. 3 overs together in the four innings of the two-match series. Their highest partnership was just 30 runs in the first innings of the second Test. All these numbers surely put a question mark on their effectiveness against such challenging conditions and also on the non-consideration of Rahul despite being in sublime form whose inclusion could have provided more stability to India's batting.
Another selection question that made a lot of buzz was the inclusion of Rishabh Pant in the playing XI instead of Wridhhiman Saha as the wicket-keeper. Saha had kept wickets in the last home season and after his fine show behind the stumps added to Rishabh Pant's exclusion from the playing XI in the limited over games against New Zealand, the former was expected to feature in the Test series against New Zealand.
Indian coach Ravi Shastri justified the move by saying that Pant's aggressive left-handed batting and not so much spin in New Zealand wickets tilted the decision in the his favour and the veteran Saha had to warm the bench for the series.
Unfortunately, the decision of having Pant in the playing XI did not help India in saving the Test series. Although Pant was decent with the gloves behind the stumps, his contribution with the bat could not justify the main reason for which he was included in the playing XI - his aggressive batting in the lower order. The left-hander managed to score only 60 runs in four innings, with a highest score of 25.
Pant was brilliant with the bat in his debut tour of England followed by that of Australia. But this time in New Zealand, he was far from making a significant contribution with the bat.
India took the field with four frontline bowlers - 3 seamers and one spinner in both the Tests, unlike New Zealand who played with four specialist bowlers and an all-rounder. And the shortage of that one extra fast bowler haunted India a lot, especially while bowling in the first innings of the first Test.
New Zealand's Colin de Grandhomme played the role of the fourth seamer and stood as a hurdle in front of the Indian batsmen with his tight line and length. Having the fourth seamer also meant that New Zealand could keep their prime bowlers fresh throughout the day's play without over exerting them. This proved to be a masterstroke for New Zealand as they successfully restricted India to low scores in both the Tests.
But India, while trying to extend the batting order, missed the trick. The absence of the fifth bowler made India toil hard for wickets after a poor show with the bat, eventually failing to put pressure on New Zealand's batsmen. Moreover, the inability of the Indian bowlers to get past the tail-enders in New Zealand's first innings of in Wellington also made them feel the need of another option with the ball.
An additional fast bowler in the form of Navdeep Saini with his lethal fast bowling could have made things easier for India with the ball, at least in the first Test when New Zealand took their first innings score from 225-7 to 348-10. But preferring to play with 7 batsmen robbed India of having this option. | english |
<filename>middileware/iis/ms15_034.py<gh_stars>100-1000
#!/usr/bin/env python
# encoding: utf-8
from t import T
import re
import urllib2,requests,urllib2,json,urlparse
class P(T):
def __init__(self):
T.__init__(self)
def verify(self,head='',context='',ip='',port='',productname={},keywords='',hackinfo=''):
timeout=3
if int(port) == 443:
protocal = "https"
else:
protocal = "http"
target_url = protocal + "://"+ip+":"+str(port)
result = {}
result['result']=False
r=None
vuln_header = {"Range": "bytes=0-18446744073709551615"}
try:
r=requests.get(url=target_url,headers=vuln_header,timeout=timeout,verify=False,allow_redirects=False)
#print r.content
if "请求范围不符合" in r.content or "Requested Range Not Satisfiable" in r.content:
result['result']=True
result['VerifyInfo'] = {}
result['VerifyInfo']['type']='iis Vulnerability'
result['VerifyInfo']['URL'] =target_url
result['VerifyInfo']['payload']=vuln_buffer
result['VerifyInfo']['result'] =r.content
except Exception,e:
print e.text
finally:
if r is not None:
r.close()
del r
return result
if __name__ == '__main__':
print P().verify(ip='192.168.127.12',port='443')
| python |
<reponame>JefferyLukas/SRIs<filename>qoopido.demand/4.0.2.json
{"demand.js":"<KEY>,"handler/css.js":"<KEY>,"handler/json.js":"<KEY>,"handler/legacy.js":"sha512-SJnxU7v1RSNcYTYe6fZx+BYmVM9PQuDgsi/WVhYbIPHBxrZjjPAnke7qwjOjLhf5dTTMlzgvvI+XLniqTD6KaQ==","handler/text.js":"<KEY>,"plugin/cookie.js":"<KEY>,"plugin/lzstring.js":"<KEY>,"plugin/sri.js":"<KEY>,"validator/isInstanceOf.js":"<KEY>} | json |
{
"TeamMentor_Article": {
"$": {
"Metadata_Hash": "0",
"Content_Hash": "0"
},
"Metadata": [
{
"Id": [
"00000000-0000-0000-0000-0000003087b2"
],
"Id_History": [
"00000000-0000-0000-0000-0000003087b2,841de4b9-c473-40a4-ac23-aefb5190aa29,"
],
"Library_Id": [
"be5273b1-d682-4361-99d9-6234f2d47eb7"
],
"Title": [
"Users Are Told to Clear the Cache After Browsing Through Untrusted Networks"
],
"Category": [
"Privacy"
],
"Phase": [
"Implementation"
],
"Technology": [
"HTML5"
],
"Type": [
"Checklist Item"
],
"DirectLink": [
"Users Are Told to Clear the Cache After Browsing Through Untrusted Networks"
],
"Author": [
""
],
"Priority": [
""
],
"Status": [
""
]
}
],
"Content": [
{
"$": {
"Sanitized": "false",
"DataType": "wikitext"
},
"Data": [
"==Applies To==\r\n\r\n* HTML5\r\n\r\n==What to Check For==\r\n\r\nVerify that users are warned to clear the cache after browsing through untrusted networks.\r\n\r\n==Why==\r\n\r\nUsers should clear the cache after browsing through untrusted networks because the operator(s) of the untrusted network might have substituted legitimate content with malicious content. Malicious content may include attack code or deceptive information. Keeping malicious content in the cache presents a danger to the user. This danger may be mitigated by clearing the cache after browsing through untrusted networks.\r\n\r\n==How to Check==\r\n\r\nTo verify that users are warned to clear the cache after browsing through untrusted networks:\r\n# **Log in and use the application.** Log in to the application and use it in the way a regular user is likely to use it for the amount of time necessary to explore most of the application's important features. \r\n# **Note if there is a warning to clear the cache.** While using the application, note whether a warning is displayed about the importance of clearing the cache after browsing untrusted networks.\r\n\r\n==How to Fix==\r\n\r\nTo remind the users to to clear the cache after browsing through untrusted networks:\r\n\r\n# **Write a warning message.** Write a message to inform the users that, if they are browsing through untrusted networks, legitimate content might be substituted with malicious content, and that therefore they should clear their cache.\r\n# **Choose how to present the warning message.** Consider the best way to present the warning message to the user. One option is to place the warning message on the main page. Some other options are to place it on its own page, include it in the user agreement, or to display it as a popup.\r\n# **Present the warning message.** Add code that displays the warning message in the manner that has been decided upon.\r\n\r\n==Privacy and Trust Guidelines==\r\n\r\n* [[00000000-0000-0000-0000-0000001de66c|Ask User Permission Before Using Geopositioning]]\r\n* [[00000000-0000-0000-0000-000000364213|Ask User Permission Before Sending a Manifest]]\r\n* [[00000000-0000-0000-0000-0000003b92c3|Tell Users to Clear the Cache after Browsing Through Untrusted Networks]]\r\n\r\n==Privacy and Trust Checklist Items==\r\n\r\n* [[00000000-0000-0000-0000-0000006e3400|The User Is Asked for Permission Before Geopositioning]]\r\n* [[00000000-0000-0000-0000-00000085555d|The User Is Asked for Permission Before Sending a Manifest]]\r\n* [[00000000-0000-0000-0000-0000003087b2|Users Are Told to Clear the Cache After Browsing Through Untrusted Networks]]\r\n\r\n"
]
}
]
}
} | json |
The Xavier School of Management will release the XAT 2022 admit cards today. Here's how you can download your respectve admit cards.
By India Today Web Desk: XAT admit card 2022: Attention candidates, the Xavier School of Management will release the awaited admit cards for the Xavier Aptitude Test (XAT) 2022. Candidates can download their respective XAT admit cards from the official website, i. e. , xatonline. in, once the link is activated. Earlier, the XAT admit cards 2022 were scheduled to be released on December 20, 2021. Xavier School of Management (XLRI) will conduct the XAT 2022 examination on January 2, 2022.
Step 1: Visit the official website, i. e. , xatonline. in.
Step 2: On the homepage, click on the link that reads, 'XAT admit card 2022'. (Once released)
Step 3: A new page will appear on the screen.
Step 4: Enter the asked credentials and click on the submit option.
Step 5: Your admit card will appear on the screen.
Step 6: Download it and take a printout for future reference.
- As per the XAT 2022 syllabus, the exam will have a total of 100 multiple-choice questions divided among four sections.
- These sections are Verbal and Logical Ability, Decision Making, Quantitative Ability and Data Interpretation, and General Knowledge.
- Candidates will be given a duration of three hours to complete the test.
- The marking scheme is such that for every correct answer, 01 marks will be awarded and for every incorrect answer, 0. 25 marks will be deducted. | english |
It's hard to imagine how to live with the thought that a person close to you is accused of a series of serious crimes, everyone turned away from him, and you become a hostage to the situation and an outcast. The editor-in-chief of the Vogue tabloid, Anna Wintour, supported the wife of Harvey Weinstein and dedicated an article to Georgina Chapman, where she first told how she survived the scandal over sexual harassment, rape and numerous accusations around her husband.
Bankruptcy or a new start?
After the scandal, which led to a wave of disclosure and the destruction of the career of many actors and producers, Weinstein's The Weinstein Company was forced to declare bankruptcy and close all projects. Until now, the producer's lawyers are dealing with numerous debts and are looking for ways to pay off. The business and reputation of 42-year-old Georgina Chapman also suffered, in dresses from the Marchesa brand, no one wants to go out on the red carpet. What did Weinstein's wife have to do? Georgina Chapman filed for divorce, enlisted the support of Anna Wintour and Scarlett Johansson.
At the past Met Gala 2018 Scarlett Johansson challenged the public and appeared in a dress from Marchesa. Despite the criticism, the actress proudly walked along the red carpet!
The next step is a frank interview for Vogue magazine, where Chapman talked about emotional experiences:
"Everything that happened was humiliating, I was broken psychologically. I was so hard and bad that I could not even go out. All this was accompanied by psychosomatics, breathing problems, mood swings, fits of rage and total impotence. I did not know whom to turn to, whom I can trust. It remained only to cry. Only the children helped me to hold myself in my arms. I thought that it would be with them after this madness, if I do not come to myself and start to patronize them and protect them from what is happening. "
Georgina confessed that in the first five days of the scandal she could neither eat nor drink and sharply lost 5 kilograms:
"My relatives were frightened for me and advised me to go to a psychotherapist. Then I was able to come to my senses and take the only right decision, pick up the children and get away from my husband. At this time he was silent, and the newspapers found more and more stories, confirming the harassment on his part. "
According to Chapman, she decided to protect children from journalists and paparazzi, and took them to London to their relatives:
Anna Wintour has long been familiar with the family of Harvey Weinstein and Jarjina Chapman, they were connected not only with business, but with friendly relations. At the beginning of her design career, she supported the Marchesa brand and helped advance in the fashion world. Now she took the side of Chapman and wrote the following words in the editor's letter:
"We are obliged to show compassion and understanding to Georgina, she should not be responsible for the actions of her partner. " | english |
<gh_stars>1-10
import { combineReducers } from 'redux';
import reduceApp from './app';
import reduceWallets from './wallet';
import reduceInterface from './interface';
import {
REDUCE_INTERFACE_NAMESPACE,
REDUCE_WALLETS_NAMESPACE,
REDUCE_APP_NAMESPACE,
} from '../constants';
const reducers = combineReducers({
[REDUCE_APP_NAMESPACE]: reduceApp,
[REDUCE_WALLETS_NAMESPACE]: reduceWallets,
[REDUCE_INTERFACE_NAMESPACE]: reduceInterface,
});
export { reducers };
| javascript |
// Copyright 2019 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package header_test
import (
"bytes"
"crypto/sha256"
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
"gvisor.dev/gvisor/pkg/rand"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/header"
)
const (
linkAddr = tcpip.LinkAddress("\x02\x02\x03\x04\x05\x06")
linkLocalAddr = tcpip.Address("\xfe\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")
linkLocalMulticastAddr = tcpip.Address("\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")
uniqueLocalAddr1 = tcpip.Address("\xfc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")
uniqueLocalAddr2 = tcpip.Address("\xfd\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02")
globalAddr = tcpip.Address("\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")
)
func TestEthernetAdddressToModifiedEUI64(t *testing.T) {
expectedIID := [header.IIDSize]byte{0, 2, 3, 255, 254, 4, 5, 6}
if diff := cmp.Diff(expectedIID, header.EthernetAddressToModifiedEUI64(linkAddr)); diff != "" {
t.Errorf("EthernetAddressToModifiedEUI64(%s) mismatch (-want +got):\n%s", linkAddr, diff)
}
var buf [header.IIDSize]byte
header.EthernetAdddressToModifiedEUI64IntoBuf(linkAddr, buf[:])
if diff := cmp.Diff(expectedIID, buf); diff != "" {
t.Errorf("EthernetAddressToModifiedEUI64IntoBuf(%s, _) mismatch (-want +got):\n%s", linkAddr, diff)
}
}
func TestLinkLocalAddr(t *testing.T) {
if got, want := header.LinkLocalAddr(linkAddr), tcpip.Address("\xfe\x80\x00\x00\x00\x00\x00\x00\x00\x02\x03\xff\xfe\x04\x05\x06"); got != want {
t.Errorf("got LinkLocalAddr(%s) = %s, want = %s", linkAddr, got, want)
}
}
func TestAppendOpaqueInterfaceIdentifier(t *testing.T) {
var secretKeyBuf [header.OpaqueIIDSecretKeyMinBytes * 2]byte
if n, err := rand.Read(secretKeyBuf[:]); err != nil {
t.Fatalf("rand.Read(_): %s", err)
} else if want := header.OpaqueIIDSecretKeyMinBytes * 2; n != want {
t.Fatalf("expected rand.Read to read %d bytes, read %d bytes", want, n)
}
tests := []struct {
name string
prefix tcpip.Subnet
nicName string
dadCounter uint8
secretKey []byte
}{
{
name: "SecretKey of minimum size",
prefix: header.IPv6LinkLocalPrefix.Subnet(),
nicName: "eth0",
dadCounter: 0,
secretKey: secretKeyBuf[:header.OpaqueIIDSecretKeyMinBytes],
},
{
name: "SecretKey of less than minimum size",
prefix: func() tcpip.Subnet {
addrWithPrefix := tcpip.AddressWithPrefix{
Address: "\x01\x02\x03\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
PrefixLen: header.IIDOffsetInIPv6Address * 8,
}
return addrWithPrefix.Subnet()
}(),
nicName: "eth10",
dadCounter: 1,
secretKey: secretKeyBuf[:header.OpaqueIIDSecretKeyMinBytes/2],
},
{
name: "SecretKey of more than minimum size",
prefix: func() tcpip.Subnet {
addrWithPrefix := tcpip.AddressWithPrefix{
Address: "\x01\x02\x03\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
PrefixLen: header.IIDOffsetInIPv6Address * 8,
}
return addrWithPrefix.Subnet()
}(),
nicName: "eth11",
dadCounter: 2,
secretKey: secretKeyBuf[:header.OpaqueIIDSecretKeyMinBytes*2],
},
{
name: "Nil SecretKey and empty nicName",
prefix: func() tcpip.Subnet {
addrWithPrefix := tcpip.AddressWithPrefix{
Address: "\x01\x02\x03\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
PrefixLen: header.IIDOffsetInIPv6Address * 8,
}
return addrWithPrefix.Subnet()
}(),
nicName: "",
dadCounter: 3,
secretKey: nil,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
h := sha256.New()
h.Write([]byte(test.prefix.ID()[:header.IIDOffsetInIPv6Address]))
h.Write([]byte(test.nicName))
h.Write([]byte{test.dadCounter})
if k := test.secretKey; k != nil {
h.Write(k)
}
var hashSum [sha256.Size]byte
h.Sum(hashSum[:0])
want := hashSum[:header.IIDSize]
// Passing a nil buffer should result in a new buffer returned with the
// IID.
if got := header.AppendOpaqueInterfaceIdentifier(nil, test.prefix, test.nicName, test.dadCounter, test.secretKey); !bytes.Equal(got, want) {
t.Errorf("got AppendOpaqueInterfaceIdentifier(nil, %s, %s, %d, %x) = %x, want = %x", test.prefix, test.nicName, test.dadCounter, test.secretKey, got, want)
}
// Passing a buffer with sufficient capacity for the IID should populate
// the buffer provided.
var iidBuf [header.IIDSize]byte
if got := header.AppendOpaqueInterfaceIdentifier(iidBuf[:0], test.prefix, test.nicName, test.dadCounter, test.secretKey); !bytes.Equal(got, want) {
t.Errorf("got AppendOpaqueInterfaceIdentifier(iidBuf[:0], %s, %s, %d, %x) = %x, want = %x", test.prefix, test.nicName, test.dadCounter, test.secretKey, got, want)
}
if got := iidBuf[:]; !bytes.Equal(got, want) {
t.Errorf("got iidBuf = %x, want = %x", got, want)
}
})
}
}
func TestLinkLocalAddrWithOpaqueIID(t *testing.T) {
var secretKeyBuf [header.OpaqueIIDSecretKeyMinBytes * 2]byte
if n, err := rand.Read(secretKeyBuf[:]); err != nil {
t.Fatalf("rand.Read(_): %s", err)
} else if want := header.OpaqueIIDSecretKeyMinBytes * 2; n != want {
t.Fatalf("expected rand.Read to read %d bytes, read %d bytes", want, n)
}
prefix := header.IPv6LinkLocalPrefix.Subnet()
tests := []struct {
name string
prefix tcpip.Subnet
nicName string
dadCounter uint8
secretKey []byte
}{
{
name: "SecretKey of minimum size",
nicName: "eth0",
dadCounter: 0,
secretKey: secretKeyBuf[:header.OpaqueIIDSecretKeyMinBytes],
},
{
name: "SecretKey of less than minimum size",
nicName: "eth10",
dadCounter: 1,
secretKey: secretKeyBuf[:header.OpaqueIIDSecretKeyMinBytes/2],
},
{
name: "SecretKey of more than minimum size",
nicName: "eth11",
dadCounter: 2,
secretKey: secretKeyBuf[:header.OpaqueIIDSecretKeyMinBytes*2],
},
{
name: "Nil SecretKey and empty nicName",
nicName: "",
dadCounter: 3,
secretKey: nil,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
addrBytes := [header.IPv6AddressSize]byte{
0: 0xFE,
1: 0x80,
}
want := tcpip.Address(header.AppendOpaqueInterfaceIdentifier(
addrBytes[:header.IIDOffsetInIPv6Address],
prefix,
test.nicName,
test.dadCounter,
test.secretKey,
))
if got := header.LinkLocalAddrWithOpaqueIID(test.nicName, test.dadCounter, test.secretKey); got != want {
t.Errorf("got LinkLocalAddrWithOpaqueIID(%s, %d, %x) = %s, want = %s", test.nicName, test.dadCounter, test.secretKey, got, want)
}
})
}
}
func TestIsV6LinkLocalMulticastAddress(t *testing.T) {
tests := []struct {
name string
addr tcpip.Address
expected bool
}{
{
name: "Valid Link Local Multicast",
addr: linkLocalMulticastAddr,
expected: true,
},
{
name: "Valid Link Local Multicast with flags",
addr: "\xff\xf2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
expected: true,
},
{
name: "Link Local Unicast",
addr: linkLocalAddr,
expected: false,
},
{
name: "IPv4 Multicast",
addr: "\xe0\x00\x00\x01",
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := header.IsV6LinkLocalMulticastAddress(test.addr); got != test.expected {
t.Errorf("got header.IsV6LinkLocalMulticastAddress(%s) = %t, want = %t", test.addr, got, test.expected)
}
})
}
}
func TestIsV6LinkLocalUnicastAddress(t *testing.T) {
tests := []struct {
name string
addr tcpip.Address
expected bool
}{
{
name: "Valid Link Local Unicast",
addr: linkLocalAddr,
expected: true,
},
{
name: "Link Local Multicast",
addr: linkLocalMulticastAddr,
expected: false,
},
{
name: "Unique Local",
addr: uniqueLocalAddr1,
expected: false,
},
{
name: "Global",
addr: globalAddr,
expected: false,
},
{
name: "IPv4 Link Local",
addr: "\xa9\xfe\x00\x01",
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := header.IsV6LinkLocalUnicastAddress(test.addr); got != test.expected {
t.Errorf("got header.IsV6LinkLocalUnicastAddress(%s) = %t, want = %t", test.addr, got, test.expected)
}
})
}
}
func TestScopeForIPv6Address(t *testing.T) {
tests := []struct {
name string
addr tcpip.Address
scope header.IPv6AddressScope
err tcpip.Error
}{
{
name: "Unique Local",
addr: uniqueLocalAddr1,
scope: header.GlobalScope,
err: nil,
},
{
name: "Link Local Unicast",
addr: linkLocalAddr,
scope: header.LinkLocalScope,
err: nil,
},
{
name: "Link Local Multicast",
addr: linkLocalMulticastAddr,
scope: header.LinkLocalScope,
err: nil,
},
{
name: "Global",
addr: globalAddr,
scope: header.GlobalScope,
err: nil,
},
{
name: "IPv4",
addr: "\x01\x02\x03\x04",
scope: header.GlobalScope,
err: &tcpip.ErrBadAddress{},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := header.ScopeForIPv6Address(test.addr)
if diff := cmp.Diff(test.err, err); diff != "" {
t.Errorf("unexpected error from header.IsV6UniqueLocalAddress(%s), (-want, +got):\n%s", test.addr, diff)
}
if got != test.scope {
t.Errorf("got header.IsV6UniqueLocalAddress(%s) = (%d, _), want = (%d, _)", test.addr, got, test.scope)
}
})
}
}
func TestSolicitedNodeAddr(t *testing.T) {
tests := []struct {
addr tcpip.Address
want tcpip.Address
}{
{
addr: "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\xa0",
want: "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xff\x0e\x0f\xa0",
},
{
addr: "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\xdd\x0e\x0f\xa0",
want: "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xff\x0e\x0f\xa0",
},
{
addr: "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\xdd\x01\x02\x03",
want: "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xff\x01\x02\x03",
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("%s", test.addr), func(t *testing.T) {
if got := header.SolicitedNodeAddr(test.addr); got != test.want {
t.Fatalf("got header.SolicitedNodeAddr(%s) = %s, want = %s", test.addr, got, test.want)
}
})
}
}
func TestV6MulticastScope(t *testing.T) {
tests := []struct {
addr tcpip.Address
want header.IPv6MulticastScope
}{
{
addr: "\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6Reserved0MulticastScope,
},
{
addr: "\xff\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6InterfaceLocalMulticastScope,
},
{
addr: "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6LinkLocalMulticastScope,
},
{
addr: "\xff\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6RealmLocalMulticastScope,
},
{
addr: "\xff\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6AdminLocalMulticastScope,
},
{
addr: "\xff\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6SiteLocalMulticastScope,
},
{
addr: "\xff\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(6),
},
{
addr: "\xff\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(7),
},
{
addr: "\xff\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6OrganizationLocalMulticastScope,
},
{
addr: "\xff\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(9),
},
{
addr: "\xff\x0a\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(10),
},
{
addr: "\xff\x0b\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(11),
},
{
addr: "\xff\x0c\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(12),
},
{
addr: "\xff\x0d\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6MulticastScope(13),
},
{
addr: "\xff\x0e\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6GlobalMulticastScope,
},
{
addr: "\xff\x0f\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
want: header.IPv6ReservedFMulticastScope,
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("%s", test.addr), func(t *testing.T) {
if got := header.V6MulticastScope(test.addr); got != test.want {
t.Fatalf("got header.V6MulticastScope(%s) = %d, want = %d", test.addr, got, test.want)
}
})
}
}
| go |
# Copyright (C) <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.****
import sys
from nemo.constants import NEMO_ENV_VARNAME_ENABLE_COLORING
from nemo.utils.env_var_parsing import get_envbool
__all__ = ["check_color_support", "to_unicode"]
def check_color_support():
# Colors can be forced with an env variable
if not sys.platform.lower().startswith("win") and get_envbool(NEMO_ENV_VARNAME_ENABLE_COLORING, False):
return True
def to_unicode(value):
"""
Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
try:
if isinstance(value, (str, type(None))):
return value
if not isinstance(value, bytes):
raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
return value.decode("utf-8")
except UnicodeDecodeError:
return repr(value)
| python |
<reponame>dharkness/jest-extended
import * as matcher from './';
expect.extend(matcher);
describe('.toBeHexadecimal', () => {
test('passes when given valid 6 digit hexadecimal', () => {
expect('#ECECEC').toBeHexadecimal();
});
test('passes when given valid 3 digit hexadecimal', () => {
expect('#000').toBeHexadecimal();
});
test('fails when given non-string', () => {
expect(() => expect(true).toBeHexadecimal()).toThrowErrorMatchingSnapshot();
});
});
describe('.not.toBeHexadecimal', () => {
test('passes when given positive number', () => {
expect(1).not.toBeHexadecimal();
});
test('fails when given valid hexadecimal', () => {
expect(() => expect('#eeffee').not.toBeHexadecimal()).toThrowErrorMatchingSnapshot();
});
});
| javascript |
<reponame>stevejay/react-performance
import React from "react";
type Ref = React.RefObject<HTMLElement>;
type RefsMapValue = {
map: Record<string, Ref>;
api: {
addRef(id: string, ref: Ref): void;
getRef(id: string): Ref | null;
removeRef(id: string, ref: Ref): void;
};
};
// A lookup of ID to component ref.
const useRefsMap = () => {
const refsMapValue = React.useRef<RefsMapValue>();
if (!refsMapValue.current) {
const value = {
map: {} as Record<string, Ref>,
api: {
addRef: (id: string, ref: Ref): void => {
value.map[id] = ref;
},
getRef: (id: string): Ref | null => value.map[id] || null,
removeRef: (id: string, ref: Ref): void => {
if (value.map[id] && value.map[id] === ref) {
delete value.map[id];
}
}
}
};
refsMapValue.current = value;
}
return refsMapValue.current.api;
};
export { useRefsMap };
| typescript |
<filename>Apps/1502.json
{"1502":{"success":true,"data":{"type":"demo","name":"Darwinia Demo","steam_appid":1502,"required_age":0,"is_free":true,"detailed_description":"Combining fast-paced action with strategic battle planning, Darwinia features a novel and intuitive control mechanism, a graphical style ripped from 80's retro classics like Tron and Defender, and a story concerning a tribe of nomadic sprites trapped in a modern 3D world.","about_the_game":"Combining fast-paced action with strategic battle planning, Darwinia features a novel and intuitive control mechanism, a graphical style ripped from 80's retro classics like Tron and Defender, and a story concerning a tribe of nomadic sprites trapped in a modern 3D world.","short_description":"","fullgame":{"appid":"1500","name":"Darwinia"},"supported_languages":"English","header_image":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/header.jpg?t=1447350871","website":"http:\/\/www.darwinia.co.uk\/","pc_requirements":{"minimum":"<p><strong>Recommended:<\/strong> Windows XP, 600MHz CPU, 128MB RAM, DX7 based video card<\/p>"},"mac_requirements":[],"linux_requirements":[],"developers":["Introversion Software"],"publishers":["Introversion Software"],"package_groups":[],"platforms":{"windows":true,"mac":false,"linux":false},"metacritic":{"score":84},"categories":[{"id":2,"description":"Single-player"},{"id":10,"description":"Game demo"}],"genres":[{"id":"2","description":"Strategy"},{"id":"23","description":"Indie"}],"screenshots":[{"id":0,"path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000598.600x338.jpg?t=1447350871","path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000598.1920x1080.jpg?t=1447350871"},{"id":1,"path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000599.600x338.jpg?t=1447350871","path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000599.1920x1080.jpg?t=1447350871"},{"id":2,"path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000600.600x338.jpg?t=1447350871","path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000600.1920x1080.jpg?t=1447350871"},{"id":3,"path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000601.600x338.jpg?t=1447350871","path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000601.1920x1080.jpg?t=1447350871"},{"id":4,"path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000602.600x338.jpg?t=1447350871","path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/0000000602.1920x1080.jpg?t=1447350871"}],"release_date":{"coming_soon":false,"date":"Jul 14, 2005"},"support_info":{"url":"","email":""},"background":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/1502\/page_bg_generated_v6b.jpg?t=1447350871"}}} | json |
<gh_stars>0
package com.forteach.external.mysql.repository;
import com.forteach.external.mysql.domain.Classes;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @Auther: zhangyy
* @Email: <EMAIL>
* @Date: 19-1-4 16:14
* @Version: 1.0
* @Description:
*/
public interface ClassesRepository extends JpaRepository<Classes, String> {
}
| java |
<reponame>ChadCYB/EatWhat<filename>www/css/map.css
body {
background-color: cadetblue;
}
h5 {
text-align: center;
font-weight: bold;
}
.content {
padding-top: 80px;
margin-bottom: 0px;
}
/* .map {
width: 100%;
height: 300px;
} */ | css |
Michael Vaughan has a lot in common with Saurav Ganguly. Both were great captains of their teams and changed the course of their cricket. Both were equally brilliant as tacticians and man-managers; hence, their understanding of strategies and players’ mentality is better than any other commentator.
Vaughan has every attribute that one wants in a commentator. He can break down the technique of a player, understand the complexities of the tactics and strategies being employed, understand the psychological make-up of a player and diagnose the problems facing a team accurately.
Vaughan has occasionally landed up in controversy, for instance, when he suggested that Stuart Broad should be dropped after England’s loss to Pakistan in the first Test of the 2018 English summer. But that is only because he is frank and candid and doesn’t sugarcoat his comments to suit the players of his erstwhile team.
Whether it is understanding the requirements of a team to accomplish a certain challenge for figuring out the reasons for their performance, Vaughan’s analysis is highly rewarding to listen to.
With him, the depth of the game and its various aspects, as well as the minute technical details, all become clear to the viewer.
That’s why he is the best. | english |
<filename>datasets/czechia-drobnepamatky/data/8850_5543.json<gh_stars>1-10
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"label:cs":"Zvonička v Bořanovicích","P31":"http://www.wikidata.org/entity/Q10861631","P31^label:cs":"Zvonička","P131^label:cs":"Bořanovice","P6736":"41771"},"geometry":{"type":"Point","coordinates":[14.47716,50.17786]}},{"type":"Feature","properties":{"label:cs":"Pamětní deska hasičského sboru v Bořanovicích","P31":"http://www.wikidata.org/entity/Q721747","P31^label:cs":"Pamětní deska","P131^label:cs":"Bořanovice","P6736":"41770"},"geometry":{"type":"Point","coordinates":[14.4776,50.17865]}},{"type":"Feature","properties":{"label:cs":"Pomník padlým v Bořanovicích","P31":"http://www.wikidata.org/entity/Q575759","P31^label:cs":"Pomník padlým","P131^label:cs":"Bořanovice","P6736":"41769"},"geometry":{"type":"Point","coordinates":[14.4788,50.17805]}},{"type":"Feature","properties":{"label:cs":"Zvonička u domu 12 v Sedlci","P31":"http://www.wikidata.org/entity/Q10861631","P31^label:cs":"Zvonička","P131^label:cs":"Sedlec","P6736":"41668"},"geometry":{"type":"Point","coordinates":[14.45969,50.18679]}},{"type":"Feature","properties":{"label:cs":"Pomník padlým v Sedlci","P31":"http://www.wikidata.org/entity/Q575759","P31^label:cs":"Pomník padlým","P131^label:cs":"Sedlec","P6736":"41666"},"geometry":{"type":"Point","coordinates":[14.45827,50.18586]}},{"type":"Feature","properties":{"label:cs":"Pomník Sedlecké lípy na východním okraji Sedlece","P31":"http://www.wikidata.org/entity/Q4989906","P31^label:cs":"Pomník","P131^label:cs":"Sedlec","P6736":"41665"},"geometry":{"type":"Point","coordinates":[14.46093,50.18617]}}]} | json |
<filename>user/pages/07.publications/documents/.revs/20180303-222904/default.sv.md
---
title: Dokument
visible: true
---
| markdown |
PM Modi announced the plan to link UPI and Lanka Pay when he was addressing the event to launch ferry services between Nagapattinam in India and Kankesanthurai in Sri Lanka, via a video message.
Previously, PM Modi and Sri Lanka President Ranil Wickremesinghe in India signed an agreement on Unified Payments Interface (UPI) acceptance in Sri Lanka during Sri Lanka President Ranil Wickremesinghe's two-day visit to India.
In 2022, National Payments Corporation Of India (NPCI), the umbrella organisation that offers UPI services, signed an MoU with France's fast and secure online payment system, called Lyra. In 2023, UPI and Singapore's PayNow signed an agreement, allowing users in either country to make cross-border transactions.
The UAE, Bhutan, and Nepal have already adopted the UPI payment system.
UPI which is run by the National Payments Corporation of India (NPCI), reported 10.56 billion transactions in September, a dip from the 10.58 billion transactions reported in August, the first time the instant payment mechanism crossed the 10 billion transaction mark.
Download The Economic Times News App to get Daily Market Updates & Live Business News.
| english |
export var settings = {
// Get a reference to the database service
// Was having a bug where the WIFI router would crash if the chunk size was bigger than 2^10
CHUNK_SIZE: Math.pow(2, 14), // size in bytes of the chunks. 2^14 is just under the limit in chrome.
ICE_SERVERS: [
{
url: 'stun:172.16.17.32',
urls: 'stun:172.16.17.32',
},
{
url: 'turn:global.turn.twilio.com:3478?transport=udp',
username:
'<PASSWORD>',
credential: '<KEY>
urls: 'turn:global.turn.twilio.com:3478?transport=udp',
},
],
POLLING_FREQUENCY: 15000,
debug: false,
}
| javascript |
Mini Mathur’s social media is a reflection of her uber-confident and charismatic personality. Every now and then the actress takes to her social media accounts to share videos, pictures and stories that are extremely personal but can help others too. From workout videos to giving her fans and followers a tour of her fantastic wardrobe, she does it all and watching her is always a delight.
Recently, she took to her Instagram account to share a story regarding her history of working out and her fitness. She wrote- “I’ve always thought of fitness as optional because my body has always been kind to me. But now I cannot imagine why I didn’t give back to it earlier. Women in your 40s please start now. It’s the only thing that will keep you sane. "
Mini stresses hard on the point that working out could help keep women over 40 sane, how true is it? See, the first thing that people need to understand is the fact that the benefits of working out can go beyond physical health, yes you heard that right, working out can help improve your mental health.
If you are exercising on a daily basis then not only can it improve your mood but can also help with your anxiety and depression. A lot of studies also suggest that working out can also help you out if you are struggling with a low-self esteem, the adrenaline rush is bound to make you feel better.
When women reach their 40s, owing to work and family pressure they succumb to different mental health issues, sometimes they are diagnosed while other times they are not. Working out will divert your mind from things that bring you down, it is known to provide you with an ample amount of peace. All you need to do is give it some time and patience. | english |
Reference (R)
Because Robert Hutton are sensitive to any happenings in Robert Hutton's career life, Robert Hutton prefer to have jobs which require little hassle and pressure. Aiming Robert Hutton's vocational directions with this in mind will result in a career of performance.
There are many remunerative occupations which might engage Robert Hutton's energies profitably. Robert Hutton's aptitude for making plans fits Robert Hutton for a whole host of businesses and trades where originality counts and this applies just as much to women as to men. Trained in another direction, the same quality would help in organising. Thus, Robert Hutton's are eminently fitted for directing the details of large commercial concerns. What Robert Hutton should avoid are all those jobs which are the same year in, year out, and where one day's work is merely a repetition of another. Routine jobs are not for Robert Hutton.
Robert Hutton will have great ability in making money in all forms of industry, business organisation or in the employment of others. Robert Hutton will always see a way out of any difficulty and be self-reliant and determined in whatever course of action Robert Hutton may decide to follow. Robert Hutton will be a speculator on a large scale in all Robert Hutton undertake. Robert Hutton will treat life more as a game than from a serious standpoint. As a general rule, luck will favour Robert Hutton during the greater part of Robert Hutton's life. In relation to finance Robert Hutton need have nothing to fear. Once the early part of Robert Hutton's life is over, Robert Hutton will begin to reap forward for the foundation Robert Hutton have laid and from that point Robert Hutton are likely to accumulate wealth and position.
| english |
Tokyo: Japan's defence ministry on Wednesday deployed three T4 training planes to collect possible radioactive material in the air following North Korea's claimed hydrogen bomb test, officials said.
"To understand the impact of possible radioactive materials released by the test, Air Self-Defence Force planes have collected dust in the air," Chief Cabinet Secretary Yoshihide Suga, the government's top spokesman, told a press conference.
"It is currently being sent to the Japan Chemical Analysis Centre," he said.
Suga added that the planes flew in Japanese airspace, while the Sankei Shimbun daily reported that the aircrafts took off from three separate bases in different parts of the country.
The cabinet secretary also said no abnormal levels of radiation have so far been detected through monitoring posts installed across Japan as of 4. 45 pm local time on Wednesday.
The results collected by the planes are expected to be released on Thursday, an official with Japan's Nuclear Regulation Authority told reporters.
North Korea's test, which came just two days before leader Kim Jong-Un's birthday, was initially detected by international seismology monitors as a 5. 1-magnitude tremor next to the North's main Punggye-ri nuclear test site in the northeast of the country.
Last month, North Korean leader Kim Jong-Un suggested Pyongyang had already developed a hydrogen bomb, though the claim was questioned by international experts and there was continued scepticism over today's announcement. (This story has not been edited by News18 staff and is published from a syndicated news agency feed - AFP) | english |
Employees' Provident Fund Organisation (EPFO), has taken on board Air India Limited for providing social security benefits like provident fund (PF), pension and insurance to its employees. It has received contributions for around 7,453 employees for December 2021.
This step was a part of the overall privatisation of the national carrier, as its employees have now come under the ambit of the Employees' Provident Fund & Miscellaneous Provisions Act 1952, with effect from December 1, 2021.
According to the gazette notification, the employer and majority of the employees have agreed to shift to provisions under the EPFO.
Prior to this shift, Air India employees were contributing in the provident fund and the money was channelised into two funds AIEPF (Air India Employees Provident Fund) and IAEPF (Indian Airlines Employees Provident Fund) with a total investment of around Rs 4,500 crore. These two funds were recognized under Provident Fund Act 1925.
With this gazette notification, the airline has completed the process of shifting employees from the old PF to the new system.
Under the PF Act, 1925, benefit of provident fund was available but there was no statutory pension or insurance scheme. The employees used to participate in self-contributory annuity-based pension scheme.
A guaranteed minimum pension of Rs 1,000 per month will be available to employees and pensions to family and dependents in case of death of employee.
An assured insurance benefit in case of death of member will be available in the range of minimum Rs 2. 50 lakh and maximum 7 lakh.
No premium is charged to the EPFO covered employees for this benefit.
The Tata Group has taken over the debt-ridden airline from the government. Air India had applied for EPFO coverage, which has been allowed, the retirement fund body said.
"EPFO onboards Air India for social security coverage to service the social security needs of their employees. Air India Ltd applied for voluntarily covered u/s 1(4) of the EPF & MP Act, 1952 which has been allowed . . . with effect from December 1, 2021," the labour ministry said in a statement issued on Saturday.
These employees of Air India now will be entitled to benefits like they will receive extra 2 per cent employer's contributions in their provident fund (PF) accounts at 12 per cent of their wages.
Earlier they were covered under the PF Act of 1925, where the contributions to the PF was at 10 per cent by employer and 10 per cent by employee.
The EPF Scheme 1952, EPS 1995 (employees pension scheme) and EDLI 1976 (group insurance) will now be applicable to the employees.
The ministry informed that since 1952-53, Air India and Indian Airlines were two separate companies that were covered under PF Act, 1925. In 2007, both the companies merged into one company, Air India Ltd.
Based on the scheme parameters, the accumulations used to be paid to the employees. There was no minimum pension guarantee and no extra benefit in case of death of a member. | english |
Genshin Impact 2. 1 will soon bring new banner rotations, and according to a new leak, The Unforged will reappear on an upcoming banner.
The Unforged is a 5-star claymore in Genshin Impact and is only available on select weapon banners. For some characters, The Unforged is a great weapon that boosts their defensive capabilities as well as their DPS. However, this claymore isn’t exactly a fan favorite in the Genshin Impact community, and many would have preferred a different 5-star weapon to return in 2. 1.
The Unforged was originally released in a weapon banner back in December 2020, and it’s yet to reappear in Genshin Impact’s gacha to this day. However, a new leak predicts The Unforged will appear alongside the soon-to-be-released Engulfing Lightning in a weapon banner. If this is true, The Unforged will be released once again on 1 September 2021.
The Unforged’s base attack is the lowest among 5-star claymores, next to Wolf’s Gravestone. While Wolf’s Gravestone compensates for this by having an incredible passive effect, The Unforged gets by with an ATK% substat. At level 90, The Unforged has a base attack of 608, and an ATK% bonus of 49. 6%.
Unfortunately, The Unforged’s passive ability is rather niche. At Refinement 1, it increases shield strength by 20%, and hitting enemies earns a 4% ATK buff for eight seconds. If The Unforged’s user has a shield up, this attack buff doubles.
Players who use Noelle, Beidou or Xinyan as their main DPS should consider wishing for The Unforged in version 2. 1. These shielding characters can make full use of The Unforged’s passive effect to obtain huge buffs to their attack stat. The Unforged can still work with other claymore DPS characters, but there are certainly better weapon options.
Most players who plan to wish from the upcoming weapon banner are likely hoping for Engulfing Lightning. Baal has been a highly-anticipated character, and this polearm will be an incredible weapon for her to wield.
Since The Unforged is so niche in its ability, many players were disappointed to hear about its upcoming return. It seems players would have preferred a more well-rounded weapon on the banner instead, in case they miss out on Engulfing Lightning.
Despite the negativity surrounding The Unforged’s return to Genshin Impact, it is still a fairly good weapon. Players who get The Unforged in 2. 1 should consider using it on a team with Zhongli or Diona to ensure constant shields.
When the claymore-user is paired with one of these shield supports, The Unforged’s full potential can be used to deal high damage numbers. | english |
<filename>BOCA/AG/src/generator.cpp
#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
const int MIN_N = 1;
const int MAX_N = 1e5;
const double MIN_V = -50.0;
const double MAX_V = 50.0;
const int rnd_test_n = 50;
template <typename T> void append(vector<T> &dest, const vector<T> &orig) {
dest.insert(dest.end(), orig.begin(), orig.end());
}
string output_tc(vector<double> &temperatures) {
ostringstream oss;
oss << temperatures.size() << endl;
for (size_t i = 0; i < temperatures.size(); i++) {
oss << temperatures[i];
oss << (i == temperatures.size() - 1 ? "\n" : " ");
}
return oss.str();
}
vector<double> generate_random_array(int n, double min_v = MIN_V,
double max_v = MAX_V) {
vector<double> v(n);
for (int i = 0; i < n; i++) {
v[i] = rnd.next(min_v, max_v);
}
return v;
}
vector<string> generate_sample_tests() {
vector<string> tests;
vector<double> temperatures;
temperatures = {25.0, 27.0, 26.0};
tests.push_back(output_tc(temperatures));
temperatures = {-10, 40, -10};
tests.push_back(output_tc(temperatures));
temperatures = {0, 0, 0};
tests.push_back(output_tc(temperatures));
return tests;
}
string rnd_test(int i) {
int min_n = MIN_N;
int max_n = MAX_N;
if(i<= rnd_test_n-10){
min_n = 1;
max_n = 10;
}
int n = rnd.next(min_n, max_n);
auto v = generate_random_array(n,MIN_V,MAX_V);
return (output_tc(v));
}
vector<string> generate_random_tests() {
vector<string> tests;
for (int i = 0; i < rnd_test_n; i++) {
tests.push_back(rnd_test(i));
}
return tests;
}
string extreme_test_1() {
auto v = generate_random_array(MAX_N,MIN_V,MAX_V);
return (output_tc(v));
}
string extreme_test_2() {
auto v = generate_random_array(MAX_N,MAX_V,MAX_V);
return (output_tc(v));
}
string extreme_test_3() {
auto v = generate_random_array(MAX_N,MIN_V,MIN_V);
return (output_tc(v));
}
vector<string> generate_extreme_tests() {
vector<string> tests;
tests.push_back(extreme_test_1());
tests.push_back(extreme_test_2());
tests.push_back(extreme_test_3());
return tests;
}
int main(int argc, char *argv[]) {
registerGen(argc, argv, 1);
vector<string> tests;
size_t test = 0;
append(tests, generate_sample_tests());
append(tests, generate_random_tests());
append(tests, generate_extreme_tests());
for (const auto &t : tests) {
startTest(++test);
cout << t;
}
return 0;
} | cpp |
/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
* File Name : BluetoothCommunication.java
* Author : <NAME>
* Version : 1.0
* Date : 1st Sep, 2014
* Description : BluetoothCommunication
********************************************************************************
* THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH PRODUCT CODING INFORMATION TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF THE SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* THIS SOURCE CODE IS PROTECTED BY A LICENSE AGREEMENT.
* FOR MORE INFORMATION PLEASE READ CAREFULLY THE LICENSE AGREEMENT FILE LOCATED
* IN THE ROOT DIRECTORY OF THIS SOFTWARE PACKAGE.
*******************************************************************************/
package com.example.multi_ndef;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
* This is the main Activity that displays the current chat session.
*/
public class BluetoothCommunication extends Activity
{
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothService mBluetoothService = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
@Override
public void onStart()
{
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled())
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
else
{
if (mBluetoothService == null)
{
StartService();
}
}
}
@Override
public synchronized void onResume()
{
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mBluetoothService != null)
{
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mBluetoothService.getState() == BluetoothService.STATE_NONE)
{
// Start the Bluetooth chat services
mBluetoothService.start();
}
}
}
private void StartService()
{
Log.d(TAG, "setupChat()");
mSendButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mBluetoothService = new BluetoothService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
@Override
public synchronized void onPause()
{
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
@Override
public void onStop()
{
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
public void onDestroy()
{
super.onDestroy();
// Stop the Bluetooth chat services
if (mBluetoothService != null) mBluetoothService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable()
{
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
{
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
* @param message A string of text to send.
*/
private void sendMessage(String message)
{
// Check that we're actually connected before trying anything
if (mBluetoothService.getState() != BluetoothService.STATE_CONNECTED)
{
return;
}
// Check that there's actually something to send
if (message.length() > 0)
{
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mBluetoothService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener()
{
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP)
{
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1)
{
case BluetoothService.STATE_CONNECTED:
//mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothService.STATE_CONNECTING:
//mTitle.setText(R.string.title_connecting);
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
//mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode)
{
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK)
{
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK)
{
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK)
{
// Bluetooth is now enabled, so set up a chat session
StartService();
}
else
{
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
finish();
}
}
}
}
/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************/ | java |
The rumor that Ohio State's head coach Ryan Day paid private investigators to look into Michigan's sign-stealing scheme had been doing the rounds. As partial reports have filtered about what information the NCAA possesses on the scandal, it has been clarified that Ryan Day had nothing to do with the matter.
Ross Dellenger of Yahoo Sports recently posted a tweet with the following information regarding the supposed involvement of Day in the investigation:
"On Monday, the NCAA notified the Big Ten that there are no known connections between Ohio State coach Ryan Day or his family and the organization’s investigation into Michigan, senior officials at both the NCAA and Big Ten tell Yahoo Sports".
What is the Michigan sign-stealing scandal?
At the center of the Michigan sign-stealing scandal is a scheme by former Wolverine analyst Connor Stalions to steal the signs from other teams ahead of their games. While stealing signs mid-game is permitted, a pre-meditated and co-ordinated effort ahead of games is prohibited by the NCAA.
Stalions has since left the Michigan Wolverines due to the pressure on him to resign, as a result of the scandal. Stalions claims that he alone was involved in the scheme and that neither Jim Harbaugh nor anyone else knew anything about the sign stealing.
Harbaugh is expected to be suspended any time now by the Big Ten, but most people expect the penalty to be a mild one. Reports from November 7 claim that NCAA investigators haven't been able to link Harbaugh directly to the scheme.
How is the season going for Ryan Day and the Ohio State Buckeyes?
Day is leading the Buckeyes to a perfect season so far, with a record of 9-0. Ohio State is ranked No. 3 in the AP Poll, a spot they've held for much of the season. When the CFP Committee divulged its first rankings of the season, Ryan Day's men took the first spot.
Ohio State has two easy encounters ahead, facing Michigan State and Minnesota over the next two weeks. They close out the season against No. 2 Michigan, in a game that will probably decide who attends the Big Ten championship game from the Big Ten East.
| english |
<filename>dist/resources/assets/@/js/index.js
'use strict';
window.App = {
camelize: function (str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (letter, index) {
return /*index == 0 ? letter.toLowerCase() :*/ letter.toUpperCase();
}).replace(/\s+/g, '');
}
};
(function (angular) {
'use strict';
angular.module('app', ['ngRoute', 'ngAnimate', 'ngMaterial'])
.controller('AppController', function ($scope, $route, $routeParams, $location, $mdDialog, $mdMedia) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
$scope.title = 'Awesovel';
$scope.loaded = true;
window.document.title = $scope.title;
$scope.menus = [];
$scope.project = null;
$scope.close = function () {
$scope.project = null;
$scope.menus = [
{
label: 'Home',
href: 'index.html'
}
];
};
$scope.open = function (project) {
$scope.project = project;
$scope.menus = [
{
label: 'Home',
href: 'index.html'
}
,
{
label: 'Models',
href: 'app/project/models/' + project
},
{
label: 'Databases',
href: 'app/project/databases/' + project
},
{
label: 'Settings',
href: 'app/project/settings/' + project
}
];
};
$scope.close();
$scope.dialog = {
confirm: function(title, message, success) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title(title)
.textContent(message)
//.ariaLabel('Lucky day')
//.targetEvent(ev)
.ok('Confirm')
.cancel('Cancel');
$mdDialog.show(confirm).then(function() {
$scope.status = 'You decided to get rid of your debt.';
console.log(success);
}, function() {
$scope.status = 'You decided to keep your debt.';
});
}
}
})
.controller('DrawerController', function ($scope) {
$scope.drawer = {
width: 300,
label: 'Menu'
}
})
.controller('ProjectController', function ($scope) {
$scope.fs = require('fs');
$scope.projects = JSON.parse(
$scope.fs.readFileSync(__dirname.replace('atom.asar/renderer/lib', '') + 'app/storage/projects.json', 'utf8')
);
$scope.path = function(project) {
var path,
id = project ? project : $scope.project;
angular.forEach($scope.projects, function(_project) {
if (_project === id) {
path = _project.path;
}
});
return path;
};
$scope.models = function(project) {
var path = $scope.path(project);
};
})
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
// Home
.when('/index.html', {
templateUrl: 'resources/views/home.html',
controller: function () {
}
})
// Catch All
.when('/:route*', {
template: function (params) {
var
route = params.route.split('/'),
controller = route[1];
if (route[0] === 'app') {
controller = App.camelize(controller) + 'Controller';
}
return '<div ng-controller="' + controller + '"><ng-include src="template"></ng-include></div>'
},
controller: 'TemplateCtrl'
})
$locationProvider.html5Mode(true);
}
])
.controller("TemplateCtrl", function ($scope, $routeParams) {
var
route = $routeParams.route.split('/'),
controller = route[1],
template = '',
layout = route[2];
if (route[0] === 'app') {
template = 'resources/views/' + controller + '/' + layout + '.html';
}
$scope.template = template;
$scope.params = $routeParams;
if (controller === 'project') {
$scope.open(route[3]);
}
})
})(window.angular);
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
| javascript |
Lucknow: Prime Minister Narendra Modi’s day-long visit to his parliamentary constituency Varanasi on Sunday was cancelled following heavy rain in the region.
Modi was very keen to visit the region but the weather played truant, Union Power Minister Piyush said this at a hurriedly convened press conference.
Asked when will the prime minister be in Varanasi next, the minister said the dates would be reworked soon by the Prime Minister’s Office.
Modi was to launch the Integrated Power Development Scheme (IPDS), one of the flagship programmes of the power ministry, to ensure 24×7 power for all.
Heavy rains have been lashing the eastern parts of Uttar Pradesh since Saturday. The venue of the launch of the IPDS and another where Modi was to address a public rally were inundated with water.
The scheme, announced in the 2014-15 union budget, is aimed at strengthening of the sub-transmission network, metering, IT application, customer care services, provision of solar panels and completion of the ongoing work of the Restructured Accelerated Power Development and Reforms Programme (RAPDRP).
The union government will provide budgetary support of Rs.45,800 crore over the entire implementation period of the IPDS.
Of the total amount, Rs.1,067 crore has been sanctioned for Uttar Pradesh, including Rs.572 crore for Varanasi.
The project envisages converting area overhead lines into underground cabling in areas around temples and ghats in Varanasi city.
The scheme includes upgradation of electrical assets at sub-centres, lines and distribution transformers, capacity enhancement and renewal of the old substations and installation of roof-top solar panels in government buildings.
The IPDS will help in reduction in aggregate technical and commercial (AT&C) losses, establishment of IT enabled energy accounting/ auditing system, improvement in billed energy based on metered consumption and improvement in collection efficiency.
Meghalaya scored 92.85 out of 100 possible points in a Gaming Industry Index and proved to be India’s most gaming-friendly state following its recent profound legislation changes over the field allowing land-based and online gaming, including games of chance, under a licensing regime.
Starting from February last year, Meghalaya became the third state in India’s northeast to legalise gambling and betting after Sikkim and Nagaland. After consultations with the UKIBC, the state proceeded with the adoption of the Meghalaya Regulation of Gaming Act, 2021 and the nullification of the Meghalaya Prevention of Gambling Act, 1970. Subsequently in December, the Meghalaya Regulation of Gaming Rules, 2021 were notified and came into force.
The move to legalise and license various forms of offline and online betting and gambling in Meghalaya is aimed at boosting tourism and creating jobs, and altogether raising taxation revenues for the northeastern state. At the same time, the opportunities to bet and gamble legally will be reserved only for tourists and visitors.
“We came out with a Gaming Act and subsequently framed the Regulation of Gaming Rules, 2021. The government will accordingly issue licenses to operate games of skill and chance, both online and offline,” said James P. K. Sangma, Meghalaya State Law and Taxation Minister speaking in the capital city of Shillong. “But the legalized gambling and gaming will only be for tourists and not residents of Meghalaya,” he continued.
To be allowed to play, tourists and people visiting the state for work or business purposes will have to prove their non-resident status by presenting appropriate documents, in a process similar to a bank KYC (Know Your Customer) procedure.
With 140 millions of people in India estimated to bet regularly on sports, and a total of 370 million desi bettors around prominent sporting events, as per data from one of the latest reports by Esse N Videri, Meghalaya is set to reach out and take a piece of a vast market.
Estimates on the financial value of India’s sports betting market, combined across all types of offline channels and online sports and cricket predictions and betting platforms, speak about amounts between $130 and $150 billion (roughly between ₹9.7 and ₹11.5 lakh crore).
Andhra Pradesh, Telangana and Delhi are shown to deliver the highest number of bettors and Meghalaya can count on substantial tourists flow from their betting circles. The sports betting communities of Karnataka, Maharashtra, Uttar Pradesh and Haryana are also not to be underestimated.
Among the sports, cricket is most popular, registering 68 percent of the total bet count analyzed by Esse N Videri. Football takes second position with 11 percent of the bets, followed by betting on FIFA at 7 percent and on eCricket at 5 percent. The last position in the Top 5 of popular sports for betting in India is taken by tennis with 3 percent of the bet count.
Meghalaya residents will still be permitted to participate in teer betting over arrow-shooting results. Teer is a traditional method of gambling, somewhat similar to a lottery draw, and held under the rules of the Meghalaya Regulation of the Game of Arrow Shooting and the Sale of Teer Tickets Act, 2018.
Teer includes bettors wagering on the number of arrows that reach the target which is placed about 50 meters away from a team of 20 archers positioned in a semicircle.
The archers shoot volleys of arrows at the target for ten minutes, and players place their bets choosing a number between 0 and 99 trying to guess the last two digits of the number of arrows that successfully pierce the target.
If, for example, the number of hits is 256, anyone who has bet on 56 wins an amount eight times bigger than their wager.
| english |
[
{
"temporarilyOffline": false,
"oneOffExecutors": [],
"offlineCauseReason": "",
"offlineCause": null,
"offline": false,
"numExecutors": 2,
"monitorData": {
"hudson.node_monitors.ClockMonitor": {
"diff": 0
},
"hudson.node_monitors.DiskSpaceMonitor": {
"size": 129721405440,
"path": "/Users/gbowles/.jenkins"
},
"hudson.node_monitors.TemporarySpaceMonitor": {
"size": 129721405440,
"path": <KEY>"
},
"hudson.node_monitors.ResponseTimeMonitor": {
"average": 0
},
"hudson.node_monitors.ArchitectureMonitor": "Mac OS X (x86_64)",
"hudson.node_monitors.SwapSpaceMonitor": {
"totalSwapSpace": 1073741824,
"totalPhysicalMemory": -1,
"availableSwapSpace": 1035993088,
"availablePhysicalMemory": -1
}
},
"manualLaunchAllowed": true,
"actions": [],
"displayName": "master",
"executors": [
{},
{}
],
"icon": "computer.png",
"idle": true,
"jnlpAgent": false,
"launchSupported": true,
"loadStatistics": {}
},
{
"temporarilyOffline": false,
"oneOffExecutors": [],
"offlineCauseReason": "This node is offline because Jenkins failed to launch the slave agent on it.",
"offlineCause": {},
"offline": true,
"numExecutors": 1,
"monitorData": {
"hudson.node_monitors.ClockMonitor": null,
"hudson.node_monitors.DiskSpaceMonitor": null,
"hudson.node_monitors.TemporarySpaceMonitor": null,
"hudson.node_monitors.ResponseTimeMonitor": {
"average": 5000
},
"hudson.node_monitors.ArchitectureMonitor": null,
"hudson.node_monitors.SwapSpaceMonitor": null
},
"manualLaunchAllowed": true,
"actions": [],
"displayName": "gbawstools",
"executors": [
{}
],
"icon": "computer-flash.gif",
"idle": true,
"jnlpAgent": false,
"launchSupported": true,
"loadStatistics": {}
}
]
| json |
package ru.job4j.threads.threadsproblems.racecondition;
public class RaceConditionsShow {
public static void main(String[] args) {
// Создаём некий класс Counter, который содержитв себе булеву переменную (просто чтобы проще было работать)
Counter counter = new Counter();
// Создаём два потока, каждый из которых планирует установить своё значение в булеву переменную.
Thread thread1 = new Thread(new RaceClass(counter, false));
Thread thread2 = new Thread(new RaceClass(counter, true));
// Кто из них добежит последним и установит своё значение - загадка.
thread1.start();
thread2.start();
try {
// даём тайм-аут главному потоку, чтобы в гонках не участвовало уже три потока
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.hasInfo);
}
}
| java |
<reponame>isabella232/OfficeDocs-AlchemyInsights-pr.sl-SI
---
title: Reševanje težav pri izmenjavi zvezkov programa OneNote
ms.author: pebaum
author: pebaum
manager: scotv
ms.date: 07/17/2020
ms.audience: Admin
ms.topic: article
ROBOTS: NOINDEX, NOFOLLOW
localization_priority: Priority
ms.collection: Adm_O365
ms.custom:
- "6048"
- "9000755"
ms.openlocfilehash: a5a182fb229920838b5a3e78842ce5a7ff592e4e
ms.sourcegitcommit: e5906a10f46be33d46e5d9a30c46ed5f2d88b7f7
ms.translationtype: MT
ms.contentlocale: sl-SI
ms.lasthandoff: 07/18/2020
ms.locfileid: "45198526"
---
# <a name="resolving-issues-sharing-onenote-notebooks"></a>Reševanje težav pri izmenjavi zvezkov programa OneNote
Gumb» skupna raba «se nahaja v zgornjem desnem kotu programa OneNote.
- Stavek v nedoločni zaimek email ogovor deliti zvezek.
- Kliknite **Skupna raba**.
Zaprite in znova odprite zvezek v OneNotu, da začnete znova deliti. | markdown |
{
"kind": "Property",
"name": "TouchEvent.touches",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches",
"description": "touches is a read-only TouchList listing all the Touch objects for touch points that are currently in contact with the touch surface, regardless of whether or not they've changed or what their target element was at touchstart time.",
"refs": [
{
"name": "Touch Events – Level 2",
"href": "https://w3c.github.io/touch-events/#dom-touchevent-touches"
},
{
"name": "Touch Events",
"href": "https://www.w3.org/TR/touch-events/#widl-TouchEvent-touches"
}
]
}
| json |
import { Routes, RouterModule } from '@angular/router';
import { DatabasematricsComponent } from './databasematrics.component';
const routes: Routes = [
{
path: '',
component: DatabasematricsComponent
}
];
export const routing = RouterModule.forChild(routes); | typescript |
National Health Mission, Madhya Pradesh (NHM MP) has invited online applications from eligible candidates for recruitment to the post of Community Health Officers. Interested and eligible candidates can apply online at nhmmp.gov.in or sams.co.in till May 31, 2021.
The application process began on May 15. The recruitment drive aims to fill up a total of 2850 vacancies. Out of these vacancies, 33% seats are reserved for female candidates in all of the categories, as per the notification.
The applicants will be recruited on a contractual basis.
Eligibility Criteria:
Age Limit: The candidates must have attained the age of 21 years and must not be more than the age of 40 years as on May 1, 2021. Upper age relaxation applicable to candidates falling under the reserved category.
Educational Qualification: The candidates should have completed BSc Nursing, post basic BSc Nursing or GNM from an institute recognised by the Indian Nursing Council, New Delhi. More details, in the notification.
Here’s the direct link to apply for CHO vacancies.
The applicants will be selected on the basis of written examination. The shortlisted candidates will receive salary of Rs 25,000 and an incentive of Rs 15000 maximum per month.
For more details, candidates are advised to visit the official website here.
| english |
import Axios from 'axios';
import { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import axiosRetry from 'axios-retry';
interface DefaultHeaders {
Authorization?: string;
'Content-Type'?: any;
Accept?: string;
[propName: string]: any;
}
interface DevHeaders {
'X-Forwarded-Proto'?: string;
'X-Forwarded-Host'?: string;
'X-Forwarded-Port'?: string;
'X-Tenant'?: string;
}
interface Headers extends DefaultHeaders, DevHeaders {}
export interface SetURL {
apiCall: any; // TODO this should be URL, but causes some type problems with Axios
headers: Headers;
}
/**
* Class to handle api calls to learn
*
* @remarks
* This method takes the responses meta.next and returns the path + params
*
* @example
* ```
* # Single request
* bridge = new Bridge('https://foo.bridgeapp.com', 'Basic abc123')
* await bridge.get('/api/author/users?id=1');
*
* # Paginated
* const allResults = bridge.getAll('/api/author/users?ide=1')
* for await (const result of allResults) {
* console.log(result);
* }
*
*```
*
*
* @param baseUrl - The base url of the request `https://foo.bridgeapp.com`
* @param apiKey - The apiKey used for learn `Basic abc123`
* @param headers - headers you want to include with the request
*/
class Bridge {
baseUrl: string;
apiKey: string;
headers: Headers;
constructor(
baseUrl: string,
apiKey: string = tableau?.password,
headers: Headers = {},
) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.headers = headers;
}
setUrl(path: any): SetURL {
let url: URL | string;
let devHeaders: DevHeaders;
const parsedUrl: URL = new URL(path, this.baseUrl);
const defaultHeaders: DefaultHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (this.apiKey) {
defaultHeaders['Authorization'] = this.apiKey;
}
if (this.addDevelopmentHeaders()) {
// Address of webpack-dev-server
url = new URL(
parsedUrl.pathname + parsedUrl.search,
'http://localhost:8888',
);
devHeaders = {
'X-Forwarded-Proto': parsedUrl.protocol,
'X-Forwarded-Host': parsedUrl.hostname,
'X-Forwarded-Port': parsedUrl.port,
'X-Tenant': parsedUrl.hostname.split('.')[0],
};
} else {
url = parsedUrl;
devHeaders = {};
}
return {
apiCall: url,
headers: { ...defaultHeaders, ...devHeaders, ...this.headers },
};
}
addDevelopmentHeaders() {
if (process.env.NODE_ENV === 'development') {
return true;
} else if (
process.env.NODE_ENV === 'test' &&
process.env.RECORD_FIXTURES
) {
return true;
} else {
return false;
}
}
/**
* Returns the meta.next url used when a response is paged
*
* @remarks
* This method takes the responses meta.next and returns the path + params
*
* @param nextUrl - The meta.next url
*/
metaNext(nextUrl: string): string {
const parsedUrl = new URL(nextUrl);
return parsedUrl.pathname + parsedUrl.search;
}
/**
* Determines if Axios response should be be retried
*
* @remarks
* By default retry will work for network errors and 5xx, this method adds 403, and 429 codes
* Bridge will return a `403 Forbidden (Rate Limit Exceeded)` if API requests are being throttled
*
* @param error - AxiosError
*/
retriableError(error: AxiosError): boolean {
const retriableCodes = [403, 429];
return (
axiosRetry.isNetworkOrIdempotentRequestError(error) ||
retriableCodes.includes(error?.response?.status) ||
false
);
}
/**
* Axios.get function
*
* @param apiCall - The url
* @param apiKey - The password/key
*/
async get(path: string): Promise<AxiosResponse> {
// By default retry will work for network errors and 5xx.
// With retries at 10, the max backoff could be between 2-5 min
axiosRetry(Axios, {
retries: 10,
retryDelay: axiosRetry.exponentialDelay,
shouldResetTimeout: true,
retryCondition: (e) => {
return this.retriableError(e);
},
});
const urlObj: SetURL = this.setUrl(path);
const req: AxiosRequestConfig = {
method: 'get',
url: urlObj.apiCall.toString(),
headers: urlObj.headers,
timeout: 60000, // 60 seconds
};
return Axios(req);
}
/**
* Generator function, that calls this.get and creates an iterable.
* If paginated, will use meta.next url
*
* @param apiCall - The url
* @param apiKey - The password/key
*/
async *getAll(path: string) {
let url = path;
while (url) {
const response = await this.get(url);
const result = await response.data;
url = result?.meta?.next ? this.metaNext(result.meta.next) : null;
yield result;
}
}
}
export { Bridge };
| typescript |
<filename>src/shrink/src/routes/new/registered.js
const express = require("express");
const validUrl = require("valid-url");
const { NotFoundError } = require("objection");
const crypto = require("crypto");
const router = express.Router();
const checkAuth = require("../../middlewares/checkAuth");
const RegisteredUrlDao = require("../../db/dao/RegisteredUrlDao");
const { DOMAIN } = require("../../../config");
const domain = DOMAIN + "r/";
router.use(checkAuth);
router.post("/", async (req, res) => {
// extract url from request body
const { url, userid } = req.body;
// if url is invalid, throw error
if (!validUrl.isUri(url) || url.length > 512) {
return res
.status(400)
.json({ status: "error", msg: "invalid url/url too long" });
}
// if url already exists, returns its shortened url
try {
const shorturl = await RegisteredUrlDao.getShortUrl(userid, url);
// return this short url
return res.status(200).json({ url, shorturl: domain + shorturl });
} catch (err) {
if (err instanceof NotFoundError) {
// if the long url is not found in the database, create new one
const shorturl = crypto
.createHash("md5")
.update(url)
.digest("hex")
.slice(0, 6);
// insert new longurl-shorturl mapping into the database
try {
await RegisteredUrlDao.insert(userid, shorturl, url);
return res
.status(200)
.json({ url, shorturl: domain + shorturl });
} catch (e) {
// if an error thrown, log it
console.log(e);
}
} else {
// this error will be a database error
console.log(err);
}
}
// if we came here, there was an error in generating url.
return res.status(400).json({
status: "error",
msg: "There was an error in shrinking your url. Please try again!",
});
});
module.exports = router;
require;
| javascript |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sagemaker/model/DescribeModelPackageGroupResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::SageMaker::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeModelPackageGroupResult::DescribeModelPackageGroupResult() :
m_modelPackageGroupStatus(ModelPackageGroupStatus::NOT_SET)
{
}
DescribeModelPackageGroupResult::DescribeModelPackageGroupResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_modelPackageGroupStatus(ModelPackageGroupStatus::NOT_SET)
{
*this = result;
}
DescribeModelPackageGroupResult& DescribeModelPackageGroupResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("ModelPackageGroupName"))
{
m_modelPackageGroupName = jsonValue.GetString("ModelPackageGroupName");
}
if(jsonValue.ValueExists("ModelPackageGroupArn"))
{
m_modelPackageGroupArn = jsonValue.GetString("ModelPackageGroupArn");
}
if(jsonValue.ValueExists("ModelPackageGroupDescription"))
{
m_modelPackageGroupDescription = jsonValue.GetString("ModelPackageGroupDescription");
}
if(jsonValue.ValueExists("CreationTime"))
{
m_creationTime = jsonValue.GetDouble("CreationTime");
}
if(jsonValue.ValueExists("CreatedBy"))
{
m_createdBy = jsonValue.GetObject("CreatedBy");
}
if(jsonValue.ValueExists("ModelPackageGroupStatus"))
{
m_modelPackageGroupStatus = ModelPackageGroupStatusMapper::GetModelPackageGroupStatusForName(jsonValue.GetString("ModelPackageGroupStatus"));
}
return *this;
}
| cpp |
#########################
#########################
# Need to account for limit in input period
#########################
#########################
# Baseline M67 long script -- NO crowding
# New script copied from quest - want to take p and ecc from each population (all, obs, rec) and put them into separate file
# Doing this so we don't have to run analyse each time
# Can write separate script for p-ecc plots
# Quest paths in this version of script
import pandas as pd
import numpy as np
import os
from astropy.coordinates import SkyCoord
from astropy import units, constants
from astropy.modeling import models, fitting
import scipy.stats
from scipy.integrate import quad
#for Quest
import matplotlib
matplotlib.use('Agg')
doIndividualPlots = True
from matplotlib import pyplot as plt
def file_len(fname):
i = 0
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def getPhs(sigma, m1=1*units.solMass, m2=1*units.solMass, m3=0.5*units.solMass):
Phs = np.pi*constants.G/np.sqrt(2.)*(m1*m2/m3)**(3./2.)*(m1 + m2)**(-0.5)*sigma**(-3.)
return Phs.decompose().to(units.day)
#similar to field, but limiting by the hard-soft boundary
def fitRagfb():
x = [0.05, 0.1, 1, 8, 15] #estimates of midpoints in bins, and using this: https://sites.uni.edu/morgans/astro/course/Notes/section2/spectralmasses.html
y = [0.20, 0.35, 0.50, 0.70, 0.75]
init = models.PowerLaw1D(amplitude=0.5, x_0=1, alpha=-1.)
fitter = fitting.LevMarLSQFitter()
fit = fitter(init, x, y)
return fit
def RagNormal(x, cdf = False):
mean = 5.03
std = 2.28
if (cdf):
return scipy.stats.norm.cdf(x,mean,std)
return scipy.stats.norm.pdf(x,mean,std)
def saveHist(histAll, histObs, histRec, bin_edges, xtitle, fname, filters = ['u_', 'g_', 'r_', 'i_', 'z_', 'y_','all']):
c1 = '#5687A6' #Dali Blue (Andrew's AAS Poster)
c2 = '#A62B1F' #Dai Red
c3 = '#BF8A26' #Dali Beige
fig,ax1 = plt.subplots(figsize=(8,6), sharex=True)#can change to include cdf with ax1, ax2
histAll = np.insert(histAll,0,0)
histObs = np.insert(histObs,0,0)
for f in filters:
histRec[f] = np.insert(histRec[f],0,0)
#PDF
ax1.step(bin_edges, histAll/np.sum(histAll), color=c1)
ax1.step(bin_edges, histObs/np.sum(histObs), color=c2)
for f in filters:
lw = 1
if (f == 'all'):
lw = 0.5
ax1.step(bin_edges, histRec[f]/np.sum(histRec[f]), color=c3, linewidth=lw)
ax1.set_ylabel('PDF')
ax1.set_yscale('log')
ax1.set_title('Globular Clusters - Baseline', fontsize = 16)
ax1.set_xlabel(xtitle)
#CDF
#cdfAll = []
#cdfObs = []
#cdfRec = dict()
#for f in filters:
# cdfRec[f] = []
# for i in range(len(histAll)):
# cdfAll.append(np.sum(histAll[:i])/np.sum(histAll))
# for i in range(len(histObs)):
# cdfObs.append(np.sum(histObs[:i])/np.sum(histObs))
# for f in filters:
# for i in range(len(histRec[f])):
# cdfRec[f].append(np.sum(histRec[f][:i])/np.sum(histRec[f]))
#ax2.step(bin_edges, cdfAll, color=c1)
#ax2.step(bin_edges, cdfObs, color=c2)
#for f in filters:
# lw = 1
# if (f == 'all'):
# lw = 0.5
# ax2.step(bin_edges, cdfRec[f], color=c3, linewidth=lw)
#ax2.set_ylabel('CDF')
#ax2.set_xlabel(xtitle)
fig.subplots_adjust(hspace=0)
fig.savefig('./plots/' + fname+'.pdf',format='pdf', bbox_inches = 'tight')
#write to a text file
with open('./eblsst_files/' + fname+'.csv','w') as fl:
outline = 'binEdges,histAll,histObs'
for f in filters:
outline += ','+f+'histRec'
outline += '\n'
fl.write(outline)
for i in range(len(bin_edges)):
outline = str(bin_edges[i])+','+str(histAll[i])+','+str(histObs[i])
for f in filters:
outline += ','+str(histRec[f][i])
outline += '\n'
fl.write(outline)
if __name__ == "__main__":
filters = ['u_', 'g_', 'r_', 'i_', 'z_', 'y_', 'all']
#get the Raghavan binary fraction fit
fbFit= fitRagfb()
print(fbFit)
#to normalize
intAll, err = quad(RagNormal, -20, 20)
intCut, err = quad(RagNormal, -20, np.log10(365*10.))
intNorm = intCut/intAll
#cutoff in percent error for "recovered"
Pcut = 0.1
#assumed mean stellar mass
mMean = 0.5
#minimum number of lines to consider in file
Nlim = 3
if (doIndividualPlots):
fmass, axmass = plt.subplots()
fqrat, axqrat = plt.subplots()
fecc, axecc = plt.subplots()
flper, axlper = plt.subplots()
fdist, axdist = plt.subplots()
fmag, axmag = plt.subplots()
frad, axrad = plt.subplots()
#bins for all the histograms
Nbins = 25
mbins = np.arange(0,10, 0.1, dtype='float')
qbins = np.arange(0,1, 0.1, dtype='float')
ebins = np.arange(0, 1.05, 0.05, dtype='float')
lpbins = np.arange(-2, 10, 0.5, dtype='float')
dbins = np.arange(0, 40, 1, dtype='float')
magbins = np.arange(11, 25, 1, dtype='float')
rbins = np.arange(0, 100, 0.2, dtype='float')
#blanks for the histograms
#All
m1hAll = np.zeros_like(mbins)[1:]
qhAll = np.zeros_like(qbins)[1:]
ehAll = np.zeros_like(ebins)[1:]
lphAll = np.zeros_like(lpbins)[1:]
dhAll = np.zeros_like(dbins)[1:]
maghAll = np.zeros_like(magbins)[1:]
rhAll = np.zeros_like(rbins)[1:]
#Observable
m1hObs = np.zeros_like(mbins)[1:]
qhObs = np.zeros_like(qbins)[1:]
ehObs = np.zeros_like(ebins)[1:]
lphObs = np.zeros_like(lpbins)[1:]
dhObs = np.zeros_like(dbins)[1:]
maghObs = np.zeros_like(magbins)[1:]
rhObs = np.zeros_like(rbins)[1:]
#Recovered
m1hRec = dict()
qhRec = dict()
ehRec = dict()
lphRec = dict()
dhRec = dict()
maghRec = dict()
rhRec = dict()
for f in filters:
m1hRec[f] = np.zeros_like(mbins)[1:]
qhRec[f] = np.zeros_like(qbins)[1:]
ehRec[f] = np.zeros_like(ebins)[1:]
lphRec[f] = np.zeros_like(lpbins)[1:]
dhRec[f] = np.zeros_like(dbins)[1:]
maghRec[f] = np.zeros_like(magbins)[1:]
rhRec[f] = np.zeros_like(rbins)[1:]
RA = []
Dec = []
recFrac = []
recN = []
rawN = []
obsN = []
fileN = []
fileObsN = []
fileRecN = []
allNPrsa = []
obsNPrsa = []
recNPrsa = []
# Lists for period and eccentricity for Andrew's circularization plots
eccAll = []
eccObs = []
eccRec = []
pAll = []
pObs = []
pRec = []
# Using prsa dataframes for these lists because of period cutoff at 1000 days
# Dataframes to write to files later; 3 files for each sub-population - append everything to these
peccAll = pd.DataFrame(columns = ['e', 'p'])
peccObs = pd.DataFrame(columns = ['e', 'p'])
peccRec = pd.DataFrame(columns = ['e', 'p'])
#Read in all the data and make the histograms
d = "./input_files/"
files = os.listdir(d)
IDs = []
for i, f in enumerate(files):
print(round(i/len(files),4), f)
fl = file_len(d+f)
if (fl >= 4):
#read in the header
header = pd.read_csv(d+f, nrows=1)
######################
#NEED TO ACCOUNT FOR THE BINARY FRACTION when combining histograms
#####################
Nmult = header['clusterMass'][0]/mMean
#Nmult = 1.
RA.append(header['OpSimRA'])
Dec.append(header['OpSimDec'])
#read in rest of the file
data = pd.read_csv(d+f, header = 2).fillna(-999)
rF = 0.
rN = 0.
Nrec = 0.
Nobs = 0.
raN = 0.
obN = 0.
fiN = 0.
fioN = 0.
firN = 0.
NallPrsa = 0.
NobsPrsa = 0.
NrecPrsa = 0.
Nall = len(data.index)/intNorm ###is this correct? (and the only place I need to normalize?)
prsa = data.loc[(data['appMagMean_r'] <= 19.5) & (data['appMagMean_r'] > 15.8) & (data['p'] < 1000) & (data['p'] > 0.5)]
# Appending for Andrew
eccAll.append(prsa['e'].values)
pAll.append(prsa['p'].values)
NallPrsa = len(prsa.index)
if (Nall >= Nlim):
#create histograms
#All
m1hAll0, m1b = np.histogram(data["m1"], bins=mbins)
qhAll0, qb = np.histogram(data["m2"]/data["m1"], bins=qbins)
ehAll0, eb = np.histogram(data["e"], bins=ebins)
lphAll0, lpb = np.histogram(np.ma.log10(data["p"].values).filled(-999), bins=lpbins)
dhAll0, db = np.histogram(data["d"], bins=dbins)
maghAll0, magb = np.histogram(data["appMagMean_r"], bins=magbins)
rhAll0, rb = np.histogram(data["r2"]/data["r1"], bins=rbins)
if (doIndividualPlots):
axmass.step(m1b[0:-1], m1hAll0/np.sum(m1hAll0), color='black', alpha=0.1)
axqrat.step(qb[0:-1], qhAll0/np.sum(qhAll0), color='black', alpha=0.1)
axecc.step(eb[0:-1], ehAll0/np.sum(ehAll0), color='black', alpha=0.1)
axlper.step(lpb[0:-1], lphAll0/np.sum(lphAll0), color='black', alpha=0.1)
axdist.step(db[0:-1], dhAll0/np.sum(dhAll0), color='black', alpha=0.1)
axmag.step(magb[0:-1], maghAll0/np.sum(maghAll0), color='black', alpha=0.1)
axrad.step(rb[0:-1], rhAll0/np.sum(rhAll0), color='black', alpha=0.1)
#account for the binary fraction, as a function of mass
dm1 = np.diff(m1b)
m1val = m1b[:-1] + dm1/2.
fb = np.sum(m1hAll0/len(data.index)*fbFit(m1val))
#account for the hard-soft boundary
Phs = getPhs(header['clusterVdisp'].iloc[0]*units.km/units.s).to(units.day).value
fb *= RagNormal(np.log10(Phs), cdf = True)
print("fb, Phs = ", fb, Phs)
Nmult *= fb
m1hAll += m1hAll0/Nall*Nmult
qhAll += qhAll0/Nall*Nmult
ehAll += ehAll0/Nall*Nmult
lphAll += lphAll0/Nall*Nmult
dhAll += dhAll0/Nall*Nmult
maghAll += maghAll0/Nall*Nmult
rhAll += rhAll0/Nall*Nmult
#Obs
obs = data.loc[data['LSM_PERIOD'] != -999]
Nobs = len(obs.index)
prsaObs = data.loc[(data['appMagMean_r'] <= 19.5) & (data['appMagMean_r'] > 15.8) & (data['p'] < 1000) & (data['p'] >0.5) & (data['LSM_PERIOD'] != -999)]
NobsPrsa = len(prsaObs.index)
# Appending for Andrew's files
eccObs.append(prsaObs['e'].values)
pObs.append(prsaObs['p'].values)
if (Nobs >= Nlim):
m1hObs0, m1b = np.histogram(obs["m1"], bins=mbins)
qhObs0, qb = np.histogram(obs["m2"]/obs["m1"], bins=qbins)
ehObs0, eb = np.histogram(obs["e"], bins=ebins)
lphObs0, lpb = np.histogram(np.ma.log10(obs["p"].values).filled(-999), bins=lpbins)
dhObs0, db = np.histogram(obs["d"], bins=dbins)
maghObs0, magb = np.histogram(obs["appMagMean_r"], bins=magbins)
rhObs0, rb = np.histogram(obs["r2"]/obs["r1"], bins=rbins)
m1hObs += m1hObs0/Nall*Nmult
qhObs += qhObs0/Nall*Nmult
ehObs += ehObs0/Nall*Nmult
lphObs += lphObs0/Nall*Nmult
dhObs += dhObs0/Nall*Nmult
maghObs += maghObs0/Nall*Nmult
rhObs += rhObs0/Nall*Nmult
#Rec
recCombined = pd.DataFrame()
prsaRecCombined = pd.DataFrame()
for filt in filters:
key = filt+'LSS_PERIOD'
if (filt == 'all'):
key = 'LSM_PERIOD'
fullP = abs(data[key] - data['p'])/data['p']
halfP = abs(data[key] - 0.5*data['p'])/(0.5*data['p'])
twiceP = abs(data[key] - 2.*data['p'])/(2.*data['p'])
rec = data.loc[(data[key] != -999) & ( (fullP < Pcut) | (halfP < Pcut) | (twiceP < Pcut))]
prsaRec = data.loc[(data['appMagMean_r'] <= 19.5) & (data['appMagMean_r'] >15.8) & (data['p'] < 1000) & (data['p'] >0.5) & (data['LSM_PERIOD'] != -999) & ( (fullP < Pcut) | (halfP < Pcut) | (twiceP < Pcut))]
Nrec = len(rec.index)
#I'd like to account for all filters here to have more accurate numbers
recCombined = recCombined.append(rec)
prsaRecCombined = prsaRecCombined.append(prsaRec)
# Going to use prsaRecCombined for ecc-p plots to account for all filters
eccRec.append(prsaRec['e'].values)
pRec.append(prsaRec['p'].values)
if (filt == 'all'):
recCombined.drop_duplicates(inplace=True)
prsaRecCombined.drop_duplicates(inplace=True)
if (Nrec >= Nlim):
m1hRec0, m1b = np.histogram(rec["m1"], bins=mbins)
qhRec0, qb = np.histogram(rec["m2"]/rec["m1"], bins=qbins)
ehRec0, eb = np.histogram(rec["e"], bins=ebins)
lphRec0, lpb = np.histogram(np.ma.log10(rec["p"].values).filled(-999), bins=lpbins)
dhRec0, db = np.histogram(rec["d"], bins=dbins)
maghRec0, magb = np.histogram(rec["appMagMean_r"], bins=magbins)
rhRec0, rb = np.histogram(rec["r2"]/rec["r1"], bins=rbins)
m1hRec[filt] += m1hRec0/Nall*Nmult
qhRec[filt] += qhRec0/Nall*Nmult
ehRec[filt] += ehRec0/Nall*Nmult
lphRec[filt] += lphRec0/Nall*Nmult
dhRec[filt] += dhRec0/Nall*Nmult
maghRec[filt] += maghRec0/Nall*Nmult
rhRec[filt] += rhRec0/Nall*Nmult
#for the mollweide
if (filt == 'all'):
Nrec = len(recCombined.index)
rF = Nrec/Nall
rN = Nrec/Nall*Nmult
raN = Nmult
obN = Nobs/Nall*Nmult
fiN = Nall
fioN = Nobs
firN = Nrec
NrecPrsa = len(prsaRecCombined.index)
NrecPrsa = NrecPrsa/Nall*Nmult
NobsPrsa = NobsPrsa/Nall*Nmult
NallPrsa = NallPrsa/Nall*Nmult
recFrac.append(rF)
recN.append(rN)
rawN.append(raN)
obsN.append(obN)
fileN.append(fiN)
fileObsN.append(fioN)
fileRecN.append(firN)
allNPrsa.append(NallPrsa)
obsNPrsa.append(NobsPrsa)
recNPrsa.append(NrecPrsa)
#print(np.sum(lphRec), np.sum(recN), np.sum(lphRec)/np.sum(recN), np.sum(lphRec0), Nrec, np.sum(lphRec0)/Nrec, np.sum(lphObs), np.sum(obsN), np.sum(lphObs)/np.sum(obsN))
# Concatenating p and ecc lists
eccAll = np.concatenate(eccAll)
eccObs = np.concatenate(eccObs)
eccRec = np.concatenate(eccRec)
pAll = np.concatenate(pAll)
pObs = np.concatenate(pObs)
pRec = np.concatenate(pRec)
# print('Ecc lists:', eccAll, eccObs, eccRec)
# print('P lists:', pAll, pObs, pRec)
# Appending lists with all the p/ecc values to our dataframes
# All dataframe
peccAll['e'] = eccAll
peccAll['p'] = pAll
# Observable dataframe
peccObs['e'] = eccObs
peccObs['p'] = pObs
# Recovered dataframe
peccRec['e'] = eccRec
peccRec['p'] = pRec
# print('Final Dataframes:', peccAll, peccObs, peccRec)
# print(peccRec.columns)
# 3 letter code corresponds to scenario (OC/GC, baseline/colossus, crowding/no crowding)
peccAll.to_csv('./pecc/all-M67BN-ecc-p.csv', header = ['e', 'p'])
peccObs.to_csv('./pecc/obs-M67BN-ecc-p.csv', header = ['e', 'p'])
peccRec.to_csv('./pecc/rec-M67BN-ecc-p.csv', header = ['e', 'p'])
#plot and save the histograms
saveHist(m1hAll, m1hObs, m1hRec, m1b, 'm1 (Msolar)', 'EBLSST_m1hist')
saveHist(qhAll, qhObs, qhRec, qb, 'q (m2/m1)', 'EBLSST_qhist')
saveHist(ehAll, ehObs, ehRec, eb, 'e', 'EBLSST_ehist')
saveHist(lphAll, lphObs, lphRec, lpb, 'log(P [days])', 'EBLSST_lphist')
saveHist(dhAll, dhObs, dhRec, db, 'd (kpc)', 'EBLSST_dhist')
saveHist(maghAll, maghObs, maghRec, magb, 'mag', 'EBLSST_maghist')
saveHist(rhAll, rhObs, rhRec, rb, 'r2/r1', 'EBLSST_rhist')
#make the mollweide
coords = SkyCoord(RA, Dec, unit=(units.degree, units.degree),frame='icrs')
lGal = coords.galactic.l.wrap_at(180.*units.degree).degree
bGal = coords.galactic.b.wrap_at(180.*units.degree).degree
RAwrap = coords.ra.wrap_at(180.*units.degree).degree
Decwrap = coords.dec.wrap_at(180.*units.degree).degree
f, ax = plt.subplots(subplot_kw={'projection': "mollweide"}, figsize=(8,5))
ax.grid(True)
#ax.set_xlabel(r"$l$",fontsize=16)
#ax.set_ylabel(r"$b$",fontsize=16)
#mlw = ax.scatter(lGal.ravel()*np.pi/180., bGal.ravel()*np.pi/180., c=np.log10(np.array(recFrac)*100.), cmap='viridis_r', s = 4)
ax.set_xlabel("RA",fontsize=16)
ax.set_ylabel("Dec",fontsize=16)
mlw = ax.scatter(np.array(RAwrap).ravel()*np.pi/180., np.array(Decwrap).ravel()*np.pi/180., c=np.array(recFrac)*100., cmap='viridis_r', s = 4)
cbar = f.colorbar(mlw, shrink=0.7)
cbar.set_label(r'% recovered')
f.savefig('./plots/' + 'mollweide_pct.pdf',format='pdf', bbox_inches = 'tight')
f, ax = plt.subplots(subplot_kw={'projection': "mollweide"}, figsize=(8,5))
ax.grid(True)
#ax.set_xlabel(r"$l$",fontsize=16)
#ax.set_ylabel(r"$b$",fontsize=16)
#mlw = ax.scatter(lGal.ravel()*np.pi/180., bGal.ravel()*np.pi/180., c=np.log10(np.array(recN)), cmap='viridis_r', s = 4)
ax.set_xlabel("RA",fontsize=16)
ax.set_ylabel("Dec",fontsize=16)
mlw = ax.scatter(np.array(RAwrap).ravel()*np.pi/180., np.array(Decwrap).ravel()*np.pi/180., c=np.log10(np.array(recN)), cmap='viridis_r', s = 4)
cbar = f.colorbar(mlw, shrink=0.7)
cbar.set_label(r'log10(N) recovered')
f.savefig('./plots/' + 'mollweide_N.pdf',format='pdf', bbox_inches = 'tight')
if (doIndividualPlots):
fmass.savefig('./plots/' + 'massPDFall.pdf',format='pdf', bbox_inches = 'tight')
fqrat.savefig('./plots/' + 'qPDFall.pdf',format='pdf', bbox_inches = 'tight')
fecc.savefig('./plots/' + 'eccPDFall.pdf',format='pdf', bbox_inches = 'tight')
flper.savefig('./plots/' + 'lperPDFall.pdf',format='pdf', bbox_inches = 'tight')
fdist.savefig('./plots/' + 'distPDFall.pdf',format='pdf', bbox_inches = 'tight')
fmag.savefig('./plots/' + 'magPDFall.pdf',format='pdf', bbox_inches = 'tight')
frad.savefig('./plots/' + 'radPDFall.pdf',format='pdf', bbox_inches = 'tight')
print("###################")
print("number of binaries in input files (raw, log):",np.sum(fileN), np.log10(np.sum(fileN)))
print("number of binaries in tested with gatspy (raw, log):",np.sum(fileObsN), np.log10(np.sum(fileObsN)))
print("number of binaries in recovered with gatspy (raw, log):",np.sum(fileRecN), np.log10(np.sum(fileRecN)))
print("recovered/observable*100 with gatspy:",np.sum(fileRecN)/np.sum(fileObsN)*100.)
print("###################")
print("total in sample (raw, log):",np.sum(rawN), np.log10(np.sum(rawN)))
print("total observable (raw, log):",np.sum(obsN), np.log10(np.sum(obsN)))
print("total recovered (raw, log):",np.sum(recN), np.log10(np.sum(recN)))
print("recovered/observable*100:",np.sum(recN)/np.sum(obsN)*100.)
print("###################")
print("total in Prsa 15.8<r<19.5 P<1000d sample (raw, log):",np.sum(allNPrsa), np.log10(np.sum(allNPrsa)))
print("total observable in Prsa 15.8<r<19.5 P<1000d sample (raw, log):",np.sum(obsNPrsa), np.log10(np.sum(obsNPrsa)))
print("total recovered in Prsa 15.8<r<19.5 P<1000d sample (raw, log):",np.sum(recNPrsa), np.log10(np.sum(recNPrsa)))
print("Prsa 15.8<r<19.5 P<1000d rec/obs*100:",np.sum(recNPrsa)/np.sum(obsNPrsa)*100.)
| python |
Disclaimer: All content and media belong to original content streaming platforms/owners like Netflix, Disney Hotstar, Amazon Prime, SonyLIV etc. 91mobiles entertainment does not claim any rights to the content and only aggregate the content along with the service providers links.
American version of the British dating reality competition in which ten singles come to stay in a villa for a few weeks and have to couple up with one another. Over the course of those weeks, they face the public vote and might be eliminated from the show. Other islanders join and try to break up the couples. | english |
PSEB Class 10 Suply Result: Punjab School Education Board, PSEB has released the results of Class 10th reappear exam 2022. The compartment exam for the students of Class 10th was conducted by Punjab School Board in the month of April 2022. The result has been declared by PSEB on its official website pseb. ac. in.
Students who appeared in Class 10th Compartment examination may now check their scores by visiting the official website of PSEB i. e. pseb. ac. in. You just need to enter a roll number to check your marks. Here is how to check the scorecard.
Candidates are advised to follow these steps to check their class 10 compartment exam results.
Step 2: On the homepage click on the result tab.
Step 3: A new page will appear, here Click on the link which reads, 'PSEB 10th compartment result 2022'.
Step 4: Enter your roll number and click on 'find results' button.
Step 5: Now PSEB Class 10 Compartment results will appear on the screen.
Step 6: Download your scorecard and take a printout for future reference.
Keep visiting us for more exam related updates. | english |
---
language: swift
exerciseType: 2
---
# --description--
Le funzioni possono avere parametri di ingresso multipli, che vengono scritti tra le parentesi della funzione, separati dalle virgole.
```swift
func saluta(name: String, nuovoUtente: Bool) -> String {
var saluto: String = "Ciao \(name)!"
if (nuovoUtente) {
saluto += " Benvenuto a bordo :)"
}
return saluto
}
// stampa "Ciao Smith! Benvenuto a bordo :)"
print(saluta(name: "Smith", nuovoUtente: true))
```
# --instructions--
Completa il codice in modo da creare una funzione valida chiamata `sommaNumeri` passando il seguente array di numeri `[15, 24, 31, 79]` e `true` per stamparne il risultato
# --seed--
```swift
func sommaNumeri(_ numeri: [Int], _ stampaRisultato: Bool) -> Int {
/* Il metodo reduce viene utilizzato per sommare tutti i numeri, partendo da 0 e utilizzando il segno +
*/
let risultato = numeri.reduce(0, +)
if [/] { print(risultato) }
return risultato
}
let risultato = [/]([/]15, 24, 31, [/][/], [/])
```
# --answers--
- sommaNumeri
- sum
- 79
- ]
- [
- true
- false
- True
- stampaRisultato
- print
- true
# --solutions--
```swift
func sommaNumeri(_ numeri: [Int], _ stampaRisultato: Bool) -> Int {
/* Il metodo reduce viene utilizzato per sommare tutti i numeri, partendo da 0 e utilizzando il segno +
*/
let risultato = numeri.reduce(0, +)
if stampaRisultato { print(risultato) }
return risultato
}
let risultato = sommaNumeri([15, 24, 31, 79], true)
```
# --output--
149
| markdown |
The Forest Advisory Committee (FAC) decided in October 2021 to approve coal mining on non-forest land adjoining a forest, when mining activity extends to both areas, even before a forest clearance is granted; the recent nod has been given for all minerals.
An environment ministry panel has allowed state governments to permit commencement of mining operations for all minerals on non-forest land contiguous with a forest, where both types of terrain are involved, even before the final clearance is accorded, drawing criticism from environmentalists and legal experts.
The Forest Advisory Committee (FAC) decided in October 2021 to approve coal mining on non-forest land adjoining a forest, when mining activity extends to both areas, even before a forest clearance is granted; the recent nod has been given for all minerals.
HT reported on November 20, 2021 that the FAC approved commencement of coal mining on non-forest land but imposed certain conditions. The panel ruled that in order to avoid a “fait accompli” situation, plans for mining in non-forest areas of a coal block will not involve any forest area; no component of mining activity in the non-forest land shall have any dependency in the forest area of the same block. The decision was criticised by environmental experts as they said it was a legal subsidy to the mining sector.
For other minerals too, the FAC has decided to allow mining on contiguous non-forest land if there is a separate mining plan or a separate lease.
“The FAC, after detailed deliberations in the matter observed that in respect of mining leases involving forest as well as non-forest land, working on non-forest land without ensuring the separate mining plan or lease for such non-forest (part) of the lease may create fait accompli situations, which is not desirable in terms of directions contained in the Hon’ble Supreme Court orders,” the Union environment ministry wrote to all state governments and UTs on February 3.
“It is hereby clarified that after obtaining the Stage-I approval, deposition of compensatory levies and environment clearance, the State/UT Government or authorities concerned should prepare a separate Mining Plan or execute a separate mining lease for full or part of non-forest land involved in the mining lease before allowing mining operations in the non-forest land of such mining leases,” the letter said. HT has seen a copy of the letter.
In 2014, a three-judge Supreme Court bench headed by justice RL Lodha said mining companies that invested money in blocks without getting all clearances took the decision at their own risk. Any investment made in anticipation of clearances cannot be justified and such coal blocks cannot be protected if the companies fail to get clearances within the time frame fixed under the law, the bench had said. Environmental experts said commencing of mining on non-forest land would result in expectations that the entire mine will be accorded clearance because of the investment involved.
“Even if they have a separate mining plan but the lease is the same, it will amount to a fait accompli situation. This is because the viability of a project is determined based on the entire capacity or area required. The cost-benefit analysis of a mining project is also based on the entire reserves available. So mining may be limited to the non-forest land in the first few years but the expectation is that a nod will be granted to the entire area, including the forest land involved,” said Ritwick Dutta, environmental lawyer.
“A decision like this can be understood as a case where a regulation by exemption is resulting in reading down the intention of a statute which argues for an assessment-based approval. The viability of most mining or any other large infrastructure projects relies on accessibility to both forest and non-forest land. Initiating work on non-forest land prior to assessments of risks and costs of forest land diversion, can affect the implementation of the project if the assessments result in delayed or no approvals. Therefore, a process which is not based on sound environmental logic is also not in the interest of business,” said Kanchi Kohli, legal researcher at the Centre for Policy Research.
“This move to allow commencement of mining in non-forest land first will save time for the project proponent but it cannot be quantified as to how much time will be saved,” a senior environment ministry official said.
In another development, in order to fast-track forest clearances, the ministry notified the guidelines on Accredited Compensatory Afforestation (ACA) on January 24.
The final guidelines were published on the ministry’s Parivesh website last week. Under ACA, any interested person or entity can develop plantations on non-forest land and trade them with the project proponent that is seeking diversion of forest land for its project.
ACA is a system of proactive afforestation, according to the ministry, where readymade plantations are available.
Until now, the project proponent of any infrastructure project involving diversion of forest land would identify land for compensatory afforestation to compensate the loss of forests. The company would submit details of the land to the environment ministry along with an undertaking to bear the entire cost of afforestation. The afforestation land was transferred and mutated in favour of the state forest department and subsequently notified as protected forest under the Indian Forest Act, 1927. The forest department would take up afforestation on the mutated land against the loss of forests due to clearance granted to the project.
“This practice has been in vogue for the last four decades. Difficulties observed during the intervening period in the implementation of the scheme primarily include delayed fund flow, untimely availability of non-forest land, uncertainty of survival percentage, etc,” said a letter issued by the ministry to all important ministries, including the home ministry, on January 24.
Under the new guidelines, the proponent of any infrastructure project requiring forest land can negotiate financial details with the person or agency holding accredited plantation and enter into an agreement for its sale.
The preconditions for afforestation plots that can be sold include: any non-forest land can be used; mined out and biologically reclaimed non-forest land, ownership of which vests with a state PSU or central PSU may also be used; land considered for raising such afforestation should be properly demarcated and fenced to ensure its protection from various biotic factors; such land should cover an area of minimum ten hectares; afforestation over land of any size situated in the continuity of land declared or notified as forest under any law, protected area, tiger reserve or within a designated or identified tiger or wildlife corridor can be considered; accreditation can be obtained after afforestation of one-hectare area with 0. 4 or more canopy density is available.
Environment ministry officials said no plantation patch has been accredited so far under the new guidelines but once the process starts it will help fast-track forest clearances. | english |
Antonio Guterres’ spokesperson said the situation in the Valley could only be solved with the full respect to human rights.
United Nations Secretary General Antonio Guterres on Wednesday expressed concerns about any potential escalation of tension between India and Pakistan after New Delhi withdrew the special status of Jammu and Kashmir, PTI reported. He urged both the countries to deal with the Kashmir dispute through dialogue.
Dujarric’s statements came after he was asked on whether Guterres plans to mediate between India and Pakistan on Kashmir during the United Nations General Assembly session later this month. Prime Minister Narendra Modi will address the session on September 27, and Pakistan Prime Minister Imran Khan will address after that.
Dujarric quoted the high commissioner for human rights, and said the situation in Kashmir could only be solved with the full respect to human rights. “You know, the position our position on mediation has, as a matter of principle, has always remained the same,” Dujarric said.
The UN chief has maintained that his office will intervene only if both sides ask for it.
The spokesperson said Guterres met Prime Minister Narendra Modi on the sidelines of the G7 Summit in Biarritz, France, and has also spoken to Pakistan’s Foreign Minister Shah Mahmood Qureshi. On Monday, Guterres also met the Permanent Representative of Pakistan to the UN Maleeha Lodhi on her request to discuss the Kashmir dispute.
On Tuesday, a team of Indian diplomats addressed the United Nations Human Rights Council in Geneva to explain New Delhi’s position on Jammu and Kashmir. They had said that Pakistan was trying to polarise the rights body to advance its agenda in South Asia.
Secretary (East), Ministry of External Affairs, Vijay Thakur had said the Pakistan delegation had given a commentary with false allegations and concocted charges against India. “World is aware that this fabricated narrative comes from epicentre of global terrorism, where ring leaders were sheltered for years,” she had said. India stressed about its free media, vibrant civil society and institutional framework that upholds human rights in the country.
Pakistan, which addressed the council before India, said the global body should conduct an international investigation into the situation in Kashmir. Pakistani Foreign Minister Shah Mahmood Qureshi, who led the delegation from Islamabad, said UN rights body must not remain “indifferent” and should not be embarrassed on the world stage by its inaction over the Kashmir dispute.
India’s response at the UNHRC meeting came a day after the UN High Commissioner for Human Rights Michelle Bachelet in her opening remarks called upon India to end the lockdown in Kashmir that was imposed.
On August 5, the Centre had revoked the special status of Jammu and Kashmir under Article 370 of Constitution, and split the state into the Union Territories of Jammu and Kashmir, and Ladakh.
India and Pakistan have witnessed a massive escalation in tension ever since Jammu and Kashmir’s special status was revoked. Pakistan, which has fought three wars with India for Kashmir since Independence, downgraded diplomatic ties and suspended trade.
Last month, Pakistan’s efforts for an international intervention in the Kashmir dispute also led to a rare closed-door meeting of the United Nations Security Council. This was the first time in over 50 years that the UN Security Council had a meeting exclusively to discuss the Kashmir matter, but it ended without any outcome.
Now, follow and debate the day’s most significant stories on Scroll Exchange.
| english |
What’s the Difference Between a Psychopath and a Sociopath? And How Do Both Differ from Narcissists?
Why Was Frederick Douglass’s Marriage to Helen Pitts Controversial?
Why Are There Only 28 Days in February?
Why Do We Drop a Ball on New Year’s Eve?
The divisions of the skull as suggested by phrenologists such as Johann Kaspar Spurzheim.
Wm. S. Pendleton/Library of Congress, Washington, D.C. (neg. no. LC-USZC4-4556)
A phrenology chart showing the suggested divisions of the skull.
in these related Britannica articles:
| english |
New Delhi: Day after 73 people died in a massive dust storm in his state and he faced a lot of flak from the opposition for not being present in Uttar Pradesh in this moment of crisis, Chief Minister Yogi Adityanath currently on an election campaign in Karnataka, is rushing back on Friday night to visit the storm-ravaged Agra.
Karnataka CM Siddaramaiah on Thursday took a potshot at Adityanath saying he felt sorry for UP whose chief minister was busy campaigning in Karnataka instead of standing by his state.
"I am sorry your CM is needed here in Karnataka," Siddaramaiah had tweeted. "I am sure he will return soon & attend to his work there. "
Adityanath was earlier scheduled to campaign in poll-bound Karnataka till Saturday noon. The state is due for elections on May 12 and Adityanath was being seen as a star campaigner for BJP who continued to campaign in the state on Friday, a day after the dust storm in UP.
Speaking to News18 from Karnataka, Yogi Adityanath said on Thursday, “Congress has had a tradition of breaking and dividing. From the partition of the country to the caste and religion based politics that we see today, all of it is a legacy of the Congress. Both Rahul Gandhi and Siddaramaiah are following the same Congress tradition. The BJP believes in Prime Minister Narendra Modi’s ‘Ek Bharat, Shreshta Bharat’ slogan. We also want a political unification of the country and from that point of view, the Karnataka election is very important to us. ”Soon, former UP CM Akhilesh Yadav, too, joined Siddaramaiah, saying Yogi should rather stay in Karnataka forever.
“CM should immediately return to the state and leave Karnataka campaign. People have chosen him to address their woes and not for politics of Karnataka. If even in such conditions he does not come back, then he should build his mutt there forever,” SP chief tweeted.
The chief minister will arrive in Agra on Friday night and visit the calamity-hit areas on Saturday morning, Principal Secretary Information Avanish Awasthi said.
Yogi will later leave for Kanpur to monitor the relief work there and in nearby districts.
A high-intensity storm ravaged Uttar Pradesh and Rajasthan on Wednesday night, leaving 73 people dead and 91 injured in UP and a total of 124 people dead across several states in north India. Agra district was the worst hit, accounting for 43 deaths and injuries to 51 others. | english |
As part of Mission Sagar, Indian Naval Ship Kesari entered Port of Moroni in Comoros on 31 May 2020. The Government of India in these difficult times is providing assistance to Friendly Foreign Countries in dealing with the COVID-19 Pandemic and towards the same INS Kesari is carrying a consignment of COVID related essential medicines for the people of Comoros.
In addition, a 14-member specialist medical team comprising Indian Navy doctors and paramedics is also embarked onboard this ship to work alongside their counterparts in Comoros, and together render assistance for Covid-19 and dengue fever. The medical team comprises specialists including Medical and Community specialists, and a Pathologist.
An official ceremony for handing over the medicines from the Government of India to Government of Comoros was held on 31 May 2020. The ceremony was attended by H.E. Mrs. Loub Yacout Zaidou, Minister of Health, Solidarity, Social Protection and Gender Promotion of Comoros. The Indian side was represented by Commander Mukesh Tayal, Commanding Officer Indian Naval Ship Kesari, and Hon. Consul of India in Comoros Mr. Saguir Sam.
Comoros and India have always enjoyed close and friendly relations and have similarities of view on regional and global issues. The assistance to Comoros is part of the Government of India outreach amidst the ongoing COVID-19 pandemic and for dengue fever. ‘Mission Sagar’, builds on the excellent relations existing between the two countries to battle the COVID-19 pandemic and its resultant difficulties. The deployment resonates the vision of our Prime Minister for ‘Security and Growth for All in the Region (SAGAR)’ and highlights the importance accorded by India to relations with the countries in the IOR. The operation is being progressed in close coordination with the Ministries of Defence and External Affairs, and other agencies of the Government of India.
| english |
<reponame>daxianji007/WindowsAppSDK-Samples
# System Font Collection (Typographic)
A font collection is an object that represents a set of fonts grouped into font families. The *system font collection*
is a special font collection that contains all the fonts installed on the computer, including fonts installed by the
current user.
You can use the system font collection to enumerate available font families, as in the list at right. The system font
collection is also the default font collections used by text layout and font fallback to mach font family names and
other properties to available fonts.
# Typographic Font Family Model
Fonts in a font collection are grouped into families according to *the font family model,* which is specified as
a parameter to the `GetSystemFontCollection` factory method. The two font family models are *typographic* and
*weight-stretch-style*. This system font collection uses the typographic model.
In the typographic font family model, fonts within a family can be differentiated by any number of properties. These
are called *axes of variation,* with each axis identified by a four-character OpenType tag. The `DWRITE_FONT_AXIS_VALUE`
structure encapsulates an axis tag and associated value. To specify the font you want in this model, you specified the
desired family name and an array of `DWRITE_FONT_AXIS_VALUE` structures. The font family name in this case should be the
*typographic family name* of the font.
# Variable Fonts
The typographic font family model is closely associated with variable fonts introduced in OpenType 1.8, although it works
with static fonts as well. One of the advantages of the typographic model is that you can select arbitrary instances of
variable fonts. For example, if a variable font supports a continuous range of weights, you can select any weight in that
range by specifying the weight axis value you want. If you use the weight-stretch-style model, DirectWrite selects the
nearest *named* instance to the specified weight, stretch, and style.
| markdown |
Eminent poets, musicians, actors, singers and artists from across the world celebrated the 52nd Earth Day on April 22, 2022, by reading 'Earth Anthem' penned by Indian poet-diplomat Abhay K.
Abhay K. wrote the anthem in 2008 inspired by the blue marble image of the earth, taken by the crew of Apollo 17, and the Indian philosophy of 'Vasudhaiva Kutumbakam'. Since then it has travelled a long distance, having so far been translated into over 150 world languages and used worldwide to celebrate Earth Day. In previous years, it has been performed by national philharmonic orchestras in Brasilia and musicians of Amsterdam Conservatorium.
The Earth Anthem was put to music initially by Sapan Ghimire in Nepal and later by renowned Indian violin player and music composer Dr L Subramaniam and was sung by veteran singer Kavita Krishnamurti.
Marking Earth Day on April 22, several eminent personalities from around the world, including actress Manisha Koirala, Miss India 1991 Ritu Vaidya, Hollywood actor Robert Lin, Member of parliament, poet, and TV commentator Ivone Soares from Mozambique, Bangladesh's High Commissioner Shumona Iqbal from Brunei, poet Ardra Manasi and actor JB Alexander from New York, poet and editor Melanie Barbato from Germany, academician Amrita Ghosh from Sweden, poet Pina Picolo from Italy, poets Sunil Sharma and Beena Vijayalakshmy from Toronto, poet Hideko Sueoka from Tokyo, Navya Lahoti from Mumbai, Kandarp Mehta from Barcelona, poets Rasata Rafaravavitafika, Tsiky Rabenimanga, Harinirina Rakouth from Madagascar, translator Selmina Rumawak from Indonesia, noted journalist Deepak Parvatiyar from New Delhi, poet Jose Luiz Ochoa from Venezuela, poet Irma Nimbe from Mexico, poet Bernard Pearson from UK, Vidya Singh from Chennai, poet Yamini Dand Shah from Kucch, Gujarat, novelist Abdullah Khan and poet Pankhuri Sinha from Bihar, poet Immanuel Mifsud from Malta, Leticia Gomes from Brazil, poet Anupama Raju from Kerala, among others. Students of the Delhi Metropolitan Education, Noida recited 'Earth Anthem' in several languages one after another.
Earth Anthem is a song that eulogizes the earth, its beauty, and its biodiversity. It is a song that can be sung by anybody, anywhere, any day to pay tribute to planet Earth. It is used across the world to celebrate Earth Day, World Biodiversity Day, and World Environment Day. It was played at the United Nations to celebrate the 50th Anniversary of Earth Day in 2020.
Speaking about the anthem, Abhay K. said, "'Earth Anthem' calls for unity among all the species, all the people and nations on Earth to tackle together the triple crisis of climate change, biodiversity loss and environmental pollution. It also calls for rising over all our differences to preserve our beautiful planet, our only home in the vast cosmos. "
Amendments in EIA notification: Can the govt really avoid public notice?
He added that the translation of 'Earth Anthem' in so many languages and its growing popularity shows the need for a common anthem for our planet which can provide hope, inspiration and solidarity to people amid these trying times.
(Only the headline and picture of this report may have been reworked by the Business Standard staff; the rest of the content is auto-generated from a syndicated feed. ) | english |
package shutdownmanager
import (
"context"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/prometheus/common/expfmt"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
ctrl "sigs.k8s.io/controller-runtime"
)
const (
ShutdownEndpoint string = "/shutdown"
DrainEndpoint string = "/drain"
HealthEndpoint string = "/healthz"
)
const (
envoyPrometheusEndpoint string = "/stats/prometheus"
envoyShutdownEndpoint string = "/healthcheck/fail"
prometheusStat string = "envoy_http_downstream_cx_active"
adminListenerPrefix string = "admin"
)
var (
logger = ctrl.Log.WithName("shutdownmanager")
)
// Manager holds configuration to run the shutdown manager
type Manager struct {
// HTTPServePort defines what port the shutdown-manager listens on
HTTPServePort int
// ShutdownReadyFile is the default file path used in the /shutdown endpoint
ShutdownReadyFile string
// ShutdownReadyCheckInterval is the polling interval for the file used in the /shutdown endpoint
ShutdownReadyCheckInterval time.Duration
// CheckDrainInterval defines time delay between polling Envoy for open connections
CheckDrainInterval time.Duration
// CheckDrainDelay defines time to wait before polling Envoy for open connections
CheckDrainDelay time.Duration
// StartDrainDelay defines time to wait before draining Envoy connections
StartDrainDelay time.Duration
// EnvoyAdminAddress specifies envoy's admin url
EnvoyAdminAddress string
// MinOpenConnections is the number of open connections allowed before performing envoy shutdown
MinOpenConnections int
}
func (mgr *Manager) envoyPrometheusURL() string {
return strings.Join([]string{mgr.EnvoyAdminAddress, envoyPrometheusEndpoint}, "")
}
func (mgr *Manager) envoyShutdownURL() string {
return strings.Join([]string{mgr.EnvoyAdminAddress, envoyShutdownEndpoint}, "")
}
// Starts the shutdown manager
func (mgr *Manager) Start(ctx context.Context) error {
logger.Info("started envoy shutdown manager")
defer logger.Info("stopped")
mux := http.NewServeMux()
srv := http.Server{Addr: fmt.Sprintf(":%d", mgr.HTTPServePort), Handler: mux}
errCh := make(chan error)
mux.HandleFunc(HealthEndpoint, mgr.healthzHandler)
mux.HandleFunc(ShutdownEndpoint, mgr.shutdownHandler)
mux.HandleFunc(DrainEndpoint, mgr.drainHandler)
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errCh <- err
}
}()
<-ctx.Done()
srv.Shutdown(ctx)
select {
case <-ctx.Done():
// Shutdown the server when the context is canceled
srv.Shutdown(ctx)
case err := <-errCh:
return err
}
return nil
}
// healthzHandler handles the /healthz endpoint which is used for the shutdown-manager's liveness probe.
func (s *Manager) healthzHandler(w http.ResponseWriter, r *http.Request) {
l := logger.WithValues("context", "healthzHandler")
if _, err := w.Write([]byte("OK")); err != nil {
l.Error(err, "healthcheck failed")
}
}
// shutdownHandler handles the /shutdown endpoint which is used by Envoy to determine if it can
// terminate safely. The endpoint blocks until the expected file exists in the filesystem.
// This endpoint is called from Envoy's container preStop hook in order to delay shutdown of the server
// until it is safe to do so or the timeout is reached.
func (mgr *Manager) shutdownHandler(w http.ResponseWriter, r *http.Request) {
l := logger.WithValues("context", "waitForDrainHandler")
ctx := r.Context()
for {
_, err := os.Stat(mgr.ShutdownReadyFile)
if err == nil {
l.Info(fmt.Sprintf("file %s exists, sending HTTP response", mgr.ShutdownReadyFile))
if _, err := w.Write([]byte("OK")); err != nil {
l.Error(err, "error sending HTTP response")
}
return
} else if os.IsNotExist(err) {
l.Info(fmt.Sprintf("file %s does not exist, recheck in %v", mgr.ShutdownReadyFile, mgr.ShutdownReadyCheckInterval))
} else {
l.Error(err, "error checking for file")
}
select {
case <-time.After(mgr.ShutdownReadyCheckInterval):
case <-ctx.Done():
l.Info("client request cancelled")
return
}
}
}
// drainHandler is called from the shutdown-manager container preStop hook and will:
// * Call Envoy container admin api to start graceful connection draining of the listeners
// * Block until the prometheus metrics returned by Envoy container admin api return the
// desired min number of connection (usually 0). The admin listener connections are not
// computed towards this value.
func (mgr *Manager) drainHandler(w http.ResponseWriter, r *http.Request) {
l := logger.WithValues("context", "DrainListeners")
ctx := r.Context()
l.Info(fmt.Sprintf("waiting %s before draining connections", mgr.StartDrainDelay))
time.Sleep(mgr.StartDrainDelay)
// Send shutdown signal to Envoy to start draining connections
l.Info("start draining envoy listeners")
// Retry any failures to shutdownEnvoy() in a Backoff time window
err := retry.OnError(
wait.Backoff{Steps: 4, Duration: 200 * time.Millisecond, Factor: 5.0, Jitter: 0.1},
func(err error) bool { return true },
func() error { l.Info("signaling start drain"); return mgr.shutdownEnvoy() },
)
if err != nil {
l.Error(err, "error signaling envoy to start draining listeners after 4 attempts")
}
l.Info(fmt.Sprintf("waiting %s before polling for draining connections", mgr.CheckDrainDelay))
time.Sleep(mgr.CheckDrainDelay)
for {
openConnections, err := mgr.getOpenConnections()
if err == nil {
if openConnections <= mgr.MinOpenConnections {
l.Info("min number of open connections found, shutting down", "open_connections", openConnections, "min_connections", mgr.MinOpenConnections)
file, err := os.Create(mgr.ShutdownReadyFile)
if err != nil {
l.Error(err, "")
}
defer file.Close()
if _, err := w.Write([]byte("OK")); err != nil {
l.Error(err, "error sending HTTP response")
}
return
}
l.Info("polled open connections", "open_connections", openConnections, "min_connections", mgr.MinOpenConnections)
} else {
l.Error(err, "")
}
select {
case <-time.After(mgr.CheckDrainInterval):
case <-ctx.Done():
l.Info("request cancelled")
w.WriteHeader(499)
return
}
}
}
// shutdownEnvoy sends a POST request to /healthcheck/fail to start draining listeners
func (mgr *Manager) shutdownEnvoy() error {
resp, err := http.Post(mgr.envoyShutdownURL(), "", nil)
if err != nil {
return fmt.Errorf("creating POST request to %s failed: %s", mgr.envoyShutdownURL(), err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("POST for %q returned HTTP status %s", mgr.envoyShutdownURL(), resp.Status)
}
return nil
}
// getOpenConnections parses a http request to a prometheus endpoint returning the sum of values found
func (mgr *Manager) getOpenConnections() (int, error) {
// Make request to Envoy Prometheus endpoint
resp, err := http.Get(mgr.envoyPrometheusURL())
if err != nil {
return -1, fmt.Errorf("creating GET request to %s failed: %s", mgr.envoyPrometheusURL(), err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return -1, fmt.Errorf("GET for %q returned HTTP status %s", mgr.envoyPrometheusURL(), resp.Status)
}
// Parse Prometheus listener stats for open connections
return parseOpenConnections(resp.Body)
}
// parseOpenConnections returns the sum of open connections from a Prometheus HTTP request
func parseOpenConnections(stats io.Reader) (int, error) {
var parser expfmt.TextParser
openConnections := 0
if stats == nil {
return -1, fmt.Errorf("stats input was nil")
}
// Parse Prometheus http response
metricFamilies, err := parser.TextToMetricFamilies(stats)
if err != nil {
return -1, fmt.Errorf("parsing Prometheus text format failed: %v", err)
}
// Validate stat exists in output
if _, ok := metricFamilies[prometheusStat]; !ok {
return -1, fmt.Errorf("error finding Prometheus stat %q in the request result", prometheusStat)
}
// Look up open connections value
for _, metrics := range metricFamilies[prometheusStat].Metric {
for _, lp := range metrics.Label {
if lp.GetValue() != adminListenerPrefix {
openConnections += int(metrics.Gauge.GetValue())
}
}
}
return openConnections, nil
}
| go |
The federal agency has announced that the H1-B petition filing for the next fiscal year will begin on March 9. And, the lottery results would be notified by March 31. Just a day after Biden administration publicity reported the continuance on the traditional lottery system, a notification for H1B schedule was released by the US Citizenship and Immigration Services (USCIS).
The window for H1B FISCAL YEAR 2022 registration process will commence between March 9 and end by March 25. The USCIS also announced that once it receives a maximum quota of registration by March 25, it will then start the lottery process by March 31. Therefore, the successful applicants would be able to join their new jobs in the US on October 1, that is when the American fiscal year starts.
A maximum of 65K HIB visas and 20K to foreign students can be issued by USCIS per annum. Initially, Trump administration was planning to implement a new skill-based system in place of the traditional lottery system. This change was delayed by the new Biden administration and instead, have gone ahead with releasing the notification for the H1B registration process for fiscal year 2022. | english |
[{"namaKab":"DOGIYAI","originalFilename":"FOTO YENI GOO.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288828,"noUrut":1,"nama":"<NAME>, SE","stringJenisKelamin":"Laki-Laki"},{"namaKab":"DOGIYAI","originalFilename":"YANUARIUS TIBAKOTO646.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288899,"noUrut":2,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"NABIRE","originalFilename":"FOTO YOSEPINA AUWE.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288890,"noUrut":3,"nama":"<NAME>","stringJenisKelamin":"Perempuan"},{"namaKab":"DOGIYAI","originalFilename":"YOSIAS PEUKI.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288907,"noUrut":4,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"DOGIYAI","originalFilename":"FOTO.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288822,"noUrut":5,"nama":"<NAME>","stringJenisKelamin":"Perempuan"},{"namaKab":"DOGIYAI","originalFilename":"FOTO ISAYAS IYAI.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288866,"noUrut":6,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"DOGIYAI","originalFilename":"BB2.pdf","namaPartai":"Partai Gerakan Perubahan Indonesia","id":289004,"noUrut":7,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"DOGIYAI","originalFilename":"1363 - Copy (6).jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288852,"noUrut":8,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"DOGIYAI","originalFilename":"FOTO SALOMINCE WAINE.jpg","namaPartai":"Partai Gerakan Perubahan Indonesia","id":288991,"noUrut":9,"nama":"<NAME>","stringJenisKelamin":"Perempuan"}] | json |
Farmers on Monday forced the suspension of trading at Lasalgaon, India’s largest wholesale market for onions located in Maharashtra’s Nashik district, following a crash in prices. The president of the Maharashtra State Onion Growers’ Association, Bharat Dighole, has threatened the stoppage of auctions in other markets as well.
Why have onion prices crashed?
First, some background.
Farmers grow three crops in the bulk: kharif (transplanted in June-July and harvested in September-October), late-kharif (transplanted in September-October and harvested in January-February) and rabi (transplanted in December-January and harvested in March-April). The harvested crop isn’t marketed in one go; farmers usually sell in tranches, ensuring no price collapse from a bunching of arrivals.
The kharif onions are marketed right up to February and the late-kharif till May-June. Both kharif and late-kharif onions contain high moisture, which allows them to be stored for a maximum of four months. This is unlike the rabi onions, which, grown during the winter-spring months, have low moisture content and can be stored for at least six months. It is the rabi crop that feeds the market through the summer and monsoon months, till October.
The current price collapse has primarily to do with a sudden rise in temperatures from around the second week of February. Onions containing high moisture are prone to quality deterioration from heat shock, with the abrupt drying-up leading to shrivelling of the bulbs.
“Normally, farmers would have been selling only the kharif crop now. But the extreme heat this time has forced them to offload even the late-kharif onions, which can no longer be stored. Since both kharif and late-kharif onions are arriving at the same time, prices have fallen,” said Suresh Deshmukh, a commission agent who operates from the Dindori market, which is about 50 km from Lasalgaon.
How much have prices fallen?
Till February 9, onion was fetching Rs 1,000-1,100 per quintal at Lasalgaon, a price that farmers claim is just above break-even. Prices dropped below Rs 1,000 on February 10 and further to Rs 800/quintal by February 14. They have continued to slide since with the last average traded price, before Monday’s forced shutdown, at Rs 500-550 levels. “Every degree rise in the mercury has resulted in prices tumbling,” added Deshmukh.
Is there any other reason for the drop in prices?
Maharashtra accounts for about 40 per cent of India’s annual onion production of 25-26 million tonnes (mt), out of which 1. 5-1. 6 mt tonnes is exported. Besides Maharashtra, Madhya Pradesh (16-17 per cent share) Karnataka (9-10 per cent), Gujarat (6-7 per cent), Rajasthan and Bihar (5-6 per cent each) are major producers.
Improved water availability from good monsoon rains this time has induced farmers in MP, Rajasthan, Karnataka and Gujarat to plant onions over a larger area. The influx of the bulb from all these states, together with the forced offloading of the late-kharif crop, triggered the price collapse.
Can the government help?
Dighole has demanded that the government fix a floor price of Rs 1,000/quintal and not allow any purchase to happen below that rate. Further, it should direct the National Agricultural Cooperative Marketing Federation of India Ltd (Nafed) to start procuring.
This comes amid social media flooding with stories of farmers being forced to make distress sales. One that made headlines was of Tukaram Chavan, a grower from Borgaon village in Solapur district’s Barshi taluka. He received a cheque of Rs 2 after the deduction of all expenses towards the sale of his 500-quintal produce at the Solapur wholesale market. This caught the attention of many, with former Maharashtra Deputy Chief Minister Ajit Pawar and other Opposition leaders seeking government intervention.
On Saturday, Nafed issued a statement that it would open procurement centres in Nashik district this week. “Farmers are requested to bring their good quality and dried stock to avail of better rates at these centres. Payment will be made online,” it said, adding that procurement of the rabi onions would begin from April this time.
How effective will these measures be?
As already pointed out, nothing much can be done with the late-kharif onions, which cannot be stored for long. Any effective government procurement is possible only with the rabi crop, which also accounts for roughly 70 per cent of the country’s total annual production.
This crop looks to be in good condition as of now, and farmers have planted 20 per cent more area compared with last year. The buffer stock to be created from Nafed’s procurement of rabi onions should ensure no tears for either farmers or consumers in the months ahead. | english |
A 20-year-old cancer patient allegedly committed suicide by hanging himself at the King Edward Memorial (KEM) Hospital here, police said on Thursday.
The incident took place on Wednesday night in a ward of the civic-run hospital where the man hanged himself from a window grill by using a cloth, a police official said.
The victim, a resident of Chembur area in Mumbai, was battling cancer and was admitted to the hospital on June 23.
His coronavirus test report came out negative on July 2, the official said. | english |
Odell Beckham Jr. hit the field in style ahead of the biggest game of his life, the NFL Super Bowl LVI. Los Angeles Rams wide-receiver OBJ teamed up with custom footwear legend and artist 'The Shoe Surgeon' to wear the most expensive cleats ever to be worn in NFL history.
The OBJ pulled out all the stops for his first Super Bowl and made sure he got all the attention even before Sunday's game coin-toss. Thanks to his custom cleats worth a staggering $200k. The encrusted diamonds and gold made sure a six-figure price tag for the cleats.
The cleats were made by Dominic Ciambrone, who is famously known as "The Shoe Surgeon" in Los Angeles.
Who is 'The Shoe Surgeon' behind Odell Beckham Jr. 's $200K diamond cleats?
Dominic Ciambrone, better known as the "Shoe Surgeon," is the CEO and founder of the "Shoe Surgeon" brand. He is a designer, an innovator, and a creative artist specializing in sneaker designing, customization, and shoemaking.
He has accumulated over 1 million Instagram followers and has worked for some very famous personalities, who are all sneakerheads, including Drake, Justin Bieber, LeBron James. He has also collaborated with Pizza Hut, Jack Daniel's, and Frito-Lay's Ruffles brand.
Born in California on April 26, 1986, the custom footwear designer rose to fame due to his passion for shoes and became a pioneer and leader in the sneaker industry.
He is a self-taught cobbler responsible for some of the most genius, most-expensive customs in demand. Ciambrone started out in high school customizing a pair of AF1 all whites into camouflage.
He started doing pro-bono paint jobs on sneakers, and the one that got him his early fame was the laser-etched design of the all-white vans, which he used Tandy leather on. Soon he climbed the ladder and made shoes for DJ Khaled, Will. I. Am, and others.
He was also the mastermind behind "Misplaces Checks," a premium Nike Air Force 1 iteration. He also lent his abilities on the YEEZY Boost. He also made the famous Nike LeBron 15 sneakers valued at $100k and was gifted to LeBron by The Shoe Surgeon in 2018.
He recently started teaching and launched Shoe Surgeon Shoe School. Ciambrone runs a creative collective of Surgeon Studios in Los Angeles.
Ciambrone told People magazine in an interview:
"It's not about making the most expensive cleats. . . Odell's not only a top player, but he's a big personality and he likes fashion and he likes to stand out and that's what I like. So it just kind of all came together. "
Royal blue and yellow pythons come together to embrace the classic colorways of the Rams. Shoes for Odell Beckham Jr. featured 1494 white diamonds, individually rounded and with a total weight of 25 carats from Jason of Beverly Hills. All of these diamonds have a flawless D color clarity. Other than diamonds, the cleats also feature 14 carats of yellow gold at 150 grams.
It took a 100 plus hours of labor to construct the cleats for Odell Beckham Jr. Ciambrone told People:
"When they won the last game, I texted them right away. I was like, 'Are you ready for the golden diamond? ' And he was just hyped and was like, 'Yep, you, me, and Jason of Beverly Hills,' who makes the diamond rings for a lot of the teams and the NFL rings last year. So it was just cool that the moment came like this. "
Dominic was asked by TMZ to make a prediction for Sunday's game, and he simply couldn't pick against his friends:
"You already know that answer, man. The Rams are gonna win. "
"I'm not into sports like that, but if my friends win, it's a win for me. "
Odell Beckham Jr. wasn't the only one to tap Ciambrone for the Super Bowl shoes, his teammates Jalen Ramsey, Von Miller, and Cooper Kupp also all wore Ciambrone's creations. | english |
"""Test motif.features.bitteli
"""
import unittest
import numpy as np
from motif.feature_extractors import bitteli
def array_equal(array1, array2):
return np.all(np.isclose(array1, array2, atol=1e-7))
class TestBitteliFeatures(unittest.TestCase):
def setUp(self):
self.ftr = bitteli.BitteliFeatures()
def test_ref_hz(self):
expected = 55.0
actual = self.ftr.ref_hz
self.assertEqual(expected, actual)
def test_poly_degree(self):
expected = 5
actual = self.ftr.poly_degree
self.assertEqual(expected, actual)
def test_min_freq(self):
expected = 3
actual = self.ftr.min_freq
self.assertEqual(expected, actual)
def test_max_freq(self):
expected = 30
actual = self.ftr.max_freq
self.assertEqual(expected, actual)
def test_freq_step(self):
expected = 0.1
actual = self.ftr.freq_step
self.assertEqual(expected, actual)
def test_vibrato_threshold(self):
expected = 0.25
actual = self.ftr.vibrato_threshold
self.assertEqual(expected, actual)
def test_get_feature_vector(self):
times = np.linspace(0, 1, 2000)
freqs_hz = 440.0 * np.ones((2000, ))
salience = 0.5 * np.ones((2000, ))
sample_rate = 2000
actual = self.ftr.get_feature_vector(
times, freqs_hz, salience, sample_rate
)
expected = np.array([
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
3600.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0
])
self.assertTrue(array_equal(expected, actual))
self.assertEqual(len(actual), len(self.ftr.feature_names))
def test_get_feature_names(self):
expected = [
'vibrato rate',
'vibrato extent',
'vibrato coverage',
'vibrato coverage - beginning',
'vibrato coverage - middle',
'vibrato coverage - end',
'0th polynomial coeff - freq',
'1st polynomial coeff - freq',
'2nd polynomial coeff - freq',
'3rd polynomial coeff - freq',
'4th polynomial coeff - freq',
'5th polynomial coeff - freq',
'polynomial fit residual - freq',
'overall model fit residual - freq',
'0th polynomial coeff - salience',
'1st polynomial coeff - salience',
'2nd polynomial coeff - salience',
'3rd polynomial coeff - salience',
'4th polynomial coeff - salience',
'5th polynomial coeff - salience',
'polynomial fit residual - salience',
'duration',
'pitch stddev (cents)',
'pitch range (cents)',
'pitch average variation',
'salience stdev',
'salience range',
'salience average variation'
]
actual = self.ftr.feature_names
self.assertEqual(expected, actual)
def test_get_id(self):
expected = 'bitteli'
actual = self.ftr.get_id()
self.assertEqual(expected, actual)
| python |
German luxury car manufacturer, Mercedes-Benz, has taken the wraps off its newest electric sport utility vehicle. The all-new Mercedes-Benz EQS electric SUV has been officially revealed and it’s now the flagship EV in the company’s global portfolio. The EQS electric SUV is based on Mercedes-Benz’s dedicated electric vehicle architecture (EVA) platform that also underpins the EQS and the EQE sedans. The new Mercedes-Benz EQS electric SUV will rival the likes of the BMW iX, Audi e-tron, Jaguar I-PACE, etc.
In terms of design, the Mercedes-Benz EQS SUV has familiar Mercedes-EQ traits and even borrows styling elements from the EQS luxury sedan. At the front, it gets a blacked-out grille that’s a closed unit, flanked by angular LED headlamps. The headlamps are connected by a horizontal LED light bar. It has a sloping silhouette, gets multi-spoke alloy wheels, flush door handles, and an optional panoramic sunroof.
At the rear, the EQS electric SUV gets LED taillights that are connected by an LED strip. It measures 5,125 mm in length, 1,959 mm in width and 1,718 mm in height. The wheelbase stands at 3,210 mm, the same as the EQS sedan. On the inside, the EQS SUV gets Mercedes-Benz’s MBUX Hyperscreen with three large displays.
There is a 12.3-inch instrument cluster, a 17.7-inch central infotainment unit, and a 12.3-inch front passenger display. Moreover, this electric SUV can seat up to seven passengers. Talking about the powertrain, the EQS SUV is offered in three different versions, EQS 450+, EQS 450 4Matic, and EQS 580 4Matic. The base EQS 450+ comes with rear-wheel-drive and develops 355 hp and 568 Nm. It is claimed to offer a range of 536 km – 660 km per charge.
The EQS 450 4Matic gets an all-wheel-drive layout and churns out 355 hp of power along with 800 Nm of torque. It is claimed to offer a driving range of 507 km – 613 km on a full charge. Finally, the top-spec EQS 580 4Matic version develops 536 hp of power and a whopping 858 Nm of peak torque. It comes with an all-wheel-drive set-up and offers a range of 507 km – 613 km on the WLTP cycle. The EQS electric SUV is expected to be launched in India next year.
Stay tuned with Express Drives for more updates and also, do subscribe to our YouTube channel for the latest auto news and reviews.
| english |
Madam, a total of five Sindhughosh class submarines have undergone modernization in Russia. One Sindhughosh class submarine is currently undergoing Medium Refit-cum-Upgradation in Russia. The modernization, which began in September, 2010, is progressing as per schedule. Another submarine is undergoing modernization in India partially with Russian assistance.
This information was given by Defence Minister Shri AK Antony in a written reply to ShrimatiShrutiChoudhary in Lok Sabha today.
| english |
When the hat-toting soul of Joe Gardner (Jamie Foxx) accidentally tumbles into the ‘Great Before’, his surrounding worlds shift dramatically, not just in look but energy too. The human world’s continuous bustle of traffic and construction transitions into a swishing swell of illuminated blues and purples. The differences between these two worlds are remarkable.
Although Soul, which released on Christmas on Disney+ Hotstar Premium, is spearheaded by co-directors Peter Docter and Kemp Powers, it is the work of Bobby Podesta, Jude Brownbill and MontaQue Ruffin, some of the film’s animators, that sells the story home.
It is not just the counsellors’ physical formation but also the vitality they give off as sentient beings which mattered. “We also wanted these characters to have an energy as if they were drawing it from the ground. And inside this line, there is a membrane that appears or disappears when a limb crosses it. So there was a lot of complicated stuff that couldn’t be done just by hand. It had to be made into a rig that not just one animator could use,” Brownbill adds.
Ruffin came into Soul eager to play in not just one world but two. He commends the sense of unity at Pixar in times of uncertainty as this fuels better storytelling.
‘ Soul’is streaming on Disney+ Hotstar Premium. | english |
Wriuen Answers
THE MINISTER OF STATE IN THE MINISTRY OF HOME AFFAIRS (SHRI VIDYA CHARAN SHULKA) : (a) and (b). The subject of Centre-State relations is being currently debated in various forums and also by political parties. While there has been a general demand for a review of Centre-State relations, Government's attention has not been drawn to any specific amendments for altering the scheme of Centre-State relations envisaged in the Constitution. The Central Government have not received any formal communication from the State Governments in this behalf.
(c) The question of Centre-State relations came up for consideration at the last meeting of the Standing Committee of the National Integration Council. The Prime Minister indicated at the meeting that the question I could be discussed by the Committee on the basis of some working papers. It was also indicated that the Government were awaiting the report of the Administrative Reforms Commission on Centre State Relations. The Commission have been requested to expedite their report.
Female Education in India
9104. SHRI D. N. PATODIA : Will the Minister of EDUCATION AND YOUTH SERVICES be pleased to state :
(a) the percentage of female education with Central Assistance in different States in the country towards the beginning of the Third Five Year Plan particularly for Rajasthan, U.P., Punjab, Haryana and Gujarat ;
(b) how the percentage has grown during the Third Plan period;
(c) whether the progress made in Rajasthan is satisfactory; and
(d) if not, the steps the Central Government propose to take to improve the
situation ?
THE MINISTER OF EDUCATION AND YOUTH SERVICES (DR. V. K. R. V. RAO): (a) and (b). In the Second Plan there was a scheme under which Central assistance of 75% of expenditure involved for promotion of girls education was given. During the Third Plan this seheme was transferred to the State Sector. There are no separate figures of progress in girls education made out of the Central assistance. However, the progress in enrolment made in
this sphere in Rajasthan, U. P., Punjab, Haryana and Gujarat at the beginning and end of the third plan is indicated in the statement laid on the Table of the House. [Placed in Library. See No. LT-1080/69].
(c) Rajasthan, like other States, has been making progress.
(d) This subject is the concern of the State Governments and they are being continuously urged to fulfill the requirement of Article 45 of the Constitution as early as possible.
Wrimen Answers
Bridge Across the Rann for National Highway No. 8A
9105. SHRI SRIRAJ MEGHRAJJI DHRANGADHRA : Will the Minister of SHIPPING AND TRANSPORT be pleased to state :
(a) whether the bridge accoss the Rann for National Highway No. 8A was scheduled to be opened in January, 1969;
(b) if so, whether the work has been completed;
(c) whether it is a fact that the approaches are still unfinished; and
(d) if so, the details of various factors contributing to the delay in completion of the work ?
THE DEPUTY MINISTER IN THE DEPARTMENT OF PARLIAMENTARY AFFAIRS, AND IN THE MINISTRY OF SHIPPING AND TRANSPORT (SHRI IQBAL SINGH): (a) No such date was fixed for formal opening of the bridge.
(b) Yes, Sir. The work on the bridge proper has been completed.
(c) and (d). The approaches to the bridge had already been made traffic-worthy and the same opened to traffic since the 3rd April, 1969. The only items of work still remaining to be done on the approaches are (i) the provision of " bitumin carpet on a length of 5600 ft. on the north approach and (ii) the pitching to a portion of the side slopes on the south approach. These items of work are not likely to hinder the free flow of traffic on the bridge and its approaches. There has been some delay in the completion of the approaches to the bridge due to difficult and peculiar site conditions, construction on saline soil and other unforeseen technical difficulties in the Rann area.
| english |
{"activities_easter": [], "activities_epiphany": [], "activities_michaelmas": [], "code": "EDUC40220", "title": "Fundamentals of Learning and Teaching in Higher Education"} | json |
#![deny(clippy::all)]
#![warn(clippy::pedantic)]
#![allow(clippy::restriction)]
#![allow(clippy::nursery)]
#![deny(clippy::cargo)]
mod automorphic_number;
mod backspaces_in_string;
mod bookseller;
mod bool_to_word;
mod create_phone_number;
mod even_fib;
mod maximum_product;
mod multiple_3_5;
mod odd_or_even;
mod power_of_two;
mod rgb_conversion;
mod sentence_smash;
mod string_ends_with;
mod strong_number;
mod sum_of_cubes;
mod word_values;
| rust |
<gh_stars>1-10
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""
@File : test_parse.py
@Author:
@Date : 2019-01-23 17:13
@Desc :
"""
import logging
import pytest
import numpy as np
import mindspore as ms
import mindspore.nn as nn
from mindspore import Tensor
from mindspore import context
from mindspore.ops import composite as C
from mindspore.common.api import ms_function, _executor
from mindspore.ops._grad.grad_base import bprop_getters
from mindspore.ops.primitive import prim_attr_register, PrimitiveWithInfer
from mindspore.ops.functional import tensor_add
from ...ut_filter import non_graph_engine
# pylint: disable=W0613,W0612
# W0613: unused-argument
log = logging.getLogger("test")
log.setLevel(level=logging.ERROR)
context.set_context(mode=context.GRAPH_MODE)
# Test case: use the parse obj interface use default parameter
class Net(nn.Cell):
""" Net definition """
def __init__(self, dim):
super(Net, self).__init__()
self.softmax1 = nn.Softmax(dim)
self.softmax2 = nn.Softmax(dim + 1)
def construct(self, input_data, input1=ms.Tensor(np.random.randn(2, 3, 4, 5).astype(np.float32))):
return self.softmax1(input_data)
@non_graph_engine
def test_parse_defalut_parameter_case2():
""" test_parse_defalut_parameter_case2 """
log.debug("begin test_parse_defalut_parameter_case2")
net = Net(0)
npd = np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32')
log.debug("input value is: %r", npd)
input_data = ms.Tensor(npd)
input_data.set_dtype(ms.float32)
log.debug("start run")
output = net(input_data)
value = output.asnumpy()
log.debug("output value = %r", value)
# Test case: use the variable parameter for parse object
class Net1(nn.Cell):
""" Net1 definition """
def __init__(self):
super(Net1, self).__init__()
def construct(self, *args):
x = args[0]
return x
def test_var_parameter_case2():
""" test_var_parameter_case2 """
log.debug("begin test_var_parameter_case2")
net = Net1()
npd = np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32')
log.debug("input value is: %r", npd)
input_data = ms.Tensor(npd)
input_data.set_dtype(ms.float32)
np1 = np.random.randn(2, 3, 4, 5).astype(np.float32)
input1 = ms.Tensor(np1)
np2 = np.random.randn(2, 3, 4, 5).astype(np.float32)
input2 = ms.Tensor(np2)
_executor.compile(net, input_data, input1, input2)
# Test case: test the global flag
g_x = Tensor(np.ones([3, 3]).astype(np.float32))
@ms_function
def tensor_add_global(x):
""" tensor_add_global """
global g_x
res = tensor_add(x, g_x)
return res
@non_graph_engine
def test_global_flag():
""" test_global_flag """
log.debug("begin test_global_flag")
x = Tensor(np.ones([3, 3]).astype(np.float32))
res = tensor_add_global(x)
log.debug("finished test_global_flag, ret = %r", res)
class NetWithNDarray(nn.Cell):
""" NetWithNDarray definition """
def __init__(self, dim):
super(NetWithNDarray, self).__init__()
self.softmax = nn.Softmax(dim)
self.x = ms.Tensor(np.ones(shape=(1)).astype(np.float32))
def construct(self, input_data):
return self.softmax(input_data) * self.x
@non_graph_engine
def test_net_with_ndarray():
""" test_net_with_ndarray """
net = NetWithNDarray(0)
input_data = np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32')
net(ms.Tensor(input_data))
def test_bprop_with_wrong_output_num():
context.set_context(check_bprop=True)
class BpropWithWrongOutputNum(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
super(BpropWithWrongOutputNum, self).__init__('BpropWithWrongOutputNum')
def __call__(self, x, y):
return x
def infer_shape(self, x_shape, yshape):
return x_shape
def infer_dtype(self, x_type, y_type):
return x_type
@bprop_getters.register(BpropWithWrongOutputNum)
def get_bprop_with_wrong_output_num(self):
"""Generate bprop for BpropWithWrongOutputNum"""
def bprop(x, y, out, dout):
return (dout,)
return bprop
class BpropWithWrongOutputNumCell(nn.Cell):
def __init__(self):
super(BpropWithWrongOutputNumCell, self).__init__()
def construct(self, x, y):
return BpropWithWrongOutputNum()(x, y)
with pytest.raises(TypeError):
C.grad_all(BpropWithWrongOutputNumCell())(1, 2)
def test_bprop_with_wrong_output_type():
context.set_context(check_bprop=True)
class BpropWithWrongOutputType(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
super(BpropWithWrongOutputType, self).__init__('BpropWithWrongOutputType')
def __call__(self, x):
return x
def infer_shape(self, x_shape):
return x_shape
def infer_dtype(self, x_type):
return x_type
@bprop_getters.register(BpropWithWrongOutputType)
def get_bprop_with_wrong_output_type(self):
"""Generate bprop for BpropWithWrongOutputType"""
def bprop(x, out, dout):
return (1,)
return bprop
class BpropWithWrongOutputTypeCell(nn.Cell):
def __init__(self):
super(BpropWithWrongOutputTypeCell, self).__init__()
def construct(self, x):
return BpropWithWrongOutputType()(x)
with pytest.raises(TypeError):
C.grad_all(BpropWithWrongOutputTypeCell())(Tensor(np.ones([64, 10]).astype(np.int32)))
def test_bprop_with_wrong_output_shape():
context.set_context(check_bprop=True)
class BpropWithWrongOutputShape(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
super(BpropWithWrongOutputShape, self).__init__('BpropWithWrongOutputShape')
def __call__(self, x):
return x
def infer_shape(self, x_shape):
return x_shape
def infer_dtype(self, x_type):
return x_type
@bprop_getters.register(BpropWithWrongOutputShape)
def get_bprop_with_wrong_output_shape(self):
"""Generate bprop for BpropWithWrongOutputShape"""
ones = Tensor(np.ones([2,]).astype(np.int32))
def bprop(x, out, dout):
return (ones,)
return bprop
class BpropWithWrongOutputShapeCell(nn.Cell):
def __init__(self):
super(BpropWithWrongOutputShapeCell, self).__init__()
def construct(self, x):
return BpropWithWrongOutputShape()(x)
with pytest.raises(TypeError):
net = BpropWithWrongOutputShapeCell()
net.set_grad()
C.grad_all(net)(Tensor(np.ones([64, 10]).astype(np.int32)))
| python |
It looks like the gap between the Telugu Desam Party and its alliance partner Bharatiya Janata Party in Andhra Pradesh is widening with every passing day.
All these days, a few BJP leaders had been criticising the TDP and chief minister N Chandrababu Naidu, sometimes strongly and other times wildly.
But the BJP ministers in the Naidu cabinet – Endowments minister P Manikyala Rao and health minister Kamineni Srinivas have been maintaining a lot of restraint.
But on Wednesday, Manikyala Rao came out strongly against the Naidu government, clearly indicating that the three and a half years-old alliance between the TDP and the BJP is on the rocks.
He warned the Naidu government he would not hesitate to “cut” the state if the TDP tries to “cut” him.
Manikyala Rao, who represents Tadepalligudem openly expressed his anguish at the ill-treatment meted out by the Naidu’s government at the Janmabhoomi programme in Ramannagudem of West Godavari district.
Attacking Tadepalligudem municipal chairman and TDP leader Mullapudi Srinivas, the minister alleged that he had been ill-treated by the TDP cadre despite of sharing power at the centre and state.
“Whatever development that took place in Tadepalligudem is only because of the central assistance. The state government never gave a single rupee. I will react like a man and pay them in the same coin if they try to pin me down,” Manikyala Rao said.
He warned the TDP government not to provoke him as he can do serious damage being a BJP man. | english |
దేశంలో విదేశీ లాయర్లు, న్యాయ సంస్థలకు ప్రవేశం !
By Telugu Lo Computer - March 15, 2023 No comments:
తరగతి గదిలో పరదా..!
By Telugu Lo Computer - September 06, 2021 No comments:
Tags afghan, mahila, parada, ఆంక్షలు, తరగతి గదిలో పరదా..!
Templatesyard is a blogger resources site is a provider of high quality blogger template with premium looking layout and robust design. The main mission of templatesyard is to provide the best quality blogger templates which are professionally designed and perfectlly seo optimized to deliver best result for your blog.
| english |
import * as core from '@actions/core';
import * as path from 'path';
import * as common from './common';
(async function() {
try {
const version = core.getInput('version', {required: true});
const arch = common.parseArch(core.getInput('architecture') || 'x64');
const distribution = common.parseDistribution(
core.getInput('distribution') || 'full'
);
const variant = common.parseVariant(core.getInput('variant') || 'regular');
await common.install(version, arch, distribution, variant);
} catch (err) {
core.setFailed(err.message);
}
})();
| typescript |
While the myTouch 3G is just now receiving Froyo, a ROM for the yet-to-be-announced myTouch 4G leaked out today, and the diligent folks over at Android Central have been pulling it apart in search of any nuggets of joy.
And what nugget could spread joy further than a promo video?
The promo video, embedded below, shows off the Genius button, HD video recording, Video Chat, and ScreenShare (sending videos to a DLNA TV) in the context of an overly-enthusiastic nuclear family.
Of course, details on the handset aren’t in great abundance, but you can expect the new myTouch to feature T-mobile’s “4G-like” HSDPA+ speeds, and not actual 4G voodoo.
The handset will be available in your choice of white, black, plum, or red, and should ship in time for the holidays.
As usual, we’ll keep you posted on any more details (such as price) as they arrive.
| english |
<filename>packages/layout/src/steps/resolveTextLayout.js<gh_stars>1000+
/* eslint-disable no-param-reassign */
import * as R from 'ramda';
import * as P from '@react-pdf/primitives';
import layoutText from '../text/layoutText';
const isType = R.propEq('type');
const isSvg = isType(P.Svg);
const isText = isType(P.Text);
const isNotSvg = R.complement(isSvg);
const isNotText = R.complement(isText);
const shouldIterate = node => isNotSvg(node) && isNotText(node);
const shouldLayoutText = node => isText(node) && !node.lines;
/**
* Performs text layout on text node if wasn't calculated before.
* Text layout is usually performed on Yoga's layout process (via setMeasureFunc),
* but we need to layout those nodes with fixed width and height.
*
* @param {Object} node
* @returns {Object} layout node
*/
const resolveTextLayout = (node, fontStore) => {
if (shouldLayoutText(node)) {
const width =
node.box.width - (node.box.paddingRight + node.box.paddingLeft);
const height =
node.box.height - (node.box.paddingTop + node.box.paddingBottom);
node.lines = layoutText(node, width, height, fontStore);
}
if (shouldIterate(node)) {
const mapChild = child => resolveTextLayout(child, fontStore);
return R.evolve({
children: R.map(mapChild),
})(node);
}
return node;
};
export default resolveTextLayout;
| javascript |
<filename>filter_multilabels.py
import logging
import logging.config
import logconfig
import os
import settings
from collections import defaultdict, Counter
def filter_multilabels(input_dir):
logger = logging.getLogger(__name__)
logger.info(logconfig.key_log(logconfig.DATA_NAME, input_dir))
paths = []
for file_name in os.listdir(input_dir):
if os.path.splitext(file_name)[-1].startswith('.depth'):
paths.append(os.path.join(input_dir, file_name))
paths.sort()
valid_id_counter = Counter()
for depth in range(len(paths)):
doc_topic_id = defaultdict(lambda: defaultdict(lambda: set())) # doc_topic[i][j] means a set about a document with [doc_text i] and [topic j]
with open(paths[depth], 'r', encoding='utf-8') as f:
line = f.readline()
while line:
line = line.strip()
if line:
line_sp = line.split('\t')
topics = line_sp[2].split(';')
if len(topics) == 2: # an empty str will be at the last
doc_topic_id[line_sp[1]][topics[0]].add(line)
line = f.readline()
with open(paths[depth] + '.filtered', 'w', encoding='utf-8') as f:
for doc, y in doc_topic_id.items():
# multi-label
if len(y) > 1:
continue
for xx, yy in y.items():
# just keep one document
lines = sorted(list(yy))
line = lines[0]
doc_id = line.split('\t', 1)[0]
if depth == 0 or (valid_id_counter[doc_id] & (1 << (depth-1))):
valid_id_counter[doc_id] += (1 << depth)
f.write(line)
f.write('\n')
break
logger.info(logconfig.key_log(logconfig.DEPTH, str(depth)))
if __name__ == '__main__':
log_filename = os.path.join(settings.log_dir, 'filter_multilabels.log')
logconfig.logging.config.dictConfig(logconfig.logging_config_dict('INFO', log_filename))
for input_dir in settings.input_dirs:
filter_multilabels(input_dir)
| python |
Bayern Munich players are facing criticism and scrutiny for taking a short holiday in Ibiza after losing 3-1 to Mainz with the Bundesliga title already wrapped up.
Bayern clinched their 10th consecutive title with three rounds to spare on April 23, then followed up with a lacklustre display in Mainz on Saturday. The Bavarian powerhouse was fortunate not to lose by more as Mainz hit the goal-frame four times in a dominant performance.
Like Bayern, mid-table Mainz had little more than pride to play for.
Despite the heavy loss, Bayern coach Julian Nagelsmann stuck to his plan of giving his players Sunday and Monday off, which the majority took advantage of by travelling to the Spanish party island of Ibiza.
Former Bayern great Lothar Matthäus slammed the trip after the team’s dismal showing in Mainz.
There’s nothing at stake for Bayern in their remaining Bundesliga games, and Nagelsmann had already signalled he would rotate the squad and give underused players a chance to play in the remaining matches against Mainz, Stuttgart and Wolfsburg.
While Mainz and Wolfsburg have little to play for, Stuttgart is fighting relegation.
Pellegrino Matarazzo’s team is only two points ahead of Arminia Bielefeld, which is second-last in a direct relegation place, while Hertha Berlin is four points above Stuttgart and could yet be dragged back into the relegation zone.
Hertha coach Felix Magath had already questioned the Bayern players’ professionalism after winning the league.
“The season lasts until the final round. I don’t know why a team can then say: ‘Nah, we’re not playing to the end of the season, we’re going to finish three weeks before. ’ It doesn’t serve the Bundesliga nor the competition,” said Magath, who coached Bayern to league and cup doubles in 2005 and 2006.
But Magath doubled down after Bayern’s poor showing in Mainz and the subsequent trip to Ibiza.
Salihamidžić said it should be evaluated in the wake of their disappointing Champions League exit to Spanish team Villarreal, and he rejected any doubts about the players’ attitude to the remaining Bundesliga games.
“It’s absolutely clear that our players will give their all on Sunday against Stuttgart,” Salihamidžić said.
Read all the Latest News , Breaking News and IPL 2022 Live Updates here. (This story has not been edited by News18 staff and is published from a syndicated news agency feed - Associated Press) | english |
import click
from numpy import argmax
from achilles.model import AchillesModel
from achilles.utils import get_dataset_labels
from colorama import Fore
from pathlib import Path
Y = Fore.YELLOW
G = Fore.GREEN
RE = Fore.RESET
@click.command()
@click.option(
"--model",
"-m",
default=None,
help="Model file HD5.",
show_default=True,
metavar="",
)
@click.option(
"--evaluation",
"-e",
default=None,
help="Evaluation file HD5 sampled from AchillesModel.",
show_default=True,
metavar="",
)
@click.option(
"--batch_size",
"-b",
default=500,
help="Evaluation batch size.",
show_default=True,
metavar="",
)
def evaluate(model, evaluation, batch_size):
""" Evaluate a model against a data set from PoreMongo """
achilles = AchillesModel(evaluation)
achilles.load_model(model_file=model)
print(f'{Y}Evaluating model: {G}{Path(model).name}{RE}')
print(f'{Y}Using evaluation data from: {G}{Path(evaluation).name}{RE}')
predicted = achilles.predict_generator(
data_type="data", batch_size=batch_size
)
print(predicted)
predicted = argmax(predicted, -1)
labels = get_dataset_labels(evaluation)
correct_labels = 0
false_labels = 0
for i, label in enumerate(predicted):
if int(label) == int(argmax(labels[i])):
correct_labels += 1
else:
false_labels += 1
print(f'False predictions in evaluation data: '
f'{correct_labels/false_labels:.2f}%')
| python |
<filename>packages/apollo-client/tsconfig.benchmark.json
{
"extends": "./tsconfig",
"compilerOptions": {
"module": "commonjs",
"outDir": "benchmark_lib",
"rootDir": "."
},
"files": [
"node_modules/typescript/lib/lib.es2015.d.ts",
"node_modules/typescript/lib/lib.dom.d.ts",
"benchmark/index.ts"
]
}
| json |
With an aim to improve nutritional choices and enhance dietary diversity of India, the NITI Aayog, in collaboration with National Centre of Excellence and Advanced Research on Diets (NCEAR-D), UNICEF India and Lady Irwin College, organised a National Workshop on “Promoting Healthy Diets Through Local Food Systems” in New Delhi today.
The inaugural session of the workshop was addressed by Amitabh Kant, CEO, NITI Aayog, Rakesh Srivastava, Secretary, Ministry of Women and Child Development, Dr. Trilochan Mohapatra, Secretary, DARE & DG, ICAR, Dr. Yasmin Ali Haque, UNICEF Representative in India and Dr Anupa Sidhu, Director, Lady Irwin College and Chairperson, NCEAR-D.
An exhibition of more than 250 best practices, innovations and local food products developed by various agriculture and food technology institutions was another attraction.
State Governments across these districts.
Under the aegis of POSHAN Abhiyaan, promoting consumption and household/community production of locally available nutritionally rich food resources has been a priority concern. The academic institutions will serve as resource centres and Nutrition Support Units to the Districts and State administration for technical, training, concurrent monitoring support to achieve the goals of POSHAN Abhiyaan.
The workshop saw the participation of State Governments, UN agencies such as UNICEF and FAO, and development partners operating at the district level. It also included over 40 academic institutions (Home science colleges, food, nutrition and extension education departments of Agriculture universities) from across 16 states, apart from eminent academics and experts who shared implementation strategies and innovative success stories.
The Aspirational Districts Dietary fact sheets were released during the Workshop which will help both academicians and policy makers in examining the gaps in the daily diets of children and mothers of reproductive age group in terms of recommended dietary intake. The analysis will help the academic institutions to make an Action Plan to fill this gap, which will also be shared with District administration for collaboration and implementation purpose.
The POSHAN (PM’s Overarching Scheme for Holistic Nourishment) Abhiyaan is aimed to ensure attainment of malnutrition free India by 2022. The programme targets reduction of under-nutrition, anemia and low birth weight by ensuring convergence of evidence-based nutrition interventions and by creating a mass movement (Jan Andolan) for food nutrition in India. One of the key nutrition interventions to meet these targets is to improve the quality of daily diets by making them nutritionally rich and locally sustainable.
The workshop provided a platform to reach a common understanding of diet diversity problems in Aspirational Districts across India and learn from national and international examples where nutrition academia and state governments have collaborated. Academic institutions were also encouraged to frame scientific methodologies and prepare achievable action plans with clearly defined indicators.
| english |
The woman who attacked Northern Territory Chief Minister Natasha Fyles with a crepe says she was frustrated about a health issue involving her husband. Real estate agent Suzi Milgate has been charged with aggravated assault over the incident at a Darwin market. Ms Milgate claims she sent a letter to Ms Fyles three years ago requesting a vaccine exemption for her husband to continue working while he was recovering from a stroke and waiting on a heart operation. Ms Fyles’ office reportedly wrote back ‘not worthy of a response’. A medical team will be checking Ms Fyles' wellbeing “just to be sure”, while she has labelled the attack as “unacceptable”. Real estate agent Suzi Milgate has been charged with aggravated assault over the incident at a Darwin market.
Ms Milgate claims she sent a letter to Ms Fyles three years ago requesting a vaccine exemption for her husband to continue working while he was recovering from a stroke and waiting on a heart operation.
Ms Fyles’ office reportedly wrote back ‘not worthy of a response’.Read more:
‘There was no force behind it’: Woman who attacked Natasha Fyles defends actionsThe woman who attacked Northern Territory Chief Minister Natasha Fyles has defended her actions. The woman claims her frustration was related to a health issue that she tried to raise with the Chief Minister some three years to four years ago. Suzi Milgate, 56, was arrested and charged with aggravated assault on Sunday evening after shoving a cream pie in Ms Fyles’ face at Darwin’s Nightcliff Markets. “Do you think a cream pie is an assault? It’s fresh cream pie,” Ms Milgate said. “It’s not even face on, I just said, ‘Hi, boom’ – that’s it, there was no force behind it.” Ms Fyles was sporting a bruised left eye as she fronted a press conference on Monday to discuss the incident.
Northern Territory Chief Minister Natasha Fyles allegedly assaulted at popular marketsNorthern Territory Chief Minister Natasha Fyles has allegedly been assaulted while out in her local electorate.
Woman who shoved cream pie in Fyles' face reveals why she did itA disgruntled Darwin resident who allegedly assaulted NT Chief Minister Natasha Fyles with a cream pie has described the move as a “slight error” as she hit out at the Northern Territory Chief Minister for “not addressing” the issues plaguing the Top End.
Moment woman allegedly attacks NT Chief Minister with cream crepeA woman has been charged with assault after Northern Territory Chief Minister Natasha Fyles was allegedly attacked with a cream crepe.
Woman charged for aggravated assault against NT Chief MinisterPolice have charged a 56-year-old woman with aggravated assault following an incident with Northern Territory Chief Minister Natasha Fyles. Footage has emerged on social media showing the perpetrator striking the minister in the face with a pancake covered in cream. Sky News Darwin Bureau Chief Matt Cunningham spoke with Ms Fyles who appeared quite shaken up by the attack and now has some bruising around her left eye. Ms Fyles was at the Nightcliff markets on Sunday morning, attending Bendigo Bank’s 15 years of service when the incident occurred. The woman has since been bailed to appear in a Darwin local court on October 10.
The woman who attacked Northern Territory Chief Minister Natasha Fyles with a crepe says she was frustrated about a health issue involving her husband.
Real estate agent Suzi Milgate has been charged with aggravated assault over the incident at a Darwin market.
Ms Milgate claims she sent a letter to Ms Fyles three years ago requesting a vaccine exemption for her husband to continue working while he was recovering from a stroke and waiting on a heart operation.
Ms Fyles’ office reportedly wrote back ‘not worthy of a response’.
A medical team will be checking Ms Fyles' wellbeing “just to be sure”, while she has labelled the attack as “unacceptable”.
| english |
<filename>spider9.md
---
title: Scrapy爬取烂番茄的年度电影榜单
name: spider9
date: 2019-03-08
id: 0
tags: [python,爬虫,scrapy]
categories: []
abstract: ""
---
分析网页结构后,发现年度电影数据最早到1950年,使用一个for循环对url进行构造
源码地址 [github](https://github.com/Landers1037/PySpider/tree/master/%E7%83%82%E7%95%AA%E8%8C%84%E7%94%B5%E5%BD%B1%E7%BD%91%E7%AB%99%E5%B9%B4%E5%BA%A6%E6%9C%80%E4%BD%B3%E7%94%B5%E5%BD%B1%E6%A6%9C%E5%8D%95/rottentomatoes)
<!--more-->
分析网页结构后,发现年度电影数据最早到1950年,使用一个for循环对url进行构造
源码地址 [github](https://github.com/Landers1037/PySpider/tree/master/%E7%83%82%E7%95%AA%E8%8C%84%E7%94%B5%E5%BD%B1%E7%BD%91%E7%AB%99%E5%B9%B4%E5%BA%A6%E6%9C%80%E4%BD%B3%E7%94%B5%E5%BD%B1%E6%A6%9C%E5%8D%95/rottentomatoes)<!--more-->
## 蜘蛛部分
```python
# -*- coding: utf-8 -*-
import scrapy
from rottentomatoes.items import RottentomatoesItem
class TomatoSpider(scrapy.Spider):
name = 'tomato'
allowed_domains = ['www.rottentomatoes.com']
start_urls = ['https://www.rottentomatoes.com/']
def parse(self, response):
datas = response.css('.table tr')
for data in datas:
item = RottentomatoesItem()
item['movieyear'] = response.url.replace('https://www.rottentomatoes.com/top/bestofrt/?year=','')
item['rank'] = data.css('td:nth-child(1)::text').extract_first()
item['movie'] = str(data.css('td a::text').extract_first()).strip()
item['tomatometer'] = str(data.css('.tMeterScore::text').extract_first()).replace('\xa0','')
yield item
def start_requests(self):
base_url = 'https://www.rottentomatoes.com/top/bestofrt/?year='
for page in range(1950,2019):
url = base_url + str(page)
yield scrapy.Request(url,callback=self.parse)
```
## pipeline部分
```python
class pgPipeline():
def __init__(self,host,database,user,password,port):
self.host = host
self.database = database
self.user = user
self.password = password
self.port = port
self.db = psycopg2.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port)
self.cursor = self.db.cursor()
@classmethod
def from_crawler(cls,crawler):
return cls(
host=crawler.settings.get('SQL_HOST'),
database=crawler.settings.get('SQL_DATABASE'),
user=crawler.settings.get('SQL_USER'),
password=crawler.settings.get('SQL_PASSWORD'),
port=crawler.settings.get('SQL_PORT'),
)
def open_spider(self,spider):
self.db = psycopg2.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port)
self.cursor = self.db.cursor()
def process_item(self,item,spider):
data = item
sql = 'insert into tomato(movieyear,rank,movie,tomatometer) values (%s,%s,%s,%s)'
try:
self.cursor.execute(sql,(data['movieyear'],data['rank'],data['movie'],data['tomatometer']))
self.db.commit()
except:
self.db.rollback()
return item
def close_spider(self,spider):
self.db.close()
```
| markdown |
{
"description": "UDP-based write utility for InfluxDB",
"dependencies": {
"lodash": "2.4.x"
},
"keywords": ["influx", "influxdb", "udp" ],
"license": "Apache-2.0",
"main": "./lib",
"name": "influx-udp",
"repository": "git://github.com/mediocre/node-influx-udp.git",
"version": "1.0.1"
}
| json |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.