text stringlengths 1 1.04M | language stringclasses 25 values |
|---|---|
<filename>src/main/java/com/fengruigan/androidbuilder/AndroidBuilder.java
package com.fengruigan.androidbuilder;
import java.io.IOException;
import java.util.Map;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class AndroidBuilder implements RequestHandler<HandlerInput, HandlerOutput>{
@Override
public HandlerOutput handleRequest(HandlerInput input, Context context) {
Map<String, String> data = input.getData();
Map<String, String> env = input.getEnv();
String buildId = data.get("buildId");
String repoName = data.get("repoName");
String repoOwner = data.get("repoOwner");
String artifactName = data.get("artifactName");
String fileKeyPrefix = FileTransferUtil.generateFileKeyPrefix(repoOwner, repoName, buildId);
String token = env.get("GITHUB_TOKEN");
String gitDirName = "/tmp/gitDir";
String[] commands = {
"git",
"clone",
"https://" + repoOwner + ":" + token + "@github.com/"+ repoOwner +"/" + repoName + ".git",
gitDirName};
try {
System.out.println("Starting git clone");
ProcessHandler.executeCommand(commands, env, "/tmp", "Git Clone");
System.out.println("Finish git clone");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
FileTransferUtil.uploadToS3("/tmp/stdout.txt", fileKeyPrefix + "stdout.txt");
return new HandlerOutput(1, "Error cloning. " + e.getMessage());
}
commands = new String[]{"./gradlew", "assembleRelease"};
int exitCode;
try {
System.out.println("Starting build");
exitCode = ProcessHandler.executeCommand(commands, env, gitDirName, "Build");
System.out.println("Finish build");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
FileTransferUtil.uploadToS3("/tmp/stdout.txt", fileKeyPrefix + "stdout.txt");
return new HandlerOutput(1, "Error building. " + e.getMessage());
}
if (exitCode != 0) {
FileTransferUtil.uploadToS3("/tmp/stdout.txt", fileKeyPrefix + "stdout.txt");
return new HandlerOutput(1, "Build failed");
}
commands = new String[]{
"apksigner", "sign",
"--ks", "app/keystore",
"--ks-pass", "env:KEYSTORE_PASS",
"--in", "app/build/outputs/apk/release/app-release-unsigned.apk",
"--out", artifactName
};
try {
System.out.println("Starting apk signing");
exitCode = ProcessHandler.executeCommand(commands, env, gitDirName, "Apk Signing");
System.out.println("Finish apk signing");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
FileTransferUtil.uploadToS3("/tmp/stdout.txt", fileKeyPrefix + "stdout.txt");
return new HandlerOutput(1, "Error signing apk. " + e.getMessage());
}
System.out.println("Starting artifact upload");
FileTransferUtil.uploadToS3("/tmp/stdout.txt", fileKeyPrefix + "stdout.txt");
FileTransferUtil.uploadToS3(gitDirName + "/" + artifactName, fileKeyPrefix + artifactName);
System.out.println("Finish artifact upload");
return new HandlerOutput(exitCode, exitCode == 0? "Build finished: 0": "Build finished: " + exitCode);
}
}
| java |
<filename>pkg/sqlite/src/client.test.ts
import { expectType } from "ts-expect";
import SQL from "./tag.js";
import { Database } from "./driver.js";
import {
ClientType,
createClient,
makeInsert,
makeUpdate,
GenericClient,
} from "./client.js";
import "./testUtils.js";
describe("createClient", () => {
it("works", () => {
const client = createClient(":memory:", undefined, {
generic: GenericClient,
});
expect(client).toMatchObject({
$db: expect.any(Database),
generic: expect.any(GenericClient),
});
});
});
describe("makeInsert", () => {
it("creates expected SQL", () => {
const actual = makeInsert("tbl", [
{ str: "value 1", num: 1 },
{ num: 2, str: SQL`NOW()` },
]);
expect(actual).toEqualSQL(
SQL`INSERT INTO "tbl" ( "str", "num" ) VALUES ( ${"value 1"}, ${1} ), ( NOW(), ${2} )`
);
});
it("requires some data", () => {
expect(() => makeInsert("tbl", [])).toThrow("no values");
});
it("verifies columns are all identical", () => {
expect(() =>
makeInsert("tbl", [{ one: "one" }, { one: "one", two: "two" }])
).toThrow("columns must be identical in all values");
expect(() =>
makeInsert("tbl", [{ one: "one", two: "two" }, { one: "one" }])
).toThrow("columns must be identical in all values");
expect(() =>
makeInsert("tbl", [
{ one: "one", two: undefined },
{ one: "one", two: "two" },
])
).not.toThrow();
expect(() =>
makeInsert("tbl", [
{ one: "one", two: "two" },
{ one: "one", three: "three" },
])
).toThrow("columns must be identical in all values");
});
});
describe("makeUpdate", () => {
it("creates expected SQL", () => {
const actual = makeUpdate("tbl", {
str: "value 1",
num: 1,
time: SQL`NOW()`,
});
const expected = SQL`UPDATE `;
expect(actual).toEqualSQL(
SQL`UPDATE "tbl" SET "str" = ${"value 1"}, "num" = ${1}, "time" = NOW()`
);
});
it("requires some data", () => {
expect(() => makeUpdate("tbl", {})).toThrow("no values");
});
});
| typescript |
Bollywood’s popular Jodi, Alia Bhatt and Ranbir Kapoor have turned heads with their adorable picture and ‘PDA’ moments at the award nights, but the wait for their wedding pictures can be a little longer.
There has been a lot of excitement and buzz about these b-town couple getting married, but neither of their families and closed ones has confirmed it yet.
There has been a lot of speculations about the dreamy wedding, locations, Alia’s outfit etc, but they won’t be getting married anytime soon this year, suggests the reports.
According to the reports Alia and Ranbir were to get married in December this year, but the wedding was postponed catering to various reasons from corona to work commitments, a source told Etimes.
According to the reports, Alia Bhatt will be seemingly busy because of lined up work assignments. Reports say she has approached Sabyasachi for designing her wedding lehenga but that has been put on hold for now. The couple would be seen together for the first time on silver screen in Ayan Mukharjee’s next, ‘Brahmastra’, it was supposed to be released in December 2020, but has been postponed. | english |
{"batchcomplete":"","query":{"normalized":[{"from":"Maja_Ognjenovi\u0107","to":"<NAME>\u0107"}],"pages":{"16192674":{"pageid":16192674,"ns":0,"title":"<NAME>\u0107","pageprops":{"defaultsort":"Ognjenovic, Maja","page_image_free":"Maja_Ognjenovic_in_2018_FIVB_WCC.jpg","wikibase-shortdesc":"Serbian volleyball player","wikibase_item":"Q2734878"}}}}} | json |
{"ast":null,"code":"/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */\nimport { connectableObservableDescriptor } from '../observable/ConnectableObservable';\nexport function multicast(subjectOrSubjectFactory, selector) {\n return function multicastOperatorFunction(source) {\n var subjectFactory;\n\n if (typeof subjectOrSubjectFactory === 'function') {\n subjectFactory = subjectOrSubjectFactory;\n } else {\n subjectFactory = function subjectFactory() {\n return subjectOrSubjectFactory;\n };\n }\n\n if (typeof selector === 'function') {\n return source.lift(new MulticastOperator(subjectFactory, selector));\n }\n\n var connectable = Object.create(source, connectableObservableDescriptor);\n connectable.source = source;\n connectable.subjectFactory = subjectFactory;\n return connectable;\n };\n}\n\nvar MulticastOperator =\n/*@__PURE__*/\nfunction () {\n function MulticastOperator(subjectFactory, selector) {\n this.subjectFactory = subjectFactory;\n this.selector = selector;\n }\n\n MulticastOperator.prototype.call = function (subscriber, source) {\n var selector = this.selector;\n var subject = this.subjectFactory();\n var subscription = selector(subject).subscribe(subscriber);\n subscription.add(source.subscribe(subject));\n return subscription;\n };\n\n return MulticastOperator;\n}();\n\nexport { MulticastOperator };","map":null,"metadata":{},"sourceType":"module"} | json |
<filename>renovate.json
{
"extends": [
"config:base"
],
"automerge": true,
"automergeType": "pr-comment",
"automergeComment": "bors r+",
"requiredStatusChecks": null,
"major": {
"automerge": false
}
}
| json |
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
var _excluded = ["onClick", "href", "route", "root", "action"];
import React, { useContext, useCallback } from 'react';
import { EluxContextComponent } from './base';
export default React.forwardRef(function (_ref, ref) {
var _onClick = _ref.onClick,
href = _ref.href,
route = _ref.route,
root = _ref.root,
_ref$action = _ref.action,
action = _ref$action === void 0 ? 'push' : _ref$action,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
var eluxContext = useContext(EluxContextComponent);
var router = eluxContext.router;
var onClick = useCallback(function (event) {
event.preventDefault();
_onClick && _onClick(event);
route && router[action](route, root);
}, [_onClick, action, root, route, router]);
props['onClick'] = onClick;
href && (props['href'] = href);
route && (props['route'] = route);
action && (props['action'] = action);
root && (props['target'] = 'root');
if (href) {
return React.createElement("a", _extends({}, props, {
ref: ref
}));
} else {
return React.createElement("div", _extends({}, props, {
ref: ref
}));
}
}); | javascript |
Farmers’ Protest December 11: The Bharatiya Kisan Union (BKU) has moved Supreme Court challenging the three farm reform laws passed by the Parliament recently that are now at the Centre of the massive protests. The farmers have also planned to intensify the agitation over the next few days in which they have planned to block highways leading to Delhi, gherao BJP leaders and offices and bring out another ‘Delhi Chalo’ march on December 14. Meanwhile, an FIR has been lodged against the farmers sitting at the Singhu border for not maintaining social distancing and following Covid-19 protocols. As the farmers’ protest enters the third week, they have announced that they will block railway tracks if their demands are not met by the government. The farmer unions, which held a meeting on Thursday, said they will soon announce a date for blocking tracks across the country.
Delhi Commissioner of Police SN Srivastava on Friday inspected security arrangements at the Tikri border amid the ongoing farmers' agitation. Commissioner Srivastava also took stock of the security road map in nearby areas.
(Inputs from Arvind Ojha)
Police in Haryana's Faridabad has issued an alert owing to the farmers' call for 'gherao' of toll plazas. The police will closely monitor those trying to disturb law and order in the guise of agitation, Faridabad Police said adding that nearly 3,500 police personnel and drone cameras will be deployed for this purpose.
(Inputs from Tanseem Haider)
'Believe farm laws won't have impact on Tamil Nadu'
General secretary of the non-political, non-religious, non-communal Farmers Association of Coimbatore B Kandaswamy (70) told India Today that claims by agitating farmers that the new farm law will lead to a great crisis are not true. "These laws won't have a major impact on Tamil Nadu or its farmers are our beliefs, Kandaswamy added.
(Inputs from Akshaya Nath)
"Proposal to resolve farmers' issues has been sent to their unions. The government is ready for further discussion," Union Minister for Agriculture Narendra Singh Tomar told news agency PTI on Friday. He went on to add that the Centre is sensitive towards farmers and is in discussion with their representatives.
While appealing to the farmers to remain vigilant and not provide their platform to "anti-social elements", Union Minister Narendra Singh Tomar alleged, "Anti-social elements conspiring to spoil the atmosphere of farmers' movement in the guise of peasants. "
Balbir S Rajewal, Bharatiya Kisan Union chief, was quoted by ANI as saying, "On December 12, we'll block Delhi-Jaipur road. On 14th, we'll stage sit-in protest in front of DC offices, houses of BJP leaders and block Reliance/Adani toll plazas. No program to stop trains. Number of farmers coming here is increasing. "
Foot massage machines have been installed for farmers at Singhu Border in Delhi-NCR. 600 to 700 farmers are being massaged every day. Social organization Khalsa Aid has installed foot massage machine for farmers protesting against the Centre's three laws at Singhu border.
Security has been tightened in all districts of Gurugram ahead of farmers' Delhi-Jaipur highway blockade call on December 12. Sixty district magistrates have been deployed at the border area and around 2,000-2,500 poloce personnel have been deployed across the city. (Tanseem Haider reports)
On farmers' call for Delhi-Jaipur highway blockade on Saturday, Union minister Gajendra Singh Shekhawat said the call is "unfortunate" and that "the government has opened all doors for dialogue. All resolution will be reached through dialogue alone. "
AIKSCC releases statement, says govt falsely claiming farmers’ unions 'have gone back on talks'
All India Kisan Sangharsh Coordination Committee (AIKSCC) has released a statement saying, "The governmenr is falsely claiming that the farmers’ organisations have gone back on talks and should not have intensified their agitation at a time when talks are on. "
"The Working Group of AIKSCC has taken affront to the Agriculture Minister's claim that the farmer unions did not respond to the Govt’s offer of solving specific issues and they have walked away. On December 5 the Govt had explained all the specific solutions in great detail. Thereafter when the farmers' organisations asked for a clear answer in Yes or No, the Ministers present, including the Agriculture Minister deliberated amongst themselves and clearly stated that they will discuss in the Govt and get back to them. Now the Govt is falsely claiming that the farmers’ organisations have gone back on talks and should not have intensified their agitation at a time when talks are on. Farmers’ organisations are always ready for talks and have responded each time the Govt has called. It is the Govt which is adamant on continuing with not repealing the 3 Acts and EB 2020 which is the main demand of the farmers. "
The Aam Aadmi Party said in a statemnet on Friday, "In solidarity with the call given by farmers, AAP would lay siege to district headquarters across Punjab on December 14 against the new agrarian laws introduced by the [Narendra] Modi government at the Centre. " (ANI)
Amit Malviya, the national in-charge of BJP's Information and Technology department, tweeted: "The government conducted nearly 1. 4 lakh training and webinar sessions reaching out to nearly 93 lakh farmers in the last six months regarding the new agriculture reforms. I wonder where were those who are protesting now. "
Union Minister Narendra Singh Tomar urges farmers to 'end agitation in interest of common people'
Agricultural Minister Narendra Singh Tomar said, "Agitation causes problems for the common people too. People of Delhi are facing troubles. So, they [farmers] should end their agitation in the interest of the common people and try to solve issues with the help of talks. "
"We agree that we are not the over-ruling power and unions might also have something in their mind. So, the government is ready to make reforms in the laws after talks", news agency ANI quoted Narendra Singh Tomar as saying.
"In our proposal, we have made an effort to suggest a solution to their objections. They should leave agitation and take the path of discussion. The government is ready for talks," he said.
(Note: An error in the post has now been corrected. )
Amid the widespread farmers’ agitation, BJP plans campaign in favour of the farm reform bills. BJP will be starting a counter campaign against the farmers’ protests. The party is drawing an elaborate plan to spread awareness about the farm laws. BJP will hold Kisan Sammelans and chaupals at 100 locations across the country to talk about the farm laws.
Farmers at Ghazipur border tried to cross barricades to move towards Delhi. But police stopped them and now they are headed back to the protest site.
Farmers unions will hold a meeting at Singhu border today around 2 pm to discuss the strategy for the future course of the ongoing agitation that has now entered the 16th day.
Indian economist and former World Bank chief Kaushik Basu has said, "I have now studied India’s new farm bills and realized they are flawed and will be detrimental to farmers. Our agriculture regulation needs change but the new laws will end up serving corporate interests more than farmers. Hats off to the sensibility and moral strength of India’s farmers. "
Ahead of the roadblocks planned by the farmer organisations to further intensify the agitation, authorities are keeping a close watch on the villages along the Rajasthan and Haryana borders. So far, there is no information of large gatherings moving towards Gurugram either from Rajasthan or South Haryana side. There is a close watch on farmers who reside in these villages and are supporters of BKU. In Gurugram, the following places will see extra security at Panchgaon Chowk, Rajiv Chowk, IFFCO Chowk and Sirhaul Chowk. Over 2000 police personnel to be deployed on the Gurugram side. Large number of police personnel from the Delhi Armed Police and Paramilitary Forces will be stationed on the Delhi side.
The ongoing farmers' agitation at the Delhi borders have entered the 16th day even as the farmers threaten to further intensify the stir till the demands are met by the government.
There are 6 petitions pending in Supreme Court against the farm laws, including one filed by DMK MP Tiruchi Siva. The latest BKU petition seeks permission to intervene in the case and present their arguments. Supreme Court had issued notice to the Centre on October 12 and sought their response on the petitions. The matters are likely to be heard in the last week of December. | english |
<reponame>taksuparth/visx<gh_stars>1000+
// This file can be deleted once https://git.io/Jk9FD lands in TypeScript
interface ResizeObserverEntry {
contentRect: {
left: number;
top: number;
width: number;
height: number;
};
}
type ResizeObserverCallback = (entries: ResizeObserverEntry[]) => void;
export interface ResizeObserver {
// eslint-disable-next-line @typescript-eslint/no-misused-new
new (callback: ResizeObserverCallback): ResizeObserver;
observe(el: Element): void;
disconnect(): void;
}
| typescript |
A subtle tweak, like a high-protein diet full of fibre and cutting down carbohydrates, aids you in losing weight.
A healthy diet and a few lifestyle changes could help you achieve your weight loss goal faster. To get rid of those few extra kilos, you can get mindful of your diet and physical exercise routine.
It may sound challenging at first, but gradually, you will get used to it. Your diet does not necessarily need to undergo big changes, but you need to make healthy choices for food. Here are three super-healthy dishes to aid your weight loss journey.
1. Veggie Hummus sandwich:
A veggie and hummus sandwich makes a fiber-rich lunch. Hummus is a spread or a dip made from cooked and mashed chickpeas blended with tahini, garlic, olive oil, lemon juice, and salt. You can pair it with any bread or use it in sandwiches. Take a few slices of multi-grain bread and spread the hummus on all slices. Add the vegetables like bell pepper, cucumber, lettuce, onion, and tomato slices, to make a delicious sandwich.
2. Upma:
Upma is a flavourful and healthy dish. You can cook it in a jiffy. It is a perfect meal option made of lightly roasted semolina, green peas, carrot, and onions and lightly tempered with mustard seeds and curry leaves. Green Peas are high in protein content and low in calories. It is loaded with vitamins K and C, manganese, and fibre.
3. Besan chilla:
Besan Chilla gets made with gram flour (besan), onions, tomatoes, herbs, and spices. You can add finely chopped or grated vegetables to increase the nutrition of the dish. Have it for your breakfast or lunch. | english |
{"h":[{"d":[{"f":"an owl領角鴞(貓頭鷹)"},{"f":"black as the burn on a pan or soot燒痕,鍋底或火爐灶上煙燻遺留的黑色粉末"}]}],"t":"'kong"} | json |
7 new streaming movies and TV shows you can watch in Australia this weekend (Oct 1-3)
With so many shows and movies to choose from on Australia's major streaming services, it can often be difficult to find the best new stuff to entertain yourself with each end of week.
In an effort to make things easier, we've hand-picked the best new shows and movies to watch on Aussie streaming platforms this weekend, covering the likes of Netflix, Disney Plus, Binge, Foxtel Now, Stan, Apple TV Plus and Amazon Prime Video.
Below, you'll find a list of new highlights, with binge-worthy TV shows sitting alongside some great big-budget movie arrivals – and a couple of oddball left-of-field entries, just for some variety.
The big new shows and movies in this entry include the highly anticipated adaptation of the complete series of Seinfeld on Netflix, the arrival of Wonder Woman 1984 on Binge, and Lego Star Wars Halloween special Terrifying Tales on Disney Plus. Here are our streaming picks for the weekend of October 1-3, 2021.
(TV series – seasons 1-9 available 01/10/2021)
One of the most groundbreaking sitcoms of all-time, Seinfeld is a self-described "show about nothing" in which four self-absorbed friends (led by comedy legend Jerry Seinfeld) go about their lives while getting caught up in a series of hilarious misadventures. Easily one of the funniest shows ever made, you can now revisit the entirety of Seinfeld on Netflix.
Jake Gyllenhaal (Nightcrawler, Donnie Darko) stars in this single-location thriller that was shot during lockdown by director Antoine Fuqua (Southpaw, Training Day) in which a demoted police officer assigned to a call dispatch desk receives an emergency phone call from a woman who has been abducted. Now, he must do everything he can to help keep her alive.
(Movie – available now)
Gal Gadot returns in Wonder Woman 1984, the '80s set sequel which sees the DC superhero face the ultimate '80s villain – a greedy businessman (Pedro Pascal) with the ability to grant wishes. Okay, so most people would agree that the film wasn't as good as its predecessor, but there's still plenty to like here.
(TV series – episode 3 available 01/10/2021)
Isaac Asimov's Foundation series of novels is one of the most influential sagas in science fiction literature, and now it's finally received the live-action treatment on Apple TV Plus – and with what appears to be an enormous budget, to boot! Spanning thousands of years, the story of Foundation sees a band of exiles set off on a journey to save humanity after the fall of the Galactic Empire. Episode 2 ended on an incredibly shocking moment that could change the entire course of the Foundation project. We can't wait to see how everyone reacts to what happened.
(TV special– available now)
LEGO Star Wars gets its own Halloween special which takes place after the events of The Rise of Skywalker. In it, Poe and BB-8 are forced to make an emergency landing on Mustafar (last seen during the climactic battle in Revenge of the Sith) where they meet the greedy Graballa the Hutt who is attempting to turn Darth Vader’s castle an all-inclusive Sith-inspired luxury hotel. Sounds appropriately ridiculous then!
(Movie – available now)
The hilarious action comedy The Nice Guys arrives on Amazon Prime Video this week, starring Russell Crowe and Ryan Gosling. The former plays a tough guy for hire, while the latter widowed private detective who's raising an adolescent daughter who's already wiser than he is. Like all good detective stories, the pair start out on their own separate cases, only to find out both are actually linked. Filled with excellent one-liners and terrific comedic performances, The Nice Guys is well worth your time.
(TV series – episode 7 available 03/10/2021)
Jack Spade's world keeps spiralling as he attempts to keep the DWL afloat by trying to put on a good show at the all-important State Fair, despite protestation from his neglected wife. Meanwhile, Rooster makes the decision to leave the DWL and join the competition after being passed up yet again for a push from Jack.
Get the hottest deals available in your inbox plus news, reviews, opinion, analysis, deals and more from the TechRadar team.
Stephen primarily covers phones and entertainment for TechRadar's Australian team, and has written professionally across the categories of tech, film, television and gaming in both print and online for over a decade. He's obsessed with smartphones, televisions, consoles and gaming PCs, and has a deep-seated desire to consume all forms of media at the highest quality possible.
He's also likely to talk a person’s ear off at the mere mention of Android, cats, retro sneaker releases, travelling and physical media, such as vinyl and boutique Blu-ray releases. Right now, he's most excited about QD-OLED technology, The Batman and Hellblade 2: Senua's Saga.
| english |
<filename>users/boopathi.json
{"copyright":"<NAME>","url":"https:\/\/boopathi.in","email":"<EMAIL>","gravatar":true} | json |
<reponame>andreicristianpetcu/batchers<gh_stars>0
package be.cegeka.batchers.taxcalculator.batch.service;
import be.cegeka.batchers.taxcalculator.batch.api.JobStartListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
@Component
public class ResetStubWebserviceService implements JobStartListener {
private static final Logger LOG = LoggerFactory.getLogger(ResetStubWebserviceService.class);
@Autowired
private String resetUrl;
@Autowired
private RestTemplate restTemplate;
@Override
public void jobHasBeenStarted(String jobName) {
try {
restTemplate.postForEntity(getUri(), null, Void.class);
LOG.info("Resetted the StubWebservice successful on restart");
} catch (RestClientException e) {
LOG.info("Failed to reset the StubWebservice on restart");
throw new IllegalStateException("Error resetting the StubWebservice... results may be unpredictable.", e);
}
}
private URI getUri() {
return URI.create(resetUrl);
}
}
| java |
There’s no doubt about the fact that life is hard enough. You won’t always succeed with everything, and that’s okay. Holding on to something as simple as daily reminders can keep you going and motivated to move forward. Even if it’s easy to feel stuck in life, all you need is the reminder to keep going.
In our day-to-day rush to get everything accomplished, it can be easy to forget how precious each day, hour, and minute of our life truly is.
If you’re finding it hard to keep moving forward and you’re dwelling on difficult emotions, you need daily reminders to help you get through tough times. Remember, your negative emotions or situations will never define you. But it will define you if that’s where you remain for a prolonged period.
Yes, this seems like a strange place to start. But everything starts with this.
One of the first things we tend to do when we think about improving our own lives is to think about the things that we need to add to our to-do list. This is dangerous – a richer life does not necessarily mean a busier life!
Beyond this, sleep is important for a number of health reasons, and being well-rested will definitely help you to enjoy the activities and people that are already a part of your life. You can always start reaching your goals and doing whatever it is you want to do after you’ve got at least 7 hours of sleep every night.
If you don’t take care of your health first by getting a good night’s sleep, not only do you have a weaker immunity, you’re also less awake during the day. You just won’t be able to move forward in the right mind if you’re constantly fatigued.
There’s so much beauty and wonder all around us, in every second of our lives. A daily reminder to remember is to explore your world as if you were a child again, and pay attention to the little details. Stop and stare at a flower blooming through the cracks in the pavement, take a deep breath and smell the fresh air, and look closely at the things you normally ignore.
As we grow up, we overlook everything that would once captivate us. Slow down, take a breath, and soon enough, you’ll learn to be more aware of the present, and learn to absorb happiness from your surroundings.
All of us feel unloved and lonely now and then, even the ones in relationships. But that doesn’t mean you don’t deserve love or affection. You need to remember every day that love starts with you.
If you love yourself, only then can you allow love to flow into you from others, and from the world around you. Set aside just one minute of your day, look into the mirror, and compliment yourself. It may be the most insignificant detail, but it shows that you love yourself, even in the smallest of ways. That’s a great start to welcome love into your life.
This is an inevitable truth and daily reminder that you need to keep in mind. Sometimes, people will let you down, and that’s okay. We all have our own problems, commitments, and distractions. And if someone doesn’t keep their word, or decides to flake on you, it isn’t a judgment on you. It has absolutely nothing to do with you.
You should never accept that people hurt you because of who you are. They hurt you because of them, who they are, their beliefs, or their problems.
Love yourself, and never change who you are for anyone but yourself. There will always be people who enter your life, your colleagues, your friends, or even a partner or a parent, who’d want you to change to suit their needs.
Revel in who you are, and stay true to yourself – even if it means being more sensitive or loyal to a fault. Change a part of yourself if you must, but only for yourself if you think it’ll improve you, not because others want you to.
Every single day! This is a really important daily reminder that all of us know, but never really care about. It seems like such a waste of time. Gratitude? It seems silly. But guess what, it works!
Every morning, wake up and thank the universe for a few things you’re grateful for. You won’t see any change in a day or even a week. But give it a month of showing gratitude every day, and you’ll feel lighter, happier, and more positive about everything you have in your life. | english |
<gh_stars>0
package winServ;
import java.nio.channels.SocketChannel;
import org.apache.http.HttpResponse;
public class HttpWrapper {
/*
* Overview: it is a wrapper for the response and serves as the object that is being passed to the main thread to be register with the correct operation.
*/
private HttpResponse resp;
private int length;//the length of the response
private boolean closed;//if the client requested to close the connection
private int OP_TYPE;//the type of operation associated to the channel
private SocketChannel client;
public HttpWrapper(HttpResponse resp, int length, boolean closed) {
this.closed=closed;
this.resp=resp;
this.length=length;
}
public HttpResponse getResp() {
return this.resp;
}
public int getLength() {
return this.length;
}
public boolean getStatus() {
return this.closed;
}
public void set_upd_op_type(int type) {
this.OP_TYPE=type;
}
public int get_op() {
return this.OP_TYPE;
}
public void set_socket(SocketChannel cl) {
this.client=cl;
}
public SocketChannel get_client() {
return this.client;
}
}
| java |
<filename>sharedtest/sharedtest.go
// Package sharedtest implements shared UpdateStore interface tests.
//
// The USTest* functions tests should be run by implementations
// of the UpdateStore interface to ensure compatability between them.
package sharedtest
import (
"github.com/briandorsey/partisci/store"
"github.com/briandorsey/partisci/version"
"testing"
"time"
)
func USTestAppSummary(s store.UpdateStore, t *testing.T) {
v := version.Version{App: "app1", Ver: "ver", Host: "a"}
v.Prepare()
s.Update(v)
if _, ok := s.App("non-existant"); ok {
t.Error("got ok for non-existant AppId")
}
if as, ok := s.App("app1"); ok {
if as.HostCount != 1 {
t.Error("expected HostCount: 1, actual: ", as.HostCount)
}
} else {
t.Error("missing expected AppId")
}
v2 := version.Version{App: "app1", Ver: "ver", Host: "b"}
v2.Prepare()
s.Update(v2)
if as, ok := s.App("app1"); ok {
if as.HostCount != 2 {
t.Error("expected HostCount: 2, actual: ", as.HostCount)
}
}
}
func USTestHostSummary(s store.UpdateStore, t *testing.T) {
v := version.Version{App: "app1", Ver: "ver", Host: "a"}
v.Prepare()
s.Update(v)
if _, ok := s.Host("non-existant"); ok {
t.Error("got ok for non-existant Host")
}
if as, ok := s.Host("a"); ok {
if as.AppCount != 1 {
t.Error("expected AppCount: 1, actual: ", as.AppCount)
}
} else {
t.Error("missing expected Host")
}
v2 := version.Version{App: "app2", Ver: "ver", Host: "a"}
v2.Prepare()
s.Update(v2)
if as, ok := s.Host("a"); ok {
if as.AppCount != 2 {
t.Error("expected AppCount: 2, actual: ", as.AppCount)
}
}
}
// test Clear() & Update() interactions
func USTestClearUpdate(s store.UpdateStore, t *testing.T) {
if vs, err := s.Versions("", "", ""); len(vs) > 0 {
if err != nil {
t.Fatal(err)
}
t.Error("Versions should be empty, len was: ", len(vs))
}
v := *new(version.Version)
v.Prepare()
s.Update(v)
if vs, err := s.Versions("", "", ""); len(vs) != 1 {
if err != nil {
t.Fatal(err)
}
t.Error(v.ExactUpdate, v.LastUpdate)
t.Error("Versions should have one entry, len was: ", len(vs))
}
if err := s.Clear(); err != nil {
t.Fatal(err)
}
if vs, err := s.Versions("", "", ""); len(vs) > 0 {
if err != nil {
t.Fatal(err)
}
t.Error("Versions should be empty, len was: ", len(vs))
}
s.Update(v)
if vs, err := s.Versions("", "", ""); len(vs) > 0 {
if err != nil {
t.Fatal(err)
}
t.Error("updates older than threshold should be discarded")
}
}
func USTestTrim(s store.UpdateStore, t *testing.T) {
// setup one version in the future and a few more
v1a := version.Version{App: "app1", Ver: "ver", Host: "a"}
v1a.Prepare()
v1a.ExactUpdate = v1a.ExactUpdate.Add(time.Duration(10 * time.Second))
s.Update(v1a)
v1b := version.Version{App: "app1", Ver: "ver", Host: "b"}
v1b.Prepare()
s.Update(v1b)
v2 := version.Version{App: "app2", Ver: "ver", Host: "a"}
v2.Prepare()
s.Update(v2)
// sanity check
if vs, err := s.Versions("", "", ""); len(vs) != 3 {
if err != nil {
t.Fatal(err)
}
t.Fatal("before: version count - expected: 2, actual: ", len(vs))
}
if l, err := s.Hosts(); len(l) != 2 {
if err != nil {
t.Fatal(err)
}
t.Fatal("before: host count - expected: 2, actual: ", len(l))
}
if l, err := s.Apps(); len(l) != 2 {
if err != nil {
t.Fatal(err)
}
t.Fatal("before: app count - expected: 2, actual: ", len(l))
}
// trim every version before 1 second in the future of one version
count, err := s.Trim(v2.ExactUpdate.Add(time.Duration(1 * time.Second)))
if err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatal("after: trim should have removed 2 versions")
}
if vs, err := s.Versions("", "", ""); len(vs) != 1 {
if err != nil {
t.Fatal(err)
}
t.Fatal("after: version count - expected: 1, actual: ", len(vs))
}
if l, err := s.Hosts(); len(l) != 1 {
if err != nil {
t.Fatal(err)
}
t.Fatal("after: host count - expected: 1, actual: ", len(l))
}
if l, err := s.Apps(); len(l) != 1 {
if err != nil {
t.Fatal(err)
}
t.Fatal("after: app count - expected: 1, actual: ", len(l))
}
// trim every version
count, err = s.Trim(v2.ExactUpdate.Add(time.Duration(20 * time.Second)))
if err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatal("after all: trim should have removed the last one version")
}
if vs, err := s.Versions("", "", ""); len(vs) != 0 {
if err != nil {
t.Fatal(err)
}
t.Fatal("after all: version count - expected: 0, actual: ", len(vs))
}
if l, err := s.Hosts(); len(l) != 0 {
if err != nil {
t.Fatal(err)
}
t.Fatal(l)
t.Fatal("after all: host count - expected: 0, actual: ", len(l))
}
if l, err := s.Apps(); len(l) != 0 {
if err != nil {
t.Fatal(err)
}
t.Fatal(l)
t.Fatal("after all: app count - expected: 0, actual: ", len(l))
}
}
| go |
A new thread of exclusionists being awful and bigoted because the last one is at like 40 tweets.So uh, yeah, starting out strong with the classic homophobic "what's next, pedophiles?!"
1) New Thread Time (Warning VERY long)Cancel Culture vs Imbalanced Power Structures So this discussion brings me to clarify a few things, because twitter SUCKS for nuanced debate, but hey,
Qui qu'a mis ça là pis qu'a pas balayé ?
| english |
AEW President Tony Khan has made a major announcement ahead of tonight's edition of Dynamite. The All Elite Chief has teased a major free agent signing for this weekend's Full Gear pay-per-view event.
AEW has been gaining steam lately, and Khan has made sure to stack the card for the 2023 edition of Full Gear. The pay-per-view will feature MJF defending his world title against Jay White, Sting's last-ever match in Los Angeles, and the highly anticipated Women's World Championship match between Hikaru Shida and 'Timeless' Tony Storm.
But fans can now expect a potentially major moment to go down at the Kia Forum as a free agent signs their contract to become All Elite. Taking to X just moments ago, Tony Khan announced that he has agreed to terms with "one of the world's best wrestlers," and their contract signing will be done live this Saturday at AEW Full Gear.
Check out the announcement below:
Many fans believe there's a good chance that this mystery signee could be former WWE Superstar Mercedes Mone or NJPW icon Will Ospreay, but what are your predictions? Let us know in the comments section below!
| english |
The Executive Committee of the Texas Republican Party voted on Thursday to push ahead and have their state convention in person this month despite a surge in coronavirus cases in Houston, where it will take place.
The committee voted 40 to 20 to host the meeting that about 6,000 people are expected to attend in Houston’s George R. Brown convention center in just over two weeks.
During a lengthy virtual meeting, those opposed to hosting the convention in person said it would endanger older delegates and would disenfranchise many people who would not go out of fear of the virus. About 50% of state delegates who would normally attend have already said they would not go.
But committee members backing the in-person convention said it was a question of personal liberty and canceling it or moving it online would set a terrible precedent for the Republican National Convention, which President Donald Trump has said will take place in person in Florida next month.
“Texas maintained our in-person convention process through World War Two, we met together after our 9/11 terrorist attacks despite the danger in the air,” said executive committee member David Covey.
Another committee member, Dr Robin Armstrong, who spoke from a Houston hospital where he was treating COVID-19 patients, said he supported an in-person convention because of the opportunity to pull it off safely.
“We can be a great example of how we can successfully get this done,” Armstrong said.
The Texas Republican Party has been under pressure to cancel their convention or host it virtually.
The Texas Medical Association, a sponsor of the convention, had urged Republicans not to hold it, and after the committee’s vote, it said it was withdrawing its sponsorship.
“An indoor gathering of thousands of people from all around the state in a city with tens of thousands of active COVID-19 cases poses a significant health risk to conventiongoers, convention workers, health care workers, and the residents of Houston,” said the association’s president, Dr Diana Fite.
Delegates will return to communities across the state, potentially spreading it in areas where there have been few cases, she said.
But several executive committee members said the party should not bow to the pressure.
“In the name of liberty, which right now seems to be in short supply in our state, I say we have our convention in Houston,” said committee member Jill Glover.
Others said the people criticizing them for wanting to host the convention were the same people who supported protests for racial equality that saw thousands gather in cities across the country.
James Dickey, the chairman of the Republican Party in Texas, said before the meeting that measures were being taken to try to host a safe convention, including free masks, hand sanitizer and encouraging people to distance as much as possible.
Texas Governor Greg Abbott, a Republican, on Thursday issued an executive order that masks must be used inside commercial buildings or outside when social distancing is not possible.
Texas has long been a Republican stronghold with Trump winning it by 9 percentage points in 2016, but Democrats have made gains in recent years. The state convention this year will decide the party’s platform and leadership in the state. | english |
Following is the text of Union Minister of State for Home Affairs, Shri Kiren Rijiju’s remarks during the Closing Ceremony of Asian Ministerial Conference for Disaster Risk Reduction (AMCDRR) 2016, here today:
“After three days of extensive deliberations, we have come to an end of this eventful Conference. This is truly an international event, where delegates of 51 countries and 9 UN agencies and numerous International Organisations were present. Besides, representative of civil society, private sector and Local Self Governments, Disaster Management Authorities, and State Governments from India have also participated in the Conference. More than 4000 participants attended the inaugural session.
We started the Conference with an inspirational speech from the Hon’ble Prime Minister of India. He introduced a 10 point agenda for renewing the effort of disaster risk reduction. The 10 point agenda focuses on imbibing the principle of disaster risk management in all developmental sector, work towards risk coverage for all starting from poor households to small and medium enterprises to multinational companies, greater involvement and leadership of women in disaster risk management, investment in risk mapping, leveraging technology to enhance efficiency of our disaster risk management efforts, developing a network of universities to work on disaster issues, utilising the opportunities provided by social media and mobile technologies, building on local capacity & initiative, learning from a disaster and greater cohesion among international agencies in response to disasters.
In the three Ministerial Sessions each participating country outlined their line of action for fulfilling the objective of disaster risk reduction under the Sendai Framework. We have seen that all the countries are committed towards implementing the objective of Sendai Framework.
The deliberations during three Featured Events have provided insightful and practical suggestions on preventing new risks from being created in the Asia-Pacific region. The first featured event on “Risk Resilient Infrastructure for Sustainable Development” has emphasized the need for strengthening and developing standards & norms for new infrastructure, need for capacity building for enforcing standards, risk assessment of new infrastructure being created, use of latest scientific and technological knowledge for reducing risk and evolving a mechanism for continuing collaborative efforts in future to come. The second featured event of “Application of science and technology for prevention of new risks” has outlined the need for applying new scientific and technological tools and knowledge for disaster risk reduction. The third featured event on “Strengthening regional cooperation for implementation of the Sendai Framework in Asia” has deliberated on how regional cooperation has made a difference in advancing DRR agenda in Asia.
We also have 22 Thematic events during the Conference, where stakeholders from Governments, civil society and private stakeholders have dwelt on issues such as Gender sensitive DRR, Child-centred DRR etc., at length.
Recently, the United Nations General Assembly (UNGA) has adopted a resolution to designate ‘November 5’ as World Tsunami Awareness Day every year. The purpose of tsunami day is to raise awareness among people in the world of the dangers of tsunami and stressing the importance of early warning systems in order to mitigate damage. I am glad that we have observed the first Tsunami Awareness day during this Conference.
This Conference has provided a regional platform to all stakeholders to share their ideas for making the whole region disaster resilient. Involvement of all stakeholders is very much required for fulfilling the goal and objective of the Sendai Framework. I am glad that all the stakeholders have been part of this conference and made the stakeholders’ statement.
The next AMCDRR Conference will be hosted by the Republic of Mongolia. I wish them all the success.
With these words, I thank you all for participating in the Conference and making it a great success. I hope that deliberations in the Conference would be useful in managing the risk from natural disaster in better way. I hope your stay in Delhi was pleasant and you will return again to this historic city.
| english |
The steps taken by the Government to curb circulation of Fake Indian Currency Notes (FICN) in the country include stepping up of vigilance by the Border Security Force and Custom authorities to prevent smuggling of fake notes; dissemination of information on security features through print and electronic media and formation of Forged Note Vigilance Cells in all the Head Offices of the banks. Additional security features have also been incorporated in the bank notes in 2005 to make counterfeiting very difficult. To strengthen the security of bank notes further, incorporation of latest security features is underway. A high Level Committee headed by the Union Home Secretary comprising officials from central agencies and other senior police officials has been constituted to monitor and draw a comprehensive strategy to combat FICN. Similar bodies have also been set up in the States. In addition, Government of India have nominated the Central Bureau of Investigation as the Nodal Agency to monitor investigation of fake currency note cases. The RBI has also strengthened the mechanism for detection of counterfeit notes by the Banks.
This information was given by the Minister of State for Finance Shri Namo Narain Meena in a written reply to a question raised in Lok Sabha today.
| english |
<filename>packages/archive-artifacts-s3/package.json
{
"name": "archive-artifacts-s3",
"version": "1.1.0",
"description": "Archive artifacts in S3 and optionally generate presigned links",
"main": "dist/index.js",
"author": "<EMAIL>",
"license": "MIT",
"private": true,
"scripts": {
"build": "tsc && ncc build --source-map ./lib/main.js -o dist"
}
}
| json |
<filename>site/xposeRota/resourcesRota/popups/popups.json<gh_stars>1-10
[
{"t":0.0020, "c":{"LEVEL1FIRSTTIME":true}, "addTutorialGamePlay":[]},
{"t":0.0010, "addLevelIndicator":[]}
] | json |
pub mod fibonacci_heap {
use std::collections::{HashMap, LinkedList};
#[derive(Debug)]
struct Node<T> {
value: T,
children: Vec<Node<T>>,
}
#[derive(Debug)]
pub struct FibonacciHeap<T> {
nodes: LinkedList<Node<T>>,
size: usize,
}
impl<T> FibonacciHeap<T> {
pub fn new() -> Self {
Self {
nodes: LinkedList::new(),
size: 0,
}
}
}
impl<T> FibonacciHeap<T> {
pub fn len(&self) -> usize {
self.size
}
}
impl<T: PartialOrd> FibonacciHeap<T> {
pub fn push(&mut self, value: T) {
let node = Node {
value,
children: vec![],
};
self.push_node(node);
self.size += 1;
}
fn push_node(&mut self, node: Node<T>) {
match self.nodes.iter().next() {
Some(first) => {
if first.value > node.value {
self.nodes.push_front(node);
} else {
self.nodes.push_back(node);
}
}
None => {
self.nodes.push_back(node);
}
}
}
pub fn pop(&mut self) -> Option<T> {
let min = match self.nodes.pop_front() {
Some(min) => min,
None => {
assert_eq!(self.size, 0);
return None;
}
};
let mut node_by_deg = HashMap::new();
let popped = min.value;
for node in min.children {
consolidate(node, &mut node_by_deg);
}
while let Some(node) = self.nodes.pop_front() {
consolidate(node, &mut node_by_deg);
}
assert!(self.nodes.is_empty());
for (_, node) in node_by_deg {
self.push_node(node);
}
assert!(self.size > 0);
self.size -= 1;
Some(popped)
}
pub fn peek(&self) -> Option<&T> {
self.nodes.iter().next().map(|node| &node.value)
}
pub fn merge(self, other: Self) -> Self {
let FibonacciHeap {
nodes: mut a_nodes,
size: a_size,
} = self;
let FibonacciHeap {
nodes: mut b_nodes,
size: b_size,
} = other;
let size = a_size + b_size;
match (a_nodes.pop_front(), b_nodes.pop_front()) {
(Some(a), Some(b)) => {
let (small, large) = if a.value < b.value { (a, b) } else { (b, a) };
a_nodes.append(&mut b_nodes);
a_nodes.push_front(large);
a_nodes.push_front(small);
Self {
nodes: a_nodes,
size,
}
}
(Some(a), None) => {
assert_eq!(a_size, size);
a_nodes.push_front(a);
Self {
nodes: a_nodes,
size,
}
}
(None, Some(b)) => {
assert_eq!(b_size, size);
b_nodes.push_front(b);
Self {
nodes: b_nodes,
size,
}
}
(None, None) => {
assert_eq!(size, 0);
Self {
nodes: LinkedList::new(),
size,
}
}
}
}
}
fn consolidate<T: PartialOrd>(node: Node<T>, node_by_deg: &mut HashMap<usize, Node<T>>) {
let degree = node.children.len();
if let Some(same_degree_node) = node_by_deg.remove(°ree) {
assert_eq!(same_degree_node.children.len(), degree);
let (mut small, large) = if same_degree_node.value < node.value {
(same_degree_node, node)
} else {
(node, same_degree_node)
};
small.children.push(large);
consolidate(small, node_by_deg);
} else {
node_by_deg.insert(degree, node);
}
}
}
#[cfg(test)]
mod tests {
use super::fibonacci_heap::*;
use rand::prelude::*;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
#[test]
fn test_fibonacci_heap() {
let mut min_heap = FibonacciHeap::new();
assert_eq!(min_heap.len(), 0);
min_heap.push(1);
assert_eq!(min_heap.len(), 1);
assert_eq!(min_heap.pop(), Some(1));
assert_eq!(min_heap.len(), 0);
min_heap.push(1);
assert_eq!(min_heap.len(), 1);
min_heap.push(2);
assert_eq!(min_heap.len(), 2);
min_heap.push(3);
assert_eq!(min_heap.len(), 3);
assert_eq!(min_heap.pop(), Some(1));
assert_eq!(min_heap.len(), 2);
assert_eq!(min_heap.pop(), Some(2));
assert_eq!(min_heap.len(), 1);
assert_eq!(min_heap.pop(), Some(3));
assert_eq!(min_heap.len(), 0);
min_heap.push(3);
min_heap.push(2);
min_heap.push(1);
assert_eq!(min_heap.pop(), Some(1));
assert_eq!(min_heap.pop(), Some(2));
assert_eq!(min_heap.pop(), Some(3));
}
#[test]
fn compare_to_binary_heap() {
let mut rng = thread_rng();
let mut max_heap = FibonacciHeap::new();
let mut binary_heap = BinaryHeap::new();
for _ in 0..2000 {
let x = rng.gen::<usize>() % 10;
if x == 0 {
assert_eq!(max_heap.pop().map(|x: Reverse<u8>| x.0), binary_heap.pop());
} else {
let v = rng.gen::<u8>();
max_heap.push(Reverse(v));
binary_heap.push(v);
}
assert_eq!(max_heap.len(), binary_heap.len());
}
}
#[test]
fn merge_heaps() {
let mut rng = thread_rng();
let mut check = vec![];
let mut a_heap = FibonacciHeap::new();
for _ in 0..2000 {
let x = rng.gen_range(0, 100);
a_heap.push(x);
check.push(x);
}
let mut b_heap = FibonacciHeap::new();
for _ in 0..2000 {
let x = rng.gen_range(0, 100);
b_heap.push(x);
check.push(x);
}
a_heap = a_heap.merge(b_heap);
assert_eq!(a_heap.len(), check.len());
check.sort();
check.reverse();
while let Some(v) = check.pop() {
let head = a_heap.pop().unwrap();
assert_eq!(head, v);
}
}
}
| rust |
<reponame>IniterWorker/rumqtt
use super::*;
use alloc::string::String;
use alloc::vec::Vec;
use bytes::{Buf, Bytes};
/// Connection packet initiated by the client
#[derive(Debug, Clone, PartialEq)]
pub struct Connect {
/// Mqtt protocol version
pub protocol: Protocol,
/// Mqtt keep alive time
pub keep_alive: u16,
/// Client Id
pub client_id: String,
/// Clean session. Asks the broker to clear previous state
pub clean_session: bool,
/// Will that broker needs to publish when the client disconnects
pub last_will: Option<LastWill>,
/// Login credentials
pub login: Option<Login>,
/// Properties
pub properties: Option<ConnectProperties>,
}
impl Connect {
pub fn new<S: Into<String>>(id: S) -> Connect {
Connect {
protocol: Protocol::V5,
keep_alive: 10,
properties: None,
client_id: id.into(),
clean_session: true,
last_will: None,
login: None,
}
}
pub fn set_login<U: Into<String>, P: Into<String>>(&mut self, u: U, p: P) -> &mut Connect {
let login = Login {
username: u.into(),
password: <PASSWORD>(),
};
self.login = Some(login);
self
}
pub fn len(&self) -> usize {
let mut len = 2 + "MQTT".len() // protocol name
+ 1 // protocol version
+ 1 // connect flags
+ 2; // keep alive
match &self.properties {
Some(properties) => {
let properties_len = properties.len();
let properties_len_len = len_len(properties_len);
len += properties_len_len + properties_len;
}
None => {
// just 1 byte representing 0 len
len += 1;
}
}
len += 2 + self.client_id.len();
// last will len
if let Some(last_will) = &self.last_will {
len += last_will.len();
}
// username and password len
if let Some(login) = &self.login {
len += login.len();
}
len
}
pub fn read(fixed_header: FixedHeader, mut bytes: Bytes) -> Result<Connect, Error> {
let variable_header_index = fixed_header.fixed_header_len;
bytes.advance(variable_header_index);
// Variable header
let protocol_name = read_mqtt_string(&mut bytes)?;
let protocol_level = read_u8(&mut bytes)?;
if protocol_name != "MQTT" {
return Err(Error::InvalidProtocol);
}
let protocol = match protocol_level {
4 => Protocol::V4,
5 => Protocol::V5,
num => return Err(Error::InvalidProtocolLevel(num)),
};
let connect_flags = read_u8(&mut bytes)?;
let clean_session = (connect_flags & 0b10) != 0;
let keep_alive = read_u16(&mut bytes)?;
// Properties in variable header
let properties = match protocol {
Protocol::V5 => ConnectProperties::read(&mut bytes)?,
Protocol::V4 => None,
};
let client_id = read_mqtt_string(&mut bytes)?;
let last_will = LastWill::read(connect_flags, &mut bytes)?;
let login = Login::read(connect_flags, &mut bytes)?;
let connect = Connect {
protocol,
keep_alive,
properties,
client_id,
clean_session,
last_will,
login,
};
Ok(connect)
}
pub fn write(&self, buffer: &mut BytesMut) -> Result<usize, Error> {
let len = self.len();
buffer.put_u8(0b0001_0000);
let count = write_remaining_length(buffer, len)?;
write_mqtt_string(buffer, "MQTT");
match self.protocol {
Protocol::V4 => buffer.put_u8(0x04),
Protocol::V5 => buffer.put_u8(0x05),
}
let flags_index = 1 + count + 2 + 4 + 1;
let mut connect_flags = 0;
if self.clean_session {
connect_flags |= 0x02;
}
buffer.put_u8(connect_flags);
buffer.put_u16(self.keep_alive);
match &self.properties {
Some(properties) => properties.write(buffer)?,
None => {
write_remaining_length(buffer, 0)?;
}
};
write_mqtt_string(buffer, &self.client_id);
if let Some(last_will) = &self.last_will {
connect_flags |= last_will.write(buffer)?;
}
if let Some(login) = &self.login {
connect_flags |= login.write(buffer);
}
// update connect flags
buffer[flags_index] = connect_flags;
Ok(len)
}
}
/// LastWill that broker forwards on behalf of the client
#[derive(Debug, Clone, PartialEq)]
pub struct LastWill {
pub topic: String,
pub message: Bytes,
pub qos: QoS,
pub retain: bool,
pub properties: Option<WillProperties>,
}
impl LastWill {
pub fn new(
topic: impl Into<String>,
payload: impl Into<Vec<u8>>,
qos: QoS,
retain: bool,
) -> LastWill {
LastWill {
topic: topic.into(),
message: Bytes::from(payload.into()),
qos,
retain,
properties: None,
}
}
fn len(&self) -> usize {
let mut len = 0;
match &self.properties {
Some(properties) => {
let properties_len = properties.len();
let properties_len_len = len_len(properties_len);
len += properties_len_len + properties_len;
}
None => {
// just 1 byte representing 0 len
len += 1;
}
};
len += 2 + self.topic.len() + 2 + self.message.len();
len
}
fn read(connect_flags: u8, mut bytes: &mut Bytes) -> Result<Option<LastWill>, Error> {
let last_will = match connect_flags & 0b100 {
0 if (connect_flags & 0b0011_1000) != 0 => {
return Err(Error::IncorrectPacketFormat);
}
0 => None,
_ => {
// Properties in variable header
let properties = WillProperties::read(&mut bytes)?;
let will_topic = read_mqtt_string(&mut bytes)?;
let will_message = read_mqtt_bytes(&mut bytes)?;
let will_qos = qos((connect_flags & 0b11000) >> 3)?;
Some(LastWill {
topic: will_topic,
message: will_message,
qos: will_qos,
retain: (connect_flags & 0b0010_0000) != 0,
properties,
})
}
};
Ok(last_will)
}
fn write(&self, buffer: &mut BytesMut) -> Result<u8, Error> {
let mut connect_flags = 0;
connect_flags |= 0x04 | (self.qos as u8) << 3;
if self.retain {
connect_flags |= 0x20;
}
match &self.properties {
Some(properties) => properties.write(buffer)?,
None => {
write_remaining_length(buffer, 0)?;
}
};
write_mqtt_string(buffer, &self.topic);
write_mqtt_bytes(buffer, &self.message);
Ok(connect_flags)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WillProperties {
pub delay_interval: Option<u32>,
pub payload_format_indicator: Option<u8>,
pub message_expiry_interval: Option<u32>,
pub content_type: Option<String>,
pub response_topic: Option<String>,
pub correlation_data: Option<Bytes>,
pub user_properties: Vec<(String, String)>,
}
impl WillProperties {
fn len(&self) -> usize {
let mut len = 0;
if self.delay_interval.is_some() {
len += 1 + 4;
}
if self.payload_format_indicator.is_some() {
len += 1 + 1;
}
if self.message_expiry_interval.is_some() {
len += 1 + 4;
}
if let Some(typ) = &self.content_type {
len += 1 + 2 + typ.len()
}
if let Some(topic) = &self.response_topic {
len += 1 + 2 + topic.len()
}
if let Some(data) = &self.correlation_data {
len += 1 + 2 + data.len()
}
for (key, value) in self.user_properties.iter() {
len += 1 + 2 + key.len() + 2 + value.len();
}
len
}
fn read(mut bytes: &mut Bytes) -> Result<Option<WillProperties>, Error> {
let mut delay_interval = None;
let mut payload_format_indicator = None;
let mut message_expiry_interval = None;
let mut content_type = None;
let mut response_topic = None;
let mut correlation_data = None;
let mut user_properties = Vec::new();
let (properties_len_len, properties_len) = length(bytes.iter())?;
bytes.advance(properties_len_len);
if properties_len == 0 {
return Ok(None);
}
let mut cursor = 0;
// read until cursor reaches property length. properties_len = 0 will skip this loop
while cursor < properties_len {
let prop = read_u8(&mut bytes)?;
cursor += 1;
match property(prop)? {
PropertyType::WillDelayInterval => {
delay_interval = Some(read_u32(&mut bytes)?);
cursor += 4;
}
PropertyType::PayloadFormatIndicator => {
payload_format_indicator = Some(read_u8(&mut bytes)?);
cursor += 1;
}
PropertyType::MessageExpiryInterval => {
message_expiry_interval = Some(read_u32(&mut bytes)?);
cursor += 4;
}
PropertyType::ContentType => {
let typ = read_mqtt_string(&mut bytes)?;
cursor += 2 + typ.len();
content_type = Some(typ);
}
PropertyType::ResponseTopic => {
let topic = read_mqtt_string(&mut bytes)?;
cursor += 2 + topic.len();
response_topic = Some(topic);
}
PropertyType::CorrelationData => {
let data = read_mqtt_bytes(&mut bytes)?;
cursor += 2 + data.len();
correlation_data = Some(data);
}
PropertyType::UserProperty => {
let key = read_mqtt_string(&mut bytes)?;
let value = read_mqtt_string(&mut bytes)?;
cursor += 2 + key.len() + 2 + value.len();
user_properties.push((key, value));
}
_ => return Err(Error::InvalidPropertyType(prop)),
}
}
Ok(Some(WillProperties {
delay_interval,
payload_format_indicator,
message_expiry_interval,
content_type,
response_topic,
correlation_data,
user_properties,
}))
}
fn write(&self, buffer: &mut BytesMut) -> Result<(), Error> {
let len = self.len();
write_remaining_length(buffer, len)?;
if let Some(delay_interval) = self.delay_interval {
buffer.put_u8(PropertyType::WillDelayInterval as u8);
buffer.put_u32(delay_interval);
}
if let Some(payload_format_indicator) = self.payload_format_indicator {
buffer.put_u8(PropertyType::PayloadFormatIndicator as u8);
buffer.put_u8(payload_format_indicator);
}
if let Some(message_expiry_interval) = self.message_expiry_interval {
buffer.put_u8(PropertyType::MessageExpiryInterval as u8);
buffer.put_u32(message_expiry_interval);
}
if let Some(typ) = &self.content_type {
buffer.put_u8(PropertyType::ContentType as u8);
write_mqtt_string(buffer, typ);
}
if let Some(topic) = &self.response_topic {
buffer.put_u8(PropertyType::ResponseTopic as u8);
write_mqtt_string(buffer, topic);
}
if let Some(data) = &self.correlation_data {
buffer.put_u8(PropertyType::CorrelationData as u8);
write_mqtt_bytes(buffer, data);
}
for (key, value) in self.user_properties.iter() {
buffer.put_u8(PropertyType::UserProperty as u8);
write_mqtt_string(buffer, key);
write_mqtt_string(buffer, value);
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Login {
pub username: String,
pub password: String,
}
impl Login {
pub fn new<U: Into<String>, P: Into<String>>(u: U, p: P) -> Login {
Login {
username: u.into(),
password: p.into(),
}
}
fn read(connect_flags: u8, mut bytes: &mut Bytes) -> Result<Option<Login>, Error> {
let username = match connect_flags & 0b1000_0000 {
0 => String::new(),
_ => read_mqtt_string(&mut bytes)?,
};
let password = match connect_flags & 0b0100_0000 {
0 => String::new(),
_ => read_mqtt_string(&mut bytes)?,
};
if username.is_empty() && password.is_empty() {
Ok(None)
} else {
Ok(Some(Login { username, password }))
}
}
fn len(&self) -> usize {
let mut len = 0;
if !self.username.is_empty() {
len += 2 + self.username.len();
}
if !self.password.is_empty() {
len += 2 + self.password.len();
}
len
}
fn write(&self, buffer: &mut BytesMut) -> u8 {
let mut connect_flags = 0;
if !self.username.is_empty() {
connect_flags |= 0x80;
write_mqtt_string(buffer, &self.username);
}
if !self.password.is_empty() {
connect_flags |= 0x40;
write_mqtt_string(buffer, &self.password);
}
connect_flags
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ConnectProperties {
/// Expiry interval property after loosing connection
pub session_expiry_interval: Option<u32>,
/// Maximum simultaneous packets
pub receive_maximum: Option<u16>,
/// Maximum packet size
pub max_packet_size: Option<u32>,
/// Maximum mapping integer for a topic
pub topic_alias_max: Option<u16>,
pub request_response_info: Option<u8>,
pub request_problem_info: Option<u8>,
/// List of user properties
pub user_properties: Vec<(String, String)>,
/// Method of authentication
pub authentication_method: Option<String>,
/// Authentication data
pub authentication_data: Option<Bytes>,
}
impl ConnectProperties {
fn _new() -> ConnectProperties {
ConnectProperties {
session_expiry_interval: None,
receive_maximum: None,
max_packet_size: None,
topic_alias_max: None,
request_response_info: None,
request_problem_info: None,
user_properties: Vec::new(),
authentication_method: None,
authentication_data: None,
}
}
fn read(mut bytes: &mut Bytes) -> Result<Option<ConnectProperties>, Error> {
let mut session_expiry_interval = None;
let mut receive_maximum = None;
let mut max_packet_size = None;
let mut topic_alias_max = None;
let mut request_response_info = None;
let mut request_problem_info = None;
let mut user_properties = Vec::new();
let mut authentication_method = None;
let mut authentication_data = None;
let (properties_len_len, properties_len) = length(bytes.iter())?;
bytes.advance(properties_len_len);
if properties_len == 0 {
return Ok(None);
}
let mut cursor = 0;
// read until cursor reaches property length. properties_len = 0 will skip this loop
while cursor < properties_len {
let prop = read_u8(&mut bytes)?;
cursor += 1;
match property(prop)? {
PropertyType::SessionExpiryInterval => {
session_expiry_interval = Some(read_u32(&mut bytes)?);
cursor += 4;
}
PropertyType::ReceiveMaximum => {
receive_maximum = Some(read_u16(&mut bytes)?);
cursor += 2;
}
PropertyType::MaximumPacketSize => {
max_packet_size = Some(read_u32(&mut bytes)?);
cursor += 4;
}
PropertyType::TopicAliasMaximum => {
topic_alias_max = Some(read_u16(&mut bytes)?);
cursor += 2;
}
PropertyType::RequestResponseInformation => {
request_response_info = Some(read_u8(&mut bytes)?);
cursor += 1;
}
PropertyType::RequestProblemInformation => {
request_problem_info = Some(read_u8(&mut bytes)?);
cursor += 1;
}
PropertyType::UserProperty => {
let key = read_mqtt_string(&mut bytes)?;
let value = read_mqtt_string(&mut bytes)?;
cursor += 2 + key.len() + 2 + value.len();
user_properties.push((key, value));
}
PropertyType::AuthenticationMethod => {
let method = read_mqtt_string(&mut bytes)?;
cursor += 2 + method.len();
authentication_method = Some(method);
}
PropertyType::AuthenticationData => {
let data = read_mqtt_bytes(&mut bytes)?;
cursor += 2 + data.len();
authentication_data = Some(data);
}
_ => return Err(Error::InvalidPropertyType(prop)),
}
}
Ok(Some(ConnectProperties {
session_expiry_interval,
receive_maximum,
max_packet_size,
topic_alias_max,
request_response_info,
request_problem_info,
user_properties,
authentication_method,
authentication_data,
}))
}
fn len(&self) -> usize {
let mut len = 0;
if self.session_expiry_interval.is_some() {
len += 1 + 4;
}
if self.receive_maximum.is_some() {
len += 1 + 2;
}
if self.max_packet_size.is_some() {
len += 1 + 4;
}
if self.topic_alias_max.is_some() {
len += 1 + 2;
}
if self.request_response_info.is_some() {
len += 1 + 1;
}
if self.request_problem_info.is_some() {
len += 1 + 1;
}
for (key, value) in self.user_properties.iter() {
len += 1 + 2 + key.len() + 2 + value.len();
}
if let Some(authentication_method) = &self.authentication_method {
len += 1 + 2 + authentication_method.len();
}
if let Some(authentication_data) = &self.authentication_data {
len += 1 + 2 + authentication_data.len();
}
len
}
fn write(&self, buffer: &mut BytesMut) -> Result<(), Error> {
let len = self.len();
write_remaining_length(buffer, len)?;
if let Some(session_expiry_interval) = self.session_expiry_interval {
buffer.put_u8(PropertyType::SessionExpiryInterval as u8);
buffer.put_u32(session_expiry_interval);
}
if let Some(receive_maximum) = self.receive_maximum {
buffer.put_u8(PropertyType::ReceiveMaximum as u8);
buffer.put_u16(receive_maximum);
}
if let Some(max_packet_size) = self.max_packet_size {
buffer.put_u8(PropertyType::MaximumPacketSize as u8);
buffer.put_u32(max_packet_size);
}
if let Some(topic_alias_max) = self.topic_alias_max {
buffer.put_u8(PropertyType::TopicAliasMaximum as u8);
buffer.put_u16(topic_alias_max);
}
if let Some(request_response_info) = self.request_response_info {
buffer.put_u8(PropertyType::RequestResponseInformation as u8);
buffer.put_u8(request_response_info);
}
if let Some(request_problem_info) = self.request_problem_info {
buffer.put_u8(PropertyType::RequestProblemInformation as u8);
buffer.put_u8(request_problem_info);
}
for (key, value) in self.user_properties.iter() {
buffer.put_u8(PropertyType::UserProperty as u8);
write_mqtt_string(buffer, key);
write_mqtt_string(buffer, value);
}
if let Some(authentication_method) = &self.authentication_method {
buffer.put_u8(PropertyType::AuthenticationMethod as u8);
write_mqtt_string(buffer, authentication_method);
}
if let Some(authentication_data) = &self.authentication_data {
buffer.put_u8(PropertyType::AuthenticationData as u8);
write_mqtt_bytes(buffer, authentication_data);
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
fn sample() -> Connect {
let connect_properties = ConnectProperties {
session_expiry_interval: Some(1234),
receive_maximum: Some(432),
max_packet_size: Some(100),
topic_alias_max: Some(456),
request_response_info: Some(1),
request_problem_info: Some(1),
user_properties: vec![("test".to_owned(), "test".to_owned())],
authentication_method: Some("test".to_owned()),
authentication_data: Some(Bytes::from(vec![1, 2, 3, 4])),
};
let will_properties = WillProperties {
delay_interval: Some(1234),
payload_format_indicator: Some(0),
message_expiry_interval: Some(4321),
content_type: Some("test".to_owned()),
response_topic: Some("topic".to_owned()),
correlation_data: Some(Bytes::from(vec![1, 2, 3, 4])),
user_properties: vec![("test".to_owned(), "test".to_owned())],
};
let will = LastWill {
topic: "mydevice/status".to_string(),
message: Bytes::from(vec![b'd', b'e', b'a', b'd']),
qos: QoS::AtMostOnce,
retain: false,
properties: Some(will_properties),
};
let login = Login {
username: "matteo".to_string(),
password: "<PASSWORD>".to_string(),
};
Connect {
protocol: Protocol::V5,
keep_alive: 0,
properties: Some(connect_properties),
client_id: "my-device".to_string(),
clean_session: true,
last_will: Some(will),
login: Some(login),
}
}
fn sample_bytes() -> Vec<u8> {
vec![
0x10, // packet type
0x9d, // remaining len
0x01, // remaining len
00, 04, // 4
0x4d, // M
0x51, // Q
0x54, // T
0x54, // T
0x05, // Level
0xc6, // connect flags
0x00, 0x00, // keep alive
0x2f, // properties len
0x11, 0x00, 0x00, 0x04, 0xd2, // session expiry interval
0x21, 0x01, 0xb0, // receive_maximum
0x27, 0x00, 0x00, 0x00, 0x64, // max packet size
0x22, 0x01, 0xc8, // topic_alias_max
0x19, 0x01, // request_response_info
0x17, 0x01, // request_problem_info
0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
0x74, // user
0x15, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // authentication_method
0x16, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // authentication_data
0x00, 0x09, 0x6d, 0x79, 0x2d, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, // client id
0x2f, // will properties len
0x18, 0x00, 0x00, 0x04, 0xd2, // will delay interval
0x01, 0x00, // payload format indicator
0x02, 0x00, 0x00, 0x10, 0xe1, // message expiry interval
0x03, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // content type
0x08, 0x00, 0x05, 0x74, 0x6f, 0x70, 0x69, 0x63, // response topic
0x09, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // correlation_data
0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
0x74, // will user properties
0x00, 0x0f, 0x6d, 0x79, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x73, 0x74, 0x61,
0x74, 0x75, 0x73, // will topic
0x00, 0x04, 0x64, 0x65, 0x61, 0x64, // will payload
0x00, 0x06, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x6f, // username
0x00, 0x07, 0x63, 0x6f, 0x6c, 0x6c, 0x69, 0x6e, 0x61, // password
]
}
#[test]
fn connect1_parsing_works() {
let mut stream = bytes::BytesMut::new();
let packetstream = &sample_bytes();
stream.extend_from_slice(&packetstream[..]);
let fixed_header = parse_fixed_header(stream.iter()).unwrap();
let connect_bytes = stream.split_to(fixed_header.frame_length()).freeze();
let connect = Connect::read(fixed_header, connect_bytes).unwrap();
assert_eq!(connect, sample());
}
#[test]
fn connect1_encoding_works() {
let connect = sample();
let mut buf = BytesMut::new();
connect.write(&mut buf).unwrap();
assert_eq!(&buf[..], sample_bytes());
}
fn sample2() -> Connect {
Connect {
protocol: Protocol::V5,
keep_alive: 10,
properties: None,
client_id: "hackathonmqtt5test".to_owned(),
clean_session: true,
last_will: None,
login: None,
}
}
fn sample2_bytes() -> Vec<u8> {
vec![
0x10, // packet type
0x1f, 0x00, // remaining len
0x04, // 4
0x4d, 0x51, 0x54, 0x54, // MQTT
0x05, // level
0x02, // connect flags
0x00, 0x0a, // keep alive
0x00, 0x00, 0x12, 0x68, 0x61, 0x63, 0x6b, 0x61, 0x74, 0x68, 0x6f, 0x6e, 0x6d, 0x71,
0x74, 0x74, 0x35, 0x74, 0x65, 0x73, 0x74, // payload
0x10, 0x11, 0x12, // extra bytes in the stream
]
}
#[test]
fn connect2_parsing_works() {
let mut stream = bytes::BytesMut::new();
let packetstream = &sample2_bytes();
stream.extend_from_slice(&packetstream[..]);
let fixed_header = parse_fixed_header(stream.iter()).unwrap();
let connect_bytes = stream.split_to(fixed_header.frame_length()).freeze();
let connect = Connect::read(fixed_header, connect_bytes).unwrap();
assert_eq!(connect, sample2());
}
#[test]
fn connect2_encoding_works() {
let connect = sample2();
let mut buf = BytesMut::new();
connect.write(&mut buf).unwrap();
let expected = sample2_bytes();
assert_eq!(&buf[..], &expected[0..(expected.len() - 3)]);
}
fn sample3() -> Connect {
let connect_properties = ConnectProperties {
session_expiry_interval: Some(1234),
receive_maximum: Some(432),
max_packet_size: Some(100),
topic_alias_max: Some(456),
request_response_info: Some(1),
request_problem_info: Some(1),
user_properties: vec![("test".to_owned(), "test".to_owned())],
authentication_method: Some("test".to_owned()),
authentication_data: Some(Bytes::from(vec![1, 2, 3, 4])),
};
let will = LastWill {
topic: "mydevice/status".to_string(),
message: Bytes::from(vec![b'd', b'e', b'a', b'd']),
qos: QoS::AtMostOnce,
retain: false,
properties: None,
};
let login = Login {
username: "matteo".to_string(),
password: "<PASSWORD>".to_string(),
};
Connect {
protocol: Protocol::V5,
keep_alive: 0,
properties: Some(connect_properties),
client_id: "my-device".to_string(),
clean_session: true,
last_will: Some(will),
login: Some(login),
}
}
fn sample3_bytes() -> Vec<u8> {
vec![
0x10, 0x6e, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x05, 0xc6, 0x00, 0x00, 0x2f, 0x11,
0x00, 0x00, 0x04, 0xd2, 0x21, 0x01, 0xb0, 0x27, 0x00, 0x00, 0x00, 0x64, 0x22, 0x01,
0xc8, 0x19, 0x01, 0x17, 0x01, 0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04,
0x74, 0x65, 0x73, 0x74, 0x15, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x16, 0x00, 0x04,
0x01, 0x02, 0x03, 0x04, 0x00, 0x09, 0x6d, 0x79, 0x2d, 0x64, 0x65, 0x76, 0x69, 0x63,
0x65, 0x00, 0x00, 0x0f, 0x6d, 0x79, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x73,
0x74, 0x61, 0x74, 0x75, 0x73, 0x00, 0x04, 0x64, 0x65, 0x61, 0x64, 0x00, 0x06, 0x6d,
0x61, 0x74, 0x74, 0x65, 0x6f, 0x00, 0x07, 0x63, 0x6f, 0x6c, 0x6c, 0x69, 0x6e, 0x61,
]
}
#[test]
fn connect3_parsing_works() {
let mut stream = bytes::BytesMut::new();
let packetstream = &sample3_bytes();
stream.extend_from_slice(&packetstream[..]);
let fixed_header = parse_fixed_header(stream.iter()).unwrap();
let connect_bytes = stream.split_to(fixed_header.frame_length()).freeze();
let connect = Connect::read(fixed_header, connect_bytes).unwrap();
assert_eq!(connect, sample3());
}
#[test]
fn connect3_encoding_works() {
let connect = sample3();
let mut buf = BytesMut::new();
connect.write(&mut buf).unwrap();
let expected = sample3_bytes();
assert_eq!(&buf[..], &expected[0..(expected.len())]);
}
#[test]
fn missing_properties_are_encoded() {}
}
| rust |
The pull-along wood-toy group was asked to work on a variation of a simple eccentric mechanism to save crucial time in developing and proving new mechanisms. Lifestyle wire product group was asked to look into the lifestyle products and were asked to decode their beauty with words. The wire group was also advised to make scaled or 1:1 models in Al or GI wire as imagining and visualizing the drawn wire forms was difficult. Along with writing the design brief, all students were suggested to make the quick-scaled models of their ideas.
The main intention of letting students to decide on the topic in the given framework and also letting them to select the user and user profile for their topic was to develop an ownership of the project and end result. As Prof. Bapat told them the end result of the Introduction to Product Design assignment will be their own creation and in one way their own child which should have that ‘WOW’ factor.
While the students were writing their initial design brief with user at its center stage Prof. Bapat also shared gadgets and toys from his collection of objects like - LED lamps, pull-along wooden toys, and pull-along plastic toys. He also shared his previous real-time design consultancy work for industries, with students. The intention of showing various interesting gadgets, contraptions and case studies to students was to widen their vision and to make them appreciate design in a way that only a designer can. Prof. Bapat also made a silent point about the expected output quality of the Introduction to Product Design assignment by showing his own old case studies to students.
| english |
<reponame>abondar24/deepLearnPython<filename>scikit/sk_random_forest_pca.py<gh_stars>1-10
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
def plot_decision_regions(x, y, classifier, resolution=0.02):
# setup marker gen and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot decision surface
x1_min, x1_max = x[:, 0].min() - 1, x[:, 0].max() + 1
x2_min, x2_max = x[:, 1].min() - 1, x[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
z = z.reshape(xx1.shape)
plt.contourf(xx1, xx2, z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.xlim(xx2.min(), xx2.max())
# plot class samples
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=x[y == cl, 0], y=x[y == cl, 1],
alpha=0.8, c=cmap(idx),
marker=markers[idx], label=cl)
wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)
x, y = wine.iloc[:, 1:].values, wine.iloc[:, 0].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)
# standardize d-dim set
stdsc = StandardScaler()
x_train_std = stdsc.fit_transform(x_train)
x_test_std = stdsc.transform(x_test)
pca = PCA(n_components=2)
lr = LogisticRegression()
x_train_pca = pca.fit_transform(x_train_std)
x_test_pca = pca.fit_transform(x_test_std)
lr.fit(x_train_pca, y_train)
plot_decision_regions(x_train_pca, y_train, classifier=lr)
plt.xlabel('PC 1')
plt.ylabel('PC 2')
plt.legend(loc='lower left')
plt.show()
plot_decision_regions(x_test_pca, y_test, classifier=lr)
plt.xlabel('PC 1')
plt.ylabel('PC 2')
plt.legend(loc='lower left')
plt.show() | python |
<reponame>yogalnuri/AskForDateSalesforce
{
"name": "API.AI Spark integration",
"description": "Api.ai Spark integration allows you to create Spark bots with natural language understanding based on Api.ai technology.",
"repository": "https://github.com/api-ai/apiai-spark-bot",
"logo": "http://xvir.github.io/img/apiai.png",
"keywords": ["api.ai", "spark", "natural language"],
"env": {
"APP_NAME": {
"description": "Copy App Name here",
"value": ""
},
"APIAI_ACCESS_TOKEN": {
"description": "Client access token for Api.ai",
"value": ""
},
"SPARK_ACCESS_TOKEN": {
"description": "Spark Access Token",
"value": ""
},
"APIAI_LANG": {
"description": "Agent language",
"value": "en",
"required": false
}
},
"engines": {
"node": "6.9.4"
}
}
| json |
<filename>twitch/json/v116226069.json
{"fps": {"audio_only": 0, "medium": 29.99897530652345, "mobile": 29.99999795470364, "low": 29.99999795470364, "chunked": 59.99651890559464, "high": 29.999588895431565}, "broadcast_id": 24296029440, "tag_list": "", "animated_preview_url": "https://vod-storyboards.twitch.tv/52aef6a02b_twitchplayspokemon_24296029440_587172342/storyboards/116226069-strip-0.jpg", "recorded_at": "2017-01-21T06:59:48Z", "status": "recorded", "created_at": "2017-01-21T07:00:05Z", "length": 4889, "published_at": "2017-01-21T07:00:05Z", "url": "https://www.twitch.tv/videos/116226069", "channel": {"logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/twitchplayspokemon-profile_image-62a73e208674dfec-300x300.png", "url": "https://www.twitch.tv/twitchplayspokemon", "mature": false, "game": "Twitch Plays", "broadcaster_language": "en", "_id": 56648155, "updated_at": "2017-07-20T16:06:44.568739Z", "partner": false, "followers": 376420, "created_at": "2014-02-12T10:44:17.97081Z", "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/twitchplayspokemon-channel_offline_image-a7bb14003c78d01d-1920x1080.png", "status": "Twitch Plays Pokemon (Enter moves via chat!!!)", "broadcaster_type": "", "description": "I'm a robot playing Pokemon, I don't know what I'm doing, tell me which buttons to press.", "display_name": "TwitchPlaysPokemon", "language": "en", "profile_banner_background_color": "", "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/twitchplayspokemon-profile_banner-2d67334f0890560a-480.png", "views": 72913126, "name": "twitchplayspokemon"}, "game": "Twitch Plays", "resolutions": {"medium": "852x480", "low": "640x360", "chunked": "1920x1080", "mobile": "400x226", "high": "1280x720"}, "viewable_at": null, "thumbnails": {"medium": [{"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-320x180.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb1-320x180.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb2-320x180.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb3-320x180.jpg"}], "template": [{"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-{width}x{height}.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb1-{width}x{height}.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb2-{width}x{height}.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb3-{width}x{height}.jpg"}], "small": [{"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-80x45.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb1-80x45.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb2-80x45.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb3-80x45.jpg"}], "large": [{"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-640x360.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb1-640x360.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb2-640x360.jpg"}, {"type": "generated", "url": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb3-640x360.jpg"}]}, "preview": {"medium": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-320x180.jpg", "template": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-{width}x{height}.jpg", "small": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-80x45.jpg", "large": "https://static-cdn.jtvnw.net/s3_vods/52aef6a02b_twitchplayspokemon_24296029440_587172342/thumb/thumb0-640x360.jpg"}, "description_html": null, "_id": "v116226069", "broadcast_type": "archive", "language": "en", "views": 45, "title": "Twitch Plays Pokemon (Enter button presses via chat!!!)", "viewable": "public", "description": null} | json |
President Bidya Devi Bhandari has congratulated Muskan Khatun for winning the prestigious International Women of Courage Award for 2021.
Khatun, an acid attack survivor, was selected for the US-based award for her continuous campaign against acid attack.
Teenager Khatun of Birgunj Metropolitan City-5 in Parsa district survived an acid attack with critical burns on her face, chest and hands, on September 6, 2019. Her acquainted neighbours had thrown acid on her while she was on her way to school.
In a tweet today, the President applauded the adolescent for transforming the pain she suffered from an acid attack into strength and thanked the US government for recognising her efforts and courage. | english |
Markets, roads and bazaars in Pakistan's Mohmand tribal district on Tuesday remained closed as people took to the streets in large numbers against the prolonged power load-shedding, Pakistan-based Dawn newspaper reported.
Load-shedding is the interruption of electric supply to avoid excessive load on the generating plant.
According to Dawn, the protesters blocked the main Peshawar-Bajaur road in front of Ghalanai grid station. They complained that the duration of power load shedding in rural areas was increased up to 23 hours per day during the past few months. They also alleged that the supply of electricity to several remote areas of the district was suspended.
The call for the protest was given by the 'Electricity Action Committee'. The members of the committee include Malik Nisar Ahmed Halimzai, Malik Mohammad Ali Shinwari, Fazal Hadi, Safdar Khan, Zahid Khan, Abdul Majeed, Ayaz Khan and Salamat Shah.
People staged protests in all the major markets of Mian Mandi, Chanda, Ghalanai and Ekkaghund.
Local political leaders and tribal elders while addressing the protesters, said that Warsak and Mohmand dams were built near the district but people of the area were deprived of electricity.
They said that the Mohmand people were deprived of their constitutional and legal rights. They alleged that the natural resources of Mohmand were being usurped.
The speakers said that people provided their land for Mohmand Dam at a very low price so it was the responsibility of Wapda authorities to give royalty to locals. They said that an uninterrupted power supply to the area should be ensured, according to Dawn.
The protestors threatened to intensify their protest if their demands were not accepted. They said that they would stage a sit-in in front of grid stations.
Some of the enraged protesters tried to attack the grid station in Ghalanai but local leaders stopped them. After a 10-hour protest, the executive engineer of Wapda and Deputy Commissioner Dr Mohammad Ehtishamul Haq held talks with the protesters.
The officials assured the protestors that a committee would be formed to arrange negotiations with Tesco's chief for controlling load-shedding.
After signing a written agreement with the officials, protesters dispersed peacefully. According to the agreement, Wapda will ensure a power supply for at least seven hours from all the feeders in Mohmand.
Asian Lite International recently reported that in the past nine years, Pakistan has faced eight major power outages and the latest major power outage on January 23 serves as a warning of the dystopian future that awaits Islamabad.
The people of Pakistan are caught in the middle, unable to understand why the country keeps failing to introduce structural reforms and if they will ever live in a country where there is not a constant threat of power breakdowns, gas outages, and water scarcity.
The Ministry of Energy confirmed that the system frequency of the national power grid "went down" at 07:00 hours on January 23 morning and caused a "widespread" breakdown in the power system across the country.
The power outage affected the entire Pakistan, including Karachi, Lahore, Quetta, Peshawar, and Islamabad, reported Asian Lite International.
READ ALSO: | english |
package main
import (
"bufio"
"flag"
"fmt"
"math"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
)
const (
namespace = "mcrouter"
)
// Exporter collects metrics from a mcrouter server.
type Exporter struct {
server string
timeout time.Duration
server_stats bool
up *prometheus.Desc
startTime *prometheus.Desc
version *prometheus.Desc
commandArgs *prometheus.Desc
commands *prometheus.Desc
commandCount *prometheus.Desc
commandOut *prometheus.Desc
commandOutFailover *prometheus.Desc
commandOutShadow *prometheus.Desc
commandOutAll *prometheus.Desc
commandOutCount *prometheus.Desc
configFailures *prometheus.Desc
configLastAttempt *prometheus.Desc
configLastSuccess *prometheus.Desc
devNullRequests *prometheus.Desc
duration *prometheus.Desc
fibersAllocated *prometheus.Desc
proxyReqsProcessing *prometheus.Desc
proxyReqsWaiting *prometheus.Desc
requests *prometheus.Desc
requestCount *prometheus.Desc
results *prometheus.Desc
resultCount *prometheus.Desc
resultFailover *prometheus.Desc
resultShadow *prometheus.Desc
resultAll *prometheus.Desc
resultAllCount *prometheus.Desc
clients *prometheus.Desc
servers *prometheus.Desc
cpuSeconds *prometheus.Desc
residentMemory *prometheus.Desc
virtualMemory *prometheus.Desc
asynclogRequests *prometheus.Desc
serverDuration *prometheus.Desc
serverProxyReqsProcessing *prometheus.Desc
serverProxyInflightReqs *prometheus.Desc
serverProxyRetransRatio *prometheus.Desc
serverMemcachedStored *prometheus.Desc
serverMemcachedNotStored *prometheus.Desc
serverMemcachedFound *prometheus.Desc
serverMemcachedNotFound *prometheus.Desc
serverMemcachedDeleted *prometheus.Desc
serverMemcachedTouched *prometheus.Desc
serverMemcachedExists *prometheus.Desc
serverMemcachedRemoteError *prometheus.Desc
serverMemcachedConnectTimeout *prometheus.Desc
serverMemcachedTimeout *prometheus.Desc
serverMemcachedSoftTKO *prometheus.Desc
serverMemcachedHardTKO *prometheus.Desc
}
// NewExporter returns an initialized exporter.
func NewExporter(server string, timeout time.Duration, server_stats bool) *Exporter {
return &Exporter{
server: server,
timeout: timeout,
server_stats: server_stats,
up: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "up"),
"Could the mcrouter server be reached.",
nil,
nil,
),
startTime: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "start_time_seconds"),
"UNIX timestamp of mcrouter startup time.",
nil,
nil,
),
version: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "version"),
"Version of mcrouter binary.",
[]string{"version"},
nil,
),
commandArgs: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "commandargs"),
"Command line arguments used to start mcrouter.",
[]string{"commandargs"},
nil,
),
commands: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "commands"),
"Average number of received requests per second drilled down by operation.",
[]string{"cmd"},
nil,
),
commandCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "command_count"),
"Total number of received requests drilled down by operation.",
[]string{"cmd"},
nil,
),
commandOut: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "command_out"),
"Average number of sent normal (non-shadow, non-failover) requests per second drilled down by operation.",
[]string{"cmd"},
nil,
),
commandOutFailover: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "command_out_failover"),
"Average number of sent failover requests per second drilled down by operation.",
[]string{"cmd"},
nil,
),
commandOutShadow: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "command_out_shadow"),
"Number of sent shadow requests per second drilled down by operation.",
[]string{"cmd"},
nil,
),
commandOutAll: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "command_out_all"),
"Total number of sent requests per second (failover + shadow + normal)",
[]string{"cmd"},
nil,
),
commandOutCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "command_out_count"),
"Total number of sent requests per second drilled down by operation.",
[]string{"cmd"},
nil,
),
configFailures: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "config_failures"),
"How many times mcrouter failed to reconfigure (if > 0 and growing, check the config is valid).",
nil,
nil,
),
configLastAttempt: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "config_last_attempt"),
"UNIX timestamp of last time mcrouter tried to reconfigure.",
nil,
nil,
),
configLastSuccess: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "config_last_success"),
"UNIX timestamp of last time mcrouter reconfigured successfully.",
nil,
nil,
),
devNullRequests: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "dev_null_requests"),
"Number of requests sent to DevNullRoute.",
nil,
nil,
),
duration: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "duration_us"),
"Average time of processing a request (i.e. receiving request and sending a reply).",
nil,
nil,
),
fibersAllocated: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "fibers_allocated"),
"Number of fibers (lightweight threads) created by mcrouter.",
nil,
nil,
),
proxyReqsProcessing: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "proxy_reqs_processing"),
"Requests mcrouter started routing but didn't receive a reply yet.",
nil,
nil,
),
proxyReqsWaiting: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "proxy_reqs_waiting"),
"Requests queued up and not routed yet.",
nil,
nil,
),
clients: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "clients"),
"Number of connected clients.",
nil,
nil,
),
servers: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "servers"),
"Number of connected memcached servers.",
[]string{"state"},
nil,
),
requests: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "request"),
"TODO.",
[]string{"type"},
nil,
),
requestCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "request_count"),
"TODO",
[]string{"type"},
nil,
),
// Result
results: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "results"),
"Average number of replies per second received for normal requests drilled down by reply result.",
[]string{"reply"},
nil,
),
resultCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "result_count"),
"Total number of replies received drilled down by reply result",
[]string{"reply"},
nil,
),
resultFailover: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "result_failover"),
"Average number of replies per second received for failover requests drilled down by result.",
[]string{"reply"},
nil,
),
resultShadow: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "result_shadow"),
"Average number of replies per second received for shadow requests drilled down by result.",
[]string{"reply"},
nil,
),
resultAll: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "result_all"),
"Average number of replies per second received for requests drilled down by reply result.",
[]string{"reply"},
nil,
),
resultAllCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "result_all_count"),
"TODO.",
[]string{"reply"},
nil,
),
cpuSeconds: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "cpu_seconds_total"),
"Number of seconds mcrouter spent on CPU.",
nil,
nil,
),
residentMemory: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "resident_memory_bytes"),
"Number of bytes of resident memory.",
nil,
nil,
),
virtualMemory: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "virtual_memory_bytes"),
"Number of bytes of virtual memory.",
nil,
nil,
),
asynclogRequests: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "asynclog_requests"),
"Number of failed deletes written to spool file.",
nil,
nil,
),
serverDuration: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_duration_us"),
"Average time of processing a request per-server (i.e. receiving request and sending a reply).",
[]string{"server"},
nil,
),
serverProxyReqsProcessing: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_proxy_reqs_processing"),
"Requests mcrouter started routing but didn't receive a reply yet (per-server metric)",
[]string{"server"},
nil,
),
serverProxyInflightReqs: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_proxy_reqs_waiting"),
"Requests queued up and not routed yet (per-server metric)",
[]string{"server"},
nil,
),
serverProxyRetransRatio: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_proxy_reqs_retrans_ratio"),
"Requests mcrouter started but that required retransmission.",
[]string{"server"},
nil,
),
serverMemcachedStored: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_stored_count"),
"Number of memcached STORED replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedNotStored: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_not_stored_count"),
"Number of memcached NOT_STORED replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedFound: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_found_count"),
"Number of memcached FOUND replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedNotFound: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_not_found_count"),
"Number of memcached NOT_FOUND replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedDeleted: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_deleted_count"),
"Number of memcached DELETED replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedTouched: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_touched_count"),
"Number of memcached TOUCHED replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedExists: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_exists_count"),
"Number of memcached EXISTS replies (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedRemoteError: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_remote_error_count"),
"Number of memcached remote errors (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedConnectTimeout: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_connect_timeout_count"),
"Number of memcached connect timeouts (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedTimeout: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_timeout_count"),
"Number of memcached timeouts (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedSoftTKO: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_soft_tko"),
"Whether or not memcached has been marked as Soft TKO (per-server metric).",
[]string{"server"},
nil,
),
serverMemcachedHardTKO: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "server_memcached_hard_tko"),
"Whether or not memcached has been marked as Hard TKO (per-server metric).",
[]string{"server"},
nil,
),
}
}
// Describe describes all the metrics exported by the mcrouter exporter. It
// implements prometheus.Collector.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- e.up
ch <- e.startTime
ch <- e.version
ch <- e.commands
ch <- e.commandCount
ch <- e.commandOut
ch <- e.commandOutFailover
ch <- e.commandOutShadow
ch <- e.commandOutAll
ch <- e.commandOutCount
ch <- e.configFailures
ch <- e.configLastAttempt
ch <- e.configLastSuccess
ch <- e.devNullRequests
ch <- e.duration
ch <- e.fibersAllocated
ch <- e.proxyReqsProcessing
ch <- e.proxyReqsWaiting
ch <- e.requests
ch <- e.requestCount
ch <- e.results
ch <- e.resultCount
ch <- e.resultFailover
ch <- e.resultShadow
ch <- e.resultAll
ch <- e.resultAllCount
ch <- e.clients
ch <- e.servers
ch <- e.cpuSeconds
ch <- e.residentMemory
ch <- e.virtualMemory
ch <- e.asynclogRequests
if e.server_stats {
ch <- e.serverDuration
ch <- e.serverProxyReqsProcessing
ch <- e.serverProxyInflightReqs
ch <- e.serverProxyRetransRatio
ch <- e.serverMemcachedStored
ch <- e.serverMemcachedNotStored
ch <- e.serverMemcachedFound
ch <- e.serverMemcachedNotFound
ch <- e.serverMemcachedDeleted
ch <- e.serverMemcachedTouched
ch <- e.serverMemcachedExists
ch <- e.serverMemcachedRemoteError
ch <- e.serverMemcachedConnectTimeout
ch <- e.serverMemcachedTimeout
ch <- e.serverMemcachedSoftTKO
ch <- e.serverMemcachedHardTKO
}
}
// Collect fetches the statistics from the configured mcrouter server, and
// delivers them as Prometheus metrics. It implements prometheus.Collector.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
network := "tcp"
if strings.Contains(e.server, "/") {
network = "unix"
}
conn, err := net.DialTimeout(network, e.server, e.timeout)
if err != nil {
ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 0)
log.Errorf("Failed to collect stats from mcrouter: %s.", err)
return
}
defer conn.Close()
s, err := getStats(conn)
if err != nil {
ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 0)
log.Errorf("Failed to collect stats from mcrouter: %s", err)
return
}
ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 1)
// Parse basic stats
ch <- prometheus.MustNewConstMetric(e.startTime, prometheus.CounterValue, parse(s, "start_time"))
ch <- prometheus.MustNewConstMetric(e.version, prometheus.GaugeValue, 1, s["version"])
ch <- prometheus.MustNewConstMetric(e.commandArgs, prometheus.GaugeValue, 1, s["commandargs"])
// Commands
for _, op := range []string{"add", "append", "cas", "decr", "flushall", "flushre", "get", "gets", "incr", "metaget", "prepend", "replace", "touch", "set", "delete", "lease_get", "lease_set"} {
key := "cmd_" + op
ch <- prometheus.MustNewConstMetric(
e.commands, prometheus.GaugeValue, parse(s, key), op)
ch <- prometheus.MustNewConstMetric(
e.commandCount, prometheus.CounterValue, parse(s, key+"_count"), op)
ch <- prometheus.MustNewConstMetric(
e.commandOut, prometheus.CounterValue, parse(s, key+"_out"), op)
ch <- prometheus.MustNewConstMetric(
e.commandOutAll, prometheus.CounterValue, parse(s, key+"_out_all"), op)
}
ch <- prometheus.MustNewConstMetric(
e.devNullRequests, prometheus.CounterValue, parse(s, "dev_null_requests"))
ch <- prometheus.MustNewConstMetric(
e.duration, prometheus.GaugeValue, parse(s, "duration_us"))
ch <- prometheus.MustNewConstMetric(
e.fibersAllocated, prometheus.GaugeValue, parse(s, "fibers_allocated"))
ch <- prometheus.MustNewConstMetric(
e.proxyReqsProcessing, prometheus.GaugeValue, parse(s, "proxy_reqs_processing"))
ch <- prometheus.MustNewConstMetric(
e.proxyReqsWaiting, prometheus.GaugeValue, parse(s, "proxy_reqs_waiting"))
// Config
ch <- prometheus.MustNewConstMetric(
e.configFailures, prometheus.CounterValue, parse(s, "config_failures"))
ch <- prometheus.MustNewConstMetric(
e.configLastAttempt, prometheus.GaugeValue, parse(s, "config_last_attempt"))
ch <- prometheus.MustNewConstMetric(
e.configLastSuccess, prometheus.GaugeValue, parse(s, "config_last_success"))
// Request
for _, op := range []string{"error", "replied", "sent", "success"} {
key := "request_" + op
ch <- prometheus.MustNewConstMetric(
e.requests, prometheus.GaugeValue, parse(s, key), op)
ch <- prometheus.MustNewConstMetric(
e.requestCount, prometheus.CounterValue, parse(s, key+"_count"), op)
}
// Result Reply
// See ProxyRequestLogger.cpp
for _, op := range []string{"busy", "connect_error", "connect_timeout", "data_timeout", "error", "local_error", "tko"} {
key := "result_" + op
ch <- prometheus.MustNewConstMetric(
e.results, prometheus.GaugeValue, parse(s, key), op)
ch <- prometheus.MustNewConstMetric(
e.resultCount, prometheus.CounterValue, parse(s, key+"_count"), op)
ch <- prometheus.MustNewConstMetric(
e.resultAll, prometheus.GaugeValue, parse(s, key+"_all"), op)
ch <- prometheus.MustNewConstMetric(
e.resultAllCount, prometheus.CounterValue, parse(s, key+"_all_count"), op)
}
// Clients
ch <- prometheus.MustNewConstMetric(
e.clients, prometheus.CounterValue, parse(s, "num_clients"))
// Servers
for _, op := range []string{"closed", "down", "new", "up"} {
key := "num_servers_" + op
ch <- prometheus.MustNewConstMetric(
e.servers, prometheus.GaugeValue, parse(s, key), op)
}
// Process stats
ch <- prometheus.MustNewConstMetric(
e.cpuSeconds, prometheus.CounterValue, parse(s, "ps_user_time_sec")+parse(s, "ps_system_time_sec"))
ch <- prometheus.MustNewConstMetric(e.residentMemory, prometheus.CounterValue, parse(s, "ps_rss"))
ch <- prometheus.MustNewConstMetric(e.virtualMemory, prometheus.CounterValue, parse(s, "ps_vsize"))
ch <- prometheus.MustNewConstMetric(e.asynclogRequests, prometheus.CounterValue, parse(s, "asynclog_requests"))
if e.server_stats {
// Per-server stats
s1, err := getServerStats(conn)
if err != nil {
ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 0)
log.Errorf("Failed to collect server stats from mcrouter: %s", err)
return
}
for server, metrics := range s1 {
ch <- prometheus.MustNewConstMetric(
e.serverDuration, prometheus.GaugeValue, parse(metrics, "avg_latency_us"), server)
ch <- prometheus.MustNewConstMetric(
e.serverProxyReqsProcessing, prometheus.GaugeValue, parse(metrics, "pending_reqs"), server)
ch <- prometheus.MustNewConstMetric(
e.serverProxyInflightReqs, prometheus.GaugeValue, parse(metrics, "inflight_reqs"), server)
ch <- prometheus.MustNewConstMetric(
e.serverProxyRetransRatio, prometheus.GaugeValue, parse(metrics, "avg_retrans_ratio"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedStored, prometheus.CounterValue, parse(metrics, "stored"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedNotStored, prometheus.CounterValue, parse(metrics, "notstored"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedFound, prometheus.CounterValue, parse(metrics, "found"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedNotFound, prometheus.CounterValue, parse(metrics, "notfound"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedDeleted, prometheus.CounterValue, parse(metrics, "deleted"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedTouched, prometheus.CounterValue, parse(metrics, "touched"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedExists, prometheus.CounterValue, parse(metrics, "exists"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedRemoteError, prometheus.CounterValue, parse(metrics, "remote_error"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedConnectTimeout, prometheus.CounterValue, parse(metrics, "connect_timeout"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedTimeout, prometheus.CounterValue, parse(metrics, "timeout"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedSoftTKO, prometheus.GaugeValue, parse(metrics, "soft_tko"), server)
ch <- prometheus.MustNewConstMetric(
e.serverMemcachedHardTKO, prometheus.GaugeValue, parse(metrics, "hard_tko"), server)
}
}
}
// Parse a string into a 64 bit float suitable for Prometheus
func parse(stats map[string]string, key string) float64 {
val, ok := stats[key]
if !ok {
return 0.0
}
v, err := strconv.ParseFloat(val, 64)
if err != nil {
log.Errorf("Failed to parse %s %q: %s", key, stats[key], err)
v = math.NaN()
}
return v
}
// Get stats from mcrouter using a basic TCP connection
func getStats(conn net.Conn) (map[string]string, error) {
m := make(map[string]string)
fmt.Fprintf(conn, "stats all\r\n")
reader := bufio.NewReader(conn)
// Iterate over the lines and extract the metric name and value(s)
// example lines:
// [STAT version 37.0.0
// [STAT commandargs --option1 value --flag2
// END
for {
line, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
if line == "END\r\n" {
break
}
// Split the line into 3 components, anything after the metric name should
// be considered as the metric value.
result := strings.SplitN(line, " ", 3)
value := strings.TrimRight(result[2], "\r\n")
m[result[1]] = value
}
return m, nil
}
// Get detailed per-server stats from mcrouter using a basic TCP connection
func getServerStats(conn net.Conn) (map[string]map[string]string, error) {
m := make(map[string]map[string]string)
fmt.Fprintf(conn, "stats servers\r\n")
reader := bufio.NewReader(conn)
// Iterate over the lines and extract the metric name and value(s)
// example lines:
// STAT 10.64.16.110:11211:ascii:plain:notcompressed-1000 avg_latency_us:302.991
// pending_reqs:0 inflight_reqs:0 avg_retrans_ratio:0 max_retrans_ratio:0
// min_retrans_ratio:0 up:5; deleted:4875 touched:33069 found:112675373
// notfound:3493823 notstored:149776 stored:3250883 exists:2653 remote_error:32
// END
// In the same line there are two type of info:
// * per-server stats about latency, requests, etc.. up to the ';' - (ProxyDestinationBase states)
// * per-server breakdown of the memcached responses (STORED, DELETED, etc..) - (Carbon results)
// The memcached responses are listed in carbon_result.thrift, and they are returned/appended only
// when > 0. Special logic needs to be implemented then to set the ones not diplayed to zero,
// since Prometheus doesn't really like metrics appearing/disappearing.
for {
line, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
if line == "END\r\n" {
break
}
line_sanitized := strings.TrimRight(line, "\r\n")
// Split the line in 2 macro-components
result := strings.SplitN(line_sanitized, ";", 2)
server_metrics := strings.Split(strings.Trim(result[0], " "), " ")
// WARNING: the memcached's result states (from ';' onward) might not be
// available all the times, since they are added only if some data is present.
// There are use cases, like mcrouter just started without any commands processed,
// that do not expose any result. The exporter needs to add some defensive code
// to avoid panic states.
memcached_responses_metrics := []string{}
if len(result) == 2 {
memcached_responses_metrics = strings.Split(strings.Trim(result[1], " "), " ")
}
// The server id is always the second element of the row (after STAT),
// and it will be used as label in all the metrics
server_id := server_metrics[1]
m[server_id] = make(map[string]string)
// The following for loops assume that the two lines to parse
// have the format: metric1:value1 metric2:value2 etc..
// There are some special cases:
// 1) the server_id string is the only exception since it is composed
// by more than one ':'.
// 2) 'soft_tko' and 'hard_tko' are server flags that appear only when one
// shard is marked with that state, so they can be present or not
// depending on the runtime environment. To keep a stable metric,
// their values are initialized to 0 and turned to 1 only when the
// flag is found.
SOFT_TKO_STATE := "soft_tko"
HARD_TKO_STATE := "hard_tko"
m[server_id][SOFT_TKO_STATE] = "0"
m[server_id][HARD_TKO_STATE] = "0"
for i := 2; i < len(server_metrics); i++ {
if server_metrics[i] == SOFT_TKO_STATE || server_metrics[i] == HARD_TKO_STATE {
m[server_id][server_metrics[i]] = "1"
} else {
metric_value := strings.SplitN(server_metrics[i], ":", 2)
if len(metric_value) == 2 {
m[server_id][metric_value[0]] = metric_value[1]
}
}
}
// See carbon_result.thrift in mcrouter's codebase
// and also https://github.com/facebook/mcrouter/wiki/Error-Handling
memcached_states := []string{"deleted", "touched", "found", "notfound", "notstored", "stored",
"exists", "timeout", "connect_timeout", "remote_error",
}
// Set all the metrics to zero to create a baseline. mcrouter reports only
// the states that have values > 0, but Prometheus doesn't like metrics
// appearing and disappearing.
for _, state := range memcached_states {
m[server_id][state] = "0"
}
for i := 0; i < len(memcached_responses_metrics); i++ {
metric_value := strings.SplitN(memcached_responses_metrics[i], ":", 2)
if len(metric_value) == 2 {
m[server_id][metric_value[0]] = metric_value[1]
}
}
}
return m, nil
}
func main() {
var (
address = flag.String("mcrouter.address", "localhost:5000", "mcrouter server TCP address (tcp4/tcp6) or UNIX socket path")
timeout = flag.Duration("mcrouter.timeout", time.Second, "mcrouter connect timeout.")
showVersion = flag.Bool("version", false, "Print version information.")
listenAddress = flag.String("web.listen-address", ":9442", "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
serverMetrics = flag.Bool("mcrouter.server_metrics", false, "Collect per-server metrics.")
)
flag.Parse()
if *showVersion {
fmt.Fprintln(os.Stdout, version.Print("mcrouter_exporter"))
os.Exit(0)
}
log.Infoln("Starting mcrouter_exporter", version.Info())
log.Infoln("Build context", version.BuildContext())
prometheus.MustRegister(NewExporter(*address, *timeout, *serverMetrics))
http.Handle(*metricsPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//nolint:errcheck
w.Write([]byte(`<html>
<head><title>Mcrouter Exporter</title></head>
<body>
<h1>Mcrouter Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
log.Infoln("Starting HTTP server on", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
| go |
The stone dust which covers Nivedita Mishra becomes her second skin, as the Delhi-based sculptor is at ease in it. Since childhood, Mishra has had a direct connection with stone, allowing nothing to come in the way. Collecting pebbles wherever she goes, even here in Chandigarh, Mishra has a “piece” of the place with her, as she gives new form to yet another block of stone as part of the ongoing stone sculpture workshop by the Chandigarh Lalit Kala Akademi.
An alumnus of the Delhi College of Art, Mishra, who is originally from Odisha, says stone was always her first choice for expressing herself, simply because of its dimension. “Many were surprised with the choice of my medium, as I was a woman, and I took it as a challenge. As a woman I am a creator, I can create a child and a sculpture. You can feel a stone’s presence, all you need is a hammer and chisel to shape it and initiate a conversation with others,” says Mishra. Human relationships, their varied faces, and forms are the subjects that Mishra constantly expresses in her work, inspired by family, friends, her contemporaries and people around her.
“I remember when my sister was pregnant; I did a series of works on pregnancy, followed by those inspired by the events in my family and then my own children. There is so much to say, and stone as a medium allows you to create with freedom. Selling my first few works was so tough, for I felt I was giving away my own children,” adds Mishra.
Be it her series on stone and spiritualism, music in stone, or the theme of relationships and nature, Mishra says she is constantly searching for herself in her sculptures. Sketching the entire concept of her work first, or demonstrating it to her helpers in the clay she constantly carries and shapes, Mishra says it is very important that people around her understand her work, which becomes even more important in a public art project like this one.
“What you convey is most important and I believe art must be open to understanding for the public, and as an artist I am responsible for it. The public should feel a part of the work and the window must be open for them, especially since people and nature are my source for inspiration. ” A work that is close to her heart is the National Police Memorial in Delhi, which has been designed and conceptualised by prominent sculptor Adwaita Charan Gadanayak, Mishra’s husband. “I was part of the project, which was such a gratifying and moving experience,” Mishra speaks of the 30-foot tall sculpture in black granite.
Here, connecting her work to the space she is in, Mishra is working on the concept of the celestial and human touch or bond. As the hand was an important element of Le Corbusier’s architecture, Mishra is creating two hands, one of a goddess and one human, with the fingers intertwined. “If you feel the touch, then I am successful as an artist. The moon, sky, movement of the clouds are close to my heart and appear in my work often, as I give different treatments to what I see and feel inside, constantly thinking what could have been, for I am never satisfied as an artist,” says Mishra. | english |
{"content": "Tories Policies 4 Sale \"Tory are getting 4,000 new donations every month \u201cfrom a wide range of people\u201d <NAME> on the #marrshow", "entities": [{"offset": 103, "type": "ne", "id": 2, "entity": "<NAME>"}, {"entity": "tory", "type": "party keyword", "id": 3, "offset": 24}, {"offset": 0, "type": "party keyword", "id": 4, "entity": "tories"}], "topics": [{"topic": "economy", "id": 1}], "tweet_id": "564361305990381569"} | json |
{
"id": "drybraised_salted_fish",
"name": "<NAME>",
"description": "Du poisson séché qui a été lentement grillé au feu de charbon. Le poisson s'est imprégné de l'odeur du vent de mer pendant son séchage la nuit précédente, ce qui lui donne un goût salé après la grillade. Ce dernier est très apprécié des Inazumiens vivant en bord de mer.",
"rarity": 1,
"ingredients": [
{
"id": "fish",
"name": "Poisson",
"amount": 1
},
{
"id": "salt",
"name": "Sel",
"amount": 1
}
],
"dish_type": "Récupération",
"results": {
"suspicious": {
"name": "<NAME> (suspect)",
"description": "Poisson séché grillé lentement au charbon de bois. Il ne reste plus la moindre goutte d'humidité dans le poisson, ce qui donne l'impression de mastiquer du bois. On peut à peine faire la différence entre la chair et les arêtes.",
"effect": "Restaure 8 % des PV max du personnage sélectionné et 800 PV supplémentaires."
},
"normal": {
"name": "<NAME>",
"description": "Du poisson séché qui a été lentement grillé au feu de charbon. Le poisson s'est imprégné de l'odeur du vent de mer pendant son séchage la nuit précédente, ce qui lui donne un goût salé après la grillade. Ce dernier est très apprécié des Inazumiens vivant en bord de mer.",
"effect": "Restaure 9 % des PV max du personnage sélectionné et 1 000 PV supplémentaires."
},
"delicious": {
"name": "<NAME> (délicieux)",
"description": "Poisson séché grillé lentement au charbon de bois. Les graisses riches suintent lorsque le poisson rencontre le gril, et au son du grésillement, il se revêt d'un manteau doré bruni. La viande est ferme mais délicieuse, et la sensation en bouche est délicate. Tel est le don inégalé de la mer.",
"effect": "Restaure 10 % des PV max du personnage sélectionné et 1 200 PV supplémentaires."
},
"special": {
"name": "Beauté de tout temps",
"description": "Spécialité culinaire de Kaedehara Kazuha. Fabriquée à partir de poisson séché pendant la nuit sur le navire. Kazuha prétend que ce sont des poissons ordinaires. Mais cette saveur... C'est sûrement ça le sens de la nature omniprésente, non ?",
"effect": "Restaure 16 % des PV max du personnage sélectionné et 1 350 PV supplémentaires.",
"character": {
"id": "kaedehara_kazuha",
"name": "<NAME>"
}
}
}
}
| json |
from app.utils.permissions import IsBotPermission
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from .serializers import UserSerializer
User = get_user_model()
class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
lookup_field = "username"
permission_classes = [IsBotPermission]
def get_queryset(self, *args, **kwargs):
return self.queryset.filter(id=self.request.user.id)
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = UserSerializer(request.user, context={"request": request})
return Response(status=status.HTTP_200_OK, data=serializer.data)
@action(url_path="get-or-create/(?P<external_id>[^/.]+)", detail=False, methods=["POST"])
def get_or_create(self, request, external_id):
user = User.objects.filter(external_id=external_id).first()
if not user:
user = User()
data = {**{"username": external_id, "external_id": external_id}, **request.data}
serializer = self.get_serializer(user, data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
| python |
import React from 'react'
import { Row, Col, Box, Button, Inputs } from 'adminlte-2-react'
import CashDropQr from './qr-code'
import fetch from 'isomorphic-fetch'
import PropTypes from 'prop-types'
const { Text, Select } = Inputs
let _this
class CashDropForm extends React.Component {
constructor (props) {
super(props)
_this = this
this.state = {
radiusOptions: ['15 min', 'Urban', 'Regional', 'Continental'],
selectedRadius: 1000,
rewardOptions: [1],
selectedReward: 1,
cashdropPins: '',
cashdropTokenName: '',
cashdropTokenTicker: '',
cashdropTokenUrl: '',
errMsg: '',
showQr: '',
amount: ''
}
}
render () {
const {
rewardOptions,
selectedReward,
errMsg,
showQr,
amount,
address
} = _this.state
return (
<Row>
<Col xs={12} className="cashdrop-form">
<Box className="text-center cashdrop-box border-none">
<Row>
<Col sm={12}>
<h3>
<span>
{showQr
? 'Pay this address and amount to add your pins to the game!'
: 'Add your tokens to the map!'}
</span>
</h3>
</Col>
{!showQr && (
<section>
<Col sm={12} className="text-center mt-2 mb-1">
<Row>
<Col sm={12}>
<Text
id="cashdrop-token-name"
name="cashdropTokenName"
label="Merchant Name"
placeholder="Enter merchant name."
labelPosition="above"
onChange={_this.handleUpdate}
/>
</Col>
<Col sm={12}>
<Text
id="cashdrop-token-ticker"
name="cashdropTokenTicker"
label="Token Ticker"
placeholder="Enter token ticker."
labelPosition="above"
onChange={_this.handleUpdate}
/>
</Col>
<Col sm={12}>
<Text
id="cashdrop-token-url"
name="cashdropTokenUrl"
label="Website"
placeholder="Enter token url."
labelPosition="above"
onChange={_this.handleUpdate}
/>
</Col>
</Row>
</Col>
<Col sm={12} className="text-center mb-2">
{!showQr && (
<Button
text="Submit"
type="primary"
className="btn-lg"
onClick={_this.handleSubmit}
/>
)}
</Col>
</section>
)}
<Col sm={12} className="text-center">
{errMsg && <p className="error-color">{errMsg}</p>}
</Col>
<Col sm={12} className="text-center">
{showQr && (
<CashDropQr
handleOnHide={_this.hideQr}
amount={amount}
address={address}
bchWallet={_this.props.bchWallet}
updateBalance={_this.props.updateBalance}
/>
)}
</Col>
</Row>
</Box>
</Col>
</Row>
)
}
async componentDidMount () {}
handleUpdate (event) {
const value = event.target.value
_this.setState({
[event.target.name]: value
})
}
async handleSubmit () {
try {
// Validate form
_this.validateInputs()
const { mapInfo } = _this.props
/**
*
* TODO: Validate mapInfo
*/
/*
*
*
* SUBMIT
*
* */
// Get the pin coordinates from the map
const pinCoords = _this.props.handlePinCoordinates()
console.log('Pin coordinates :', pinCoords)
const cashdropPins = pinCoords.length
const sats = cashdropPins * 10000
const {
cashdropTokenName,
cashdropTokenTicker,
cashdropTokenUrl
} = _this.state
const SERVER = process.env.SERVER
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
campaign: {
drops: pinCoords,
merchant: 'test',
lat: mapInfo.latitude,
long: mapInfo.longitude,
radius: mapInfo.radius,
tokenName: cashdropTokenName,
tokenTicker: cashdropTokenTicker,
tokenUrl: cashdropTokenUrl,
tokenQty: cashdropPins,
satsToPay: sats
}
})
}
const data = await fetch(`${SERVER}/campaigns`, options)
const campaign = await data.json()
console.log(campaign)
console.log(`Pay this BCH address: ${campaign.campaign.bchAddr}`)
if (!campaign.campaign.bchAddr) {
throw new Error('Address not found!')
}
_this.setState({
showQr: true,
amount: _this.convertToBch(sats),
address: campaign.campaign.bchAddr
})
_this.resetForm()
} catch (error) {
_this.setState({
errMsg: error.message
})
}
}
validateInputs () {
const {
cashdropPins,
cashdropTokenName,
cashdropTokenTicker,
cashdropTokenUrl
} = _this.state
// Get the number of pins placed on the map.
const pinCoords = _this.props.handlePinCoordinates()
const pinsNumber = pinCoords.length
if (!pinsNumber) {
throw new Error('Please place some pins on the map')
}
if (pinsNumber <= 0) {
throw new Error('Amount must be greater than 1')
}
if (!cashdropTokenName) {
throw new Error('Must add a merchant name')
}
if (!cashdropTokenTicker) {
throw new Error('Must add a token ticker')
}
if (!cashdropTokenUrl) {
throw new Error('Must add a token url')
}
}
hideQr () {
_this.setState({
showQr: false
})
}
convertToBch (amount) {
try {
const bch = (amount / 100000000).toFixed(8)
return bch
} catch (error) {
console.error(error)
}
}
resetForm () {
_this.setState({
selectedRadius: 1000,
selectedReward: 1,
cashdropPins: '',
cashdropTokenName: '',
cashdropTokenTicker: '',
cashdropTokenUrl: '',
errMsg: ''
})
}
}
CashDropForm.propTypes = {
mapInfo: PropTypes.object,
handlePinCoordinates: PropTypes.func.isRequired, // Function to get the pin data from the map
bchWallet: PropTypes.object,
updateBalance: PropTypes.func.isRequired
}
export default CashDropForm
| javascript |
{% extends "home/header.html" %}
{% block content %}
{% load custom_tags %}
<a class="row mar-b-20 btn btn-warning" href="{% url 'home:dashboard' %}">Back</a>
{% if 'faculty' in request.session %}
<h3 class="mar-b-20">{{ studnt_data.name }}</h3>
<table class="table table-hover table-stripped">
<!--<tr>-->
<!--<th>Name:</th>-->
<!--<td>{{ studnt_data.name }}</td>-->
<!--</tr>-->
<tr>
<th>Gender:</th>
<td>{% if studnt_data.gender == 1 %}{{ 'Male' }}{% else %}{{ 'Female' }}{% endif %}</td>
</tr>
<tr>
<th>Mother's Name:</th>
<td>{{ studnt_data.mother_name }}</td>
</tr>
<tr>
<th>Univ Roll No.:</th>
<td>{{ studnt_data.roll_no }}</td>
</tr>
<tr>
<th>E-mail:</th>
<td>{{ studnt_data.email }}</td>
</tr>
<tr>
<th>Phone No.:</th>
<td>{{ studnt_data.phone }}</td>
</tr>
</table>
<h3>Attendance Day-wise:</h3>
<div class="row mar-l-15">
{% for attendance in attendance_data %}
{% if attendance.faculty == request.session.faculty %}
<p class="col-md-6"><span class="mar-r-15">{{ forloop.counter }}</span>{{attendance.attendance_date}}</p>
{% with attendance.student|split:"," as attndnc %}
{% with studnt_data.pk|int_to_str as studnt_id %}
{% if studnt_id in attndnc %}
<p class="col-md-6"><span style="background-color: rgb(163, 228, 163)">{{ ' Present ' }}</span></p>
{% else %}
<p class="col-md-6">{{ ' Absent ' }}</p>
{% endif %}
{% endwith %}
{% endwith %}
{% endif %}
<div class="clearfix"></div>
{% endfor %}
</div>
{% else %}
<p>You are not authorised to access the page.</p>
{% endif %}
{% endblock %} | html |
<reponame>Datenschule/schulscraper-data
{"name":"<NAME>","id":"NI-74743-1","address":"Stettiner Str. 3, 26316 Varel","school_type":"Bildungsangebot","phone":"04451 9505-0","email":"<EMAIL>","programs":{"programs":[]},"state":"NI","lon":8.139017,"lat":53.401888}
| json |
<gh_stars>1-10
import { createStyles, Theme, withStyles, WithStyles } from '@material-ui/core/styles'
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'
import ChevronRightIcon from '@material-ui/icons/ChevronRight'
import * as React from 'react'
import { Link, LinkProps } from 'react-router-dom'
import { List, Divider, Drawer, IconButton, ListItem, ListItemIcon, ListItemText } from '@material-ui/core'
import { Home, FormatPaint, CameraAlt, Transform, PlaylistPlay, FileDownload, ImageAspectRatio } from '@material-ui/icons';
import { ListItemProps } from '@material-ui/core/ListItem';
// import { ToolbarSeparator } from '@material-ui/';
export const drawerWidth = 240;
const styles = (theme: Theme) => createStyles({
drawerPaper: {
position: 'relative',
width: drawerWidth,
paddingLeft: '10px',
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
...theme.mixins.toolbar,
}
})
const drawer = (props: WithStyles<typeof styles> & { open: boolean, handleDrawerClose: () => void }) => (
<Drawer
variant="persistent"
anchor="left"
open={props.open}
classes={{
paper: props.classes.drawerPaper,
}}
>
<div className={props.classes.drawerHeader}>
<IconButton onClick={props.handleDrawerClose}>
{props.theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</div>
<Divider />
<List component="nav" dense={true}>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="home" {...props} onClick={() => { }} />}>
<ListItemIcon>
<Home />
</ListItemIcon>
<ListItemText primary="Home" />
</ListItem>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="imageFrame" {...props} />}>
<ListItemIcon>
<ImageAspectRatio />
</ListItemIcon>
<ListItemText primary="Image easy effects" />
</ListItem>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="convertDemo" {...props} />}>
<ListItemIcon>
<Transform />
</ListItemIcon>
<ListItemText primary="Convert playground" />
</ListItem>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="encipher" {...props} />}>
<ListItemIcon>
<Transform />
</ListItemIcon>
<ListItemText primary="Cypher images" />
</ListItem>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="imageInformation" {...props} />}>
<ListItemIcon>
<Transform />
</ListItemIcon>
<ListItemText primary="Extract image information" />
</ListItem>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="convertFormat" {...props} />}>
<ListItemIcon>
<Transform />
</ListItemIcon>
<ListItemText primary="Convert Format" />
</ListItem>
{/* <ListItem> <ToolbarSeparator></ToolbarSeparator></ListItem> */}
{/* <ListItem component={(props: ListItemProps & LinkProps) => <Link to="compositeCommands" {...props} />}>
<ListItemIcon>
<PlaylistPlay />
</ListItemIcon>
<ListItemText primary="Composite Commands" />
</ListItem>
<ListItem component={(props: ListItemProps & LinkProps) => <Link to="SimpleCLITransformationEditor" {...props} />}>
<ListItemIcon>
<FormatPaint />
</ListItemIcon>
<ListItemText primary="Basic CLI transformation tool" />
</ListItem> */}
{/* <ListItem component={(props: ListItemProps & LinkProps) => <Link to="TestImages" {...props} />}>
<ListItemIcon>
<CameraAlt />
</ListItemIcon>
<ListItemText primary="See test images" />
</ListItem> */}
{/* <ListItem component={(props: ListItemProps & LinkProps) => <Link to="download" {...props} />}>
<ListItemIcon>
<FileDownload />
</ListItemIcon>
<ListItemText primary="Download Results" />
</ListItem> */}
{/* <ListItem component={(props: ListItemProps & LinkProps) => <Link to="ImageHandleEditorTest" {...props} />}>
<ListItemIcon>
<FileDownload />
</ListItemIcon>
<ListItemText primary="ImageHandleEditorTest" />
</ListItem> */}
</List>
</Drawer>
)
export default withStyles(styles, { withTheme: true })(drawer)
| typescript |
#include <bts/blockchain/exceptions.hpp>
#include <bts/blockchain/market_engine.hpp>
#include <fc/real128.hpp>
#include <algorithm>
namespace bts { namespace blockchain { namespace detail {
#define MARKET_ENGINE_PASS_PROCESS_MARGIN_CALLS 0
#define MARKET_ENGINE_PASS_PROCESS_EXPIRED_COVERS 1
#define MARKET_ENGINE_PASS_PROCESS_ASK_ORDERS 2
#define MARKET_ENGINE_PASS_COUNT 3
market_engine::market_engine( const pending_chain_state_ptr ps, const chain_database_impl& cdi )
:_pending_state(ps),_db_impl(cdi)
{
_pending_state = std::make_shared<pending_chain_state>( ps );
_prior_state = ps;
//_eval_state._pending_state = _pending_state;
}
bool market_engine::execute( asset_id_type quote_id, asset_id_type base_id, const fc::time_point_sec timestamp )
{
try
{
_quote_id = quote_id;
_base_id = base_id;
oasset_record quote_asset = _pending_state->get_asset_record( _quote_id );
oasset_record base_asset = _pending_state->get_asset_record( _base_id );
FC_ASSERT( quote_asset.valid() && base_asset.valid() );
FC_ASSERT( !quote_asset->flag_is_active( asset_record::halted_markets ) );
FC_ASSERT( !base_asset->flag_is_active( asset_record::halted_markets ) );
// The order book is sorted from low to high price. So to get the last item (highest bid),
// we need to go to the first item in the next market class and then back up one
const price current_pair = price( 0, quote_id, base_id );
const price next_pair = (base_id+1 == quote_id) ? price( 0, quote_id+1, 0 ) : price( 0, quote_id, base_id+1 );
_bid_itr = _db_impl._bid_db.lower_bound( market_index_key( next_pair ) );
_ask_itr = _db_impl._ask_db.lower_bound( market_index_key( price( 0, quote_id, base_id ) ) );
int last_orders_filled = -1;
asset trading_volume(0, base_id);
price opening_price, closing_price, highest_price, lowest_price;
if( !_ask_itr.valid() ) _ask_itr = _db_impl._ask_db.begin();
//
// following logic depends on the internals of cached_level_map class.
// if lower_bound() argument is past the end of the collection,
// then result will point to end() which has valid() == false
//
// so we need to decrement the returned iterator, but
// decrement operator may be undefined for end(), so we
// special-case the result.
//
// one day we should write a greatest_element_below() method
// for our DB class to implement the logic we're doing
// directly here
//
// decrementing begin() OTOH is well-defined and returns
// end() which is invalid, thus overflow of --itr here is
// ok as long as we check valid() later
//
if( _bid_itr.valid() ) --_bid_itr;
else _bid_itr = _db_impl._bid_db.last();
// Market issued assets cannot match until the first time there is a median feed; assume feed price base id 0
if( quote_asset->is_market_issued() && base_asset->id == 0 )
{
_feed_price = _db_impl.self->get_active_feed_price( _quote_id );
const omarket_status market_stat = _pending_state->get_market_status( _quote_id, _base_id );
if( (!market_stat.valid() || !market_stat->last_valid_feed_price.valid()) && !_feed_price.valid() )
FC_CAPTURE_AND_THROW( insufficient_feeds, (quote_id)(base_id) );
}
/*
if( _feed_price.valid() )
_short_at_limit_itr = std::set< pair<price,market_index_key> >::reverse_iterator(
_db_impl._short_limit_index.lower_bound(
std::make_pair( *_feed_price, market_index_key( current_pair ))
));
*/
_current_bid.reset();
for( _current_pass=0; _current_pass<MARKET_ENGINE_PASS_COUNT; _current_pass++ )
{
_current_ask.reset();
while( true )
{
if( (!_current_bid.valid()) || (_current_bid->get_balance().amount <= 0) )
{
ilog("getting next bid");
get_next_bid();
if( (!_current_bid.valid()) )
{
ilog("market engine terminating due to no more bids");
break;
}
idump( (_current_bid) );
}
if( (!_current_ask.valid()) || (_current_ask->get_balance().amount <= 0) )
{
ilog("getting next ask");
get_next_ask();
if( (!_current_ask.valid()) )
{
ilog("market engine terminating due to no more asks");
break;
}
idump( (_current_ask) );
}
// Make sure that at least one order was matched every time we enter the loop
FC_ASSERT( _orders_filled != last_orders_filled, "We appear caught in an order matching loop!" );
last_orders_filled = _orders_filled;
// Initialize the market transaction
market_transaction mtrx;
mtrx.bid_owner = _current_bid->get_owner();
mtrx.ask_owner = _current_ask->get_owner();
if( _feed_price )
{
mtrx.bid_price = _current_bid->get_price( *_feed_price );
mtrx.ask_price = _current_ask->get_price( *_feed_price );
}
else
{
mtrx.bid_price = _current_bid->get_price();
mtrx.ask_price = _current_ask->get_price();
}
mtrx.bid_type = _current_bid->type;
mtrx.ask_type = _current_ask->type;
if( mtrx.bid_price < mtrx.ask_price )
{
wlog( "bid_price ${b} < ask_price ${a}; exit market loop", ("b",mtrx.bid_price)("a",mtrx.ask_price) );
break;
}
if( _current_ask->type == ask_order && _current_bid->type == bid_order )
{
const asset bid_quantity_xts = _current_bid->get_quantity( _feed_price ? *_feed_price : price() );
const asset ask_quantity_xts = _current_ask->get_quantity( _feed_price ? *_feed_price : price() );
const asset quantity_xts = std::min( bid_quantity_xts, ask_quantity_xts );
// Everyone gets the price they asked for
mtrx.ask_received = quantity_xts * mtrx.ask_price;
mtrx.bid_paid = quantity_xts * mtrx.bid_price;
mtrx.ask_paid = quantity_xts;
mtrx.bid_received = quantity_xts;
// Handle rounding errors
if( quantity_xts == bid_quantity_xts )
mtrx.bid_paid = _current_bid->get_balance();
if( quantity_xts == ask_quantity_xts )
mtrx.ask_paid = _current_ask->get_balance();
mtrx.quote_fees = mtrx.bid_paid - mtrx.ask_received;
pay_current_bid( mtrx, *base_asset, *quote_asset );
pay_current_ask( mtrx, *base_asset, *quote_asset );
}
push_market_transaction( mtrx );
quote_asset->collected_fees += mtrx.quote_fees.amount;
base_asset->collected_fees += mtrx.base_fees.amount;
if( mtrx.ask_received.asset_id == 0 )
trading_volume += mtrx.ask_received;
else if( mtrx.bid_received.asset_id == 0 )
trading_volume += mtrx.bid_received;
if( opening_price == price() )
opening_price = mtrx.bid_price;
closing_price = mtrx.bid_price;
//
// Remark: only prices of matched orders are used to update market history
//
// Because of prioritization, we need the second comparison
// in the following if statements. Ask-side orders are
// only sorted by price within a single pass.
//
if( highest_price == price() || highest_price < mtrx.bid_price)
highest_price = mtrx.bid_price;
// TODO check here: store lowest ask price or lowest bid price?
if( lowest_price == price() || lowest_price > mtrx.ask_price)
lowest_price = mtrx.ask_price;
}
}
// update any fees collected
_pending_state->store_asset_record( *quote_asset );
_pending_state->store_asset_record( *base_asset );
// Update market status and market history
{
omarket_status market_stat = _pending_state->get_market_status( _quote_id, _base_id );
if( !market_stat.valid() ) market_stat = market_status( _quote_id, _base_id );
market_stat->last_error.reset();
_pending_state->store_market_status( *market_stat );
// Remark: only prices of matched orders be updated to market history
update_market_history( trading_volume, highest_price, lowest_price, opening_price, closing_price, timestamp );
}
//_eval_state.update_delegate_votes();
_pending_state->apply_changes();
return true;
}
catch( const fc::exception& e )
{
wlog( "error executing market ${quote} / ${base}\n ${e}", ("quote",quote_id)("base",base_id)("e",e.to_detail_string()) );
omarket_status market_stat = _prior_state->get_market_status( _quote_id, _base_id );
if( !market_stat.valid() ) market_stat = market_status( _quote_id, _base_id );
market_stat->last_error = e;
_prior_state->store_market_status( *market_stat );
}
return false;
} // execute(...)
void market_engine::push_market_transaction( const market_transaction& mtrx )
{ try {
// If not an automatic market cancel
if( mtrx.ask_paid.amount != 0
|| mtrx.ask_received.amount != 0
|| mtrx.bid_received.asset_id != 0
|| mtrx.bid_paid.amount != 0 )
{
FC_ASSERT( mtrx.bid_paid.amount >= 0 );
FC_ASSERT( mtrx.ask_paid.amount >= 0 );
FC_ASSERT( mtrx.bid_received.amount >= 0 );
FC_ASSERT( mtrx.ask_received.amount>= 0 );
FC_ASSERT( mtrx.bid_paid >= mtrx.ask_received );
FC_ASSERT( mtrx.ask_paid >= mtrx.bid_received );
FC_ASSERT( mtrx.quote_fees.amount >= 0 );
FC_ASSERT( mtrx.base_fees.amount >= 0 );
}
_market_transactions.push_back(mtrx);
} FC_CAPTURE_AND_RETHROW( (mtrx) ) }
void market_engine::pay_current_bid( market_transaction& mtrx, asset_record& base_asset, asset_record& quote_asset )
{ try {
FC_ASSERT( _current_bid->type == bid_order );
FC_ASSERT( mtrx.bid_type == bid_order );
_current_bid->state.balance -= mtrx.bid_paid.amount;
FC_ASSERT( _current_bid->state.balance >= 0 );
FC_ASSERT( base_asset.address_is_whitelisted( mtrx.bid_owner ) );
auto bid_payout = _pending_state->get_balance_record(
withdraw_condition( withdraw_with_signature(mtrx.bid_owner), _base_id ).get_address() );
if( !bid_payout )
bid_payout = balance_record( mtrx.bid_owner, asset(0,_base_id), 0 );
share_type issuer_fee = 0;
if( base_asset.market_fee_rate > 0 )
{
FC_ASSERT( base_asset.market_fee_rate <= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE );
issuer_fee = mtrx.bid_received.amount * base_asset.market_fee_rate;
issuer_fee /= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE;
}
mtrx.base_fees.amount += issuer_fee;
mtrx.bid_received.amount -= issuer_fee;
bid_payout->balance += mtrx.bid_received.amount;
bid_payout->last_update = _pending_state->now();
bid_payout->deposit_date = _pending_state->now();
_pending_state->store_balance_record( *bid_payout );
// if the balance is less than 1 XTS then it gets collected as fees.
if( (_current_bid->get_quote_quantity() * mtrx.bid_price).amount == 0 )
{
mtrx.quote_fees.amount += _current_bid->state.balance;
_current_bid->state.balance = 0;
}
_pending_state->store_bid_record( _current_bid->market_index, _current_bid->state );
} FC_CAPTURE_AND_RETHROW( (mtrx) ) }
void market_engine::pay_current_ask( market_transaction& mtrx, asset_record& base_asset, asset_record& quote_asset )
{ try {
FC_ASSERT( _current_ask->type == ask_order );
FC_ASSERT( mtrx.ask_type == ask_order );
_current_ask->state.balance -= mtrx.ask_paid.amount;
FC_ASSERT( _current_ask->state.balance >= 0, "balance: ${b}", ("b",_current_ask->state.balance) );
FC_ASSERT( quote_asset.address_is_whitelisted( mtrx.ask_owner ) );
auto ask_balance_address = withdraw_condition( withdraw_with_signature(mtrx.ask_owner), _quote_id ).get_address();
auto ask_payout = _pending_state->get_balance_record( ask_balance_address );
if( !ask_payout )
ask_payout = balance_record( mtrx.ask_owner, asset(0,_quote_id), 0 );
share_type issuer_fee = 0;
if( quote_asset.market_fee_rate > 0 )
{
FC_ASSERT( quote_asset.market_fee_rate <= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE );
issuer_fee = mtrx.ask_received.amount * quote_asset.market_fee_rate;
issuer_fee /= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE;
}
mtrx.quote_fees.amount += issuer_fee;
mtrx.ask_received.amount -= issuer_fee;
ask_payout->balance += mtrx.ask_received.amount;
ask_payout->last_update = _pending_state->now();
ask_payout->deposit_date = _pending_state->now();
_pending_state->store_balance_record( *ask_payout );
// if the balance is less than 1 XTS * PRICE < .001 USD XTS goes to fees
if( (_current_ask->get_quantity() * mtrx.ask_price).amount == 0 )
{
mtrx.base_fees.amount += _current_ask->state.balance;
_current_ask->state.balance = 0;
}
_pending_state->store_ask_record( _current_ask->market_index, _current_ask->state );
} FC_CAPTURE_AND_RETHROW( (mtrx) ) } // pay_current_ask
/**
* if there are bids above feed price, take the max of the two
* if there are shorts at the feed take the next short
* if there are bids with prices above the limit of the current short they should take priority
* - shorts need to be ordered by limit first, then interest rate *WHEN* the limit is
* lower than the feed price.
*/
bool market_engine::get_next_bid()
{ try {
if( _current_bid && _current_bid->get_quantity().amount > 0 )
return _current_bid.valid();
++_orders_filled;
_current_bid.reset();
optional<market_order> bid;
if( _bid_itr.valid() )
{
market_order abs_bid( bid_order, _bid_itr.key(), _bid_itr.value() );
if( abs_bid.get_price().quote_asset_id == _quote_id && abs_bid.get_price().base_asset_id == _base_id )
{
bid = abs_bid;
}
}
if( !_feed_price )
{
_current_bid = bid;
--_bid_itr;
return _current_bid.valid();
}
/*
// if bids are less than feed price, then we can consider shorts
if( !bid || (bid->get_price(*_feed_price) < *_feed_price) )
{
// first consider shorts at the feed price
if( _short_at_feed_itr != _db_impl._shorts_at_feed.rend() )
{
// if we skipped past the range for our market, note that we reached the end
if( _short_at_feed_itr->order_price.quote_asset_id != _quote_id ||
_short_at_feed_itr->order_price.base_asset_id != _base_id )
{
_short_at_feed_itr = _db_impl._shorts_at_feed.rend();
}
else // fetch the order
{
optional<order_record> oshort = _pending_state->get_short_record( *_short_at_feed_itr );
FC_ASSERT( oshort.valid() );
bid = market_order( short_order, *_short_at_feed_itr, *oshort );
_current_bid = bid;
++_short_at_feed_itr;
return _current_bid.valid();
}
}
else
{
wlog( "feed at short itr is null" );
}
// if we have a short with a limit below the feed
if( _short_at_limit_itr != _db_impl._short_limit_index.rend() )
{
//wdump((*_short_at_limit_itr) );
if( _short_at_limit_itr->first.quote_asset_id != _quote_id ||
_short_at_limit_itr->first.base_asset_id != _base_id )
{
_short_at_limit_itr = _db_impl._short_limit_index.rend();
}
else
{
// if the limit price is better than a current bid
if( !bid || (_short_at_limit_itr->first > bid->get_price(*_feed_price)) )
{
// then the short is game.
optional<order_record> oshort = _pending_state->get_short_record( _short_at_limit_itr->second );
FC_ASSERT( oshort );
bid = market_order( short_order, _short_at_limit_itr->second, *oshort );
_current_bid = bid;
++_short_at_limit_itr;
return _current_bid.valid();
}
}
}
// then consider shorts by limit
}
*/
if( bid )
{
_current_bid = bid;
switch( uint8_t(bid->type) )
{
case bid_order:
--_bid_itr;
break;
default:
FC_ASSERT( false, "Unknown Bid Type" );
}
}
return _current_bid.valid();
} FC_CAPTURE_AND_RETHROW() }
bool market_engine::get_next_ask()
{ try {
if( _current_ask && _current_ask->state.balance > 0 )
return _current_ask.valid();
_current_ask.reset();
++_orders_filled;
switch( _current_pass )
{
case MARKET_ENGINE_PASS_PROCESS_ASK_ORDERS:
return get_next_ask_order();
default:
FC_ASSERT( false, "_current_pass value is unknown" );
}
return false;
} FC_CAPTURE_AND_RETHROW()
}
bool market_engine::get_next_ask_order()
{
/**
* Process asks.
*/
if( !_ask_itr.valid() )
return false;
market_order abs_ask = market_order( ask_order, _ask_itr.key(), _ask_itr.value() );
if( (abs_ask.get_price().quote_asset_id != _quote_id) || (abs_ask.get_price().base_asset_id != _base_id) )
return false;
_current_ask = abs_ask;
++_ask_itr;
return true;
}
/**
* This method should not affect market execution or validation and
* is for historical purposes only.
*/
void market_engine::update_market_history( const asset& trading_volume,
const price& highest_price,
const price& lowest_price,
const price& opening_price,
const price& closing_price,
const fc::time_point_sec timestamp )
{
// Remark: only prices of matched orders be updated to market history
if( trading_volume.amount > 0 )
{
market_history_key key(_quote_id, _base_id, market_history_key::each_block, _db_impl._head_block_header.timestamp);
market_history_record new_record(highest_price,
lowest_price,
opening_price,
closing_price,
trading_volume.amount);
//LevelDB iterators are dumb and don't support proper past-the-end semantics.
auto last_key_itr = _db_impl._market_history_db.lower_bound(key);
if( !last_key_itr.valid() )
last_key_itr = _db_impl._market_history_db.last();
else
--last_key_itr;
key.timestamp = timestamp;
//Unless the previous record for this market is the same as ours...
// TODO check here: the previous commit checks for volume and prices change here,
// I replaced them with key comparison, but looks odd as well.
// maybe need to remove the judgements at all? since volume info is
// always needed to be updated to market history,
// even if prices and volumes are same to last block.
if( (!(last_key_itr.valid()
&& last_key_itr.key() == key)) )
{
//...add a new entry to the history table.
_pending_state->market_history[key] = new_record;
}
fc::time_point_sec start_of_this_hour = timestamp - (timestamp.sec_since_epoch() % (60*60));
market_history_key old_key(_quote_id, _base_id, market_history_key::each_hour, start_of_this_hour);
if( auto opt = _db_impl._market_history_db.fetch_optional(old_key) )
{
auto old_record = *opt;
old_record.volume += new_record.volume;
old_record.closing_price = new_record.closing_price;
if( new_record.highest_bid > old_record.highest_bid || new_record.lowest_ask < old_record.lowest_ask )
{
old_record.highest_bid = std::max(new_record.highest_bid, old_record.highest_bid);
old_record.lowest_ask = std::min(new_record.lowest_ask, old_record.lowest_ask);
}
// always update old data since volume changed
_pending_state->market_history[old_key] = old_record;
}
else
_pending_state->market_history[old_key] = new_record;
fc::time_point_sec start_of_this_day = timestamp - (timestamp.sec_since_epoch() % (60*60*24));
old_key = market_history_key(_quote_id, _base_id, market_history_key::each_day, start_of_this_day);
if( auto opt = _db_impl._market_history_db.fetch_optional(old_key) )
{
auto old_record = *opt;
old_record.volume += new_record.volume;
old_record.closing_price = new_record.closing_price;
if( new_record.highest_bid > old_record.highest_bid || new_record.lowest_ask < old_record.lowest_ask )
{
old_record.highest_bid = std::max(new_record.highest_bid, old_record.highest_bid);
old_record.lowest_ask = std::min(new_record.lowest_ask, old_record.lowest_ask);
}
// always update old data since volume changed
_pending_state->market_history[old_key] = old_record;
}
else
_pending_state->market_history[old_key] = new_record;
}
}
asset market_engine::get_interest_paid(const asset& total_amount_paid, const price& apr, uint32_t age_seconds)
{
// TOTAL_PAID = DELTA_PRINCIPLE + DELTA_PRINCIPLE * APR * PERCENT_OF_YEAR
// DELTA_PRINCIPLE = TOTAL_PAID / (1 + APR*PERCENT_OF_YEAR)
// INTEREST_PAID = TOTAL_PAID - DELTA_PRINCIPLE
fc::real128 total_paid( total_amount_paid.amount );
fc::real128 apr_n( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) * apr).amount );
fc::real128 apr_d( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) ).amount );
fc::real128 iapr = apr_n / apr_d;
fc::real128 age_sec(age_seconds);
fc::real128 sec_per_year(365 * 24 * 60 * 60);
fc::real128 percent_of_year = age_sec / sec_per_year;
fc::real128 delta_principle = total_paid / ( fc::real128(1) + iapr * percent_of_year );
fc::real128 interest_paid = total_paid - delta_principle;
return asset( interest_paid.to_uint64(), total_amount_paid.asset_id );
}
asset market_engine::get_interest_owed(const asset& principle, const price& apr, uint32_t age_seconds)
{
// INTEREST_OWED = TOTAL_PRINCIPLE * APR * PERCENT_OF_YEAR
fc::real128 total_principle( principle.amount );
fc::real128 apr_n( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) * apr).amount );
fc::real128 apr_d( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) ).amount );
fc::real128 iapr = apr_n / apr_d;
fc::real128 age_sec(age_seconds);
fc::real128 sec_per_year(365 * 24 * 60 * 60);
fc::real128 percent_of_year = age_sec / sec_per_year;
fc::real128 interest_owed = total_principle * iapr * percent_of_year;
return asset( interest_owed.to_uint64(), principle.asset_id );
}
} } } // end namespace bts::blockchain::detail
| cpp |
. I tried GTA San andreas on the lappy and it runs cool. I have not tried any of the new high end games as I know that they will not run on Intel GMA. The battery performance is decent and it runs absolutely without any heat. I usually run it on balanced performance mode. The camera quality is OK but cannot be compared to 2MP camera phone image quality. You can record videos as well. The software for the Web Cam also has a face detection mechanism which I have seen for the first time.
I only had one problem. The lappy came with a single 136 GB partition and a secondary backup partition of 10 GB. But I needed more partition so I had to format it on the first day. They have given a CD which is the recommended way of creating partitions. But that also creates a single Windows partition and a seconday backup partition. So I had to use the Windows CD to create more partitions any ways. Also there is no automatic way of installing all the required drivers. You have to manually install each driver which is tedious. Also I feel that I have not recieved one CD as there are two things missing. First is 30 day McAfee trial versoin. Second is a docklet which was there before I formatted the system but now I can't find it on any CD. The docklet had controls for every dell software. Now I have to control everything from the start menu. I will contact Dell about this soon.
The lid also doesn't have any locking mechanism which is a bit pain. They have made the lid movement stiff to balance that but I feel a less stiff lid with a locking system is a better choice.
Overall I am happy with the laptop. But as I am new to laptops, so I am facing a questions. Should I always run my laptop on charging if I am not outside or should I run it on battery and charge it only when it's low on battery. Someone told me that the baterry has fixed charge cycles so I should keep it on charging to extend my battery life. But another person told me that he used to keep his laptop on charging all the time but now his laptop gives backup of only 5 minutes. So I am confused with which is the better choice.
I would be thankful to anyone who can help.
| english |
<filename>docs/ru/docs/user/reference/alarm-classes/config/policy-violations.md
---
uuid: 581b6801-6606-48ff-bcdf-fac8d988409a
---
# Config | Policy Violations
Base Alarm Class for umbrella alarms.
## Symptoms
## Probable Causes
New changes or rolling back previous configuration.
## Recommended Actions
Go to the hardware and analyze the configuration.
| markdown |
The research says that child obesity is linked to multiple factors such as mothers smoking in pregnancy, children skipping breakfast and not having a regular bedtime or sufficient sleep.
New Delhi: As per a new research, insufficient sleep and skipping the first meal of the day can raise the chances of obesity.
The research says that child obesity is linked to multiple factors such as mothers smoking in pregnancy, children skipping breakfast and not having a regular bedtime or sufficient sleep.
All three issues appear to be important factors in predicting whether a child will become overweight or obese.
Since they are early life factors, they can be modified and the research highlights the possibility that prompt intervention could curb the growth in childhood obesity.Being overweight or obese is linked to a child having poorer mental health, which can extend into adolescence and adulthood.
This poorer psychosocial well-being includes low self-esteem, unhappiness as well as risky behaviours such as cigarette smoking and alcohol consumption.
The research is based on the Millennium Cohort Study, a study of children born into 19,244 families in the UK between September 2000 and January 2002. Data on weight and height was collected when the children were 3, 5, 7 and 11.
This research used observational information which does not allow firm cause and effect conclusions to be drawn.
However the results are based on data from thousands of children and the researchers were able to take account of many of the influences on the development of a child`s weight.
(With IANS inputs)
| english |
<gh_stars>10-100
[{"Similarity":"0.946","Title":"The Representational Effect in Complex Systems A Distributed Representation Approach","Year":2000},{"Similarity":"0.937","Title":"Geometry-based Affordances","Year":2017},{"Similarity":"0.917","Title":"Constraints of Embodiments on Action Coordination","Year":2000},{"Similarity":"0.908","Title":"Salience Based Hierarchical Spatial Representations","Year":2007},{"Similarity":"0.894","Title":"A computational theory of human perceptual mapping","Year":2011},{"Similarity":"0.89","Title":"Your Task is my Task Shared Task Representations in Dyadic Interactions","Year":2003}] | json |
While the Indian cricket team were busy preparing for their first Test against England in Rajkot tomorrow, skipper Virat Kohli took his time off to attend the press conference on Tuesday. The right-hand batsman addressed the media regarding various issues surrounding the series and even went on to admit his modest batting record against the English team.
The skipper went on to state that the tour to England back in 2014 was a defining moment in his career as he got an opportunity to realise what he needed to improve in his batting. "I can put it very simply as that was the phase when I didn’t perform too well and it happened to be England and could have been any other country in the world," Kohli told reporters on Tuesday.
Kohli, who averages 45. 56 in Tests overall has struggled to score against English bowlers in the past. He averages just 20 in the 17 innings that he has played against England. In the five-match Test series against England in 2014, he scored a total of 134 runs at an average of 13. 4, which is by far his worst Test series in terms of average. The batsman had a miserable outing against the Three Lions with a high score of 39 in that series.
"I just take it as a setback in my career, and not motivate myself in a way that I have to prove people wrong or I have to do something special against a particular opposition," he said.
Upon his return home, Kohli concentrated on managing this weakness. He had few sessions with Sachin Tendulkar at the Wankhede Stadium to assess flaws in his game and the batsman has turned out to be pretty impressive ever since that series. He has scored around 1700 runs in 31 Test innings at an average slightly above 53.
Speaking about his emergence since the England tour, Kohli said that the series was a turing point in his career and made him a better player. He also went on to add that the failure in the England tour nwas a learning curve for him. He said, "It made me realise what I need to improve in my game so I am pretty thankful to England for that. I have been a really improved cricketer from then on. "
The 28-year old went on to add that he was no longer thinking about his past experience and was looking forward to the upcoming Test series to prove his mettle. “For me, I'm playing a cricket ball, be it any game, any opposition, anywhere in the world. Those things do not change for me so I don't put those things in my head," he stated. | english |
AEW TNT Champion Christian Cage isn't the most likable character in pro wrestling today. Meanwhile, a WWE veteran has revealed his biggest pet peeve with The Patriarch.
The name in question is Vince Russo. He worked with the current AEW star in WWE during the Attitude Era and in TNA in the mid-2000s.
On the latest edition of The Wrestling Outlaws, Vince Russo revealed that he didn't always see eye-to-eye with Cage on certain things. It was mainly because the current AEW star was a perfectionist.
Russo added that Cage's abovementioned character trait never impacted his push in TNA or his booking of the star. He also explained why the TNT Champion seemingly could not meet the sky-high expectations WWE officials had for him.
You can watch the full episode of The Wrestling Outlaws right here:
This perfectionist trait might not have done Christian Cage any favors in WWE or TNA. However, in AEW, it seems to be working fine, as he has been the TNT Champion for a long time.
Cage made his third and most challenging defense of his crown on the December 6, 2023, edition of Dynamite against Adam Copeland in Montreal. It was the first time since 2010 that the former WWE Tag Team Champions faced each other one-on-one.
After a hard-hitting contest, Christian Cage picked up the win, thanks to some help from Nick Wayne's mother, who took out Copeland with the title belt. Shayna Wayne seemingly assaulted the Hall of Famer to avenge the latter's attack on her son.
Do you think Christian Cage is a worthy TNT Champion? Let us know in the comments section below.
Please credit The Wrestling Outlaws and give an H/T to Sportskeeda Wrestling when using quotes from this article.
| english |
Congress leader Shashi Tharoor on Monday filed his nomination from Thiruvananthapuram Parliamentary Constituency in Kerala.
Before filing the nomination papers, Tharoor offered prayers at Sree Padmanabha Swamy temple in Kerala.
“Offered prayers at the Sree Padmanabha Swamy temple, before filing my nomination papers today. The deity is considered the guardian of the city, and in His divine presence, I felt energised to fight for all that Thiruvananthapuram holds dear. My sister @ShobhaTharoor joined me,” Shashi Tharoor tweeted.
Tharoor also shared his views on Twitter by saying the election campaign in Thiruvananthapuram has entered its final and most intense phase.
“Momentous start to the ‘paryadanam’ today morning, as the election campaign in Thiruvananthapuram enters its final and most intense phase. Over the next 3 weeks @INCKerala & @udfkerala will fight for the progressive values that have defined India, and for the soul of our country,” Tharoor added. | english |
<reponame>Civil-Service-Human-Resources/lpg-admin
import {DateStartEndCommand} from '../dateStartEndCommand'
export class DateStartEndCommandFactory {
create(data: any) {
let dateStartEndCommand = new DateStartEndCommand()
dateStartEndCommand.startDay = data.startDay
dateStartEndCommand.startMonth = data.startMonth
dateStartEndCommand.startYear = data.startYear
dateStartEndCommand.endDay = data.endDay
dateStartEndCommand.endMonth = data.endMonth
dateStartEndCommand.endYear = data.endYear
return dateStartEndCommand
}
}
| typescript |
#!/usr/bin/env python
#
# util.py
#
# Utility classes
#
# Copyright 2017 <NAME>
# COBHUNI Project, Universität Hamburg
#
# 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 os
import pprint as pp
from collections import namedtuple
from configparser import ConfigParser, MissingSectionHeaderError, \
ExtendedInterpolation, NoSectionError, NoOptionError
#
# CLASSES
#
class CorpusDoc():
""" Class representig the data model
of a documnent of the corpus.
"""
def __init__(self, text=None, annotation=None):
""" Constructor.
Args:
text (str): text of the document
annotations (dict): set of instance annotations.
Each value is a list containing dicts of the form:
{ "val" : str,
"ini" : int,
"end" : int }
"""
self.text = text
self.annotation = annotation
def __repr__(self):
return "<CorpusDoc text:%s annotations:%s>" % (self.text, self.annotation)
def __str__(self):
return "Instance of class CorpusDoc:\n\ntext = %s\n\nannotations =\n%s" % (self.text, pp.pformat(self.annotation))
_HadithMeta = namedtuple('_HadithMeta', ['PIDSTART', 'PIDEND', 'BOOKID', 'CHAPTERID', 'SUBCHAPTERID', 'SECTIONID'])
class HadithMeta(_HadithMeta):
""" Class to store metadata from hadith filenames.
Attributes:
PIDSTART (int): pid variable for reconstucting url in start position.
PIDEND (int): pid variable for reconstucting url in end position.
BOOKID (int): book that constains document.
CHAPTERID (int): chapter that constains document.
SUBCHAPTERID (int): subchapter that constains document.
SECTIONID (int): section that constains document.
"""
def __str__(self):
return """Instance of class HadithMeta:\n \
PIDSTART = %s\n \
PIDEND = %s\n \
BOOKID = %s\n \
CHAPTERID = %s\n \
SUBCHAPTERID = %s\n \
SECTIONID = %s\n \
""" % (self.PIDSTART,
self.PIDEND,
self.BOOKID,
self.CHAPTERID,
self.SUBCHAPTERID,
self.SECTIONID)
class Config():
""" Configuration constants. """
def load(cfgpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini'),
globals = globals()):
""" Load configuration file.
Args:
cfgpath (String): path of configuration file.
globals (dict): global variables, to keep track of the module path.
Returns:
ConfigParser: Object read from configuration file.
Raise:
ValueError: if any error is find in config file.
"""
cfg = ConfigParser(inline_comment_prefixes=('#'), interpolation=ExtendedInterpolation())
cfg.optionxform = str # make parser case sensitive
try:
cfg.read(cfgpath)
except MissingSectionHeaderError:
raise ValueError('Error in module {__file__}: no sections in config file'.format(**globals))
if not cfg.sections():
raise ValueError('Error in module {__file__}: config file missing or empty'.format(**globals))
return cfg
#
# SUBROUTINES
#
def getfiles(path):
""" Generate list of file paths and names from directory path.
Args:
path (str): input directory
Yields:
str, str: full path of file and name
"""
fobjs = (f for f in os.scandir(path) if f.is_file())
for f in fobjs:
yield (f.path, os.path.splitext(f.name)[0])
def loadmeta_altafsir(madhab_path, tafsir_path):
""" Load metadata text files for altafsir.
Args:
madhab_path (str): path for madhab file.
tafsir_path (str): path for tafsir file.
returns:
dict, dict: madhab metadata and tafsir metadata.
"""
with open(madhab_path) as fp:
lines = (li.split('|') for li in filter(None, (l.strip() for l in fp)) if not li.startswith('#'))
madhab_mapping = {_id.strip() : name.strip() for _id, name in lines}
with open(tafsir_path) as fp:
lines = (list(map(str.strip, li.split('|'))) for li in filter(None, (l.strip() for l in fp)) if not li.startswith('#'))
tafsir_mapping = {_id : {'name':name, 'author':author, 'date':date} for _id, name, author, date in lines}
return madhab_mapping, tafsir_mapping
def parse_hadith_fname(fname):
""" Extract metadata from fname.
Example of fname: hadith.al-islam-10904-10907_33-76.json, where
PIDSTART = 10904
PIDEND = 10907
BOOKID = 33
CHAPTER = 76
SUBCHAPTERID = None
SECTION = None
Args:
fname (str): file name to parser.
Return:
namedtuple: metadata.
"""
pidrange, _, rest = fname.partition('_')
bookid, docmeta = (lambda x: (x[0], list(map(int, x[1:]))))(rest.split('-'))
return HadithMeta(*list(map(int, pidrange.rsplit('-',2)[1:])), bookid, *docmeta, *([None]*(3-len(docmeta))))
#FIXME jarrrl habia quedado mejor con zip_longest
# metadata = dict(itertools.zip_longest(('pidstart', 'pidend', 'book', 'chapter', 'subchapter', 'section'),
# itertools.chain(*(i.split('-') for i in fname.split('-',2)[-1].split('_')))))
| python |
{
"type": "enderio:grindingball",
"grindingball": {
"item": "enderio:redstone_alloy_ball"
},
"grinding": 1.0,
"chance": 1.0,
"power": 0.35,
"durability": 30000
} | json |
<filename>api/Reports/section-data.json
{
"name": "Reports",
"version": "2009-01-01",
"methods": ["requestReport", "getReportRequestList", "getReportRequestListByNextToken", "getReportRequestCount", "cancelReportRequests", "getReportList", "getReportListByNextToken", "getReportCount", "getReport", "manageReportSchedule", "getReportScheduleList", "getReportScheduleCount", "updateReportAcknowledgements"]
} | json |
<reponame>sasjs/cli
import { Target, getAbsolutePath } from '@sasjs/utils'
import { getLocalOrGlobalConfig } from '../../../utils/config'
export async function getAllJobFolders(target: Target) {
const { configuration } = await getLocalOrGlobalConfig()
let allJobs: string[] = []
if (configuration?.jobConfig?.jobFolders)
allJobs = [...configuration.jobConfig.jobFolders]
if (target?.jobConfig?.jobFolders)
allJobs = [...allJobs, ...target.jobConfig.jobFolders]
allJobs = allJobs.filter((s) => !!s) as string[]
const { buildSourceFolder } = process.sasjsConstants
allJobs = allJobs.map((job) => getAbsolutePath(job, buildSourceFolder))
return [...new Set(allJobs)]
}
| typescript |
#![feature(linked_list_cursors)]
mod app;
mod buffer;
use std::{thread::sleep, time::Duration};
use app::*;
fn main() {
let mut app = App::new();
app.run();
}
| rust |
package com.midounoo.midounoo.Model;
public class Results {
public String message_id;
}
| java |
{"name":"Fish","symbol":"ISLDA","logoURI":"https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/Forgp6AYPyCpMmd6o7PENRjwHjw2mcDeNB1Qx15DekLc/logo.png","decimals":0,"address":"Forgp6AYPyCpMmd6o7PENRjwHjw2mcDeNB1Qx15DekLc","chainId":101,"tags":["game-token","staking","gamble"],"extensions":{"website":"https://moomoons.io/","twitter":"https://twitter.com/IslandaNFT","discord":"https://discord.gg/7n9sFPFe9b","description":"Islanda is moving away from the copy and paste profile picture art and is expanding out to places where only few go..."}} | json |
Former actress and model Gayatri Joshi from Swades fame has been in the headlines lately owing to the unfortunate Italy car crash incident wherein Gayatri’s car collided with a camper van and a Ferrari. Since the news broke out, her fans have been left distraught and several updates have also poured in from the same. Notably, a photograph of Gayatri Joshi from Italy, merely minutes after the collision took place, has been doing rounds on the internet. Check out the picture inside.
The news of the accident has left everyone perplexed and panic-stricken. However, much to the relief of fans, reports mentioned that Gayatri and her husband Vikas Oberoi escaped unhurt. In an update from the incident, a photograph of the Swades actress has been going viral on the internet. Remarkably, the picture is from Italy, clicked just minutes after the accident took place. The picture shows her sitting on the road while she remains enveloped by people and police officials. Check out the viral picture below.
A report by The Free Press Journal recently disclosed the specifications of the accident and revealed that it took place when Gayatri and Vikas were driving on a rural road in Italy in their Lamborghini and it crashed with a Ferrari and a camper van. The two cars made an attempt to overtake the van, which was ahead of them when the collision happened. Notably, The Free Press Journal contacted Gayatri Joshi and she gave details about Vikas and her whereabouts. “Vikas and I are in Italy. We met with an accident here (multiple-car collision). With God’s grace, we both are absolutely fine,” the portal quoted the actress saying.
In a recent update from the mishap, Gayatri’s husband Vikas is under scrutiny as local authorities continue to probe the case, mentioned reports. If found guilty, Vikas could be imprisoned for up to seven years.
NET Worth: ~ 41.7 MN USD (RS 345 cr)
| english |
<filename>assets/css/preloader.css
.preloaderPage {
height: 100vh;
overflow: auto;
width: 100%;
background: #fafafa;
margin-right: -8px;
overflow-x: hidden;
}
.preloader-box {
display: flex;
align-items: center;
justify-content: center !important;
height: 100%;
/*background: #fafafa;*/
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 2;
font-size: 32px;
}
.bg-dk-purple {
background: #424a5d;
} | css |
The letter primarily addresses a seemingly narrow set of alleged infractions by Microsoft in drawing information from Twitter’s database of tweets. But the move could foreshadow more serious developments. Musk has previously accused Microsoft and its partner OpenAI in a tweet of “illegally” using Twitter data to develop sophisticated AI systems such as ChatGPT.
The next issue of Calgary Herald Headline News will soon be in your inbox. We encountered an issue signing you up. Please try again” Lawsuit time,” Musk wrote in that April tweet. But the letter, signed by Musk lawyer Alex Spiro, tiptoed around that concern. It noted that Microsoft’s agreement with Twitter barred it from overuse of the service’s data such as exceeding “reasonable request volume” or “excessive or abusive usage.” Spiro then noted that “despite these limitations,” Microsoft had retrieved more than 26 billion tweets in 2022 alone.
He provided no context for those numbers. The process of training AI systems requires enormous amounts of data such as written text, which AI algorithms scour for patterns that the AI can use to make sense of language and large bodies of knowledge.
The letter stated that Microsoft had failed to provide such notification. Microsoft spokesman Frank Shaw provided a statement noting that Microsoft will review questions raised by the letter and then will “respond appropriately.” The statement added that “we look forward to continuing our long term partnership” with Twitter, which it did not refer to by name. Shaw declined to address specifics from the letter.Read more:
'DRAG IS SOMETHING TO CELEBRATE': San Francisco to name 1st-in-nation drag laureateMayor London Breed says it was a natural step to create a position that embraces drag culture and puts government resources toward it.
Twitter accuses Microsoft of misusing its data, foreshadowing a possible fight over AIA lawyer for Twitter owner Elon Musk accused Microsoft of misusing the service's data and demanded an audit from the software giant.
| english |
[
null,
{"id":1,"expanded":false,"name":"MAP001","order":1,"parentId":0,"scrollX":528.5,"scrollY":406}
] | json |
Accenture has agreed to acquire N3, a tech-driven sales and demand-generation firm, that helps clients drive sales growth in an increasingly virtual environment. The acquisition adds approximately 2,200 employees to Accenture globally, along with artificial intelligence (AI) and machine learning (ML) capabilities.
N3’s unique model of specialized sales talent – across complex areas like cloud, software platforms and 5G networks – is supported by cloud-based, AI/ML technology that enables smarter, more efficient customer interactions and sales conversions. With Accenture’s SynOps platform, these combined capabilities could offer a client the ability to aggregate millions of interaction points into actionable insights that drive sales growth.
Founded in 2004, N3 serves many of the world’s leading brands, such as Microsoft, Cisco and SAP. The company is headquartered in Atlanta, with additional locations including Brazil, Costa Rica, Ireland, Germany, Japan, Singapore and the UK.
| english |
Mathura (UP): Preparations in Mathura are in full swing ahead of PM Modi’s visit to Vrindavan on November 23. Prime Minister Narendra Modi is scheduled to attend the Braj Raj Utsav in Vrindavan. While dust compressors were run to reduce pollution, wall paintings and colorful lights adorned the city. "We're running a special cleanliness campaign in the city...sweeping being done...we're trying to make our horticulture better...sprinkling of water being done to reduce AQI. The city is also being lit up...", said Shashank Chaudhary, the Municipal Commissioner of Mathura. The festival, running from Nov 14 to 27 at railway grounds, has been organized by the Uttar Pradesh Braj Teerth Vikas Parishad and Tourism Department.
| english |
<reponame>smlrepo/libsacloud
// Copyright 2016-2019 The Libsacloud 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 sacloud
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
var testCouponJSON = `
{
"AppliedAt": "2019-01-10T11:12:13+09:00",
"ContractID": 111111111111,
"CouponID": "xxxxxxxxxxxxxxxx",
"Discount": 999999,
"MemberID": "abc99999",
"ServiceClassID": 50122,
"UntilAt": "2019-03-31T23:59:59+09:00"
}
`
func TestMarshalCouponJSON(t *testing.T) {
var d Coupon
err := json.Unmarshal([]byte(testCouponJSON), &d)
assert.NoError(t, err)
assert.NotEmpty(t, d)
}
| go |
Actor-turned-politician Mohan Babu, who recently joined the YSRCP was in the eye of a storm when he had planned to take out a rally in Tirupati protesting the government not sanctioning over Rs 19 crore of fee reimbursements to students.
“I repeatedly asked for reimbursement of fees for engineering colleges but the Andhra Pradesh government remained a mute spectator to the pathetic conditions of the students The state government cannot remain adamant on an issue that is adversely affecting the students,” he told media persons. “The students cannot afford the fee which amounts to crores of rupees and the government has to shoulder responsibility,” Babu said, adding that the government has failed to keep the promises made to people.
While in preparations for the peaceful rally, the police had shown up at his doorstep and advised him against it, claiming law and order problems and tried to stop the rally. But things escalated when it was said that the police had house arrested Mohan Babu on the same day in the morning, in a bid to stop the rally, on the charges of violation of police 30 act and 144 CRPC.
Mohan Babu has now come out with a tweet that rubbishes any claim of him being under house arrest saying that he was safe in his house at Hyderabad. He claims that certain media houses are doing so only as a propaganda mechanism. | english |
<reponame>lukaselflein/sarah_folderstructure
"""Vary the rhoref parameter to find a sane value.
Copyright 2019 Simulation Lab
University of Freiburg
Author: <NAME> <<EMAIL>>
"""
from __future__ import print_function
import os
import shutil
#import multiprocessing
#import sys
import random
from loop_cost_functions import calc_cost_function
from smamp.tools import cd
from smamp.tools import check_existence
def testprint(*args, **kwargs):
return 'args: {}, kwargs: {}'.format(args, kwargs)
def get_tasks(path_to_subdir):
"""Vary the lnrho weighting parameter, create folder and execute."""
sweep_dir = 'lnrho_sweep'
if os.path.exists(sweep_dir):
# print('Removing old dir')
# shutil.rmtree(sweep_dir)
pass
else:
print('making dir')
os.mkdir(sweep_dir)
print('dir made.')
tasks = []
skipped = 0
for sigma in [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4]:
#for lnrho in [-9, -8, -7, -6, -5, -4, -3, -2]:
for lnrho in [-7, -6, -5.5, -5, -4.75, -4.5, -4.25, -4, -3.5]:
output_name = os.path.join(sweep_dir, 'cost_{}_{}.h5'.format(lnrho, sigma))
if os.path.exists(output_name):
# print('{} exists. Do not include in worklist.'.format(output_name))
skipped += 1
continue
else:
tasks += [(path_to_subdir, lnrho, sigma, output_name)]
print('{} files found and skipped.'.format(skipped))
return tasks
def calculate_tasks(tasks):
print('{} items in worklist.'.format(len(tasks)))
random.shuffle(tasks)
for task in tasks:
if os.path.exists(task[-1]):
#print('{} exists. Skipping ahead.'.format(task[-1]))
continue
print('starting {} {} in {}'.format(task[1], task[2], task[0]))
with cd(task[0]):
calc_cost_function(*task)
def main():
""" Execute everything."""
print('This is {}.'.format(__file__))
print('Current working dir: {}'.format(os.getcwd()))
tasks = []
# Crawl the directory structure
for subdir, dirs, files in sorted(os.walk('.')):
# Exclude template folders from search
if 'template' in subdir or 'exclude' in subdir or 'lnrho_sweep' in subdir:
continue
# Select the folder to calculate in
if 'horton_cost_function' in subdir:
print('Moving to {}'.format(subdir))
with cd(subdir):
subdir_tasks = get_tasks(subdir)
tasks += subdir_tasks
calculate_tasks(tasks)
print('Done.')
if __name__ == '__main__':
main()
| python |
<reponame>railz-ai/railz-visualizations
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import {
RVAccountingProviders,
RVReportFrequency,
RVReportTypes,
} from '@railzai/railz-visualizations';
import { distinctUntilChanged } from 'rxjs';
import { ApiService } from '../../../services/api';
import { AuthenticationParameters } from '../../../types/authentication';
import { Filter } from '../../../types/form-submission';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent implements OnInit {
@Output() filterEvent = new EventEmitter<Filter>();
@Output() authEvent = new EventEmitter<string>();
@Input() options?: string;
authForm = new FormGroup({
authUrl: new FormControl('', Validators.required),
});
filterForm = new FormGroup({
serviceName: new FormControl(RVAccountingProviders.QUICKBOOKS, Validators.required),
businessName: new FormControl('', Validators.required),
connectionId: new FormControl('', Validators.required),
reportType: new FormControl(RVReportTypes.BALANCE_SHEET, Validators.required),
reportFrequency: new FormControl(RVReportFrequency.MONTH, Validators.required),
startDate: new FormControl('', Validators.required),
endDate: new FormControl('', Validators.required),
});
requiresNoFrequency = (type: string) =>
[
RVReportTypes.INVOICES,
RVReportTypes.BILLS,
RVReportTypes.BANK_ACCOUNT,
RVReportTypes.CREDIT_SCORE,
].includes(type as RVReportTypes);
requiresNoDate = (type: string) =>
[RVReportTypes.BANK_ACCOUNT, RVReportTypes.CREDIT_SCORE].includes(type as RVReportTypes);
token = '';
constructor(private apiService: ApiService) {
this.checkValueChanges();
}
ngOnInit(): void {}
checkValueChanges(): void {
this.filterForm
?.get('businessName')
?.valueChanges.pipe(distinctUntilChanged())
.subscribe((val) => {
if (this.filterForm) {
if (val) {
this.filterForm.controls['connectionId'].clearValidators();
this.filterForm.controls['connectionId'].disable();
} else {
this.filterForm.controls['connectionId'].setValidators([Validators.required]);
this.filterForm.controls['connectionId'].enable();
}
this.filterForm.controls['connectionId'].updateValueAndValidity();
}
});
this.filterForm
?.get('connectionId')
?.valueChanges.pipe(distinctUntilChanged())
.subscribe((val) => {
if (this.filterForm) {
if (val) {
this.filterForm.controls['businessName'].clearValidators();
this.filterForm.controls['businessName'].disable();
this.filterForm.controls['serviceName'].clearValidators();
this.filterForm.controls['serviceName'].disable();
} else {
this.filterForm.controls['businessName'].setValidators([Validators.required]);
this.filterForm.controls['businessName'].enable();
this.filterForm.controls['serviceName'].setValidators([Validators.required]);
this.filterForm.controls['serviceName'].enable();
}
this.filterForm.controls['businessName'].updateValueAndValidity();
this.filterForm.controls['serviceName'].updateValueAndValidity();
}
});
this.filterForm
?.get('reportType')
?.valueChanges.pipe(distinctUntilChanged())
.subscribe((reportTypeValue) => {
if (this.filterForm) {
if (reportTypeValue) {
if (this.requiresNoDate(reportTypeValue)) {
this.filterForm.controls['startDate'].clearValidators();
this.filterForm.controls['startDate'].disable();
this.filterForm.controls['endDate'].clearValidators();
this.filterForm.controls['endDate'].disable();
} else {
this.filterForm.controls['startDate'].setValidators([Validators.required]);
this.filterForm.controls['startDate'].enable();
this.filterForm.controls['endDate'].setValidators([Validators.required]);
this.filterForm.controls['endDate'].enable();
}
if (this.requiresNoFrequency(reportTypeValue)) {
this.filterForm.controls['reportFrequency'].clearValidators();
this.filterForm.controls['reportFrequency'].disable();
} else {
this.filterForm.controls['reportFrequency'].setValidators([Validators.required]);
this.filterForm.controls['reportFrequency'].enable();
}
} else {
this.filterForm.controls['startDate'].setValidators([Validators.required]);
this.filterForm.controls['startDate'].enable();
this.filterForm.controls['endDate'].setValidators([Validators.required]);
this.filterForm.controls['endDate'].enable();
this.filterForm.controls['reportFrequency'].setValidators([Validators.required]);
this.filterForm.controls['reportFrequency'].enable();
}
this.filterForm.controls['startDate'].updateValueAndValidity();
this.filterForm.controls['endDate'].updateValueAndValidity();
this.filterForm.controls['reportFrequency'].updateValueAndValidity();
}
});
}
authorize = (config: AuthenticationParameters) => {
this.apiService.getAccessToken(config).subscribe((data: any) => {
this.token = data.access_token;
this.authEvent.emit(this.token);
});
};
onFilterSubmit() {
if (this.filterForm && this.filterForm.valid) {
this.filterEvent.emit(this.filterForm.value);
}
}
onAuthSubmit() {
if (this.authForm && this.authForm.valid) {
this.authorize(this.authForm.value);
}
}
}
| typescript |
/* ==UserStyle==
@name 谷歌美化-少女前线G36
@namespace USO Archive
@author 王比利
@description `部分代码取自脚本https://greasyfork.org/zh-CN/scripts/14178作者浮生@未歇、AC、王比利背景图画师:-薯子Imoko-`
@version 20200221.11.17
@license CC0-1.0
@preprocessor uso
@advanced dropdown image "选择背景图片" {
image "默认*" <<<EOT https://s2.ax1x.com/2019/04/29/E37N5t.jpg EOT;
image-custom-dropdown "Custom" <<<EOT /*[[image-custom]]*\/ EOT;
}
@advanced text image-custom "选择背景图片 (Custom)" "https://example.com/image.png"
@advanced color color "背景填充色" #F1F4ED
==/UserStyle== */
@-moz-document regexp("^http[s]?://www.google.com.*") {
/**背景*/
body{
background: /*[[color]]*/ url(/*[[image]]*/) no-repeat fixed top right !important;
background-size:cover !important;
}
/**计数器背景*/
.appbar{
background:transparent !important
}
/*额外结果*/
div.rl_feature, .rlc__slider, .rlc__slider-page{
background: transparent;
}
.rl_center{
border: none
}
/**搜索结果*/
.kp-blk{
border-radius:0;
border: none
}
.bkWMgd .g a:hover h3 {
text-decoration:none
}
.B6fmyf {
visibility: visible;
top: 8px
}
.NJjxre {
display: none;
}
/*联想结果*/
.aajZCb,.minidiv .aajZCb{
box-shadow: 0 5px 10px rgba(0,0,0,0.05);
border-radius: 0
}
/*链接右边的小箭头*/
.GHDvEf.ab_button,.GHDvEf.ab_button:hover{
background: transparent
}
/**侧栏*/
.Wnoohf {
background: rgba(255,255,255,0.5) ;
box-shadow: 0 5px 10px rgba(0,0,0,0.05);
transition: all 0.5s;
}
.mnr-c :hover {
background: rgba(255,255,255,1) ;
box-shadow: none;
transition: all 1s;
}
.kno-ftr :hover{
background: transparent
}
.rhsvw .kno-ftr:hover{
background:rgba(255,255,255,0);
}
#main .mw #rhs {
margin-left: 1020px;
}
.kp-header:first-child .kno-liu .img-kc-m,.kp-blk .kp-header:first-child .img-brk {
border-top-right-radius: 0px !important;
border-top-left-radius: 0px !important;
}
/**地图结果**/
.srg .g:last-of-type {
margin-bottom: 20px;
}
.vk_c, .vk_cxp, .vk_ic{
background-color: rgba(255,255,255,0.3);
border: none;
border-radius: 0 !important;
box-shadow: 0 5px 10px rgba(0,0,0,0.05);
width:104%;
margin-left: -17px;
margin-bottom:20px !important;
transition: all 0.5s
}
.vk_c:hover, .vk_cxp:hover, .vk_ic:hover{
background-color: rgba(255,255,255,1);
box-shadow: none
}
.lu-fs{
width:100%;
height:120%
}
.yyjhs {
background: rgba(255, 255, 255, .8);
padding: 3px 16px;
}
/**自定义按钮**/
#myuser .myuserconfig{
background:transparent !important;
color:grey !important;
box-shadow:none !important;
border:0 !important;
margin-right:10px !important
}
#myuser .myuserconfig:hover{
background:transparent !important;
color:black !important;
border:0
}
/**顶栏**/
.minidiv .sfbg{
background: rgba(255,255,255,0.8) !important;
box-shadow: 0 5px 10px rgba(0,0,0,0.05);
}
#hdtbSum{
background: transparent !important;
}
#hdtb {
border: none;
}
/*文本框*/
.RNNXgb, .minidiv .RNNXgb{
border-color: rgba(0,0,0,0.1);
border-style: solid;
border-width: 0px 0px 1px;
border-radius: 0;
background: transparent ;
transition: all 0.5s
}
.emcav .RNNXgb{
box-shadow:none;
background: #fff !important;
padding:0 0 0 2px
}
.sbfc{
background: #fff !important;
box-shadow: none;
border-color: rgba(0,0,0,0.1)!important;
}
.RNNXgb:hover, .minidiv .RNNXgb:hover{
background: #fff !important;
box-shadow: none !important;
border-color: rgba(0,0,0,0);
border-style: solid;
border-width: 0px 0px 1px;
border-radius: 0;
}
/**相关内容下划线**/
.aR1mEe{
border-bottom: none !important;
}
/**图片结果**/
g-section-with-header {
margin: 0;
padding: 10px 5px;
}
/**AC-Baidu**/
div.res_top_banner #foot,
#page .fk,
#head .headBlock,
#rs_top_new,
#content_right,
.srg>table,
.srg>div[id*="30"],
.srg .c-recommend,
.srg .leftBlock,
.srg .hit_top_new,
.srg #fld,
.srg div.rrecom-btn-parent,
#content_right,
#demo {
display:none!important
}
body[google] {
background-color:#fdfdfd
}
#form .bdsug {
width:76%
}
#ala_img_results {
overflow:hidden
}
a,
a em {
text-decoration:none
}
#head,
#s_tab {
background-color:#f8f8f8
}
#head {
border-bottom:0
}
#form {
background-color:unset
}
#form .bdsug li {
width:auto;
color:#000;
font:15px arial;
line-height:26px
}
#form .s_ipt_wr.bg {
background:#fff;
width:76%
}
#form .s_btn {
background:#2866bd;
border-bottom:1px solid #4879bd
}
#form .s_btn:hover {
background:#4879bd;
border-bottom:1px solid #2866bd
}
#s_tab b {
color:#2866bd;
border-bottom:3px #2866bd solid
}
#s_tab {
border-bottom:#e0e0e0 1px solid
}
#u a {
text-decoration:none
}
#container .head_nums_cont_outer .search_tool_conter,
#container .head_nums_cont_outer .nums {
width:630px
}
#search .srg,
.med>#ires .bkWMgd>.srg {
animation-name:left_logoR;
-webkit-animation-duration:.1s;
-webkit-animation-timing-function:ease
}
#rs,
.bkWMgd .g {
width:760px;
padding:0 20px 15px;
margin-top:0;
margin-bottom:40px;
background-color:rgba(255,255,255,0.3);
transition: all 0.5s;
box-sizing:border-box;
box-shadow: 0 5px 10px rgba(0,0,0,0.05);
border-radius: 0
}
#rs,
.bkWMgd .g div.rc .s {
max-width:unset
}
.bkWMgd .g:hover {
box-shadow:none;
background:rgb(255, 255, 255)!important
}
.bkWMgd .g[tpl=soft] .op-soft-title,
.bkWMgd .g div.r {
background-color:rgba(248, 248, 248, .6);
margin:0 -20px 10px;
padding:8px 20px 5px;
border-radius: 0
}
.srg .f13 a,
.srg .f13 em,
.srg .c-span18 a,
.srg .subLink_factory a,
.srg .c-tabs-content a,
.srg .op_offical_weibo_content a,
.srg .op_offical_weibo_pz a,
.srg .op_tieba2_tablinks_container a,
.srg .op-tieba-general-right,
.srg .op_dq01_title,
.srg .op_dq01_table a,
.srg .op_dq01_morelink a,
.srg .op-tieba-general-mainpl a,
.srg .op-se-listen-recommend,
.srg .c-offset>div a {
text-decoration:none;
color:#2866bd
}
.srg .f13 a:hover,
.srg .f13 em:hover,
.srg .subLink_factory a:hover,
.srg .c-tabs-content a:hover,
.srg .op_tieba2_tablinks_container a:hover,
.srg .op-tieba-general-right:hover,
.srg .op_dq01_title:hover,
.srg .op_dq01_table a:hover,
.srg .op_dq01_morelink a:hover,
.srg .op-tieba-general-mainpl a:hover,
.srg .op-se-listen-recommend:hover,
.srg .c-offset>div a:hover {
text-decoration:underline!important
}
.srg .f13 a {
color:green
}
.srg .c-span18,
.srg .c-span24 {
width:100%;
min-width:unset
}
.srg .c-border {
width:auto;
border:0;
border-bottom-color:transparent;
border-right-color:transparent;
box-shadow:0 0 0 transparent;
}
.srg .se_com_irregular_gallery ul li,
.srg .op_jingyan_list,
.bkWMgd .g .op-img-address-link-type {
display:inline-block;
margin-left:10px
}
.bkWMgd .g[tpl=soft] .op-soft-title a,
.bkWMgd .g[tpl=soft] .op-soft-title a em,
.bkWMgd .g div.r>a,
.bkWMgd .g a h3,
.bkWMgd .g div.r>a em {
color:#2866bd;
font-weight:700
}
.srg .op-soft-title a:visited,
.srg .op-soft-title a:visited em,
.bkWMgd .g div.r>a:visited,
.bkWMgd .g div.r>a:visited em,
.bkWMgd .g a:visited h3 {
color:#609
}
.srg .op-soft-title a,
.bkWMgd .g div.r>a {
position:relative
}
.srg .op-soft-title a em,
.bkWMgd .g div.r>a em {
text-decoration:none
}
.srg .op-soft-title a:hover:after,
.bkWMgd .g div.r>a:hover:after {
left:0;
width:100%;
-webkit-transition:width 350ms;
-moz-transition:width 350ms;
transition:width 350ms
}
.srg .op-soft-title a:after,
.bkWMgd .g div.r>a:after {
content:"";
position:absolute;
border-bottom:2px solid #2866bd;
bottom:-2px;
left:100%;
width:0;
-webkit-transition:width 350ms,left 350ms;
-moz-transition:width 350ms,left 350ms;
transition:width 350ms,left 350ms
}
.srg .op-soft-title a .bkWMgd .g div.r>a {
position:relative
}
.srg .op-soft-title a:visited:hover:after,
.bkWMgd .g div.r>a:visited:hover:after {
left:0;
width:100%;
-webkit-transition:width 350ms;
-moz-transition:width 350ms;
transition:width 350ms
}
.srg .op-soft-title a:visited:after,
.bkWMgd .g div.r>a:visited:after {
content:"";
position:absolute;
border-bottom:2px solid #609;
bottom:-2px;
left:100%;
width:0;
-webkit-transition:width 350ms,left 350ms;
-moz-transition:width 350ms,left 350ms;
transition:width 350ms,left 350ms
}
#rs {
margin-top:0;
padding:0 20px 15px;
}
#rs .tt {
margin:0 -20px 5px;
padding:5px 20px;
background-color:#f8f8f8;
}
#rs table {
width:630px;
padding:5px 15px
}
#rs table tr a {
margin-top:5px;
margin-bottom:5px;
color:#2866bd
}
#rs table tr a:hover {
text-decoration:underline
}
#page {
min-width:710px;
height:40px;
line-height:40px;
padding-top:5px;
margin:0 0 50px 80px
}
.op-img-address-desktop-cont {
overflow:hidden
}
#page a,
#page strong {
color:#2866bd;
height:auto;
box-shadow:none
}
#page .n:hover,
#page a:hover .pc {
border:1px solid transparent;
background:#d8d8d8;
color:#0057da
}
#page strong .pc {
background:#4879bd;
color:#fff
}
@-webkit-keyframes left_logoR {
0% {
-webkit-transform:translateY(64px);
opacity:0
}
50% {
opacity:0
}
100% {
opacity:1
}
}
.bkWMgd>div:not([class]) {
width:730px
}
.bkWMgd>div:not([class]) {
margin-left:18px;
margin-right:18px
}
.bkWMgd .g .exp-outline {
display:none
}
#main .mw #rhs {
margin-left:1020px
}
#res .g .ts {
max-width:unset
}
@media screen and (max-width:1400px) {
.mw #rhs {
display:none
}
}
cite {
font-weight:400
}
#res .r {
line-height:1.3
}
#res {
padding:0
}
#rs,
.bkWMgd .g {
margin-bottom:20px;
}
.c2xzTb .g,
.ruTcId .g,
.fm06If .g,
.cUnQKe .g,
.HanQmf .g {
width:758px;
padding-left:20px!important;
padding-right:20px!important;
box-shadow:0 0 0 0 rgba(0,0,0)
}
div .xfxx5d {
margin-bottom:-18px!important;
margin-top:-25px!important
}
div .xaqJzf.xfxx5d .kno-ftr {
margin-top:10px!important
}
div .kno-ftr a {
position:sticky
}
} | css |
package mock
import (
"context"
"github.com/satori/go.uuid"
log "github.com/Microsoft/presidio/pkg/logger"
"github.com/Microsoft/presidio/pkg/stream"
)
type mock struct {
stream mockImpl
topic string
}
type mockImpl struct {
partitions map[string][]string
}
type mockMessage struct {
Value string
Key string
Partition string
}
//New Return new Mock Producer stream
func New(topic string) stream.Stream {
m := mockImpl{}
err := m.New(topic)
if err != nil {
log.Fatal(err.Error())
}
return &mock{
stream: m,
topic: topic,
}
}
//Receive message from mock topic
func (m *mock) Receive(receiveFunc stream.ReceiveFunc) error {
for {
msg, err := m.stream.Receive()
if err != nil {
return err
}
if msg == nil {
break
}
err = receiveFunc(context.Background(), msg.Partition, msg.Key, msg.Value)
if err != nil {
log.Error(err.Error())
}
}
return nil
}
//Send message to mock topic
func (m *mock) Send(message string) error {
err := m.stream.Send(message)
return err
}
// Mock impl
func (m *mockImpl) Send(message string) error {
log.Info("Sending: %s", message)
m.partitions["1"] = append(m.partitions["0"], message)
return nil
}
func (m *mockImpl) New(topic string) error {
m.partitions = make(map[string][]string, 1)
m.partitions["1"] = make([]string, 0)
log.Info("New topic: %s", topic)
return nil
}
func (m *mockImpl) Receive() (*mockMessage, error) {
var value string
if len(m.partitions["1"]) == 0 {
return nil, nil
}
value, m.partitions["1"] = m.partitions["1"][0], m.partitions["1"][1:]
msg := mockMessage{
Partition: "1",
Value: value,
Key: uuid.NewV4().String(),
}
return &msg, nil
}
| go |
Sonali Phogat murder mystery: Who killed her and what was the motive?
Is China preparing to attack Taiwan?
2 held for desecrating mazaar in Bijnor wearing saffron turbans: Sinister plot to disrupt communal harmony in UP?
OPINION | Kashmir at crossroads: Development or radical Islamist terror?
OPINION | Has Pakistan bitten more than it can chew in Afghanistan? | english |
NAFSA (NAFSA: Association of International Educators)
NAFSA is based in the United States of America and is an association of worldwide educators in higher education. It is an online and physical space for providers to improve their professional development and network with other members within this field, through events created such as conferences.
NASFA is a networking platform so membership is available in one of the following categories; new member, individual member, International member, retired professional, student member or group member. To be become a member, create a NASFA account and answer some set up questions.
| english |
{
"environment": "publishing",
"dataFilesPath": "../../data",
"mediaFilesPath": "../../data/media",
"openapiSpecsPath": "../../../api-specs"
} | json |
{
"variants": {
"powered=false": { "model": "noel:block/frosted_pressure_plate" },
"powered=true": { "model": "noel:block/frosted_pressure_plate_down" }
}
}
| json |
the desirable league. These beautiful women with immense talent and potential are all set to take the world by storm.
Disha Patani is in the top spot this year. The actress, who made her Bollywood debut with M. S. Dhoni: The Untold Story (2016), catapulted into the big league with the Salman Khan-starrer, Bharat, last year. She was recently seen in Baaghi 3 and Malang.
Joining her in the Top 10 are, Suman Rao (Miss World 2019 – 2nd Runner-up and Miss World Asia 2019) at number 2, Katrina Kaif at number 3, Deepika Padukone at number 4, Vartika Singh (Miss Diva Universe 2019) at number 5. Kiara Advani, Shraddha Kapoor, Yami Gautam, Aditi Rao Hydari (Chennai Times Most Desirable Woman of 2019) and Jacqueline Fernandez take the sixth, seventh, eighth, ninth and tenth place, respectively. | english |
<gh_stars>0
//@ts-nocheck
import React, { useEffect, useState } from 'react'
import dots from '../../assets/icons/appstatus/ic-menu-dots.svg'
import emptyPageIcon from '../../assets/icons/ic-empty-data.svg'
import { PopupMenu, Pod as PodIcon, Trash, showError, Progressing, useAsync, copyToClipboard, not, useSearchString } from '../common';
import { NavLink } from 'react-router-dom'
import { useRouteMatch, useParams, generatePath, useHistory, useLocation } from 'react-router';
import { toast } from 'react-toastify'
import { deletePod as deletePodService } from './service'
import { ReactComponent as DropDown } from '../../assets/icons/ic-dropdown-filled.svg'
import { AggregatedNodes, Nodes, NodeType, NodeDetailTabs, NodeDetailTabsType, AggregationKeys, AggregationKeysType } from './types'
import { ReactComponent as ErrorImage } from '../../assets/icons/misc/errorInfo.svg';
import { ReactComponent as Clipboard } from '../../assets/icons/ic-copy.svg';
import { ReactComponent as CubeIcon } from '../../assets/icons/ic-object.svg';
import { getAggregator } from './details/appDetails/utils';
import Tippy from '@tippyjs/react';
interface ResourceTree {
appName: string;
environmentName: string;
nodes: AggregatedNodes;
describeNode: (name: string, containerName?: string) => void;
isAppDeployment: boolean;
}
function ignoreCaseCompare(a: string, b: string): boolean {
return a.toLowerCase() === b.toLowerCase()
}
function getGenricRowFields(kind: NodeType): string[] {
switch (kind) {
case Nodes.Service:
return ['name', 'url']
case Nodes.Pod:
return ['name', 'ready', ''] // empty string denotes menu
default:
return ['name']
}
}
export const StatusFilterButton: React.FC<{ status: string; count?: number }> = ({ status, count }) => {
const location = useLocation()
const history = useHistory()
const { queryParams } = useSearchString()
const statusFilter = queryParams.has('status') ? queryParams.get('status') : ''
return (
<Tippy
className="default-tt"
arrow={false}
placement="bottom"
content={status === 'All' ? 'All Objects' : status}
>
<div
data-testid={`${status}-filter-button`}
onClick={(e) => {
if (status.toLowerCase() === 'all') {
queryParams.delete('status')
}
else {
queryParams.set('status', status);
}
history.replace(location.pathname + '?' + queryParams.toString());
}}
style={{
height: '32px',
border: (!statusFilter && status.toLowerCase() === 'all') || ignoreCaseCompare(statusFilter, status) ? '1px solid var(--B500)' : '1px solid var(--N200)',
background: (!statusFilter && status.toLowerCase() === 'all') || ignoreCaseCompare(statusFilter, status) ? 'var(--B100)' : 'transparent',
}}
className="pointer ml-8 br-4 flex left p-6"
>
{status !== 'All' && <div className={`app-summary__icon icon-dim-16 mr-6 ${status.toLowerCase()} ${status.toLowerCase()}--node`} style={{ zIndex: 'unset' }} />}
<span className="capitalize">{count || status}</span>
</div>
</Tippy>
);
}
const ResourceTreeNodes: React.FC<ResourceTree> = ({ nodes, describeNode, isAppDeployment = false, appName, environmentName }) => {
const { url, path } = useRouteMatch()
const params = useParams<{ appId: string, envId: string, kind?: NodeType }>()
const history = useHistory()
const { queryParams, searchParams } = useSearchString()
const orderedAggregators: AggregationKeysType[] = [
AggregationKeys.Workloads,
AggregationKeys.Networking,
AggregationKeys['Config & Storage'],
AggregationKeys['Custom Resource'],
AggregationKeys.RBAC,
AggregationKeys.Administration,
AggregationKeys.Other
];
useEffect(() => {
if (!searchParams.status || !params.kind) return;
outerloop:
for (let kind of Object.keys(nodes.nodes)) {
const kindNodes = nodes.nodes[kind];
for (let [nodeName, nodeDetails] of kindNodes) {
if ((nodeDetails?.status || nodeDetails?.health?.status) === searchParams.status) {
history.push(generatePath(path, { ...params, kind: nodeDetails.kind }) + '?' + queryParams.toString())
break outerloop
}
}
}
}, [searchParams.status]);
if (!params.kind) {
if (nodes.nodes.Pod) {
history.replace(`${url}/Pod`)
}
else {
const allNodes = Object.keys(nodes.nodes)
if (allNodes.length) {
history.replace(`${url}/${allNodes[0]}`)
}
}
return null
}
return (
<div
style={{
width: '100%',
display: 'grid',
gridTemplateColumns: '270px 1fr',
height: '700px',
maxHeight: '700px',
overflow: 'hidden',
gridTemplateRows: '72px 1fr',
}}
>
<div className="flex left pl-24 pr-24 bcn-0" style={{ gridColumn: '1 / span 2' }}>
<span className="fs-14 fw-6 cn-7 flex"><CubeIcon className="icon-dim-20 mr-8 fcn-7" /> APPLICATION OBJECTS</span>
<div style={{ marginLeft: 'auto' }} className="flex right">
<StatusFilterButton status={'All'} />
{Object.entries(nodes.statusCount).map(([status, count]) => (
<StatusFilterButton key={status} status={status} count={count} />
))}
</div>
</div>
<div
className="bcn-0"
style={{
height: '100%',
gridColumn: '1 / span 1',
gridRow: '2',
overflowY: 'auto',
borderRight: '1px solid var(--N200)',
}}
>
<div
style={{
display: 'grid',
gridColumnGap: '8px',
gridTemplateColumns: '24px 1fr',
gridAutoRows: '36px',
placeItems: 'center',
}}
className="p-8"
>
{orderedAggregators
.filter((aggregator) => !!nodes.aggregation[aggregator])
.map((aggregator) => (
<NodeGroup
key={aggregator}
title={aggregator as AggregationKeysType}
data={nodes.aggregation[aggregator]}
aggregatedNodes={nodes}
/>
))}
</div>
</div>
<div style={{ gridColumn: '2', gridRow: '2', overflowY: 'auto' }} className="bcn-0">
{(function (kind: NodeType) {
if (kind === 'Pod') {
return nodes.nodes[kind] ? (
<AllPods
appName={appName}
nodes={nodes}
environmentName={environmentName}
isAppDeployment={isAppDeployment}
pods={nodes.nodes[kind]}
describeNode={describeNode}
/>
) : null;
} else {
return nodes.nodes[kind] ? (
<GenericInfo
nodes={nodes}
describeNode={describeNode}
type={params.kind}
Data={nodes.nodes[kind]}
appName={appName}
environmentName={environmentName}
/>
) : null;
}
})(params.kind as NodeType)}
</div>
</div>
);
}
export const NodeGroup: React.FC<{ title: AggregationKeysType, data: Object; aggregatedNodes: AggregatedNodes }> = ({ title, data, aggregatedNodes }) => {
const [collapsed, setCollapsed] = useState(true)
const { url, path } = useRouteMatch()
const params = useParams<{ appId: string; envId: string; kind: NodeType; tab?: NodeDetailTabsType }>()
const location = useLocation();
const { searchParams, queryParams } = useSearchString()
const filterStatus = queryParams.has('status') ? queryParams.get('status') : '';
useEffect(() => {
const aggregator = getAggregator(params.kind);
if (aggregator === title) {
setCollapsed(false);
}
}, [params.kind]);
if (filterStatus && filterStatus !== 'All') {
if (
!aggregatedNodes ||
!aggregatedNodes.aggregatorStatusCount ||
!aggregatedNodes.aggregatorStatusCount[title] ||
!aggregatedNodes.aggregatorStatusCount[title][filterStatus]
)
return null;
}
return (
<>
<>
<DropDown
onClick={(e) => setCollapsed(not)}
className={`rotate icon-dim-24 pointer ${!collapsed ? 'fcn-9' : 'fcn-5'}`}
style={{ ['--rotateBy' as any]: collapsed ? '-90deg' : '0deg' }}
/>
<div data-testid={title} onClick={(e) => setCollapsed(not)} className="fs-14 pointer w-100 fw-6 flex left pl-8 pr-8">
{title}
{aggregatedNodes.aggregatorStatusCount[title]?.Degraded > 0 && collapsed && (
<ErrorImage
className="icon-dim-16 rotate"
style={{ ['--rotateBy' as any]: '180deg', marginLeft: 'auto' }}
/>
)}
</div>
</>
{!collapsed &&
Object.keys(data)
.filter((kind) => !filterStatus || (aggregatedNodes.nodeStatusCount[kind] && aggregatedNodes.nodeStatusCount[kind][filterStatus]))
.map((kind) => (
<React.Fragment key={kind}>
<span />
<NavLink
activeClassName="active"
data-testid={kind + "-anchor"}
key={kind}
to={generatePath(path, { ...params, kind }) + location.search}
style={{ height: '36px' }}
className="no-decor fs-14 cn-9 node-link w-100 flex left pl-8 pr-8"
>
{kind}
{aggregatedNodes?.nodeStatusCount[kind]?.Degraded > 0 && (
<ErrorImage
className="icon-dim-16 rotate"
style={{ ['--rotateBy' as any]: '180deg', marginLeft: 'auto' }}
/>
)}
</NavLink>
</React.Fragment>
))}
</>
);
}
interface AllPods {
appName: string;
environmentName: string;
isAppDeployment: boolean;
pods: Map<string, any>;
nodes: AggregatedNodes;
describeNode: (nodeName: string, containerName?: string) => void;
}
export const AllPods: React.FC<AllPods> = ({ isAppDeployment, pods, describeNode, appName, environmentName, nodes }) => {
const params = useParams<{ appId: string, envId: string }>()
const podsArray = Array.from(pods).map(([podName, pod], idx) => pod)
const [podTab, selectPodTab] = useState<'old' | 'new'>('new')
const { newPods, oldPods, newPodStats, oldPodStats, allPodStats } = podsArray.reduce((agg, curr, idx) => {
let podStatus = curr.info.filter(({ name, value }) => name === 'Status Reason')[0]?.value || ''
podStatus = podStatus.toLowerCase()
curr.status = podStatus
if (curr.isNew) {
agg.newPods.set(curr.name, curr)
agg.newPodStats[podStatus] = (agg.newPodStats[podStatus] || 0) + 1
agg.newPodStats['all'] += 1
}
else {
agg.oldPods.set(curr.name, curr);
agg.oldPodStats[podStatus] = (agg.oldPodStats[podStatus] || 0) + 1;
agg.oldPodStats['all'] += 1;
}
agg.allPodStats[podStatus] = (agg.allPodStats[podStatus] || 0) + 1;
agg.allPodStats['all'] += 1;
return agg
}, {
newPods: new Map(),
oldPods: new Map(),
newPodStats: { running: 0, all: 0 },
oldPodStats: { running: 0, all: 0 },
allPodStats: { running: 0, all: 0 }
});
return (
<div>
{isAppDeployment ? (
<>
<div className="flex left old-new-switch-container">
<div
className={`no-decor old-new-link flex left column pl-16 pr-16 pointer ${podTab === 'new' ? 'active' : ''
}`}
onClick={(e) => selectPodTab('new')}
data-testid="all-pods-new"
>
<div className="fs-14 fw-6">New Pods ({newPodStats.all})</div>
<div className="flex left fs-12 cn-9">
{Object.keys(newPodStats)
.filter((n) => n !== 'all')
.map((status, idx) => (
<React.Fragment key={idx}>
{!!idx && <span className="bullet mr-4 ml-4"></span>}
<span key={idx} data-testid={`new-pod-status-${status}`}>
{newPodStats[status]} {status}
</span>
</React.Fragment>
))}
</div>
</div>
<div
className={`no-decor old-new-link flex left column pl-16 pr-16 pointer ${podTab === 'old' ? 'active' : ''
}`}
onClick={(e) => selectPodTab('old')}
data-testid="all-pods-old"
>
<div className="fs-14 fw-6">Old Pods ({oldPodStats.all})</div>
<div className="flex left fs-12 cn-9">
{Object.keys(oldPodStats)
.filter((n) => n !== 'all')
.map((status, idx) => (
<React.Fragment key={idx}>
{!!idx && <span className="bullet mr-4 ml-4"></span>}
<span key={idx}>
{oldPodStats[status]} {status}
</span>
</React.Fragment>
))}
</div>
</div>
</div>
<NestedTable
type={Nodes.Pod}
Data={podTab === 'new' ? newPods : oldPods}
nodes={nodes}
describeNode={describeNode}
level={1}
appName={appName}
environmentName={environmentName}
/>
</>
) : (
<GenericInfo
nodes={nodes}
level={1}
Data={nodes.nodes[Nodes.Pod]}
type={Nodes.Pod}
describeNode={describeNode}
appName={appName}
environmentName={environmentName}
/>
)}
</div>
);
}
export const GenericInfo: React.FC<{ appName: string; environmentName: string; nodes: AggregatedNodes; level?: number; Data: Map<string, any>; type: NodeType; describeNode: (nodeName: string, containerName?: string) => void }> = ({ appName, environmentName, nodes, Data, type, describeNode, level = 1 }) => {
return (
<div className={`generic-info-container flex left column top w-100`}>
{level === 1 && (
<div
className="flex left column w-100 generic-info-header"
>
<div style={{ height: '64px' }} className="pl-16 pr-16 flex column left">
<div className="fs-14 fw-6 cn-9">{type} ({nodes.nodes[type].size})</div>
<div className="flex left">
{nodes.nodeStatusCount[type] &&
Object.entries(nodes.nodeStatusCount[type]).map(([status, count], idx, arr) => (
<React.Fragment key={status}>
<div>
{count} {status.toLowerCase()}
</div>
{idx !== arr.length - 1 && <span className="bullet ml-6 mr-6"></span>}
</React.Fragment>
))}
</div>
</div>
</div>
)}
<NestedTable
type={type}
Data={Data}
nodes={nodes}
describeNode={describeNode}
level={level}
appName={appName}
environmentName={environmentName}
/>
</div>
);
}
export const NestedTable: React.FC<{ appName: string; environmentName: string; level: number; type: NodeType; Data: Map<string, any>; nodes: AggregatedNodes; describeNode: (nodeName: string, containerName: string) => void }> = ({ appName, environmentName, level, type, Data, nodes, describeNode }) => {
const tableColumns = getGenricRowFields(type)
return (
<table className={`resource-tree ${level === 1 ? 'ml-10' : ''}`} style={{ width: level === 1 ? 'calc( 100% - 10px )' : '100%' }}>
<thead>
<tr>
<th></th>
{/* for dropdown */}
{tableColumns.map((field) => (
<th key={field}>{field === 'name' && level > 1 ? type : field}</th>
))}
</tr>
</thead>
<tbody>
{Array.from(Data)?.map(([nodeName, nodeDetails], idx) => (
<GenericRow
nodes={nodes}
key={idx}
nodeName={nodeName}
nodeDetails={nodeDetails}
describeNode={describeNode}
level={level}
appName={appName}
environmentName={environmentName}
/>
))}
{Data.size === 0 && (
<tr>
<td colSpan={tableColumns.length + 1}>
<div className="w-100 flex" style={{ height: '400px' }}>
<NoPod selectMessage="No Available Pods" />
</div>
</td>
</tr>
)}
</tbody>
</table>
);
}
const URL: React.FC<{ url: string }> = ({ url }) => {
return (
<td>
<div className="flex left">
{url}
<Clipboard
className="icon-dim-16 ml-8"
onClick={(e) => copyToClipboard(url, () => toast.success('Copied to clipboard'))}
style={{ cursor: 'pointer' }}
/>
</div>
</td>
);
};
export const Name: React.FC<{ nodeDetails: any, describeNode: (nodeName: string, containerName?: string) => void }> = ({ nodeDetails, describeNode }) => {
const { path } = useRouteMatch();
const history = useHistory();
const params = useParams();
const { queryParams } = useSearchString();
const [copied, setCopied] = useState(false);
useEffect(() => {
if (!copied) return
setTimeout(() => setCopied(false), 2000)
}, [copied])
function showManifest(tab) {
queryParams.set('kind', nodeDetails.kind === Nodes.Containers ? Nodes.Pod : nodeDetails.kind);
const newUrl = generatePath(path, { ...params, tab }) + '?' + queryParams.toString();
describeNode(nodeDetails?.name);
history.push(newUrl);
}
return (
<td className="hover-trigger" data-testid={`${nodeDetails.name}-hover-trigger`}>
<div className="flex left top">
<div className="flex left column">
<div className="flex left">
{nodeDetails?.name}
<Tippy
className="default-tt"
arrow={false}
placement="bottom"
content={copied ? 'Copied!' : 'Copy to clipboard.'}
trigger='mouseenter click'
>
<Clipboard
className="hover-only icon-dim-18 pointer"
onClick={(e) => copyToClipboard(nodeDetails?.name, () => setCopied(true))}
/>
</Tippy>
</div>
{(nodeDetails?.status || nodeDetails?.health?.status) && (
<span
className={` app-summary__status-name f-${(
nodeDetails?.status || nodeDetails?.health?.status
).toLowerCase()}`}
>
{nodeDetails?.status || nodeDetails?.health?.status}
</span>
)}
</div>
{nodeDetails.kind !== Nodes.Containers && (
<>
<span
data-testid={`${nodeDetails.name}-manifest`}
className="hover-only fw-6 anchor pointer ml-6"
onClick={(e) => showManifest(NodeDetailTabs.MANIFEST)}
>
MANIFEST
</span>
<span
data-testid={`${nodeDetails.name}-events`}
className="hover-only fw-6 anchor pointer ml-6"
onClick={(e) => showManifest(NodeDetailTabs.EVENTS)}
>
EVENTS
</span>
</>
)}
{[Nodes.Pod, Nodes.Containers].includes(nodeDetails.kind) && (
<span
data-testid={`${nodeDetails.name}-logs`}
className="hover-only fw-6 anchor pointer ml-6"
onClick={(e) => showManifest(NodeDetailTabs.LOGS)}
>
LOGS
</span>
)}
{nodeDetails.kind.toLowerCase() === 'pod' ?
<span data-testid={`${nodeDetails.name}-logs`}
className="hover-only fw-6 anchor pointer ml-6"
onClick={(e) => showManifest(NodeDetailTabs.TERMINAL)}>
TERMINAL
</span> : null}
</div>
</td>
);
}
export const Menu: React.FC<{ appName: string; environmentName: string; name, namespace, describeNode }> = ({ appName, environmentName, name, namespace, describeNode }) => {
const { path } = useRouteMatch();
const history = useHistory();
const params = useParams();
const { queryParams } = useSearchString();
function describeNodeWrapper(tab) {
queryParams.set('kind', Nodes.Pod);
const newUrl = generatePath(path, { ...params, tab }) + '?' + queryParams.toString();
describeNode(name);
history.push(newUrl);
}
return (
<td>
<PopupMenu autoClose>
<PopupMenu.Button isKebab={true}>
<img src={dots} className="pod-info__dots" />
</PopupMenu.Button>
<PopupMenu.Body>
<PodPopup
name={name}
namespace={namespace}
describeNode={describeNodeWrapper}
appName={appName}
environmentName={environmentName}
/>
</PopupMenu.Body>
</PopupMenu>
</td>
);
}
export const GenericRow: React.FC<{ appName: string; environmentName: string; nodes: AggregatedNodes, nodeName: string; nodeDetails: any; describeNode: (nodeName: string, containerName?: string) => void; level?: number }> = ({ appName, environmentName, nodes, nodeName, nodeDetails, describeNode, level }) => {
const [collapsed, setCollapsed] = useState<boolean>(true);
const tableColumns = getGenricRowFields(nodeDetails.kind)
return (
<React.Fragment>
<tr className={`data-row `}>
<td>
{(nodeDetails.children || nodeDetails?.containers?.length) ? (
<DropDown
data-testid="collapse-icon"
className="icon-dim-24 rotate"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setCollapsed(not);
}}
style={{ ['--rotateBy' as any]: collapsed ? '-90deg' : '0deg' }}
/>
) : null}
</td>
{tableColumns.map((column) => {
if (column === 'url') return <URL key={column} url={nodeDetails.url} />;
else if (column === 'name')
return <Name key={column} nodeDetails={nodeDetails} describeNode={describeNode} />;
else if (column === '') {
return (
<Menu
name={nodeDetails.name}
namespace={nodeDetails.namespace}
describeNode={describeNode}
appName={appName}
environmentName={environmentName}
key={column}
/>
);
} else return <td key={column}>{nodeDetails[column] || ''}</td>;
})}
</tr>
{!collapsed && (nodeDetails.children || nodeDetails.containers) && (
<tr style={{ height: '100%' }}>
<td className="indent-line"></td>
<td colSpan={tableColumns.length} style={{ padding: '0' }}>
{nodeDetails.children &&
Object.keys(nodeDetails.children).map((childrenType) => (
<NestedTable
appName={appName}
environmentName={environmentName}
level={level + 1}
key={childrenType}
type={childrenType as NodeType}
describeNode={describeNode}
nodes={nodes}
Data={nodeDetails.children[childrenType].reduce((agg, childName) => {
agg.set(childName, nodes.nodes[childrenType].get(childName))
return agg
}, new Map)}
/>
))}
{nodeDetails.kind === Nodes.Pod && nodeDetails?.containers?.length &&
<NestedTable
type={Nodes.Containers}
describeNode={(containerName) => describeNode(nodeDetails?.name, containerName)}
level={level + 1}
Data={nodeDetails.containers.reduce((agg, containerName) => {
agg.set(containerName, { name: containerName, kind: Nodes.Containers })
return agg
}, new Map)}
nodes={nodes}
appName={appName}
environmentName={environmentName}
/>
}
</td>
</tr>
)}
</React.Fragment>
);
}
const PodPopup: React.FC<{ appName: string, environmentName: string, name: string, namespace: string, describeNode: (tab?: NodeDetailTabsType) => void }> = ({ appName, environmentName, name, namespace, describeNode }) => {
const params = useParams<{ appId: string; envId: string }>();
async function asyncDeletePod(e) {
let apiParams = {
appId: +params.appId,
appName,
env: environmentName,
envId: +params.envId,
namespace,
name,
};
try {
await deletePodService(apiParams);
toast.success('Deletion initiated successfully.');
} catch (err) {
showError(err);
}
}
return <div className="pod-info__popup-container">
<span className="flex pod-info__popup-row"
onClickCapture={e => describeNode(NodeDetailTabs.EVENTS)}>
View Events
</span>
<span className="flex pod-info__popup-row"
onClick={e => describeNode(NodeDetailTabs.LOGS)}>
View Container Logs
</span>
<span className="flex pod-info__popup-row pod-info__popup-row--red"
onClick={asyncDeletePod}>
<span>
Delete Pod
</span>
<Trash style={{ width: '20px', height: '20px' }} />
</span>
</div>
}
export function NoPod({ selectMessage = "Select a pod to view events", style = {} }) {
return <div data-testid="no-pod" className="no-pod no-pod--pod" style={{ ...style }}>
<PodIcon color="var(--N400)" style={{ width: '48px', height: '48px', marginBottom: '12px' }} />
<p>{selectMessage}</p>
</div>
}
export function EmptyPage({ title = "Data not available" }) {
return <div className="flex column" style={{ height: '100%', width: '100%' }}>
<img src={emptyPageIcon} style={{ height: '48px', width: '48px', marginBottom: '8px' }} />
<div className="title" style={{ fontSize: '16px', marginBottom: '4px', color: 'var(--N900)' }}>{title}</div>
<div className="subtitle" style={{ fontSize: '12px', color: 'var(--N700)', width: '200px', textAlign: 'center' }}>please modify configuration and redeploy.</div>
</div>
}
export default ResourceTreeNodes | typescript |
<reponame>sages-pl/2022-01-pythonsqlalchemy-aptiv<gh_stars>0
"""
* Assignment: OOP Method Syntax
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Define class `Calculator`
2. Define method `add` in class `Calculator`
3. Method `add` take `a` and `b` as arguments
4. Method returns sum of `a` and `b`
5. Run doctests - all must succeed
Polish:
1. Zdefiniuj klasę `Calculator`
2. Zdefiniuj metodę `add` w klasie `Calculator`
3. Metoda `add` przyjmuje `a` i `b` jako argumenty
4. Metoda zwraca sumę `a` i `b`
5. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> from inspect import isclass, ismethod
>>> assert isclass(Calculator)
>>> calc = Calculator()
>>> assert ismethod(calc.add)
>>> calc.add(1, 2)
3
"""
| python |
<reponame>scholzj/kafka-test-apps
package cz.scholz.kafka.testapps.producer;
public class KafkaTestProducerConfig {
private final String bootstrapServers;
private final String topic;
private final int timer;
private final int numberOfKeys;
private final Long messageCount;
private final String acks;
private final String sslTruststoreCertificates;
private final String sslKeystoreKey;
private final String sslKeystoreCertificateChain;
private final boolean hostnameVerification;
private final String username;
private final String password;
private final String auth;
private final String token;
private final String message;
public KafkaTestProducerConfig(String bootstrapServers, String topic, int timer, int numberOfKeys, Long messageCount,
String acks, String sslTruststoreCertificates, String sslKeystoreKey, String sslKeystoreCertificateChain,
boolean hostnameVerification, String username, String password, String auth, String token, String message) {
this.bootstrapServers = bootstrapServers;
this.topic = topic;
this.timer = timer;
this.numberOfKeys = numberOfKeys;
this.messageCount = messageCount;
this.acks = acks;
this.sslTruststoreCertificates = sslTruststoreCertificates;
this.sslKeystoreKey = sslKeystoreKey;
this.sslKeystoreCertificateChain = sslKeystoreCertificateChain;
this.hostnameVerification = hostnameVerification;
this.username = username;
this.password = password;
this.auth = auth;
this.token = token;
this.message = message;
}
public static KafkaTestProducerConfig fromEnv() {
String bootstrapServers = System.getenv("BOOTSTRAP_SERVERS");
String topic = System.getenv("TOPIC");
int timer = Integer.parseInt(System.getenv("TIMER"));
int numberOfKeys = Integer.parseInt(System.getenv("NUMBER_OF_KEYS") == null ? "1" : System.getenv("NUMBER_OF_KEYS"));
Long messageCount = System.getenv("MESSAGE_COUNT") == null ? null : Long.valueOf(System.getenv("MESSAGE_COUNT"));
String acks = System.getenv("ACKS") == null ? "1" : System.getenv("ACKS");
String sslTruststoreCertificates = System.getenv("CA_CRT");
String sslKeystoreKey = System.getenv("USER_KEY");
String sslKeystoreCertificateChain = System.getenv("USER_CRT");
boolean hostnameVerification = System.getenv("HOSTNAME_VERIFICATION") == null || Boolean.parseBoolean(System.getenv("HOSTNAME_VERIFICATION"));
String username = System.getenv("USERNAME") == null ? null : System.getenv("USERNAME");
String password = System.getenv("PASSWORD") == null ? null : System.getenv("PASSWORD");
String auth = System.getenv("AUTH") == null ? null : System.getenv("AUTH");
String token = System.getenv("TOKEN") == null ? null : System.getenv("TOKEN");
String message = System.getenv("MESSAGE") == null ? "Hello World" : System.getenv("MESSAGE");
return new KafkaTestProducerConfig(bootstrapServers, topic, timer, numberOfKeys, messageCount, acks,
sslTruststoreCertificates, sslKeystoreKey, sslKeystoreCertificateChain, hostnameVerification, username,
password, auth, token, message);
}
public String getBootstrapServers() {
return bootstrapServers;
}
public String getTopic() {
return topic;
}
public int getTimer() {
return timer;
}
public int getNumberOfKeys() {
return numberOfKeys;
}
public Long getMessageCount() {
return messageCount;
}
public String getAcks() {
return acks;
}
public String getSslTruststoreCertificates() {
return sslTruststoreCertificates;
}
public String getSslKeystoreKey() {
return sslKeystoreKey;
}
public String getSslKeystoreCertificateChain() {
return sslKeystoreCertificateChain;
}
public boolean isHostnameVerification() {
return hostnameVerification;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getAuth() {
return auth;
}
public String getToken() {
return token;
}
public String getMessage() {
return message;
}
}
| java |
Are you want to add Guest Post system with frontend form, this plugin will help you to do this very easily. You just need to use two shortcodes.
- Use this shortcode [mlgp-form] to show post submission form.
- Use this shortcode [mlgp-post] to show post on frontend.
- Upload the plugin files to the “/wp-content/plugins/ml-guest-post/” directory, or install the plugin through the WordPress plugins screen directly.
- Activate the plugin through the “Plugins” screen in WordPress.
There are no reviews for this plugin.
Translate “Safan Guest Post” into your language.
Interested in development?
Browse the code, check out the SVN repository, or subscribe to the development log by RSS.
| english |
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]
pub enum LogLevel {
Quiet,
Error,
Info,
}
impl LogLevel {
pub fn write(&self, level: &Self) -> Box<dyn std::io::Write> {
match level {
Self::Error => Box::from(std::io::stderr()),
_ => Box::from(std::io::stdout()),
}
}
}
impl From<LogLevel> for &'static str {
fn from(log_level: LogLevel) -> &'static str {
match log_level {
LogLevel::Quiet => "quiet",
LogLevel::Info => "info",
LogLevel::Error => "error",
}
}
}
impl std::str::FromStr for LogLevel {
type Err = String;
fn from_str(s: &str) -> Result<LogLevel, Self::Err> {
match s {
"quiet" => Ok(Self::Quiet),
"info" | "all" => Ok(Self::Info),
"error" => Ok(Self::Error),
level => Err(format!("I don't know the log level of {:?}", level)),
}
}
}
#[macro_export]
macro_rules! outln {
($config:ident#$level:path, $($expr:expr),+) => {{
use $crate::log::LogLevel::*;
writeln!($config.log_level.write(&$level), $($expr),+).expect("Can't write output");
}}
}
| rust |
SummaryWhile progress has been made over the past 250 years, recent events suggest a reversal of fortune. Climate change poses the biggest threat to continued progress, and political arrangements have undergone profound changes.
It has been 10 years since I wrote The Great Escape, which tells the story of how human life improved over the past 250 years, particularly in terms of longevity and material living standards. But the past decadeHI has been unkind to my overwhelmingly positive account. My observation that “life is better now than at any time in history" may have been true in 2013, but it probably is not today, even for the typical person. The question is whether this reversal will be temporary, or whether it is only the beginning of worse to come. Do recent events demand that the basic story be retold?
| english |
{
"name": "@rayo/storm",
"version": "1.2.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "<KEY>
}
}
}
| json |
<filename>src/v3/handshake.rs
use std::{fmt, rc::Rc};
use ntex::time::Seconds;
use super::codec as mqtt;
use super::shared::MqttShared;
use super::sink::MqttSink;
/// Connect message
pub struct Handshake<Io> {
io: Io,
pkt: Box<mqtt::Connect>,
shared: Rc<MqttShared>,
}
impl<Io> Handshake<Io> {
pub(crate) fn new(pkt: Box<mqtt::Connect>, io: Io, shared: Rc<MqttShared>) -> Self {
Self { io, pkt, shared }
}
pub fn packet(&self) -> &mqtt::Connect {
&self.pkt
}
pub fn packet_mut(&mut self) -> &mut mqtt::Connect {
&mut self.pkt
}
#[inline]
pub fn io(&mut self) -> &mut Io {
&mut self.io
}
/// Returns mqtt server sink
pub fn sink(&self) -> MqttSink {
MqttSink::new(self.shared.clone())
}
/// Ack handshake message and set state
pub fn ack<St>(self, st: St, session_present: bool) -> HandshakeAck<Io, St> {
HandshakeAck {
session_present,
io: self.io,
shared: self.shared,
session: Some(st),
keepalive: Seconds(30),
return_code: mqtt::ConnectAckReason::ConnectionAccepted,
}
}
/// Create connect ack object with `identifier rejected` return code
pub fn identifier_rejected<St>(self) -> HandshakeAck<Io, St> {
HandshakeAck {
io: self.io,
shared: self.shared,
session: None,
session_present: false,
keepalive: Seconds(30),
return_code: mqtt::ConnectAckReason::IdentifierRejected,
}
}
/// Create connect ack object with `bad user name or password` return code
pub fn bad_username_or_pwd<St>(self) -> HandshakeAck<Io, St> {
HandshakeAck {
io: self.io,
shared: self.shared,
session: None,
session_present: false,
keepalive: Seconds(30),
return_code: mqtt::ConnectAckReason::BadUserNameOrPassword,
}
}
/// Create connect ack object with `not authorized` return code
pub fn not_authorized<St>(self) -> HandshakeAck<Io, St> {
HandshakeAck {
io: self.io,
shared: self.shared,
session: None,
session_present: false,
keepalive: Seconds(30),
return_code: mqtt::ConnectAckReason::NotAuthorized,
}
}
/// Create connect ack object with `service unavailable` return code
pub fn service_unavailable<St>(self) -> HandshakeAck<Io, St> {
HandshakeAck {
io: self.io,
shared: self.shared,
session: None,
session_present: false,
keepalive: Seconds(30),
return_code: mqtt::ConnectAckReason::ServiceUnavailable,
}
}
}
impl<T> fmt::Debug for Handshake<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.pkt.fmt(f)
}
}
/// Ack connect message
pub struct HandshakeAck<Io, St> {
pub(crate) io: Io,
pub(crate) session: Option<St>,
pub(crate) session_present: bool,
pub(crate) return_code: mqtt::ConnectAckReason,
pub(crate) shared: Rc<MqttShared>,
pub(crate) keepalive: Seconds,
}
impl<Io, St> HandshakeAck<Io, St> {
/// Set idle time-out for the connection in seconds
///
/// By default idle time-out is set to 30 seconds.
pub fn idle_timeout(mut self, timeout: Seconds) -> Self {
self.keepalive = timeout;
self
}
#[doc(hidden)]
#[deprecated(since = "0.7.6", note = "Use memory pool config")]
#[inline]
/// Set read/write buffer sizes
///
/// By default max buffer size is 4kb for both read and write buffer,
/// Min size is 256 bytes.
pub fn buffer_params(
self,
_max_read_buf: u16,
_max_write_buf: u16,
_min_buf_size: u16,
) -> Self {
self
}
}
| rust |
As a new week begins today, know what opportunities and obstacles Monday will most likely bring in your life. Read what's in store for you and what the planets have to say about your day in our daily prediction report. From the relationship front to the professional front, read all about your day here and plan the next 24 hours accordingly.
Wondering what Monday has in store for you? Read today's astrology prediction and find out!
Today you may be blessed by your destiny, your postponed projects may be started now, with the help of elder’s blessings, a messy situation is now under control. which may speed up your project. Disputes between family members may likely to be resolved which may increase in domestic harmony. your creativity may be improved now into artefacts. You may be attracted by glamour.
Today is a good day, you are enthusiastic today. With the help of good focus, you may perform well in business and work. your boss may be supportive, you may get some new responsibilities in terms of promotion. there may be some visit to a religious place. it is advised to avoid arrogance in your love life.
Today you are blessed by the moon, your destiny is with you, your postponed projects are likely to be started now. You may have elder’s blessings, which may help you to come out from the messy situation which may boost the speed of your work. Domestic harmony may make you happy after resolving some disputes between family members. your creativity may be improved now, into artefacts, movies, glamour may attract you.
Today, Your moon is not in a good position, you may feel dull and you may have health issues. You may face losses in this period . it is advised not to invest in risky assets. Your gains may likely to convert into loses. You should stop to invest in worthless objects. You should avoid being involved in controversies, otherwise, it may pull you down negatively.
Today you are blessed by the moon. Love would be in the air in terms of personal life. Singles may find a suitable match. You may do better in terms of professional life. Your friends and subordinate staff may likely to support you.
Today you may have confidence which may reflect into your way of working. You are in the winning position in terms of opponents and enemies. You may have a good focus on your goals. Health issues may be good. In domestic life try to avoid unnecessary arguments, it may affect your domestic harmony.
Today you may feel negative vibrations around you, which may make you unhappy, you are advised to avoid making investments on worthless assets. You may also notice that friends and people around you may not be supportive today. You are advised to not to expect more from anyone in terms of help, otherwise, it may make you nervous. It is advised to take independent decisions today.
Today you may not able to present yourself in a practical way. You may have a dull feeling, which may give you a lack of confidence. So need to follow your intuition while taking decisions in terms of investment. People around you, may not be cooperative in terms of routine work. You are advised to be careful in eating unhealthy food to avoid stomach issues.
Today, you may be bust with your family and friends. You may plan to renovate your house or may bring some creative stuff to maintain your social status, which may increase your prestige. You may expect an increase in your fixed assets.
Today is a positive day in terms of gains. you may get result with a less effort. You losses may convert into profits with the help of your wisdom. You may plan for higher studies to groom your career. you may donate some amount to religious place or charity. You may also help to a needy person. Some investment in an intellectual asset may be possible. Students may do better.
Today you may feel dull, you may have some health-related issues. Chronic disease may reappear. You are advised to avoid rush driving and hurry. You advised to avoid conflicts with the business partner, so avoid to take important decisions in terms of business. Investments in business or work can get postponed. With the blessings from elders, by the late evening, things may be under control.
The author, Samir Jain, is a Jaipur based astrologer who is an expert in astrology, numerology, palmistry, and Vastu. He is also an expert in Jain Temple Vastu and Jain Jyotish. Over the last several years, he has consulted clients from the USA, Brazil, Mexico, Canada, the UK, Australia, Turkey, France, Italy, South Africa, and Germany. | english |
After a long gap Sandalwood queen Ramya came before the media on Wednesday morning at the ÂAryan launch at Kanteerava studio  Prasad studio adjacent to Dr Raj Memorial and was cool in discussing on various topics.
Ramya Congress-I youth wing leader today is taking up the campaigning for her candidates. She has already started for a few candidates in Bangalore. For the second round the star campaigner is advised to take ÂHelicopter to reach wide areas in Karnataka where Congress-I candidates are contesting.
For traveling in air it is a big botheration for Ramya. She has traveled many a times but it is cumbersome she feels. The person sitting next to me is pestered and I prefer A1 seat near the window so that I can jump. I was very much scared when I traveled for ÂSanju Weds Geetha shoot to Bidar. I have even consulted a few people on this fear stated Ramya.
This year is the time to rejoice for Ramya as she has finished a decade of stay in Kannada cinema and undoubtedly the ÂHeroine of the decade in Kannada filmdom like Puneeth Rajakumar hero of the last one decade.
I have not got awards at the state level and other prestigious places are not bothering me. I never went behind it she says. On her Kodi Ramakrishna project a bilingual she is very confident on the response. Kodi sir is recovering. That film will be in the ÂArundhathi pattern. It is at the graphic stage mentioned Ramya.
With a few days of work for ÂDil Ka Raaja with Prajwal Devaraj, Ramya is keen on finishing her two projects  Neer Dosai with Jaggesh and Aryan that has just started with Shivarajakumar. With these two films Ramya is now left out in films of V Ravichandran and Ramesh Aravind top actors of Kannada film.
Ramya alias Divya Spandana in Tamil has given nod for a periodic cinema in the direction of Vasanth Balan that has AR Rahman music.
How about her role in ÂAryan the first combination with century star Shivarajakumar? It has two shades and I have to work out to look a good athlete. I was in to sports when I was studying in Ooty. I am very confident of good progress of this film and I am happy for a film with Shivanna says Ramya. Veteran director D Rajendra Babu is the director of ÂAryan and I have worked with him in ÂBombaat Kannada film Ramya remembers.
Follow us on Google News and stay updated with the latest! | english |
<reponame>NitaiFraire/ClonInstagram
var url = 'http://localhost/Actividades/masterPhp/clonInstagram/public/';
window.addEventListener("load", function(){
// boton like
function like() {
$('.btn-like').unbind('click').click(function(){
$(this).addClass('btn-dislike').removeClass('btn-like');
$(this).attr('src', url + 'img/heartR.png');
$.ajax({
url: url + 'like/' + $(this).data('id'),
type: 'GET',
success: function(response){
if(response.like){
console.log('has dado like a la publicación');
}else{
console.log('error');
}
}
});
dislike();
});
}
like();
// boton dislike
function dislike() {
$('.btn-dislike').unbind('click').click(function(){
$(this).addClass('btn-like').removeClass('btn-dislike');
$(this).attr('src', url + 'img/heart.png');
$.ajax({
url: url + 'disLike/' + $(this).data('id'),
type: 'GET',
success: function(response){
if(response.like){
console.log('has dado dislike a la publicación');
}else{
console.log('error');
}
}
});
like();
});
}
dislike();
// buscador
$('#buscador').submit(function(e){
$(this).attr('action', url + '/gente/' + $('#buscador #search').val());
});
}); | javascript |
"""
Define the Movie model
"""
from . import db
from .abc import BaseModel, MetaBaseModel
class Movie(db.Model, BaseModel, metaclass=MetaBaseModel):
""" The Movie model """
__tablename__ = "movies"
movie_id = db.Column(db.String(300), primary_key=True)
title = db.Column(db.String(300))
author = db.Column(db.String(300))
release_year = db.Column(db.Integer)
def __init__(self, movie_id, title, author, release_year):
""" Create a new movie """
self.movie_id = movie_id
self.title = title
self.author = author
self.release_year = release_year
| python |
Niti Aayog’s proposal to create a cloud-based platform to store and share the health data of Indians has raised alarm among health and digital rights activists, but medical technology companies have welcomed it.
Called the National Health Stack, the platform will facilitate the flow of information between multiple stakeholders – patients, doctors, national health programmes, insurance companies, medical researchers, health technology companies. In the document outlining the proposal, Niti Aayog has argued that this will improve access and affordability of healthcare and boost medical research.
Medical technology companies are optimistic about the plan. “The National Health Stack approach looks at technology as an integral part of healthcare delivery,” said Prasad Kompalli, chief executive officer and co-founder of mfine, a company that has built a mobile application to connect doctors and patients. The app is powered by an artificial intelligence system to create “virtual hospitals”, that is, the app does not simply connect doctors and patients but also collects, structures and analyses the patient’s medical data to help the doctor diagnose and treat the patient.
According to the Niti Aayog proposal, the National Health Stack will be based on a system of open application programme interfaces to transfer information, with a national health ID that is possibly linked to the biometrics-based identity system Aadhaar. As reported by Scroll.in on July 12, digital rights activists have pointed out the dangers of having sensitive medical information stored and shared on an open application programme interface system. Although the document states that the patient will own and control his data, it is unclear who will own and control the health stack. The system is based on India Stack, a cloud-based set of open application programme interface systems for digital payments, over which there have been questions of private companies’ access to both public resources and citizens’ Aadhaar data. Moreover, there is uncertainty over how the National Health Stack will be able to ensure confidentiality of patient data and that any medical information is only shared with the informed consent of the patient.
However, Kompalli said as a technologist he sees infrastructure like a universal digital health ID that can be recognised across health systems in the country, a system of health record management and open application programme interfaces leading to better data standards – that is, data that is collected and recorded more accurately, is more complete and formatted uniformly to enable easier sharing. “When data quality improves, a lot of innovation is possible for diagnosis, diagnostics, long-term care, identifying root causes of patient’s problems, geographical spread of viral infections, predicting and preventing diseases based on geography and patient age groups,” he said.
India now has several medical technology companies like mfine that offer a range of services. Apart from medical device and prosthetics manufacturers, a number of companies are investing in the “Internet of Medical Things” – using the internet to offer clinical services like video consultations, remotely monitoring a patient’s vitals, artificial intelligence to control ICU devices and so on. These technologies are also used for non-clinical use such as connecting ambulances to hospital networks and to streamline hospital appointments and rescheduling. There is little documentation on the current size of this fast growing new sector.
Nair co-founded and ran Paycillin, a digital tool for billing and payments at medical clinics, and a nationwide telemedicine network called MeraDoctor. He said a database of the National Health Stack could be a potential “gold mine” for medical research.
The health stack system could help gather such data, Nair said.
Kompalli believes that a company like mfine can use a platform like the National Health Stack to provide better healthcare services. Mfine connects patients to doctors over the internet through a mobile phone application. The doctor gets structured patient data through the app, which stores patient medical data. The artificial intelligence system powering the app also analyses the patient data and presents the doctor with evidence and options, before the doctor makes a final diagnosis. The artificial intelligence system also learns from the doctor’s decision and patient feedback such has how long he took to recover and what his vitals were after medication. This helps the system present a doctor with better analysis the next time there is a similar case, said Kompalli.
With a national health identifier, such as proposed under the National Health Stack, Kompalli said that mfine will be able to retrieve data more easily. “If a patient wants data to be obtained from a hospital using this ID, we should be able to do it,” he said.
Kompalli also believes that mfine can potentially serve as a health registry within the National Health Stack “by storing data and making it accessible to patients and for whatever uses the patient has authenticated”.
Moreover, all universal healthcare systems run on some kind of universal identifiers, Nair pointed out. “That being said, you need to have protections for data and you need to protect against people not being denied coverage of care [if they do not have an ID], especially emergency care, where you might also need different access rules or a waiver for consent [because the patient might not have the capacity to consent],” he added.
Similarly, MeraDoctor had a privacy policy that gave the patients control of their data. This is easily done on these mobile apps, where the patient can give his consent before each online consultation. But as health activists have pointed out, giving patients control of their data will be significantly more difficult on a pan-India platform that reaches out to patients in urban and rural areas, with varying levels of education and who may or may not be able to use smartphones. Speaking to Scroll.in earlier, health researcher Prasanna Saligram said that the system outlined in the document “places the onus of control on the user with an assumption that they know how to control the flow of information through APIs [application programme interfaces], like a software engineer. In reality, the user is more likely to be an elderly lady with low levels of literacy who earns by selling coriander”.
The National Health Stack also proposes a system in which the patient is the owner and controller of his or her data but the question is open as to how it will implement patient control and enable their consent in an open application programme interface framework.
| english |
{
"kid": "https://akv-mule-integration-key.vault.azure.net/keys/akv-mule-key/<KEY>",
"value": "<KEY>"
} | json |
art training facilities.
they be re-trained accordingly.
opinion or their demands in a democratic set-up. These trainings, he stressed,
day-to-day dealing with public and improve the image of police.
in the NCR.
doubled from 167 at present to 334.
raised from Rs 2 lakh at present to Rs 10 lakh.
police trainers of the police training institutions along with the medal.
to Central Detective Training Institute.
Dr. Meeran C Borwankar,
16 years at present.
was attended by a large number of dignitaries including Shri. K Durga Prasad,
Academy, Shri Anurag Sharma, DGP Telangana, Shri. Radhakrishnan Kini A,
Secretary (Security), Shri Alok Pateria ADG Madhya Pradesh, Shri M Malkondiah,
along with several public representatives.
instituted at the national level for CAPFs and States/ UTs in three categories,
Minister’s Commendation Disc for excellence in training.
includes a trophy and Rs. 2 lakh for infrastructure development.
conferred this medal by Union Home Minister has been announced.
such, awards of Rs 1.5 crores have been given away by the Union Home Minister,
Winners of Trophy of Best Training Institutions at National Level CAPFs/CPOs)
Ms. Aruna Bahuguna ,IPS,Director,
CTC Neemuch (CRPF)
RTC Neemuch,( CRPF)
National Level (States/UTs)
Grey Hounds Trg Centre PV pet, Hyderabad,
Sh. Govind Singh, IPS, ADG (Ops),
(Octopus & Grey Hounds)
Sr. No.
Satpal Rawat,
/ Principal, CTC CRPF (Neemuch)
/ Principal, RTC CRPF( Neemuch)
& MD APSR TC Vijaywada A.P. (former Director, RBVRR TSP Academy)
of Police Rachkonda, Hyderabad (former IGP, Grey Hounds TS)
Sr. No.
Sr. No.
latest knowledge of scientific techniques and best practices in investigation.
The police officers from the States of MP, UP, Delhi, Bihar, Uttarakhand,
trained at CDTS Ghaziabad.
Cyber Crimes’, ‘Interrogation Techniques’, ‘Investigation of Organized Crime’,
Building, Guest House, Hostel for Women, an Auditorium, Badminton Court,
| english |
<reponame>meesokim/openmsx-0.13.0
#include "MSXKanji12.hh"
#include "MSXException.hh"
#include "serialize.hh"
namespace openmsx {
static const byte ID = 0xF7;
MSXKanji12::MSXKanji12(const DeviceConfig& config)
: MSXDevice(config)
, MSXSwitchedDevice(getMotherBoard(), ID)
, rom(getName(), "Kanji-12 ROM", config)
{
unsigned size = rom.getSize();
if ((size != 0x20000) && (size != 0x40000)) {
throw MSXException("MSXKanji12: wrong kanji ROM, it should be either 128kB or 256kB.");
}
reset(EmuTime::dummy());
}
void MSXKanji12::reset(EmuTime::param /*time*/)
{
address = 0; // TODO check this
}
byte MSXKanji12::readSwitchedIO(word port, EmuTime::param time)
{
byte result = peekSwitchedIO(port, time);
switch (port & 0x0F) {
case 9:
address++;
break;
}
return result;
}
byte MSXKanji12::peekSwitchedIO(word port, EmuTime::param /*time*/) const
{
byte result;
switch (port & 0x0F) {
case 0:
result = byte(~ID);
break;
case 1:
result = 0x08; // TODO what is this
break;
case 9:
if (address < rom.getSize()) {
result = rom[address];
} else {
result = 0xFF;
}
break;
default:
result = 0xFF;
break;
}
return result;
}
void MSXKanji12::writeSwitchedIO(word port, byte value, EmuTime::param /*time*/)
{
switch (port & 0x0F) {
case 2:
// TODO what is this?
break;
case 7: {
byte row = value;
byte col = ((address - 0x800) / 18) % 192;
address = 0x800 + (row * 192 + col) * 18;
break;
}
case 8: {
byte row = (address - 0x800) / (18 * 192);
byte col = value;
address = 0x800 + (row * 192 + col) * 18;
break;
}
}
}
template<typename Archive>
void MSXKanji12::serialize(Archive& ar, unsigned /*version*/)
{
ar.template serializeBase<MSXDevice>(*this);
// no need to serialize MSXSwitchedDevice base class
ar.serialize("address", address);
}
INSTANTIATE_SERIALIZE_METHODS(MSXKanji12);
REGISTER_MSXDEVICE(MSXKanji12, "Kanji12");
} // namespace openmsx
| cpp |
<gh_stars>10-100
// $Id: MessengerHandler.cpp 85583 2009-06-09 13:47:38Z calabrese_p $
#include "MessengerHandler.h"
#include "ace/OS_NS_time.h"
#include <iostream>
// Implementation skeleton constructor
MessengerHandler::MessengerHandler (CORBA::ORB_ptr orb)
: time_(0)
, orb_(CORBA::ORB::_duplicate(orb))
{
}
// Implementation skeleton destructor
MessengerHandler::~MessengerHandler (void)
{
}
void MessengerHandler::send_message (
CORBA::Boolean ami_return_val,
const char * message,
CORBA::Long time
)
{
if (ami_return_val)
{
time_ = time;
time_t t = time_;
const ACE_TCHAR * time_str = ACE_OS::ctime(&t);
if (time_str != 0) {
std::cout << std::endl << "Message sent at " <<
ACE_TEXT_ALWAYS_CHAR (time_str) << std::endl;
}
std::cout << "Content of message: " << message << std::endl;
}
else
{
std::cerr << "Error: Message was not sent." << std::endl;
}
// Our simple test just shuts down after sending one message.
orb_->shutdown(false);
}
void MessengerHandler::send_message_excep (Messaging::ExceptionHolder* excep_holder)
{
// We'll print an error message and shut down the orb
try
{
excep_holder->raise_exception();
}
catch(const CORBA::Exception& ex)
{
std::cerr << "A CORBA Exception was thrown: " << ex << std::endl;
}
orb_->shutdown(false);
}
| cpp |
package com.xmc.hospitalrec.dao;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.xmc.hospitalrec.model.BackupTask;
@Repository("brDao")
@Transactional(propagation = Propagation.SUPPORTS)
public class BrDao extends AbstractDao {
public void setBackupTask(BackupTask backupTask) {
BackupTask task = (BackupTask) this.find(BackupTask.class, backupTask.getVnfName());
if(task==null) {
this.insert(backupTask);
} else {
this.update(backupTask);
}
}
}
| java |
{
"id":6,
"name":"TARS stabilisation",
"description": "Moving TARS applications to AWS",
"theme": "TARS",
"location": "Leeds/Nottingham",
"phase":"alpha",
"phase_modifier":"Private",
"sro":"<NAME>",
"service_man":"TBC",
"phase-history":{
"discovery": [
{"label":"Started", "date": "October 2016"},
{"label":"Completed", "date": "January 2017"}
],
"alpha": [
{"label":"Started", "date": "October 2017"},
{"label":"Completed", "date": "December 2017"}
]
},
"priority":"1",
"prototype":""
}
| json |
LONDON: At least three persons of Indian origin are to be the Members of European Parliament (MEPs) in the ninth European Parliament.
Claude Moraes and Neena Gill who were first ever Indian-origin MEPs elected in 1999, retained their seats this time again. A new face Dinesh Dhamija, 69 years old multimillionaire, is elected to European Union Parliament (EUP) representing the Liberal Democrats.
Dinesh Dhamija bats for European Union. He argues, ‘Being part of EU gives better negotiating power. Collective GDP of EU is worth US$18 trillion a year far greater than UK’s just US $ 3 trillion. Brexit party did not win in London.
(Agencies) | english |
New Delhi: RBI Governor Shaktikanta Das has tested positive for the coronavirus, he tweeted on Sunday."I have tested COVID-19 positive. Asymptomatic.Feeling very much alright.Have alerted those who came in contact in recent days.Will continue to work from isolation. Work in RBI will go on normally. I am in touch with all Dy. Govs and other officers through VC and telephone," he wrote.COVID-19 cases reported in India in a span of 24 hours remained below 55,000 for the third consecutive day, while the new fatalities recorded in a day dropped to 578 after almost three months, according to the Union Health Ministry on Sunday.
| english |
Saudi Arabia’s recent theatrical execution of 47 men, including the Shia cleric and activist, Nimr al-Nimr, speaks volumes about the Saudi regime and sectarian tensions in the Middle East. Saudi policies may look complex, but they are driven by a single impulse: Fear.
Above all, Saudi rulers fear Iranians, Shiites and democrats. Iranians threaten the kingdom’s pretensions to regional hegemony; Shias might be agents of Iran; and democrats challenge the Saudi model of no elections, no rights, and no popular participation. Al-Nimr, who advocated both Shia rights and political liberalisation, represented everything that makes Saudi princes panic.
Consequently, Saudi Arabia wages war on Iran, and Iran on Saudi Arabia, through proxies. The oil behemoths often turn what might have started as manageable local battles into national conflagrations. What look like primordial, unsolvable sectarian conflicts between Sunnis and Shiites in Syria, Yemen, Iraq, Lebanon, Bahrain, and even Pakistan, are often fuelled by the Saudi-Iranian conflict.
While geopolitical rivalry undergirds sectarianism, there are real and growing tensions between Sunnism and Shi’ism. Arab nationalism, including its secular variants, has long treated orthodox Sunni Islam as the proper religion of the Arabs and Shi’ism as a Persian corruption of Islam. While this is historically inaccurate, some Sunni Arabs see their Shia brethren as an Iranian fifth column. Some see the ascent of the Shia majority in Iraq following Saddam Hussein’s ouster much like some whites in the US regard Barack Obama’s presidency — an alarming perversion of the natural order.
By executing al-Nimr, Saudi rulers advertise to Sunnis that they will lead the fight against both Iran and the Shia menace. By attacking Saudi Arabia for its treatment of al-Nimr, Iran poses as the defender of the Shias. But al-Nimr didn’t just advocate Shia equality. He also extolled the Arab Spring uprisings, which frightened Saudi rulers even more.
Anything that smacks of popular empowerment spooks Saudi rulers, even if inspired by Muslim religiosity. The rise of the Muslim Brotherhood in Egypt and al-Nahda in Tunisia struck the Saudi princes as an existential threat. The result is the spectacle of a regime that pretends to be the sword of the faith backing staunchly secularist regimes against popular Islamists.
Since they fear not only all Shias but also Sunnis who wish to replace the current power structures, the timorous princes are left battling everyone, except militantly secularist dictators and the Israelis. Little wonder, they invest so heavily in fighting Shias — that’s the only claim they can make to political leadership of the faithful.
Memories of the Arab Spring aren’t the only things frightening the princes. A leadership succession looms. Following the death of King Abdullah in January 2015, the helm of state fell to the 80-year-old Salman and his 30-year-old favourite son, Mohammad bin Salman. Like Kim Jung-un, young Mohammad impresses with his youth, lust for lucre, arrogance and belligerence. Last year, he took charge of the effort to put down the Houthi rebellion in Yemen, which promptly degenerated into a quagmire.
Wars, along with plunging oil prices, have cut the kingdom’s capacity to buy popular acquiescence. In 2011, Abdullah responded to the Arab Spring with a $70 billion package for housing and healthcare. With oil at one-third of its 2011 price and the government running a $100 billion annual deficit, the princes cannot afford such sops today. Given their hostility to sharing any power with their subjects and their declining capacity to buy their subjects’ loyalty, playing to popular nationalism and prejudice may be one of the few tools the Saudi rulers have left. Attacking Shias and confronting Iran are crowd-pleasers at home.
Iranian hardliners, such as Ayatollah Ali Khamenei, make a similar wager. The interests of the hardliners on each side converge. Both Prince Mohammad and Khamenei would delight in derailing Iran’s nuclear deal with the West — which open confrontation between Riyadh and Tehran would do. Both seek to use conflict with the other to whip up support and silence calls for reform.
The interests of ordinary people also converge in certain ways. Each month, Iran shells out $1-2bn to fight Saudi-backed rebels in Syria and Saudi Arabia spends $3-4bn battling Iranian-backed insurgents in Yemen. The people gain nothing from such expenditures. Implementation of the nuclear deal, which 75 per cent of Iranians support, frees up $58bn in frozen assets and enables Iran to boost oil exports by 1. 5 million barrels a day.
If Saudi Arabia and Iran seem to be locked in a ludicrous contest to see which side can bankrupt itself first with its efforts to undermine the other, the reason is in the mac-hinations of hardliners, not in the interests of ordinary people. But both regimes are fraying, and their rulers’ tacit game of mutual support against the masses might not last forever. | english |
Mysore/Mysuru: A housewife and a 15-year-old girl have gone missing in separate cases in city.
In the first incident, a housewife has gone missing from her parents’ house and a missing complaint has been lodged at Yelwal Police Station. The missing woman, identified as Sindhu of Chatradakoppal village in the taluk was given in marriage to one H. K. Naveen of Hebbal village in K. R. Nagar taluk and she had come to her parents’ house for Gowri-Ganesha festival.
A few days ago, Naveen had taken Sindhu to a hospital for check-up and had again left her in her parents’ house. But a missing complaint was lodged stating that she went missing from the house on Aug. 28 midnight, according to Yelwal Police.
Those having any information about the missing woman may contact Yelwal Police on Ph: 0821-2402222 or 94808-05031.
In the second case, a 15-year-old girl, identified as Priyanka Parge, daughter of Tulajaram Shastry, residing near Abhishek Circle in Manchegowdanakoppal, has gone missing.
On Sept. 3, when Priyanka’s father and brother had been to Shivarampet and her mother was having her bath, Priyanka went missing, according to the complaint lodged by her father with Hebbal Police.
She is 4. 3 ft. tall, speaks Kannada and Marathi and was wearing a red coloured chudidhar at the time of going missing.
Those having any information about the missing girl may contact Hebbal Police on Ph: 0821-2418318 or Police Control Room on Ph: 0821-2418339. | english |
package com.fr.swift.cloud.query.result.detail;
import com.fr.swift.cloud.result.detail.MergeDetailQueryResultSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;
/**
* Create by lifan on 2019-07-02 16:17
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({DetailResultQuery.class})
public class DetailResultQueryTest {
@Test
public void merge() throws Exception {
List queries = mock(List.class);
List resultsets = mock(List.class);
int fetchSize = mock(Integer.class);
MergeDetailQueryResultSet mergeDetailQueryResultSet = mock(MergeDetailQueryResultSet.class);
whenNew(MergeDetailQueryResultSet.class).withArguments(fetchSize, resultsets).thenReturn(mergeDetailQueryResultSet);
assertEquals(mergeDetailQueryResultSet, new DetailResultQuery(fetchSize, queries).merge(resultsets));
}
} | java |
package com.example.administrator.ttt_test.fragment.local.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;
import com.example.administrator.ttt_test.R;
import com.example.administrator.ttt_test.bean.QuestionOptionVO;
import com.example.administrator.ttt_test.util.path.ImagePath;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Acer on 2017/4/9.
*/
public class PictureSelectAdapter extends RecyclerView.Adapter {
private List<QuestionOptionVO> list=new ArrayList<>();
private Context context;
private long questionnaireId;
private class mViewHolder extends RecyclerView.ViewHolder {
private RadioButton rb_choice;
private ImageView iv_choice;
public mViewHolder(View itemView) {
super(itemView);
rb_choice= (RadioButton) itemView.findViewById(R.id.radioButton_item_single_image_choice);
iv_choice= (ImageView) itemView.findViewById(R.id.imageView_item_single_image_choice);
}
}
public PictureSelectAdapter(List<QuestionOptionVO> list,Context context,long questionnaireId){
this.list=list;
this.context=context;
this.questionnaireId=questionnaireId;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_single_image_choice,parent,false);
mViewHolder holder=new mViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
File file=new File(ImagePath.getImagePath()+questionnaireId+"/"+list.get(position).getOption());
if(file.exists()){
Bitmap bitmap= BitmapFactory.decodeFile(file.getAbsolutePath());
((mViewHolder)holder).iv_choice.setImageBitmap(bitmap);
}
else {
Toast.makeText(context,"图片不存在",Toast.LENGTH_SHORT).show();
}
}
@Override
public int getItemCount() {
return list.size();
}
}
| java |
<h2>Terms and Conditions</h2>
<p>Welcome to PolyForest® Time!</p>
<p>These terms and conditions outline the rules and regulations for the use of PolyForest Time's Website, located at <a href="https://time.polyforest.com">https://time.polyforest.com</a>.</p>
<p>The following terminology applies to these Terms and Conditions, Privacy Statement and Disclaimer Notice and all Agreements: "Client", "You" and "Your" refers to you, the person log on this website and compliant to the Company's terms and conditions. "The Company", "Ourselves", "We", "Our" and "Us", refers to our Company. "Party", "Parties", or "Us", refers to both the Client and ourselves.</p>
<p>By accessing this website we assume you accept these terms and conditions. Do not continue to use PolyForest Time if you do not agree to take all of the terms and conditions stated on this page.</p>
<p>PolyForest Time uses Google services, whose terms and conditions may be found separately at <a href="https://www.google.com/drive/terms-of-service/" title="Google Drive TOS">https://www.google.com/drive/terms-of-service/</a></p>
<h3>Cookies</h3>
<p>We employ the use of cookies. By accessing PolyForest Time, you agreed to use cookies in agreement with the PolyForest Time's Privacy Policy.</p>
<p>Most interactive websites use cookies to let us retrieve the user's details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.</p>
<h3>License</h3>
<p>Unless otherwise stated, PolyForest Time and/or its licensors own the intellectual property rights for all material on PolyForest Time. All intellectual property rights are reserved. You may access this from PolyForest Time for your own personal use subjected to restrictions set in these terms and conditions.</p>
<p>You must not:</p>
<ul>
<li>Republish material from PolyForest Time</li>
<li>Sell, rent or sub-license material from PolyForest Time</li>
<li>Reproduce, duplicate or copy material from PolyForest Time</li>
<li>Redistribute content from PolyForest Time</li>
</ul>
<p>Exceptions include personal content provided by Google services, which are governed by Google's terms of service.</p>
<p>This Agreement shall begin on the date hereof.</p>
<p>No use of PolyForest Time's logo or other artwork will be allowed for linking absent a trademark license agreement.</p>
<h3>iFrames</h3>
<p>Without prior approval and written permission, you may not create frames around our Webpages that alter in any way the visual presentation or appearance of our Website.</p>
<h3>Content Liability</h3>
<p>We shall not be hold responsible for any content that appears on your Website. You agree to protect and defend us against all claims that is rising on your Website. No link(s) should appear on any Website that may be interpreted as libelous, obscene or criminal, or which infringes, otherwise violates, or advocates the infringement or other violation of, any third party rights.</p>
<h3>Reservation of Rights</h3>
<p>We reserve the right to request that you remove all links or any particular link to our Website. You approve to immediately remove all links to our Website upon request. We also reserve the right to amend these terms and conditions and its linking policy at any time. By continuously linking to our Website, you agree to be bound to and follow these linking terms and conditions.</p>
<h3>Removal of links from our website</h3>
<p>If you find any link on our Website that is offensive for any reason, you are free to contact and inform us any moment. We will consider requests to remove links but we are not obligated to or so or to respond to you directly.</p>
<p>We do not ensure that the information on this website is correct, we do not warrant its completeness or accuracy; nor do we promise to ensure that the website remains available or that the material on the website is kept up to date.</p>
<h3>Disclaimer</h3>
<p>To the maximum extent permitted by applicable law, we exclude all representations, warranties and conditions relating to our website and the use of this website. Nothing in this disclaimer will:</p>
<ul>
<li>limit or exclude our or your liability for death or personal injury;</li>
<li>limit or exclude our or your liability for fraud or fraudulent misrepresentation;</li>
<li>limit any of our or your liabilities in any way that is not permitted under applicable law; or</li>
<li>exclude any of our or your liabilities that may not be excluded under applicable law.</li>
</ul>
<p>The limitations and prohibitions of liability set in this Section and elsewhere in this disclaimer: (a) are subject to the preceding paragraph; and (b) govern all liabilities arising under the disclaimer, including liabilities arising in contract, in tort and for breach of statutory duty.</p>
<p>We will not be liable for any loss or damage of any nature.</p>
<h3>Trademarks</h3>
<p>PolyForest® is a registered trademark of Poly Forest, LLC.</p>
<p>Google Drive is a trademark of Google Inc. Use of this trademark is subject to Google Permissions. <a href="https://developers.google.com/drive/api/v3/branding">https://developers.google.com/drive/api/v3/branding</a></p>
| html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.