text
stringlengths 1
1.04M
| language
stringclasses 25
values |
|---|---|
Search Results for "auditory hallucination"
What can be the common side effects of using Fennel Oil?
What can be the common side effects of using Ropinirole?
Schizophrenia is a chronic problem caused by Neuro chemical disturbance in brain. It is characterised by fear, odd experiences and distorted thought pattern. Treatment is with antipsychotic medicines which may need to continue throughout life. Coping with a mental disorder as serious as schizophrenia can be challenging, both for the person with the condition and for friends and family. Here are some ways to cope: 1. Learn about schizophrenia. Education about the disorder can help motivate the person with the disease to stick to the treatment plan. Education can help friends and family understand the disorder and be more compassionate with the person who has it. 2. Join a support group. Support groups for people with schizophrenia can help them reach out to others facing similar challenges. Support groups may also help family and friends cope. 3. Stay focused on goals. Managing schizophrenia is an ongoing process. Keeping treatment goals in mind can help the person with schizophrenia stay motivated. Help your loved one remember to take responsibility for managing the illness and working toward goals. 4. Ask about social services assistance. These services may be able to assist with affordable counselling services, job placements and other daily activities. 5. Learn relaxation and stress management. The person with schizophrenia and loved ones may benefit from stress-reduction techniques such as meditation, yoga or tai chi. Please see a psychiatrist for further guidance.
Auditory hallucinations in elderly can occur due to primary neurochemical disturbance or secondary to a metabolic problem. Please see a psychiatrist asap. Medicines can resolve the symptoms but evaluation is necessary.
What can be the common side effects of using Citicoline?
What can be the common side effects of using Entacapone?
What can be the common side effects of using Piracetam?
What can be the common side effects of using Altretamine?
What can be the common side effects of using Benzhexol?
What can be the common side effects of using Ketamine?
The common side effects seen with use of Ketamine are: Nausea, Agitation, Double vision, Erythema, Vomiting, Nightmare, Abnormal dreams, Abnormal behavior, Hallucination, Generalized tonic-clonic seizure, Increased respiratory rate , Hypertonia, Increased blood pressure, Tachycardia, Confusion, Nystagmus (involuntary eye movement)
What can be the common side effects of using Benserazide?
What can be the common side effects of using Carbidopa?
|
english
|
{
"main": {
"select_state": "Select your state",
"before_hospital": "Before hospital visit",
"during_hospital": "During hospital visit",
"after_hospital": "After hospital visit",
"search": "검색",
"select_provider": "보험사 선택"
}
}
|
json
|
Mumbai, Sep 13: Despite Raj Thackeray's belief that Hindi filmdom is biased against Marathi, there is a long list of actors who speak the language almost as well as he does. And, most of them were not even born into Maharashtrian families.
Virar ka chhokra Govinda, for instance, studied in a Marathi medium school and still converses in the language with many of his friends. Actor Rekha, who is the daughter of Tamilian superstar Gemini Ganeshan, speaks in Marathi to her staff and photographers. Veteran actor Dilip Kumar would travel from Bandra to the Marathi heartland of Dadar to watch a number of Marathi plays at Shivaji Mandir. Recalls a senior Marathi journalist, "People called Dilip Kumar an outsider, but I remember him watching Ghashiram Kotwal. He spoke such fluent Marathi that I was floored. "
Fifteen years ago, Chennai-based actor Kamal Hasan stunned the audience attending the Maharashtra state awards function at Rang Bhavan in Bandra. "After a spate of speeches, the compere turned to Kamal Hasan, who was the chief guest of the function, and wondered if he had understood what the others had said in Marathi," says journalist Dilip Thakur, who has written several books on Hindi cinema. The actor walked to the mike and spoke in chaste Marathi. "He obviously got a huge round of applause from the audience," Thakur said.
Congress MP and actor Govinda considers himself a Maharashtrian. "My entire education has been in Marathi and I have grown up in Virar. Most of my friends are Maharashtrians. I am more a Maharashtrian than a north Indian," he told TOI.
Jeetendra, the Jumping Jack of Bollywood and superstar Rajesh Khanna grew up in the narrow bylanes of Girgaum and speak fluent Marathi. During Ganeshotsav, Jeetendra still visits the chawl in which he lived, every year. "I remember Vinod Khanna speaking in Marathi to his wife Kavita in Dalhousie during the shooting of his son's film Himalaya Putra,"' said Thakur.
Viewers of Fear Factor, the reality show on TV, may have watched Akshay Kumar speaking to actor Sonali Kulkarni in Marathi. "The staff of most actors are Maharashtrians. So, the stars interact with them in Marathi," said Pradeep Bandekar, who been a freelance photographer in the film industry for over 32 years. "Jackie Shroff and Anil Kapoor will give any Marathi boy a complexwith their mastery overthe language. "
An old-timer insists that actors Rekha and Dimple Kapadia speak Marathi better than even Madhuri Dixit. Actor Sachin Pilgaonkar adds, "Quite a few of our actors speak in Marathi. I interact with Dimple Kapadia, Rekha and Rajeshwari Sachdev only in Marathi. "
Vidya Malavade of Chak De fame has just finished shooting with Suniel Shetty and Dimple Kapadia. "Suniel speaks fluent Marathi and even Dimpleji too. I think most of those who work in Mumbai definitely know and speak the language even if it is broken Marathi. "
Incidentally, superstar Amitabh Bachchan whose family triggered the latest offensive from Raj Thackeray and his MNS men, has written in his blog about how his wife is fluent in Marathi too. "Jaya has had her education at the FTII in Pune. She speaks fluent Marathi and a major portion of her staff are Maharashtrians," he wrote.
|
english
|
In New York City, the days of overlooked and underfunded training of police officers are long gone, according to the NYPD’s First Deputy Commissioner Benjamin Tucker, who credited the ongoing training of their officers for the “steady decline” in the number of instances deadly force is involved.
According to the NYPD’s 2018 Use of Force Report, out of the 6. 1 million 911 calls the NYPD received that, officers discharged their weapon only 35 times.
Tucker was instrumental in opening the new College Point training facility following the death of Eric Garner in 2014. The 39-year-old Garner, who was Black, died after officer Daniel Pantaleo put him in a chokehold alleging that the man was resisting arrest.
Tucker said it was then he realized that officers who had received tactical training during the academy never received it again. Before his current role, Tucker was appointed as the deputy commissioner for training by Commissioner Bill Bratton.
That year, the NYPD’s 22,000 patrol officers were retrained and received body cameras.
“Having that video. It's made our officers more effective, more efficient," Tucker said.
Some believe police body cameras have helped improve the accountability of police departments. The video aids in corroborating the facts of police encounters so that discipline can be taken if needed. Like in the June 2020 suspension of Officer David Afanador, who reportedly held a Queens man in a chokehold while resisting arrest.
Tucker said body camera video does more than just help people see how officers are arresting people and who needs more training. He said the videos also allow the public to see the dangers that officers face every day.
Tucker added that the type of force that is used on suspects is something officers contemplate in every situation, but the training NYPD officers receive specifically focuses on de-escalation. He said training takes place on a regular basis.
Other types of training are based on legislation passed by the New York City Council. Most recently passed was legislation that requires officers to avoid the diaphragm area during an arrest.
NYPD FIRST DEPUTY COMMISSIONER: DISMANTLING POLICE IS 'UNREALISTIC AND DOESNT MAKE SENSE' BUT AGREES THERES ROOM FOR 'OTHER IMPROVEMENTS'
Police in New York City and other jurisdictions across the U. S. have been under increased scrutiny since the death of George Floyd in police custody in Minneapolis. Although the NYPD has taken steps to address criticized methods and excessive use of force in their training strategies, some critiques say this training is too little, too late and that most of the NYPD’s training is reactive, not proactive.
“There is no preventive measures, there’s nothing to make policing more quintessential, there’s nothing that entails professional development to be proactive as opposed to reactive,” retired NYPD Lieutenant Darrin Porcher told Fox 5 New York.
“We need a system that works for not just police officers, but New York. Ultimately we need to keep both sides safe," Porcher added.
According to a report released on Monday, police and law enforcement across the country used force against protesters in at least 125 separate incidents in the 10 days following the death of George Floyd on May 25.
Protesters have taken to the streets in droves since Floyd’s death, and Tucker said they are “reviewing tactics used by the violent protesters” as well as their own tactics to handle these situations.
|
english
|
<reponame>minhnb/TodoList-Angular
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { MHttp } from './mHttp';
import { AppConfig } from '../app.config';
import { AppConstant } from '../app.constant';
@Injectable()
export class ToDoService {
private toDoListUrl = AppConfig.API_URL + 'todo_lists';
private toDoChildUrl: string = 'todos';
constructor(private mHttp: MHttp) { }
createList(name: string): Observable<any> {
let toDoList = {
name: name
};
return this.mHttp.post(this.toDoListUrl, toDoList);
}
getList(): Observable<any> {
return this.mHttp.get(this.toDoListUrl);
}
editList(id: string, name: string): Observable<any> {
let toDoList = {
name: name
};
return this.mHttp.put(this.toDoListUrl + '/' + id, toDoList);
}
deleteList(id: string): Observable<any> {
return this.mHttp.delete(this.toDoListUrl + '/' + id, {});
}
getAllToDosByListId(listId: string): Observable<any> {
return this.mHttp.get(this.toDoListUrl + '/' + listId + '/' + this.toDoChildUrl);
}
addAToDoToList(listId: string, name: string, done: boolean = false): Observable<any> {
let toDo = {
name: name,
done: done
};
return this.mHttp.post(this.toDoListUrl + '/' + listId + '/' + this.toDoChildUrl, toDo);
}
updateAToDoInList(listId: string, id: string, name: string, done: boolean = false): Observable<any> {
let toDo = {
name: name,
done: done
};
return this.mHttp.put(this.toDoListUrl + '/' + listId + '/' + this.toDoChildUrl + '/' + id, toDo);
}
deleteAToDoInList(listId: string, id: string): Observable<any> {
return this.mHttp.delete(this.toDoListUrl + '/' + listId + '/' + this.toDoChildUrl + '/' + id, {});
}
}
|
typescript
|
package org.gradle.profiler.report;
import org.gradle.profiler.ScenarioDefinition;
import org.gradle.profiler.result.BuildInvocationResult;
import org.gradle.profiler.result.Sample;
import java.util.List;
public interface BuildScenarioResult<T extends BuildInvocationResult> {
ScenarioDefinition getScenarioDefinition();
/**
* Returns the names of the samples collected for each build invocation in this scenario.
*/
List<Sample<? super T>> getSamples();
/**
* Returns all results, including warm-up builds.
*/
List<T> getResults();
}
|
java
|
<filename>src/testModule/java/lol/bai/megane/module/test/provider/TestItemProvider.java
package lol.bai.megane.module.test.provider;
import lol.bai.megane.api.provider.ItemProvider;
import net.minecraft.block.entity.ChestBlockEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryEntry;
import org.jetbrains.annotations.NotNull;
public class TestItemProvider extends ItemProvider<ChestBlockEntity> {
private static final ItemStack NOT_RANDOM_STACK = new ItemStack(Items.DIAMOND, 42);
@Override
public int getSlotCount() {
return 13;
}
@Override
public @NotNull ItemStack getStack(int slot) {
return slot == 0 ? NOT_RANDOM_STACK : new ItemStack(Registry.ITEM.getRandom(getWorld().random).map(RegistryEntry::value).orElse(Items.ACACIA_BOAT));
}
}
|
java
|
<filename>src/drugcentral.py
#!/usr/bin/env python3
import io
import csv
from model.network import Network
from model.drug import Drug
from model.disease import Disease
from model.edge import Edge
network = Network()
with io.open('../data/DrugCentral/drugcentral_mappings.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
next(reader, None)
for row in reader:
ids = ['DrugCentral:%s' % row[0], 'DrugBank:%s' % row[1]]
if row[2]:
ids.append('RxNorm:%s' % row[2])
network.add_node(Drug(ids, [row[3]]))
with io.open('../data/DrugCentral/drugcentral_indications.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
next(reader, None)
for row in reader:
disease = Disease(['SnoMedCT:%s' % row[2], 'UMLS:%s' % row[3]], [row[1]])
network.add_node(disease)
drug = network.get_node_by_id('DrugBank:%s' % row[0], 'Drug')
e = Edge(drug, disease, 'INDICATES', {'source': 'DrugCentral'})
network.add_edge(e)
with io.open('../data/DrugCentral/drugcentral_contraindications.csv', 'r', encoding='utf-8', newline='') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
next(reader, None)
for row in reader:
disease = Disease(['SnoMedCT:%s' % row[2], 'UMLS:%s' % row[3]], [row[1]])
network.add_node(disease)
drug = network.get_node_by_id('DrugBank:%s' % row[0], 'Drug')
e = Edge(drug, disease, 'CONTRAINDICATES', {'source': 'DrugCentral'})
network.add_edge(e)
network.save('../data/DrugCentral/graph.json')
|
python
|
Premier League action was back in town this weekend after two frustrating weeks if international games. Teams from around the table fought hard for their goals at the weekend and there were a number of star performers from around the country. There were a few interesting results at the weekend but there were some excellent individual performances that lit up the weekend. So here is the team of the week for Match Day 8 of the Barclays Premier League:
Maarten Stekelenburg (Everton):
A mammoth effort in front of the sticks to keep Aguero away with two penalty saves and also many others in normal play makes Stekelenburg the best performer in his position for this week.
Adam Smith (AFC Bournemouth):
Stuck to his task well at the back to keep his side away from danger and also helped at the other end, setting up the 4th goal for the side in an impressive performance by Smith.
David Luiz (Chelsea):
Playing as a part of the 3-man defense for Conte, Luiz played as a sweeper and played it exceptionally. He snuffed every Leicester attack out early and gave them no time in front of goal.
Winston Reid (West Ham):
Worked hard all night against Palace to keep the likes of Benteke away from danger as he helped his side keep a clean sheet and gave them three much-needed points from this weekend.
Charlie Daniels (AFC Bournemouth):
Another impressive performance from Daniels who picked up a goal and an assist on the night and also put in a mammoth shift on the wing at both ends of the field.
Joe Allen (Stoke City):
Turning things around for the Stoke City side, Joe Allen picked up a brace this weekend to add to his goal against Manchester United as he gave his side all three points against the Black Cats.
N Golo Kante (Chelsea):
Pumped up facing his former side, Kante, was in blistering form on the night as he gave his former side no time on the ball and helped Chelsea to all three points from this weekend.
Theo Walcott (Arsenal):
The English winger is in sublime form early this season as he added to his already impressive return in front of goal with a brace to give Arsenal all three points against Swansea.
Mesut Ozil (Arsenal):
The German international was simply unplayable on the night as he controlled the game and often broke through the Swansea defense. He also picked up a goal that later turned out to be the winner.
Junior Stanislas (AFC Bournemouth):
With a couple of goals and an assist, Stanislas was the most influential player in the league this weekend as he helped his side set up a 6-1 victory over Hull City this weekend.
Romelu Lukaku (Everton):
Though absent for most of the game in Manchester, Lukaku came up with some brilliant skill and determination to give Everton the lead at the Etihad and a point to go from the game.
|
english
|
package dev.cheos.armorpointspp.core.render;
import dev.cheos.armorpointspp.core.IRenderComponent;
import dev.cheos.armorpointspp.core.RenderContext;
import dev.cheos.armorpointspp.core.adapter.IConfig.BooleanOption;
import dev.cheos.armorpointspp.core.texture.ITextureSheet;
public class ToughnessComponent implements IRenderComponent {
@Override
public boolean render(RenderContext ctx) {
if (!ctx.shouldRenderToughness() || !ctx.config.bool(BooleanOption.TOUGHNESS_ENABLE) || !ctx.config.bool(BooleanOption.TOUGHNESS_BAR))
return false;
ctx.profiler.push("toughness");
ITextureSheet tex = tex(ctx).bind(ctx);
int toughness = ctx.data.toughness();
for (int i = 0; i < 10; i++)
tex.drawToughness(ctx, ctx.x + 8 * i, ctx.y, (int) ((toughness - 2 * (i + 1) + 20) * 0.05F), (toughness % 20) - 2 * i == 1, false);
return popReturn(ctx, true);
}
}
|
java
|
Creative writing contest 14/08/2021.
When, how, and how many persons I intend to recruit to steemit.
Hello steemians, hope you will are doing good! It’s a great pleasure in participating in this contest.
Am gradually working towards bringing new members to steemit next week because I have been talking to some few persons about steemit and they are developing interest in joining. About how many persons I have recruited. I have recruited just 1 person which is @cristele that is because I joined steemit platform not long ago, am trying my best to creat more awareness. How I creat awareness is by telling people on the benefits of steem, encouraging them to join, publishing Articles, posting videos, hosting meetup talks. How I plan recruiting people to steem,
- Organizing meetup talks.
2.prepare an effective job description.
3.constant encouragement.
My target population is Bamenda because it’s my home town and because I know so many people here who I can easily talk too.
|
english
|
package com.dao;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import com.entity.Address;
public class Address_db extends DB {
/*
* 地址
*/
public List<Address> getAddressList(String sql, List<Object> params) {
List<Address> add_list = new ArrayList<Address>();
try {
if (conn.isClosed())
conn = DriverManager.getConnection(url, user, password);
pstmt = conn.prepareStatement(sql);
if (params != null)
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i + 1, params.get(i));
}
rs = pstmt.executeQuery();
while (rs.next()) {
Address add = new Address();
add.setAddress(rs.getString("address"));
add.setRecipients(rs.getString("recipients"));
add.setTel(rs.getString("tel"));
add_list.add(add);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return add_list;
}
}
|
java
|
New Delhi: Just days after Sonia Gandhi's trip to her constituency Rae Bareli, BJP president Amit Shah today visited the Congress bastion, saying his party would put an end to "dynastic" politics in the area that has "not seen development since Independence".
"I have come here to make it clear that the BJP will rid Rae Bareli of 'parivarvad' (dynastic politics) and will start the campaign from today for taking it on the path of 'vikasvad' (development)," Mr Shah said at a rally in Rae Bareli, a Lok Sabha seat Sonia Gandhi has won four successive times.
Faced with an aggressive Congress that has repeatedly taken on the BJP and Prime Minister Narendra Modi in particular over the the Unnao and Kathua rapes, the BJP has scaled up its "dynastic politics" barb as a comeback.
Earlier this week, without mentioning the Congress, PM Modi referred to "one family" more than once at a town hall event in London, saying he was absolutely okay with criticism of his government but lamented that criticism had degenerated into "allegation".
Though the BJP had swept Uttar Pradesh in the 2014 general election, winning 71 of the 80 seats in the states, it lost both Rae Bareli and Amethi to the Congress. The party had fielded Smriti Irani in Amethi opposite Rahul Gandhi who won the election but his victory margin was reduced by over 2. 5 lakh votes.
Last week Ms Irani visited Amethi, saying despite her defeat, development work "ignored by the Gandhi family for five decades had been completed in four years of Modi government".
"In four years, more than 80 development works have been undertaken. . . they all will testify how this area had been deprived of development until now," Ms Irani had said.
Today, Mr Shah said the people of Rae Bareli will see development. "We will develop it as an ideal constituency and a model district," he claimed.
He also took on Rahul Gandhi after a court in Hyderabad acquitted five people accused in the 2007 blast in Hyderabad's Mecca Masjid, including Assemanand, a saffron-robed monk.
"You and your party leader leaders tarnished Hindu culture by using the words saffron terror. You need to apologise," said the BJP chief.
He also welcomed a lawmaker from Rae Bareli --- Dinesh Pratap Singh --- into the BJP. Mr Singh had quit the Congress earlier this month.
|
english
|
from django.shortcuts import render,get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from monitor.models import Machine, Crash, Testcase, Profile, DupCrash
from track.models import Issue
from django.http import Http404
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate, login, logout, views
from django.contrib.auth.models import User
from django.utils.timesince import timesince
from django.template import defaultfilters
import datetime
import glob
import os
import hashlib
import threading
from django.contrib.auth.decorators import login_required
def CheckPostVariable(POST, parameter):
for param in parameter:
if param not in POST:
return False
return True
@login_required
def index(request):
machine_count = Machine.objects.filter(owner=request.user).count()
crash_count = Crash.objects.filter(owner=request.user).count()
issue_count = Issue.objects.filter(owner=request.user).count()
cve_count = Issue.objects.filter(owner=request.user).exclude(cve__exact='').count()
server_count = Machine.objects.filter(owner=request.user).values('pub_ip').distinct().count()
profiles = Profile.objects.all()
myprofile = Profile.objects.get(owner=request.user)
profilenum = profiles.order_by('-id')[0].id
context = {'server_count':server_count, 'cve_count':cve_count,'issue_count':issue_count, 'crash_count': crash_count, 'machine_count': machine_count, 'userinfo':request.user, 'profilenum':profilenum, 'profile':profiles, 'myprofile':myprofile}
return render(request, 'monitor/index.html', context)
@login_required
def fuzzer_list(request):
machine_list = Machine.objects.filter(owner=request.user).order_by('-ping')#.all()#[::-1]#.filter(idx>0).order_by('-idx')
now = datetime.datetime.now() - datetime.timedelta(minutes=5)
myprofile = Profile.objects.get(owner=request.user)
context = {'machine_list': machine_list, 'userinfo':request.user, 'now':now, 'myprofile':myprofile}
return render(request, 'monitor/fuzzer/list.html', context)
@login_required
def fuzzer_details(request, idx):
fuzzer_info = None
try:
fuzzer_info = Machine.objects.get(id=idx, owner=request.user)
except ObjectDoesNotExist:
raise Http404
myprofile = Profile.objects.get(owner=request.user)
context = {'fuzzer': fuzzer_info, 'userinfo':request.user, 'myprofile':myprofile}
return render(request, 'monitor/fuzzer/detail.html', context)
@login_required
def crash_list(request):
crash_info = Crash.objects.filter(owner=request.user)[::-1]
myprofile = Profile.objects.get(owner=request.user)
context = {'crashes': crash_info, 'userinfo':request.user, 'myprofile':myprofile}
return render(request, 'monitor/crash/list.html', context)
@login_required
def crash_details(request, idx):
crash_info = None
try:
crash_info = Crash.objects.get(id=idx, owner=request.user)
except ObjectDoesNotExist:
raise Http404
myprofile = Profile.objects.get(owner=request.user)
context = {'crash': crash_info, 'userinfo':request.user, 'myprofile':myprofile}
return render(request, 'monitor/crash/detail.html', context)
@login_required
def crash_details_dupcrash(request, idx, page=0):
crash_info = None
result = {}
try:
crash_info = Crash.objects.get(id=idx, owner=request.user)
Dcrash = DupCrash.objects.filter(owner=request.user, fuzzer=crash_info.fuzzer, original_crash=crash_info)
result["total"] = len(Dcrash)
for i in range(0, len(Dcrash)):
tmp = {}
tmp["size"] = defaultfilters.filesizeformat(Dcrash[i].crash_file.size)
tmp["hash"] = Dcrash[i].crash_hash
tmp["count"] = Dcrash[i].dup_crash
tmp["reg_date"] = defaultfilters.date(Dcrash[i].reg_date)
result[i+1] = tmp
# crash_path = crash_info.crash_file.path.split("/")[:-1]
# crash_path = "/".join(crash_path)
# crashes = (glob.glob(crash_path+"/*"))
# for i in range(0, len(crashes)):
# tmp = {}
# tmp["size"] = os.path.getsize(crashes[i])
# tmp["name"] = os.path.basename(crashes[i])
# tmp["hash"] = hashlib.md5(open(crashes[i],'rb').read()).hexdigest()
# result[i] = tmp
except ObjectDoesNotExist:
raise Http404
return JsonResponse(result)
@login_required
def crash_details_modify(request, idx):
crash_info = None
parameterList = ['comment']
if not CheckPostVariable(request.POST, parameterList):
raise Http404
try:
comment = request.POST['comment']
crash_info = Crash.objects.get(id=idx, owner=request.user)
except ObjectDoesNotExist:
raise Http404
crash_info.comment = comment
crash_info.save()
myprofile = Profile.objects.get(owner=request.user)
context = {'crash': crash_info, 'userinfo':request.user, 'myprofile':myprofile}
return render(request, 'monitor/crash/detail.html', context)
@login_required
def settings_page(request):
machine_count = Machine.objects.filter(owner=request.user).count()
crash_count = Crash.objects.filter(owner=request.user).count()
issue_count = Issue.objects.filter(owner=request.user).count()
testcase_count = Testcase.objects.filter(owner=request.user).count()
cve_count = Issue.objects.filter(owner=request.user).exclude(cve__exact='').count()
server_count = Machine.objects.filter(owner=request.user).values('pub_ip').distinct().count()
profile = Profile.objects.all()
myprofile = Profile.objects.get(owner=request.user)
notification_setting = {'USE_EMAIL_ALERT':settings.USE_EMAIL_ALERT,'USE_TELEGRAM_ALERT':settings.USE_TELEGRAM_ALERT}
context = {'testcase_count':testcase_count, 'server_count':server_count, 'cve_count':cve_count,'issue_count':issue_count, 'crash_count': crash_count, 'machine_count': machine_count,'userinfo':request.user, 'profiles':profile, 'myprofile':myprofile, 'notification_setting':notification_setting, 'myprofile':myprofile}
return render(request, 'settings.html', context)
|
python
|
<filename>networkapi/grupo/resource/GroupUserGetByIdResource.py
# -*- coding:utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
from networkapi.admin_permission import AdminPermission
from networkapi.auth import has_perm
from networkapi.infrastructure.xml_utils import dumps_networkapi
import logging
from networkapi.rest import RestResource, UserNotAuthorizedError
from networkapi.grupo.models import UGrupo, GrupoError, UGrupoNotFoundError
from django.forms.models import model_to_dict
from networkapi.exception import InvalidValueError
from networkapi.util import is_valid_int_greater_zero_param
class GroupUserGetByIdResource(RestResource):
log = logging.getLogger('GroupUserGetByIdResource')
def handle_get(self, request, user, *args, **kwargs):
"""Treat requests GET to get Group User.
URL: ugroup/get/<id_ugroup>/
"""
try:
self.log.info("Get Group User by ID")
id_ugroup = kwargs.get('id_ugroup')
# User permission
if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.READ_OPERATION):
self.log.error(
u'User does not have permission to perform the operation.')
raise UserNotAuthorizedError(None)
# Valid Group User ID
if not is_valid_int_greater_zero_param(id_ugroup):
self.log.error(
u'The id_ugroup parameter is not a valid value: %s.', id_ugroup)
raise InvalidValueError(None, 'id_ugroup', id_ugroup)
# Find Group User by ID to check if it exist
ugroup = UGrupo.get_by_pk(id_ugroup)
ugroup_map = dict()
ugroup_map['user_group'] = model_to_dict(ugroup)
return self.response(dumps_networkapi(ugroup_map))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except UserNotAuthorizedError:
return self.not_authorized()
except UGrupoNotFoundError, e:
return self.response_error(180, id_ugroup)
except GrupoError, e:
return self.response_error(1)
|
python
|
Kantabanji: Water scarcity problems have started to haunt residents from the very beginning of summer at ward no. 10 and ward no. 11 under Kantabanjhi N. A. C of Bolangir district, reports said.
Residents of the two wards have started feeling the pinch of water scarcity for their daily purposes. Despite repeated complaints, officials concerned are least bothered and do not pay any heed, locals alleged.
Adding to the woes of the residents, only pond that quenched the thirst of the residents here has dried up. Locals have been demanding supply water for drinking purposes, but to no avail as their pleas are left unheard.
Fed up with the apathy of the officials concerned, residents of these two wards have given a written complaint to N. A. C executive officer Smt. Bishnupriya Padhi who recently joined Kantabanji N. A. C office.
Smt. Padhi assured residents to provide water by a tanker of Public Health Department every morning and evening until the water problem was solved.
|
english
|
{
"citations" : [ {
"textCitation" : "[See pjadj2 on Metamath](http://us.metamath.org/mpegif/pjadj2.html)"
} ],
"names" : [ "pjadj2" ],
"language" : "METAMATH_SET_MM",
"lookupTerms" : [ "#T_cT", "#T_wcel", "#T_crn", "#T_cpjh", "#T_wi", "#T_cado", "#T_cfv", "#T_cT", "#T_wceq", "#T_cT" ],
"metaLanguage" : "METAMATH",
"remarks" : " A projector is self-adjoint. Property (i) of [Beran] p. 109. (Contributed by NM, 3-Jun-2006.) (New usage is discouraged.) ",
"statement" : "pjadj2 $p |- ( T e. ran projh -> ( adjh ` T ) = T ) $."
}
|
json
|
{
"name": "@ffdc/uxg-angular-components/repeater",
"version": "0.20.0",
"author": "xaviermonvoisin <<EMAIL>>"
}
|
json
|
<reponame>alephtimwu/movie-app
import styled, { css } from '@emotion/native';
import { StyleSheet, View, Text } from 'react-native';
export const StyledHeading = styled.Text`
text-align: left;
font-family: Montserrat;
color: #fff;
font-size: 21px;
line-height: 21px;
`;
export const StyledViewAll = styled.Text`
text-align: right;
font-family: Montserrat;
color: #9da3b4;
font-size: 10px;
line-height: 10px;
`;
|
typescript
|
A 27-year-old Sub-Inspector on Tuesday allegedly committed suicide by shooting himself in his head on the premises of Kerameri police station in Adilabad district, police said. In a suicide note found at the spot, purportedly written by him, the sub-inspector K Sridhar stated that he was under depression for last one year. He suffered head injuries after he allegedly shot himself on his temple with his service weapon at around 8. 30 am in his residential quarters on the police station premises, a senior police officer told PTI.
hospital in Asifabad where doctors declared him brought dead, the officer said, adding the "SI went into coma soon after shooting himself. " A suicide note was found from the scene in which Sridhar purportedly wrote that he was under depression for over past one year, the officer said, while refusing to elaborate on the likely cause behind depression. "It is prima-facie a case of suicide. We are further investigating.
An inquiry has been ordered into the incident. A case under section 174 CrPC has been registered and further probe is on.
Can Opposition political parties unitedly will fight against BJP in the General Elections to be held next year in 2024?
|
english
|
<filename>proto_vs_json/data/user-782.json
{"gender":"male","name":{"title":"Monsieur","first":"Nico","last":"Laurent"},"email":"<EMAIL>","login":{"username":"lazyfish282","uuid":"M6sucRg8SAOOzvfgz9+LdA==","isloggedin":false},"picture":{"large":"https://randomuser.me/api/portraits/men/72.jpg","medium":"https://randomuser.me/api/portraits/med/men/72.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/men/72.jpg"},"location":{"street":{"number":1731,"name":"Route de Genas"},"city":"Dättlikon","state":"Appenzell Ausserrhoden","country":"Switzerland","postcode":5417,"coordinates":{"latitude":9.2435,"longitude":-94.0642},"timezone":{"offset":"+11:00","description":"Magadan, Solomon Islands, New Caledonia"}},"isactive":false}
|
json
|
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
/*nav*/
nav{
text-align: right;
padding: 5vh, 5vh 0 0;
font-family: 'lato';
}
nav > a{
color:#000000;
font-weight: 300;
text-decoration: none;
margin-right: 10px;
padding: 1vh ;
}
nav > a:hover{
text-decoration: underline;
}
/*Fondo*/
header {
background: #C9D6FF;
background: -webkit-linear-gradient(to right, #e2e2e285, #c9d6ff7e), url(../fotografias/escritorio.jpg) ;
background: linear-gradient(to right, #e2e2e286, #c9d6ff7e), url(../fotografias/escritorio.jpg);
background-attachment: fixed;
background-size: cover;
position: relative;
width: 100%;
height: 600px;
}
header .textos-header{
display: flex;
height: 430px;
width: 100%;
align-items: center;
justify-content: center;
flex-direction: column;
text-align: center;
}
.textos-header h1{
font-size: 10vh;
color:#000000;
font-family: 'Baskerville';
}
/*informacion del documento*/
body { background: #f7f4f0; }
#main {
max-width: 800px;
width: 94%;
margin: 2% auto;
background: #fafafa;
box-shadow: 0 0 6px 2px rgba(0,0,0,0.4);
}
#cabecera { background: #daae96; }
#pie { background: #daae96;
clear: both;
text-align: center; }
#cabecera, #pie { padding: 10px; }
#contenido { width: 75%; }
#lateral { width: 25%; }
#contenido, #lateral { float: left; padding: 10px; }
p { padding: 0 0 0 20px; }
#tipo { font: 2em serif;
color: #999;
text-align: center;
margin-bottom: 25px; }
/* footer */
footer{
background: #b2c9b5;
padding: 60px 0 30px 0;
margin: auto;
overflow: hidden;
}
.contenedor-footer{
display: flex;
width: 90%;
justify-content: space-evenly;
margin: auto;
padding-bottom: 50px;
border-bottom: 1px solid #eaeaea;
}
.content-foo{
text-align: center;
}
.content-foo h4{
color: #373838 ;
font-size: 18px;
border-bottom: 3px solid #eaeaea;
padding-bottom: 5px;
margin-bottom: 10px;
}
.content-foo p{
color: #373838 ;
}
.titulo-final{
text-align: center;
font-size: 14px;
margin: 20px 0 0 0;
color: #f7f4f0;
}
|
css
|
What do you think?
"Me: I feel like I am my best friend. When I'm able to get through a meal without eating too much, there's this thing I feel inside of me—this strength. It's like a place of power, and when I don't eat too much, or when I exercise enough, it makes me feel invincible. It keeps me company." (Hardcover, page 228)
Ana is a good girl and she feels as though she’s not good enough for the perfect façade her family presents to the public. The one thing Ana knows she can control is her eating. Ana is spiraling, but she’s not eating it’s the best she’s felt in a long time. I remember loving Go Ask Alice in middle school; it’s one of the books that I consider to be a part of my childhood favorites. When I saw the this was free on Simon Pulse It I jumped to read it (that’s how long ago it’s been- there isn’t even a Simon Pulse It, now it’s called Riveted) and I instantly disliked Ana. Ana is my biggest problem with this novel and that isn’t a good thing when the novel is a diary. At first, Ana is a normal girl with good, healthy eating habits- until Ana’s best friend and her “perfect” mom make a comment about Ana losing a little more weight. She starves herself because her friend said it would be FUN. This is a horrible example of eating habits and disorders to display to younger audiences. Naturally, she runs all the time even though she has no fuel in her body- goes to rehab- then collapses and dies- the typical “anonymous” storyline. I’m sorry but this a pile of crap and after two year of ruminating on this it’s one of those novels I forget about, but once I remember it I’m angry. It left a bad taste in my mouth. These type of storylines make it seem like eating disorders have no chance of recovery and overcoming the problem; using death to display tragedy after multiple failed rehabilitation or attempts at intervention is not a positive message to send to younger readers. Also Ana was a completely judgmental twat to her mom and it only fueled my dislike for her and this “novel”.
Overall, I suggest skipping over this one. It’s a newer anonymous novel so I don’t consider it to be a classic or necessary for your angsty teen reads (there’s better stuff out there). I suggest Wintergirls by Laurie Halse Anderson instead because it’s a beautiful novel that portrays eating disorders in a stark, gut-wrenching story that has stayed with me since my middle school years.
|
english
|
export const reverseNumber = (num: number): number => {
const reversedNum = num
.toString()
.split('')
.reverse()
.join('')
return parseInt(reversedNum) * Math.sign(num)
}
|
typescript
|
package kerror
import "testing"
func TestNil(t *testing.T) {
defer func() {
v := recover()
t.Logf("%+v", v)
if ClassOf(Recovered(v)) != ENil {
t.Fail()
return
}
}()
Nil()
}
func TestPanic(t *testing.T) {
const message = "keep calm, this is a test panic"
defer func() {
v := recover()
t.Logf("%+v", v)
err := Recovered(v)
if ClassOf(err) != EPanic || MessageOf(err) != message {
t.Fail()
return
}
}()
Panic(message)
}
func TestRecovered__Nil(t *testing.T) {
defer func() {
if Recovered(recover()) != nil {
t.Fail()
return
}
}()
}
func TestRecovered__String(t *testing.T) {
const message = "keep calm, this is a test panic"
defer func() {
v := recover()
t.Logf("%+v", v)
err := Recovered(v)
if ClassOf(err) != nil || MessageOf(err) != message {
t.Fail()
return
}
}()
panic(message)
}
func TestRecovered__PackageError(t *testing.T) {
const class = Label("test.Error")
const message = "keep calm, this is a test panic"
defer func() {
v := recover()
t.Logf("%+v", v)
err := Recovered(v)
if ClassOf(err) != class || MessageOf(err) != message {
t.Fail()
return
}
}()
panic(New(class, message))
}
func TestTry__Error(t *testing.T) {
const class = Label("test.Error")
const message = "test error"
err := Try(func() error {
return New(class, message)
})
t.Logf("%+v", err)
if err == nil || ClassOf(err) != class || MessageOf(err) != message {
t.Fail()
return
}
}
func TestTry__NativePanic(t *testing.T) {
const message = "keep calm, this is a test panic"
err := Try(func() error {
panic(message)
return nil
})
t.Logf("%+v", err)
if err == nil || ClassOf(err) != nil || MessageOf(err) != message {
t.Fail()
return
}
}
func TestTry__PackagePanic(t *testing.T) {
const message = "keep calm, this is a test panic"
err := Try(func() error {
Panic(message)
return nil
})
t.Logf("%+v", err)
if err == nil || ClassOf(err) != EPanic || MessageOf(err) != message {
t.Fail()
return
}
}
func TestCatch(t *testing.T) {
const errorClass = Label("test.Error")
const errorMessage = "test error"
const panicMessage = "keep calm, this is a test panic"
err := func() (err error) {
defer Catch(&err)
err = New(errorClass, errorMessage)
Panic(panicMessage)
return
}()
t.Logf("%+v", err)
if err == nil {
t.Fail()
return
}
if errs, ok := err.(MultiError); !ok || len(errs) != 2 ||
ClassOf(errs[0]) != errorClass || MessageOf(errs[0]) != errorMessage ||
ClassOf(errs[1]) != EPanic || MessageOf(errs[1]) != panicMessage {
t.Fail()
return
}
}
func TestCatch__NilTarget(t *testing.T) {
defer func() {
v := recover()
t.Logf("%+v", v)
if v == nil {
t.Fail()
return
}
}()
_ = func() (err error) {
defer Catch(nil)
panic("keep calm, this is a test panic")
return
}()
}
|
go
|
<gh_stars>0
# Generated by Django 3.0.3 on 2020-05-24 16:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('get_random_quote', '0007_auto_20200524_2138'),
]
operations = [
migrations.RenameField(
model_name='quote',
old_name='image',
new_name='Photo',
),
]
|
python
|
<filename>recipes/Python/577380_Dragon_Lexical_Analyzer/recipe-577380.py
import sys
import os
EOF = ""
def get_num():
digits = []
t = getchar()
while t.isdigit():
digits.append(t)
t = getchar()
if t != EOF:
ungetc(t)
num = int("".join(digits))
return num
def get_word():
chars = []
t = getchar()
while t.isalnum():
chars.append(t)
t = getchar()
if t != EOF:
ungetc(t)
s = "".join(chars)
return s
class DragonException(Exception):
pass
class Tag(object):
NONE = -1
NUM = 256
DIV = 257
MOD = 258
ID = 259
DONE = 260
class Token(object):
def __init__(self, t, value=''):
self.tag = t
self.value = value
def __str__(self):
return "Token([%s] [%s])" % (str(self.tag), str(self.value))
class Num(Token):
def __init__(self, v):
Token.__init__(self, Tag.NUM, v)
class Word(Token):
def __init__(self, tag, lexeme):
Token.__init__(self, tag, lexeme)
class Lexer(object):
def __init__(self):
self.lineno = 0
self.lookahead = None
self.out = []
self.sym_table = {} # symbol table: lexeme -> token tag
self.insert("div", Tag.DIV)
self.insert("mod", Tag.MOD)
def lookup(self, key):
return self.sym_table.get(key, None)
def insert(self, key, tag):
self.sym_table[key] = tag
def parse(self):
self.lookahead = self.lexan()
while self.lookahead.tag != Tag.DONE:
self.expr()
self.match(';')
return self
def lexan(self):
token = None
while not token:
t = getchar()
if t == ' ' or t == '\t':
pass # strip out white space
elif t == '\n':
self.lineno += 1
elif t.isdigit():
ungetc(t)
num = get_num()
token = Num(num)
elif t.isalpha():
ungetc(t)
word = get_word()
tag = self.lookup(word)
if not tag:
tag = Tag.ID
self.insert(word, tag)
token = Word(tag, word)
elif t == EOF:
token = Token(Tag.DONE)
else:
token = Token(t)
return token
def expr(self):
self.term()
while True:
token = self.lookahead
if token.tag == '+' \
or token.tag == '-':
self.match(token.tag)
self.term()
self.emit(token)
else:
break
def term(self):
self.factor()
while True:
token = self.lookahead
if token.tag == '*' \
or token.tag == '/' \
or token.tag == Tag.DIV \
or token.tag == Tag.MOD:
self.match(token.tag)
self.factor()
self.emit(token)
else:
break
def factor(self):
token = self.lookahead
if token.tag == '(':
self.match('(')
self.expr()
self.match(')')
elif token.tag == Tag.NUM:
self.emit(token)
self.match(Tag.NUM)
elif token.tag == Tag.ID:
self.emit(token)
self.match(Tag.ID)
else:
raise DragonException("factor: bad token tag - %s" % token)
def match(self, tag):
if self.lookahead.tag == tag:
self.lookahead = self.lexan()
else:
raise DragonException("match: tag %s doesn't match %s" % (tag, self.lookahead))
def emit(self, token):
tag = token.tag
value = token.value
if tag == '+' or tag == '-' or tag == '*' or tag == '/':
out = "%s" % tag
elif tag == Tag.DIV:
out = "DIV"
elif tag == Tag.MOD:
out = "MOD"
elif tag == Tag.NUM:
out = "%d" % value
elif tag == Tag.ID:
out = "%s" % value
else:
out = "emit: %s" % (token)
self.out.append(out)
print out
def db(self, intro=""):
print "%s %s" % (intro, self.lookahead)
def main():
lex = Lexer().parse()
print lex.out
# python specific
import StringIO
FP = None
def getchar():
if FP:
return FP.read(1)
def ungetc(c=''):
if FP:
FP.seek(-1, os.SEEK_CUR)
SRC = """1 + (2 + 3);
4 * (5 + 6);
7 div (8 - 9);
10 mod (11 + 12);
"""
if __name__ == "__main__":
FP = StringIO.StringIO(SRC)
main()
|
python
|
New Zealand telco Spark is piling pressure on industry regulator the Commerce Commission to justify new wholesale copper broadband charges that it says will be "massively out of line with comparable countries".
Spark has now launched a campaign website, becounted.org.nz, which it said will give the public a voice.
The Commerce Commission is in the final stages of a long and fractious review of wholesale charges for accessing Chorus' monopoly copper broadband network.Ever since the regulator slashed the proposed regulated copper price in 2013, arguments have been raging over the correct methodology to reset the prices that Chorus charges to the likes of Spark.
Chorus called on the government to intervene, warning that the scale of the cuts would create a billion-dollar shortfall in the revenue needed to complete the rollout of a new, government-backed Ultra-Fast Broadband fibre network.
Originally, the government looked sympathetic toward legislating the problem away, but public backlash forced it to back down and let the regulatory process run.
The indication now is that the commission is favouring a price north of its original proposed monthly wholesale price per connection of NZ$34.44.
"Spark has been working to give customers more value in their broadband plans," Spark managing director Simon Moutter said in a statement announcing Be Counted.
"However, the Commerce Commission is proposing to increase what Chorus can charge to access their network, which is already pushing up the price everyone pays.
"The proposed Chorus charges are almost 80 percent higher per line than the median charge of comparable countries -- that's up to NZ$180 more per year. We think that's not on, and that Chorus charges should actually be reduced."
Spark said the Be Counted site provides information about what makes up the price of broadband, and allows users to easily send a submission to the Commerce Commission.
Spark said the wholesale charge is around half the amount that customers pay for broadband.
"Spark is working to give our customers more value, and the Commerce Commission needs to justify to ordinary internet users why they're pushing charges up to levels well above comparable countries."
|
english
|
{"body": "Hi Robert,\n\n\nSometimes, depending on the method used to build the model, you can get\nlight leakage where planes meet: very small floating point errors can cause\notherwise unnoticeable gaps, especially when the number of nodes (defined\npoints) on one plane edge doesn't equal the number of nodes on the adjoining\nedge. (Although this may just be a problem with the geometry builder I use.)\n\n\nNick L.\n___\n<sup>Automatically generated content from [radiance mailing-list](https://radiance-online.org/pipermail/radiance-general/2002-July/000340.html).</sup>", "attachments": [], "created_by_name": "<NAME>", "created_at": "July 12, 2002 at 09:31AM", "created_by": "Nicholas_Lander", "parent_id": "radiance-general_000334", "id": "radiance-general_000340"}
|
json
|
WordPress (638 programs)
PROS: Quick setup for registrations and roles. Admin can manage all members. Restrict file access. Add extensions for more functionality.CONS: Advanced extensions only available in Premium.
PROS: Secure your complete site or specific content. Unlock all protected content with a master password. Set password restrictions bases on time and user roles. Set passwords with shortcodes or built-in modules in specific page builders.CONS: It doesn’t protect images and uploaded files.
PROS: Frontend user friendly. Updates are done often. Compatible with other plugins.CONS: The sign up process could use some work.
PROS: Monitor audience conversions. Used across all devices. Improve marketing campaigns.CONS: May be challenging to set up APIs and codes.
PROS: Let you add up to 14 custom fields. You can show or hide fields on specific pages. Simple reset option. You can sort of duplicate fields.CONS: No WPML support.
PROS: Insert responsive slides onto your site. Optimized for SEO. Add transition effects. Customize for a personal touch.CONS: Animation and layer effects are only available as Premium.
PROS: Free to download and use. Helps build website SEO. Improves user experience.CONS: Occasional crashes.
PROS: Simple to use and fully customizable. Supports paid and free directory listings. Useful for other types of directories besides business listings. Import and export CSV files.CONS: Not suitable for classified listings. Some features require a paid premium upgrade.
PROS: Supports different plugins. Advanced search results. Ability to filter searches.CONS: Free versions have some limits.
PROS: Free to download and use. Helps increase international traffic. Translates to over 100 languages.CONS: The free version has limited features.
PROS: Hides login page from hackers. Changes the login page URL to a unique one.CONS: Support isn’t guaranteed. Noted security concerns.
PROS: Integrates with WordPress themes. Lets you customize your pages and documents. Is 100% compatible with Elementor. Lets you track visitor activity.CONS: Limited widgets and shortcodes.
PROS: Quick task assign. Manage milestones and deadlines. Customize user roles.CONS: Dependent on your hosting server. Slow hosting disturbs workflow.
PROS: Social marketplace availability/BBPress and Buddypress compatibility. Migration support. Vendors can track shipments.CONS: No NFTs.
PROS: Integrates with WordPress Customizer. Live preview while you work. Save as you go along. Share a preview link. Don’t need coding knowledge.CONS: Only basic customization options.
PROS: Dashboard for stats. Customizable themes and widget. Easy to insert the information on your site.CONS: Features can be overwhelming for new website owners.
|
english
|
Saudi Arabia's oil company Aramco is now listed and has started trading on the Saudi Tadawul stock exchange on Wednesday for the first time after a mammoth $25.6 billion initial public offering that set the record as the biggest ever in history.
The state-owned company had announced a sale of 1.5% of its shares at 32 Saudi riyals a share, or what is $8.53. At that price, Aramco is the world's most valuable company at $1.7 trillion. That's more than the top five oil companies - Exxon Mobil, Total, Royal Dutch Shell, Chevron and BP - combined.
|
english
|
Aiden Blizzard cracked a 39-ball 54 as Mumbai Indians posted a challenging 160 for five against Somerset in the second semifinal of the Champions League Twenty20 on Saturday.
Aiden Blizzard cracked a 39-ball 54 as Mumbai Indians posted a challenging 160 for five against Somerset in the second semifinal of the Champions League Twenty20 on Saturday.
Opener Blizzard cracked five fours and three sixes and stitched 19, 43 and 24 runs respectively, with Sarul Kanwar (2), Ambati Rayudu (19) and James Franklin (6) respectively to lay the foundation after Mumbai Indians skipper Harbhajan Singh won the toss and elected to bat.
Blizzard, however, didn’t get much support from the middle-order and if it had not been for the late charge by Suryakumar Yadav (23 not out) and Rajagopal Sathish (25 not out), Mumbai would have ended with a much low score.
After a watchful start, Mumbai reached 76 for two in the first 10 overs. Blizzard then changed gears and brought up his fifty in style, blasting Murali Kartik for a six over mid-wicket in the 11th over.
However, Roelef van der Merwe trapped Franklin plumb in front of the wicket in the next over, while Murali cleaned up the 27-year-old Blizzard in the 13th over as all of a sudden Mumbai were reduced to 92 for four.
Big-hitting West Indian all-rounder Kieron Pollard then joined hands with Yadav, who was drafted into the side in place of Andrew Symonds, and brought up Mumbai’s hundred with a six over deep midwicket off van der Merwe.
Pollard repeated his feat against Peter Trego, dispatching him over deep midwicket in the 16th over before Alfonso Thomas destroyed his timbers to once again push Mumbai on the backfoot.
Yadav and Sathish, however, produced the much-needed late onslaught and amassed 43 runs off just 22 balls to take Mumbai across the 150-mark and post a challenging total at the slow MA Chidambaram Stadium track.
For Somerset, skipper Thomas, Steve Kirby, Adam Dibble, Murali Kartik and van der Merwe — all chipped in with a wicket each. (PTI)
|
english
|
{"template":{"small":"https://static-cdn.jtvnw.net/emoticons/v1/{image_id}/1.0","medium":"https://static-cdn.jtvnw.net/emoticons/v1/{image_id}/2.0","large":"https://static-cdn.jtvnw.net/emoticons/v1/{image_id}/3.0"},"channels":{"halvardor":{"title":"Halvardor","channel_id":71185641,"link":"http://twitch.tv/halvardor","desc":null,"plans":{"$4.99":"62417","$9.99":"62420","$24.99":"62421"},"id":"halvardor","first_seen":"2017-07-02 18:25:05","badge":null,"badge_starting":null,"badge_3m":null,"badge_6m":null,"badge_12m":null,"badge_24m":null,"badges":null,"bits_badges":null,"cheermote1":null,"cheermote100":null,"cheermote1000":null,"cheermote5000":null,"cheermote10000":null,"set":62417,"emotes":[{"code":"halvarLove","image_id":251094,"set":62417}]}}}
|
json
|
<filename>advisories/unreviewed/2022/05/GHSA-r293-h3gq-5mmr/GHSA-r293-h3gq-5mmr.json
{
"schema_version": "1.2.0",
"id": "GHSA-r293-h3gq-5mmr",
"modified": "2022-05-13T01:20:47Z",
"published": "2022-05-13T01:20:47Z",
"aliases": [
"CVE-2018-8351"
],
"details": "An information disclosure vulnerability exists when affected Microsoft browsers improperly allow cross-frame interaction, aka \"Microsoft Browser Information Disclosure Vulnerability.\" This affects Internet Explorer 11, Microsoft Edge, Internet Explorer 10.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-8351"
},
{
"type": "WEB",
"url": "https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2018-8351"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/105015"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id/1041457"
}
],
"database_specific": {
"cwe_ids": [
"CWE-829"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
|
json
|
import { flatten, sortBy, times } from 'lodash'
import mongoose from 'mongoose'
import { errAsync } from 'neverthrow'
import supertest, { Session } from 'supertest-session'
import getFormModel from 'src/app/models/form.server.model'
import getLoginModel from 'src/app/models/login.server.model'
import { IUserSchema } from 'src/types'
import { createAuthedSession } from 'tests/integration/helpers/express-auth'
import { setupApp } from 'tests/integration/helpers/express-setup'
import { buildCelebrateError } from 'tests/unit/backend/helpers/celebrate'
import dbHandler from 'tests/unit/backend/helpers/jest-db'
import { FormAuthType, FormResponseMode } from '../../../../../shared/types'
import { DatabaseError } from '../../core/core.errors'
import { BillingRouter } from '../billing.routes'
import * as BillingService from '../billing.service'
const app = setupApp('/billing', BillingRouter, {
setupWithAuth: true,
})
const FormModel = getFormModel(mongoose)
const LoginModel = getLoginModel(mongoose)
describe('billing.routes', () => {
let request: Session
let defaultUser: IUserSchema
beforeAll(async () => await dbHandler.connect())
beforeEach(async () => {
request = supertest(app)
const { user } = await dbHandler.insertFormCollectionReqs()
defaultUser = user
})
afterEach(async () => {
await dbHandler.clearDatabase()
jest.restoreAllMocks()
})
afterAll(async () => await dbHandler.closeDatabase())
describe('GET /billing', () => {
const VALID_ESRVCID_1 = 'mockEsrvcId1'
const VALID_ESRVCID_2 = 'mockEsrvcId2'
const INVALID_ESRVCID = 'invalidEsrvcId'
const VALID_QUERY_YR = new Date().getFullYear()
const VALID_QUERY_MTH = new Date().getMonth()
it('should return 200 with array of results of form SPCP logins of the given esrvcId', async () => {
// Arrange
// Log in user.
const session = await createAuthedSession(defaultUser.email, request)
// Generate login statistics.
const { generatedLoginTimes, generatedForms } =
await generateLoginStatistics({
user: defaultUser,
esrvcIdToCheck: VALID_ESRVCID_1,
altEsrvcId: VALID_ESRVCID_2,
})
// Act
const response = await session.get('/billing').query({
esrvcId: VALID_ESRVCID_1,
yr: VALID_QUERY_YR,
mth: VALID_QUERY_MTH,
})
// Assert
// Only first two forms returned, as those have logins with
// VALID_ESRVCID_1.
// Should not contain third form with VALID_ESRVCID_2.
const expectedStats = [
{
adminEmail: defaultUser.email,
formName: generatedForms[0].title,
total: generatedLoginTimes[0],
formId: String(generatedForms[0]._id),
authType: FormAuthType.SP,
},
{
adminEmail: defaultUser.email,
formName: generatedForms[1].title,
total: generatedLoginTimes[1],
formId: String(generatedForms[1]._id),
authType: FormAuthType.SP,
},
]
expect(response.status).toEqual(200)
// Check shape.
expect(response.body).toEqual({
loginStats: expect.any(Array),
})
// Sort by total and compare.
expect(sortBy(response.body.loginStats, ['total'])).toEqual(
sortBy(expectedStats, ['total']),
)
})
it('should return 200 with empty array when no esrvcId matches logins', async () => {
// Arrange
// Log in user.
const session = await createAuthedSession(defaultUser.email, request)
// Act
const response = await session.get('/billing').query({
esrvcId: INVALID_ESRVCID,
yr: VALID_QUERY_YR,
mth: VALID_QUERY_MTH,
})
// Assert
expect(response.status).toEqual(200)
expect(response.body).toEqual({ loginStats: [] })
})
it('should return 400 when query.esrvcId is not provided', async () => {
// Arrange
// Log in user.
const session = await createAuthedSession(defaultUser.email, request)
// Act
const response = await session.get('/billing').query({
// No esrvcId provided.
yr: VALID_QUERY_YR,
mth: VALID_QUERY_MTH,
})
// Assert
expect(response.status).toEqual(400)
expect(response.body).toEqual(
buildCelebrateError({ query: { key: 'esrvcId' } }),
)
})
it('should return 400 when query.yr is not provided', async () => {
// Arrange
// Log in user.
const session = await createAuthedSession(defaultUser.email, request)
// Act
const response = await session.get('/billing').query({
esrvcId: VALID_ESRVCID_1,
// No yr provided.
mth: VALID_QUERY_MTH,
})
// Assert
expect(response.status).toEqual(400)
expect(response.body).toEqual(
buildCelebrateError({ query: { key: 'yr' } }),
)
})
it('should return 400 when query.mth is not provided', async () => {
// Arrange
// Log in user.
const session = await createAuthedSession(defaultUser.email, request)
// Act
const response = await session.get('/billing').query({
esrvcId: VALID_ESRVCID_1,
yr: VALID_QUERY_YR,
// No mth provided.
})
// Assert
expect(response.status).toEqual(400)
expect(response.body).toEqual(
buildCelebrateError({ query: { key: 'mth' } }),
)
})
it('should return 401 when user session does not exist', async () => {
// Act
// Call endpoint directly without first logging in.
const response = await request.get('/billing').query({
esrvcId: VALID_ESRVCID_1,
yr: VALID_QUERY_YR,
mth: VALID_QUERY_MTH,
})
// Assert
expect(response.status).toEqual(401)
expect(response.body).toEqual({ message: 'User is unauthorized.' })
})
it('should return 500 when error occurs whilst querying the database', async () => {
// Arrange
// Log in user.
const session = await createAuthedSession(defaultUser.email, request)
// Mock database error from service call.
const retrieveStatsSpy = jest
.spyOn(BillingService, 'getSpLoginStats')
.mockReturnValueOnce(errAsync(new DatabaseError()))
// Act
const response = await session.get('/billing').query({
esrvcId: VALID_ESRVCID_1,
yr: VALID_QUERY_YR,
mth: VALID_QUERY_MTH,
})
// Assert
expect(retrieveStatsSpy).toBeCalled()
expect(response.status).toEqual(500)
expect(response.body).toEqual({
message: 'Error in retrieving billing records',
})
})
})
})
/**
* Helper method to generate login statistics for testing.
*/
const generateLoginStatistics = async ({
user,
esrvcIdToCheck,
altEsrvcId,
}: {
user: IUserSchema
esrvcIdToCheck: string
altEsrvcId: string
}) => {
// Generate login statistics.
// Create 3 random forms.
const formPromises = times(3, (idx) =>
FormModel.create({
title: `example form title ${idx}`,
admin: user._id,
responseMode: FormResponseMode.Email,
emails: [user.email],
}),
)
const forms = await Promise.all(formPromises)
// Login to first two forms a set number of times with the same esrvcId.
const esrvc1LoginTimes = [4, 2]
const loginPromises = flatten(
forms.map((form, idx) =>
times(esrvc1LoginTimes[idx], () =>
LoginModel.create({
form: form._id,
admin: user._id,
agency: user.agency,
authType: FormAuthType.SP,
esrvcId: esrvcIdToCheck,
}),
),
),
)
// Login to third form with a different esrvcId.
loginPromises.push(
...times(5, () =>
LoginModel.create({
form: forms[2]._id,
admin: user._id,
agency: user.agency,
authType: FormAuthType.SP,
esrvcId: altEsrvcId,
}),
),
)
await Promise.all(loginPromises)
return {
generatedLoginTimes: esrvc1LoginTimes,
generatedForms: forms,
}
}
|
typescript
|
Why you can trust TechRadar We spend hours testing every product or service we review, so you can be sure you’re buying the best. Find out more about how we test.
Close comparison of an Alpha 77 Mark II with the original Alpha 77 reveals few obvious differences. The two cameras have the same overall shape and control layout and the vertical grip that was produced for the original A77 can be used with the new camera.
There is a slight difference to the new camera's mode dial, however: it has a lock button to prevent it from being knocked out of position. The hotshoe has also been changed from the Sony (Minolta) proprietary shape to the more common universal style. It has also been upgraded to make it a multi-shoe capable of accepting a range of accessories.
In addition, the function (Fn) button has a greater range of customisation options. The A77 II has 27 features that can be assigned to one of the twelve slots in the Function menu. If you like using the Picture Effects (Toy Camera, Pop Color, Posterization, Retro Photo, Soft High-key, Partial Color, High Contrast Mono, Soft Focus, HDR Painting, Rich-tone Monochrome, Miniature, Watercolor, Illustration), it's worth assigning this and image quality to the Function menu so that you can quickly turn off raw recording and access the effects.
As with other Sony cameras, the Creative Style options (Standard, Vivid, Neutral, Clear, Deep, Light, Portrait, Landscape, Sunset, Night, Autumn, Black and White and Sepia), which give JPEG images a particular appearance, can be used when shooting raw images simultaneously.
It's also possible to customise the function of many of the buttons on the camera, but I found that the default settings worked well.
Like the camera it replaced, the Alpha 77 Mark II feels pretty tough and durable. The grip on the front of the camera is deep and generously sized to provide a comfortable hold. There are also seals to keep dust and moisture at bay so you can use the camera in fairly harsh environments.
Like the A77, the A77 II has plenty of buttons and dials to give direct access to many of the key features, as befits an enthusiast-level camera.
It's quick and easy to select the desired autofocus point using the mini-joystick style controller on the back of the camera. Helpfully, if you find 61 points too many to choose from in Flexible Spot mode you can restrict it to just 15.
Strangely, Sony has continued with having the 12fps shooting option located on the mode dial. Given the rethinking about the AF options, we might have expected this to be part of the drive mode options. Sony's explanation is that it's a major feature of the camera and that there are aspects such as the aperture locking at the start of the shoot that need to be considered.
On the back of the camera is a three-inch vari-angle screen, which provides a detailed, clear view of the scene, but isn't touch-sensitive. Its resolution, however, has been boosted from 921,000 dots to 1,228,000 dots and, like the screen on the new Nikon D810, it's an RGBW (red, green, blue, white) device for greater brightness.
While the screen is useful for composing images from awkward angles, the articulating hinge seems unnecessarily complicated and it takes a while to get used to its quirks and limitations. The hinges on cameras such as the Canon 70D and Nikon D5300 are much more straightforward.
As on the Sony A7 and 7R, the 2.3-million dot electronic viewfinder (EVF) is bright and clear with plenty of detail visible. As usual with an EVF, this brings the benefit of seeing the image as it will be captured.
|
english
|
<gh_stars>0
# Help/es
## Foro
El primer lugar donde puedes pedir ayuda es el [foro de FreeCAD](https://forum.freecadweb.org/viewforum.php?f=3). Por favor, lee [este post](https://forum.freecadweb.org/viewtopic.php?f=3&t=2264) antes de hacer cualquier pregunta. Recuerda que [información importante](Important_information/es.md) sobre tu sistema es necesario cuando pidas ayuda.
Hay diferentes subforos para usuarios y desarrolladores de FreeCAD. Asegúrate de buscar en internet, y leer las preguntas existentes antes de pedir ayuda. Hay subforos donde puedes discutir temas más específicos, dar tus impresiones sobre FreeCAD, discutir nuevas ideas, etc. Los foros son muy activos y deberías recibir una respuesta muy rápidamente.
## Wiki
Si necesitas ayuda o tienes cuestiones relativas a una página particular de esta wiki de documentación, siempre puedes dejar ideas o comentarios en la pestaña de \"discusión\" de cada página.
## Internet Relay Chat (IRC)
También existe un [IRC \#freecad sala de chat en Freenode](irc://chat.freenode.net/freecad). \#openFOAM-IRC también está en Freenode.
## Reddit
Si estás en Reddit puedes usar el [r/FreeCAD](https://www.reddit.com/r/FreeCAD/), o el [r/flossCAD](https://www.reddit.com/r/flossCAD/) usando el estilo de FreeCAD. El subreddit de r/flossCAD también tiene [una sala de chat](https://s.reddit.com/channel/300896_dfacaa912e069e3d3f7e55e5cedfb25483d8d68a) donde se pueden hacer preguntas. También hay [r/ElmerFEM](https://www.reddit.com/r/ElmerFEM/), [r/openscad](https://www.reddit.com/r/openscad/), [r/LibreCAD/](https://www.reddit.com/r/LibreCAD/) [r/OpenFOAM](https://www.reddit.com/r/OpenFOAM/), y [r/Modelica](https://www.reddit.com/r/Modelica/) subreddits.
## Telegram
If you are on Telegram you may use the [t.me/FreeCAD\_EN](https://t.me/FreeCAD_EN).
## Twitter y Mastodon
También puede seguir la [cuenta oficial de Twitter para FreeCAD](https://twitter.com/FreeCADNews) y/o [los desarrolladores](https://twitter.com/fsfarimani/lists/freecad). También hay [cuenta oficial de FreeCAD Mastodon](https://fosstodon.org/@FreeCAD) que puedes seguir.
## Facebook
Puedes unirte al [Grupo público de Facebook de FreeCAD](https://www.facebook.com/groups/416491481766626)
## Discord
<div class="mw-translate-fuzzy">
Tenemos un [official Servidor Discord dedicado a FreeCAD](https://discord.gg/BgZh2n7Kn9) con una variedad de canales para varios sub-temas. También hay varios servidores de terceros con canales de discusión relacionados con FreeCAD. El servidor [Elmer FEM](https://discordapp.com/invite/NeZEBZn) tiene un canal para casi todas las herramientas CAD, CAM y CAE que existen, ya sean de código abierto o propietarias, y tiene un canal \"freecad\" bastante bien establecido. La gran variedad de canales y comunidades que atrae este servidor significa que puede ser bueno para tener discusiones con gente de comunidades relacionadas. El servidor [OpenFOAM](https://discordapp.com/invite/P9p9eHn) tiene un canal \"freecad-salome-etc\", donde puedes encontrar gente más interesada en el solapamiento entre FreeCAD y las herramientas de dinámica de fluidos computacional como OpenFOAM. El servidor [Modelica Lengua](https://discordapp.com/invite/bp2yeYU) también tiene un canal \"freecad\" si estás interesado en FreeCAD desde una perspectiva de modelado multidominio. Sin embargo, por favor, no utilices los grupos de chat como medio principal de intercambio de datos. No están indexados por los motores de búsqueda y la información producida en estas plataformas no se acumula adecuadamente, como ocurre en los foros, las entradas de blog o las páginas wiki.
</div>
---
 [documentation index](../README.md) > [Help](Category_Help.md) > Help/es
|
markdown
|
{"nom":"Saint-Benoît-d'Hébertot","circ":"4ème circonscription","dpt":"Calvados","inscrits":324,"abs":196,"votants":128,"blancs":3,"nuls":1,"exp":124,"res":[{"nuance":"REM","nom":"<NAME>","voix":65},{"nuance":"LR","nom":"<NAME>","voix":59}]}
|
json
|
<p></p>
{% import _self as ownMacro %}
{{ ownMacro.generateMessagesPreview(messages) }}
{% macro generateMessagesPreview(messages) %}
{% if messages | length %}
{% set message = messages.shift() %}
<hr>
<blockquote>
<span><strong>Subject:</strong> {{ message.subject }}</span><br>
<span><strong>On {{ message.sent_at | date }} {{ message.authorName({ 'proper': true }) }} wrote:</strong></span><br>
<div style="margin: 1em 0 0 1em;">
{{ message.body }}
{{ ownMacro.generateMessagesPreview(messages) }}
</div>
</blockquote>
{% endif %}
{% endmacro %}
|
html
|
from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import range, zip, map, reduce, filter
from keras.layers import Input, Conv2D, Conv3D, Activation, Lambda
from keras.models import Model
from keras.layers.merge import Add, Concatenate
import tensorflow as tf
from keras import backend as K
from .blocks import unet_block, unet_blocks, gaussian_2d
import re
from ..utils import _raise, backend_channels_last
import numpy as np
def custom_unet(input_shape,
last_activation,
n_depth=2,
n_filter_base=16,
kernel_size=(3,3,3),
n_conv_per_depth=2,
activation="relu",
batch_norm=False,
dropout=0.0,
pool_size=(2,2,2),
n_channel_out=1,
residual=False,
prob_out=False,
long_skip=True,
eps_scale=1e-3):
""" TODO """
if last_activation is None:
raise ValueError("last activation has to be given (e.g. 'sigmoid', 'relu')!")
all((s % 2 == 1 for s in kernel_size)) or _raise(ValueError('kernel size should be odd in all dimensions.'))
channel_axis = -1 if backend_channels_last() else 1
n_dim = len(kernel_size)
# TODO: rewrite with conv_block
conv = Conv2D if n_dim == 2 else Conv3D
input = Input(input_shape, name="input")
unet = unet_block(n_depth, n_filter_base, kernel_size, input_planes=input_shape[-1],
activation=activation, dropout=dropout, batch_norm=batch_norm,
n_conv_per_depth=n_conv_per_depth, pool=pool_size, long_skip=long_skip)(input)
final = conv(n_channel_out, (1,)*n_dim, activation='linear')(unet)
if residual:
if not (n_channel_out == input_shape[-1] if backend_channels_last() else n_channel_out == input_shape[0]):
raise ValueError("number of input and output channels must be the same for a residual net.")
final = Add()([final, input])
final = Activation(activation=last_activation)(final)
if prob_out:
scale = conv(n_channel_out, (1,)*n_dim, activation='softplus')(unet)
scale = Lambda(lambda x: x+np.float32(eps_scale))(scale)
final = Concatenate(axis=channel_axis)([final, scale])
return Model(inputs=input, outputs=final)
def uxnet(input_shape,
n_depth=2,
n_filter_base=16,
kernel_size=(3, 3),
n_conv_per_depth=2,
activation="relu",
last_activation='linear',
batch_norm=False,
dropout=0.0,
pool_size=(2, 2),
residual=True,
odd_to_even=False,
shortcut=None,
shared_idx=[],
prob_out=False,
eps_scale=1e-3):
"""
Multi-body U-Net which learns identity by leaving one plane out in each branch
:param input_shape:
:param n_depth:
:param n_filter_base:
:param kernel_size:
:param n_conv_per_depth:
:param activation:
:param last_activation:
:param batch_norm:
:param dropout:
:param pool_size:
:param prob_out:
:param eps_scale:
:return: Model
"""
# TODO: fill params
# TODO: add odd-to-even mode
# Define vars
channel_axis = -1 if backend_channels_last() else 1
n_planes = input_shape[channel_axis]
if n_planes % 2 != 0 and odd_to_even:
raise ValueError('Odd-to-even mode does not support uneven number of planes')
n_dim = len(kernel_size)
conv = Conv2D if n_dim == 2 else Conv3D
# Define functional model
input = Input(shape=input_shape, name='input_main')
# TODO test new implementation and remove old
# Split planes (preserve channel)
input_x = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1))(input) for i in range(n_planes)]
# We can train either in odd-to-even mode or in LOO mode
if odd_to_even:
# In this mode we stack together odd and even planes, train the net to predict even from odd and vice versa
# input_x_out = [Concatenate(axis=-1)(input_x[j::2]) for j in range(2)]
input_x_out = [Concatenate(axis=-1)(input_x[j::2]) for j in range(1, -1, -1)]
else:
# Concatenate planes back in leave-one-out way
input_x_out = [Concatenate(axis=-1)([plane for i, plane in enumerate(input_x) if i != j]) for j in range(n_planes)]
# if odd_to_even:
# input_x_out = [Lambda(lambda x: x[..., j::2],
# output_shape=(None, None, n_planes // 2),
# name='{}_planes'.format('even' if j == 0 else 'odd'))(input)
# for j in range(1, -1, -1)]
# else:
# # input_x_out = [Lambda(lambda x: x[..., tf.convert_to_tensor([i for i in range(n_planes) if i != j], dtype=tf.int32)],
# # output_shape=(None, None, n_planes-1),
# # name='leave_{}_plane_out'.format(j))(input)
# # for j in range(n_planes)]
#
# input_x_out = [Lambda(lambda x: K.concatenate([x[..., :j], x[..., (j+1):]], axis=-1),
# output_shape=(None, None, n_planes - 1),
# name='leave_{}_plane_out'.format(j))(input)
# for j in range(n_planes)]
# U-Net parameters depend on mode (odd-to-even or LOO)
n_blocks = 2 if odd_to_even else n_planes
input_planes = n_planes // 2 if odd_to_even else n_planes-1
output_planes = n_planes // 2 if odd_to_even else 1
# Create U-Net blocks (by number of planes)
unet_x = unet_blocks(n_blocks=n_blocks, input_planes=input_planes, output_planes=output_planes,
n_depth=n_depth, n_filter_base=n_filter_base, kernel_size=kernel_size,
activation=activation, dropout=dropout, batch_norm=batch_norm,
n_conv_per_depth=n_conv_per_depth, pool=pool_size, shared_idx=shared_idx)
unet_x = [unet(inp_out) for unet, inp_out in zip(unet_x, input_x_out)]
# Version without weight sharing:
# unet_x = [unet_block(n_depth, n_filter_base, kernel_size,
# activation=activation, dropout=dropout, batch_norm=batch_norm,
# n_conv_per_depth=n_conv_per_depth, pool=pool_size,
# prefix='out_{}_'.format(i))(inp_out) for i, inp_out in enumerate(input_x_out)]
# TODO: rewritten for sharing -- remove commented below
# Convolve n_filter_base to 1 as each U-Net predicts a single plane
# unet_x = [conv(1, (1,) * n_dim, activation=activation)(unet) for unet in unet_x]
if residual:
if odd_to_even:
# For residual U-Net sum up output for odd planes with even planes and vice versa
unet_x = [Add()([unet, inp]) for unet, inp in zip(unet_x, input_x[::-1])]
else:
# For residual U-Net sum up output with its neighbor (next for the first plane, previous for the rest
unet_x = [Add()([unet, inp]) for unet, inp in zip(unet_x, [input_x[1]]+input_x[:-1])]
# Concatenate outputs of blocks, should receive (None, None, None, n_planes)
# TODO assert to check shape?
if odd_to_even:
# Split even and odd, assemble them together in the correct order
# TODO tests
unet_even = [Lambda(lambda x: x[..., i:i+1],
output_shape=(None, None, 1),
name='even_{}'.format(i))(unet_x[0]) for i in range(n_planes // 2)]
unet_odd = [Lambda(lambda x: x[..., i:i+1],
output_shape=(None, None, 1),
name='odd_{}'.format(i))(unet_x[1]) for i in range(n_planes // 2)]
unet_x = list(np.array(list(zip(unet_even, unet_odd))).flatten())
unet = Concatenate(axis=-1)(unet_x)
if shortcut is not None:
# We can create a shortcut without long skip connection to prevent noise memorization
if shortcut == 'unet':
shortcut_block = unet_block(long_skip=False, input_planes=n_planes,
n_depth=n_depth, n_filter_base=n_filter_base, kernel_size=kernel_size,
activation=activation, dropout=dropout, batch_norm=batch_norm,
n_conv_per_depth=n_conv_per_depth, pool=pool_size)(input)
shortcut_block = conv(n_planes, (1,) * n_dim, activation='linear', name='shortcut_final_conv')(shortcut_block)
# Or a simple gaussian blur block
elif shortcut == 'gaussian':
shortcut_block = gaussian_2d(n_planes, k=13, s=7)(input)
else:
raise ValueError('Shortcut should be either unet or gaussian')
# TODO add or concatenate?
unet = Add()([unet, shortcut_block])
# unet = Concatenate(axis=-1)([unet, shortcut_unet])
# Final activation layer
final = Activation(activation=last_activation)(unet)
if prob_out:
scale = conv(n_planes, (1,)*n_dim, activation='softplus')(unet)
scale = Lambda(lambda x: x+np.float32(eps_scale))(scale)
final = Concatenate(axis=channel_axis)([final, scale])
return Model(inputs=input, outputs=final)
def common_unet(n_dim=2, n_depth=1, kern_size=3, n_first=16, n_channel_out=1,
residual=True, prob_out=False, long_skip=True, last_activation='linear'):
"""
Construct a common CARE neural net based on U-Net [1]_ and residual learning [2]_
to be used for image restoration/enhancement.
Parameters
----------
n_dim : int
number of image dimensions (2 or 3)
n_depth : int
number of resolution levels of U-Net architecture
kern_size : int
size of convolution filter in all image dimensions
n_first : int
number of convolution filters for first U-Net resolution level (value is doubled after each downsampling operation)
n_channel_out : int
number of channels of the predicted output image
residual : bool
if True, model will internally predict the residual w.r.t. the input (typically better)
requires number of input and output image channels to be equal
prob_out : bool
standard regression (False) or probabilistic prediction (True)
if True, model will predict two values for each input pixel (mean and positive scale value)
last_activation : str
name of activation function for the final output layer
Returns
-------
function
Function to construct the network, which takes as argument the shape of the input image
Example
-------
>>> model = common_unet(2, 1,3,16, 1, True, False)(input_shape)
References
----------
.. [1] <NAME>, <NAME>, <NAME>x, *U-Net: Convolutional Networks for Biomedical Image Segmentation*, MICCAI 2015
.. [2] <NAME>, <NAME>, <NAME>, <NAME>. *Deep Residual Learning for Image Recognition*, CVPR 2016
"""
def _build_this(input_shape):
return custom_unet(input_shape, last_activation, n_depth, n_first, (kern_size,)*n_dim, pool_size=(2,)*n_dim,
n_channel_out=n_channel_out, residual=residual, prob_out=prob_out, long_skip=long_skip)
return _build_this
def common_uxnet(n_dim=2, n_depth=1, kern_size=3, n_first=16,
residual=True, prob_out=False, last_activation='linear',
shared_idx=[], odd_to_even=False, shortcut=None):
def _build_this(input_shape):
return uxnet(input_shape=input_shape, last_activation=last_activation, n_depth=n_depth, n_filter_base=n_first,
kernel_size=(kern_size,)*n_dim, pool_size=(2,)*n_dim,
residual=residual, prob_out=prob_out,
shared_idx=shared_idx, odd_to_even=odd_to_even, shortcut=shortcut)
return _build_this
modelname = re.compile("^(?P<model>resunet|unet)(?P<n_dim>\d)(?P<prob_out>p)?_(?P<n_depth>\d+)_(?P<kern_size>\d+)_(?P<n_first>\d+)(_(?P<n_channel_out>\d+)out)?(_(?P<last_activation>.+)-last)?$")
def common_unet_by_name(model):
r"""Shorthand notation for equivalent use of :func:`common_unet`.
Parameters
----------
model : str
define model to be created via string, which is parsed as a regular expression:
`^(?P<model>resunet|unet)(?P<n_dim>\d)(?P<prob_out>p)?_(?P<n_depth>\d+)_(?P<kern_size>\d+)_(?P<n_first>\d+)(_(?P<n_channel_out>\d+)out)?(_(?P<last_activation>.+)-last)?$`
Returns
-------
function
Calls :func:`common_unet` with the respective parameters.
Raises
------
ValueError
If argument `model` is not a valid string according to the regular expression.
Example
-------
>>> model = common_unet_by_name('resunet2_1_3_16_1out')(input_shape)
>>> # equivalent to: model = common_unet(2, 1,3,16, 1, True, False)(input_shape)
Todo
----
Backslashes in docstring for regexp not rendered correctly.
"""
m = modelname.fullmatch(model)
if m is None:
raise ValueError("model name '%s' unknown, must follow pattern '%s'" % (model, modelname.pattern))
# from pprint import pprint
# pprint(m.groupdict())
options = {k:int(m.group(k)) for k in ['n_depth','n_first','kern_size']}
options['prob_out'] = m.group('prob_out') is not None
options['residual'] = {'unet': False, 'resunet': True}[m.group('model')]
options['n_dim'] = int(m.group('n_dim'))
options['n_channel_out'] = 1 if m.group('n_channel_out') is None else int(m.group('n_channel_out'))
if m.group('last_activation') is not None:
options['last_activation'] = m.group('last_activation')
return common_unet(**options)
def receptive_field_unet(n_depth, kern_size, pool_size=2, n_dim=2, img_size=1024):
"""Receptive field for U-Net model (pre/post for each dimension)."""
x = np.zeros((1,)+(img_size,)*n_dim+(1,))
mid = tuple([s//2 for s in x.shape[1:-1]])
x[(slice(None),) + mid + (slice(None),)] = 1
model = custom_unet (
x.shape[1:],
n_depth=n_depth, kernel_size=[kern_size]*n_dim, pool_size=[pool_size]*n_dim,
n_filter_base=8, activation='linear', last_activation='linear',
)
y = model.predict(x)[0,...,0]
y0 = model.predict(0*x)[0,...,0]
ind = np.where(np.abs(y-y0)>0)
return [(m-np.min(i), np.max(i)-m) for (m, i) in zip(mid, ind)]
|
python
|
Afghanistan’s first day in Test cricket was not what they would have expected. Up against world number one side India, they were given a reality check on what Test cricket is all about. The excitement of the debut Test match took the back seat when Indian openers Shikhar Dhawan and Murali Vijay ripped them apart in the first session of the day.
By the time the first session ended, India were 158 for no loss with Dhawan’s 87-ball ton being the highlight of the show.
In the process, Dhawan became the first ever Indian batsman to score a century in the first session of a Test match.
Dhawan hit Rashid Khan for three boundaries to complete a half-century in 47 balls. The hundred also came off the same bowler as Dhawan hit a flowing cover drive to reach the milestone. Overall, India hit 25 boundaries and four sixes in the first session, thus fully stamping their authority over Test cricket’s latest entrants.
Afghanistan finally heaved a sigh of relief when Yamin Ahmadzai sent back Dhawan soon after lunch. At the end of the day, Afghanistan had something to cheer about as they managed to take 5 wickets in quick time to reduce India to 347 for 6. Ahmadzai was the pick of the bowlers, picking up 2 for 32. While other bowlers were taken for cleaners, the pacer conceded less than 3.
Speaking after the day’s play, he said that the beginning of the Test journey was “little stressful”.
“Well, this was a dream which has come true for our nation. It was enjoyable, but a little stressful. Nevertheless, playing against India, the number one team, was a good experience. Still there are four days to go and we will try to do our best,” Ahmadzai said at the press conference.
“Getting a Test cap is the most important thing in cricketers’ lives. It is same for me as well. I cannot express it in words. There was excitement when we walked onto the field, but also were nervous,” he added.
He further defended his teammates who just failed to contain the Indian batsmen in the first two sessions.
“Our bowlers especially Rashid was trying too much in the first session, but he bowled wicket-to-wicket on a pitch which began to grip in the last session. That is the reason why we came back strongly. Our bowlers picked five wickets,” he said.
|
english
|
<reponame>lucasccdias/abstreet
use geom::{Polygon, Pt2D, Triangle};
use widgetry::tools::PopupMsg;
use widgetry::{
EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text,
TextExt, VerticalAlignment, Widget,
};
use crate::app::{App, Transition};
pub struct PolygonDebugger {
panel: Panel,
noun: String,
items: Vec<Item>,
idx: usize,
center: Option<Pt2D>,
}
pub enum Item {
Point(Pt2D),
Triangle(Triangle),
Polygon(Polygon),
}
impl PolygonDebugger {
pub fn new_state(
ctx: &mut EventCtx,
noun: &str,
items: Vec<Item>,
center: Option<Pt2D>,
) -> Box<dyn State<App>> {
if items.is_empty() {
return PopupMsg::new_state(ctx, "Woops", vec![format!("No {}, never mind", noun)]);
}
Box::new(PolygonDebugger {
panel: Panel::new_builder(Widget::col(vec![
Widget::row(vec![
Line("Geometry debugger").small_heading().into_widget(ctx),
ctx.style().btn_close_widget(ctx),
]),
Widget::row(vec![
// TODO Make these inactive when on the first/last. More generally, refactor
// some kind of pagination helper.
ctx.style()
.btn_prev()
.hotkey(Key::LeftArrow)
.build_widget(ctx, "previous"),
"noun X/Y".text_widget(ctx).named("pointer").centered_vert(),
ctx.style()
.btn_next()
.hotkey(Key::RightArrow)
.build_widget(ctx, "next"),
])
.evenly_spaced(),
]))
.aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
.build(ctx),
noun: noun.to_string(),
items,
idx: 0,
center,
})
}
}
impl State<App> for PolygonDebugger {
fn event(&mut self, ctx: &mut EventCtx, _: &mut App) -> Transition {
ctx.canvas_movement();
if let Outcome::Clicked(x) = self.panel.event(ctx) {
match x.as_ref() {
"close" => {
return Transition::Pop;
}
"previous" => {
if self.idx != 0 {
self.idx -= 1;
}
}
"next" => {
if self.idx != self.items.len() - 1 {
self.idx += 1;
}
}
_ => unreachable!(),
}
}
self.panel.replace(
ctx,
"pointer",
format!("{} {}/{}", self.noun, self.idx + 1, self.items.len()).text_widget(ctx),
);
Transition::Keep
}
fn draw(&self, g: &mut GfxCtx, app: &App) {
// This is drawn in screen-space, so zooming doesn't affect the text size
let mut batch = GeomBatch::new();
match &self.items[self.idx] {
Item::Point(pt) => {
batch.append(
Text::from(self.idx.to_string())
.bg(app.cs.panel_bg)
.render(g)
.centered_on(g.canvas.map_to_screen(*pt).to_pt()),
);
}
Item::Triangle(ref tri) => {
for pt in [tri.pt1, tri.pt2, tri.pt3] {
batch.append(
Text::from(self.idx.to_string())
.bg(app.cs.panel_bg)
.render(g)
.centered_on(g.canvas.map_to_screen(pt).to_pt()),
);
}
g.draw_polygon(app.cs.selected, Polygon::from_triangle(tri));
}
Item::Polygon(ref poly) => {
g.draw_polygon(app.cs.selected, poly.clone());
batch.append(
Text::from(self.idx.to_string())
.bg(app.cs.panel_bg)
.render(g)
.centered_on(g.canvas.map_to_screen(poly.center()).to_pt()),
);
}
}
if let Some(pt) = self.center {
batch.append(
Text::from("c")
.bg(app.cs.panel_bg)
.render(g)
.centered_on(g.canvas.map_to_screen(pt).to_pt()),
);
}
let draw = g.upload(batch);
g.fork_screenspace();
g.redraw(&draw);
g.unfork();
self.panel.draw(g);
}
}
|
rust
|
{
"General": {
"Symbol": "SETH",
"Name": "Sether",
"Description": "<p>Sether is a platform that provides blockchain integration with social network APIs, allowing companies to get information, analyse and monitor social networks. The SETH token is a standard ERC20 token that can be used by multiple wallets and trading platforms. The token will be used as the only currency for interacting with the Sether platform.</p>",
"Features": null,
"Technology": null,
"TotalCoinSupply": "100000000",
"Algorithm": null,
"ProofType": null,
"BlockReward": null,
"Explorer": null,
"StartDate": "04/12/2017",
"TotalCoinsMined": null,
"Twitter": "@setherplatform",
"Telegram": null,
"Youtube": null,
"Video": null,
"BlockchainInfo": null,
"Facebook": null,
"Slack": null,
"Website": null,
"GitHub": null,
"OnMarkets": [
"EtherDelta",
"HitBTC"
],
"Wallets": {
"desktop": {
"win": null,
"linux": null,
"mac": null
},
"mobile": {
"android": null,
"ios": null
},
"types": []
}
},
"ICO": {
"Status": "Finished",
"Description": "<p>Sether is a platform that provides blockchain integration with social network APIs, allowing companies to get information, analyse and monitor social networks. The SETH token is a standard ERC20 token that can be used by multiple wallets and trading platforms. The token will be used as the only currency for interacting with the Sether platform.</p><p><strong>Team</strong>:</p><ul><li><strong><NAME>:</strong> CEO <a href=\"https://www.linkedin.com/in/ovidiu-oancea-3961a71/\" target=\"_blank\"><img src=\"/media/1383931/likedin_logo_final.png?width=14&height=13\" alt=\"\" data-id=\"202867\"></a></li><li><strong><NAME>:</strong> CTO <a href=\"https://www.linkedin.com/in/flaviusburca/\" target=\"_blank\"><img src=\"/media/1383931/likedin_logo_final.png?width=14&height=13\" alt=\"\" data-id=\"202867\"></a></li><li><strong><NAME>:</strong> COO <a href=\"https://www.linkedin.com/in/cristi-savescu-235a356/\" target=\"_blank\"><img src=\"/media/1383931/likedin_logo_final.png?width=14&height=13\" alt=\"\" data-id=\"202867\"></a></li><li><strong><NAME>:</strong> Technical Manager <a href=\"https://www.linkedin.com/in/dan-chirila-897a7731/\" target=\"_blank\"><img src=\"/media/1383931/likedin_logo_final.png?width=14&height=13\" alt=\"\" data-id=\"202867\"></a></li></ul><p>The Sether ICO will start on the 4th of December 2017 and will last until the 15th of February 2018 or until the 165,000 ETH hard cap is reached. The ICO token allocation represents 55% of the total coin supply. The coins will be available for a 0.003 ETH starting price and can be purchased with BTC, ETH, LTC or DASH</p><p><strong>Token Reserve Split (45%):</strong></p><ul><li>35% for the company to be diluted</li><li>7% per year for incentives to the community, beta testers and strategic partners;</li><li>10% to be sold directly on the platform for service consumers. These tokens will be locked for 6 months after the end of the crowdsale.</li></ul>",
"TokenType": "ETH (ERC20)",
"WebsiteLink": "https://www.sether.io/for-investors",
"FundingCap": "165,000 ETH",
"FundingTarget": "N/A",
"Date": 1512345600,
"EndDate": 1515974400,
"FundsRaisedList": "22,000 ETH",
"FundsRaisedUSD": "24307140",
"StartPrice": "0.003",
"StartPriceCurrency": "ETH",
"Jurisdiction": "N/A",
"BlogLink": "https://medium.com/@contact_47998",
"WhitePaperLink": "https://github.com/mware-solutions/icosite/blob/master/SETHER%20Whitepaper.pdf"
},
"ccId": "419209"
}
|
json
|
const express = require('express');
const router = express.Router();
const path = require('path')
router.get('/design-shirt', (req, res) => {
console.log(req.query)
console.log(req.protocol + '://' + req.get('host') + req.originalUrl)
res.render('design-shirt.ejs', {
title: 'Design your shirt',
query: req.query,
url: req.protocol + '://' + req.get('host') + req.originalUrl
})
})
// router.get('/design-shirt/step-:step', (req, res) => {
// res.render('design-shirt.ejs', {
// query: req.query,
// step: req.params.step ? req.params.step : "1",
// url: eq.protocol + '://' + req.get('host') + req.originalUrl
// })
// })
module.exports = router;
|
javascript
|
<gh_stars>1-10
import { lowerBound } from './lower-bound';
export function binarySearch<T>(
arr: T[],
value: T,
less = (a: T, b: T) => a < b
): boolean {
const index = lowerBound(arr, value, less);
return index !== arr.length && !less(value, arr[index]);
}
|
typescript
|
<!DOCTYPE HTML>
<!--
Telephasic by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Harmonics - by <NAME></title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body class="homepage is-preload">
<div id="page-wrapper">
<!-- Header -->
<div id="header-wrapper">
<div id="header" class="container">
<!-- Logo -->
<h1 id="logo"><a href="index.html">Harmonics</a></h1>
<!-- Nav -->
<nav id="nav">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="learn-scales.html">Learn Scales</a></li>
<li class="break"><a href="generator.html">Melody Generator</a></li>
<li><a href="reddit-music.html">r/music</a></li>
</ul>
</nav>
</div>
<!-- Hero -->
<section id="hero" class="container">
<header>
<h2><strong>Harmonics</strong> helps you generate
<br />ideas for your next jamming session</h2>
</header>
<p>Built by <a href = #portfoliowebsite><NAME></a></p>
<ul class="actions">
<li><a href="generator.html" class="button">Let's Find Your Melody!</a></li>
</ul>
</section>
</div>
<!-- Features 1 -->
<div class="wrapper">
<div class="container">
<div class="row">
<section class="col-6 col-12-narrower feature">
<div class="image-wrapper first">
<a href="generator.html" class="image featured first"><img src="images/chord-progression-pic.jpg" alt="" /></a>
</div>
<header>
<h2>Need something to start your creativity?</h2>
</header>
<p>Harmonics's Melody Generator allows you to create a customizable chord progression that will spark your idea to create new music or to jam out with your friends!
</p>
<ul class="actions">
<li><a href="generator.html" class="button">Generate My Melody</a></li>
</ul>
</section>
<section class="col-6 col-12-narrower feature">
<div class="image-wrapper">
<a href="learn-scales.html" class="image featured"><img src="images/melody-generator-pic.jpg" alt="" /></a>
</div>
<header>
<h2>Curious about how it works?</h2>
</header>
<p>Harmonics will provide you with some musical theory to understand on scales!
</p>
<ul class="actions">
<li><a href="learn-scales.html" class="button">Learn More</a></li>
</ul>
</section>
</div>
</div>
</div>
<!-- Footer -->
<div id="footer-wrapper">
<div id="footer" class="container">
<header class="major">
<h2>"To send light into the darkness of men's hearts - such is the duty of the artist."</h2>
<p><NAME></p>
</header>
</div>
<div id="copyright" class="container">
<ul class="menu">
<li>Copyright © 2020 <NAME>. All rights reserved.</li>
</ul>
</div>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.dropotron.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
|
html
|
<reponame>bitcoinnano/btcnano-message
{
"name": "btcnano-message",
"main": "./btcnano-message.min.js",
"version": "0.1.0",
"homepage": "https://github.com/bitcoinnano/btcnano-message",
"authors": [
"Btcnano"
],
"description": "Btcnano Message Verification and Signing for Btcnano",
"moduleType": [
"globals"
],
"keywords": [
"btcnano",
"bitcoin",
"bitcore",
"btn",
"satoshi",
"message",
"signing"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
|
json
|
//
// Created by <NAME> on 1/16/21.
//
#include "Constraints.h"
Edge2d ConnectionConstraint::getGuide() const {
Eigen::Vector2d dir = (edge.second - edge.first).normalized();
return {edge.first - dir * startGuideExtention, edge.second + dir * endGuideExtension};
}
|
cpp
|
{
"someString": "string",
"someInt": 42,
"someMinusInt": -42,
"someFloat": -4.2,
"someObject": {},
"someArray": [],
"someTrue": true,
"someFalse": false,
"someNull": null
}
|
json
|
import torch
import torch.nn as nn
import torch.nn.functional as F
# this file contains the TransUNet architecture
class TransUNet(nn.Module):
"""
Reference: https://arxiv.org/pdf/2102.04306.pdf
"""
def __init__(self, num_of_subbands):
super().__init__()
def forward(self, x):
return x
|
python
|
Britt Baker was the first female talent to be signed to All Elite Wrestling promotion alongside Brandi Rhodes. Unlike the latter talent, she has been a former AEW Women’s World Champion who carried the women’s division of the company during the pandemic as a full-time in-ring performer. Her rise to the top of the fame has been well-documented but we haven’t seen her around much in recent memory.
Being a prominent figure in All Elite Wrestling since its launch in 2019, her absence from television has been felt in 2023. Alongside Britt Baker, names like Thunder Rosa, Riho, Jamie Hayter, Saraya and more have missed TV time which expectedly hampered AEW’s booking around their female roster.
During this absence, Britt Baker also expressed her frustration about her lack of TV time and promo time compared to the male talents of the AEW. The Wrestling Observer then revealed that her absence is due to a bad back and an illness that is preventing her from traveling to recent shows in her hometown of Pittsburgh. The health-related issue is why her limited involvement in storylines and her focus on promoting other talents in recent months led to her long absence.
The source emphasized the injury situation while nothing was noted regarding the return of the top female star of AEW. Only Tony Khan recently stated in an interview that he will bring some of the top free agents for the female roster in 2024 while some former champions will also be back to shake things up for his promotion.
Britt Baker has become a veteran female talent on how to cut a promo and deliver some special matches. There was a time when she was featured on every show of AEW, but those days seem to be in the past. Apart from some segments to promote Timeless Toni Storm, not much emphasis has been given to female talents segments which led to a fan backlash. Hopefully, things will be better around the AEW Women’s Division in 2024 where Britt Baker can certainly expect to get a ton of TV as well as promo time.
|
english
|
Xiaomi has confirmed that the Mi Mix 2S will be its first smartphone to receive the latest MIUI 10 version based on Android 9 Pie. Google has already started the rollout of Android 9 Pie, the latest version of its operating system, to phones across the globe - starting with its own Pixel devices. During the launch of Android 9 Pie, Google had announced the companies that participated in the Beta programme, namely Essential, HMD Global, OnePlus, Oppo, Sony, Vivo, and Xiaomi, will receive the update by the end of this fall. While the Essential PH-1 has been issued its update, devices that are available under the Android One initiative will receive the update sometime around the rollout for the devices listed under the Beta programme. These include Essential PH-1, Nokia 7 Plus, OnePlus 6, Oppo R15 Pro, Sony Xperia XZ2, Vivo X21, Vivo X21 UD, and Xiaomi Mi Mix 2S.
As announced in an MIUI forum, Xiaomi is calling Mi Mix 2S users to be beta testers for the MIUI 10 that will be adapted to Android 9 Pie and the newly introduced features. Notably, the deadline to be a beta tester is August 9 and there is a list of requirements to enrol. Xiaomi is not limiting regions to be a beta tester, and for the project, you will have to be able to communicate in English over the QQ app. Other recruitment requirements include an unlocked bootloader and the latest MIUI Global Beta ROM. Since it is a project for enthusiasts, Xiaomi wants you to have an interest in flashing ROMs and bootloader unlocking.
To enlist, Mi Mix 2S users will have to enrol for the 'recruitment' via the MIUI official forum page or app. Once there, go to the Recruitment page and enter details. Notably, the entries page will be closing on August 9, and three days later Xiaomi will announce who gets to be an MIUI Beta Tester. Notably, the update also brings MIUI 10 developer ROM.
The Mi Mix 2S is one of the first smartphones to support Google ARCore. The Android 9 Pie bring several AI features and it will be interesting to see how the Chinese smartphone manufacturer will implement them in the new MIUI version.
|
english
|
---
uid: web-forms/videos/net-4/routing/aspnet-4-quick-hit-imperative-webforms-routing
title: ASP.NET 4 Quick Hit - Imperative WebForms Routing
author: JoeStagner
description: "In this video you will learn how to use an expression builder to do WebForms routing imperatively."
ms.author: riande
ms.date: 11/05/2009
ms.assetid: c78fd810-4309-4d58-afd9-81e9ffa77429
msc.legacyurl: /web-forms/videos/net-4/routing/aspnet-4-quick-hit-imperative-webforms-routing
msc.type: video
---
# ASP.NET 4 "Quick Hit" - Imperative WebForms Routing
by [<NAME>](https://github.com/JoeStagner)
In this video you will learn how to use an expression builder to do WebForms routing imperatively.
[▶ Watch video (12 minutes)](https://channel9.msdn.com/Blogs/ASP-NET-Site-Videos/aspnet-4-quick-hit-imperative-webforms-routing)
> [!div class="step-by-step"]
> [Previous](aspnet-4-quick-hit-permanent-redirect.md)
> [Next](aspnet-4-quick-hit-declarative-webforms-routing.md)
|
markdown
|
<filename>src/plugins/CreateElectricCircuitsMeta/CreateElectricCircuitsMeta.js<gh_stars>1-10
/*globals define*/
/*eslint-env node, browser*/
define([
'webgme-json-importer/JSONImporter',
'text!./metadata.json',
'plugin/PluginBase',
'electric-circuits/Constants',
'common/util/guid',
'text!./PySpice/elements.json'
], function (
JSONImporter,
pluginMetadata,
PluginBase,
Constants,
generateGuid,
PySpiceElements
) {
'use strict';
PySpiceElements = JSON.parse(PySpiceElements);
pluginMetadata = JSON.parse(pluginMetadata);
const MODELICA_ELECTRICAL_COMPONENTS_PREFIX = 'Modelica.Electrical.Analog';
const MODELICA_PIN_ATTR_NAME = 'Pin';
const DEFAULT_META_TAB = 'META';
const DECORATOR_ID = 'ElectricCircuitsDecorator';
const VISUALIZER_ID = 'ElectricCircuitsEditor';
const TO_NETLIST_PLUGIN = 'ConvertCircuitToNetlist';
const FROM_NETLIST_PLUGIN = 'ConvertNetlistToCircuit';
const EXTRA_NODES = {
SchottkyDiode: 'Diode',
LED: 'Diode'
};
const EXTRA_TAB_NAMES = {
SchottkyDiode: 'Semiconductors',
LED: 'Semiconductors'
};
const EXTRA_ATTRIBUTES = {
LED: {
attributes: [{
color: '#FF0000'
}],
attribute_meta:[{
color: {
type: 'string',
description: 'The color of the LED'
}
}]
}
};
const PYSPICE_CATEGORIES = {
'Basic': 'high_level_elements'
};
const SKIP_NODES = ['EMF', 'TranslationalEMF', 'HeatingResistor'];
const CURRENT_SOURCES = ['CCC', 'CCV'];
class CreateElectricCircuitsMeta extends PluginBase {
constructor(props) {
super(props);
this.metaSheets = {};
this.sheetCounts = {};
this.documentation = '';
this.positionGenerator = CreateElectricCircuitsMeta.getPositionGenerator();
this.pluginMetadata = pluginMetadata;
}
async main(callback) {
const importer = new JSONImporter(this.core, this.rootNode);
const {electricalState, pin} = await this.getModelicaLibraryState(importer);
this.modelicaState = electricalState;
this.modelicaPinState = pin;
const config = this.getCurrentConfig();
this.core.removeLibrary(this.rootNode, 'Modelica');
const state = await this.getBaseModel(importer);
const categories = this.getElectricalComponentCategories();
this.createCategories(state, categories);
categories.forEach(cat => {
this.createModelicaNodesOfType(state, cat);
this.createPySpiceNodesOfType(state, cat);
});
this.createExtraNodes(state);
this.renamePinsOfTransistorMoSFET(state);
await importer.apply(this.rootNode, state);
this.createDocumentationNode();
if (config.updateBranch === false) {
this.branchName = null;
}
await this.addWiresToCurrentSources();
const res = await this.save('Created ElectricCircuits Metamodel');
if (config.updateBranch === false) {
await this.project.createBranch('meta_' + Date.now(), res.hash);
}
this.result.setSuccess(true);
callback(null, this.result);
}
async getBaseModel(importer) {
const placeholder = name => ({id: `@name:${name}`});
const language = {
id: '@name:ElectricCircuits',
children: [],
};
const root = await importer.toJSON(this.rootNode, true);
this.language = language;
this.metaSheets.META = this.createMetaSheetTab(root, 'META');
root.registry.validPlugins = root.registry.validPlugins.replace(this.getName(), '');
root.registry.validDecorators = `${DECORATOR_ID} ${root.registry.validDecorators}`;
root.registry.validVisualizers = `${root.registry.validVisualizers} ${VISUALIZER_ID}`;
root.children = [
placeholder('FCO'),
language
];
const existingNodes = [
'Circuit',
'ComponentBase',
'PortBase',
'ConnectionBase',
'Wire',
'Pin',
'ElectricCircuitsFolder',
'Documentation',
'Junction',
'Voltage',
'Current',
'Basic',
'Ground'
].map(name => {
let node = placeholder(name);
node.registry = {};
if (['Pin',
'Circuit',
'ElectricCircuitsFolder',
'Voltage',
'Wire',
'Junction',
'Current',
'Ground',
].includes(name)) {
if(name !== 'Wire'){
node.registry.decorator = DECORATOR_ID;
}
node.registry.isAbstract = false;
}
if (!['Basic', 'Semiconductors', 'Ground'].includes(name)){
node.registry.position = this.positionGenerator();
}
if (['ConnectionBase', 'PortBase', 'ComponentBase'].includes(name)) {
node.registry.isAbstract = true;
}
if (name === 'Circuit') {
node.registry.position.y -= 50;
node.registry.validPlugins = `${TO_NETLIST_PLUGIN}`;
node.registry.validVisualizers = `${VISUALIZER_ID} ModelEditor`;
}
if (name === 'ElectricCircuitsFolder') {
node.registry.validPlugins = `${FROM_NETLIST_PLUGIN}`;
}
return node;
});
this.addNodeToMeta(root, language);
existingNodes.forEach(node => language.children.push(node));
return root;
}
async getModelicaLibraryState(importer) {
const modelicaRoot = this.core.getLibraryRoot(this.rootNode, 'Modelica');
if (!modelicaRoot) {
const err = 'Modelica is not installed as a library';
this.logger.error(err);
throw new Error(err);
}
const children = await this.core.loadChildren(modelicaRoot);
const electricalRoot = children.find(node => {
return this.core.getAttribute(node, 'name')
.startsWith(MODELICA_ELECTRICAL_COMPONENTS_PREFIX);
});
const pin = children.find(node => {
return this.core.getAttribute(node, 'name') === MODELICA_PIN_ATTR_NAME;
});
return {
electricalState: await importer.toJSON(electricalRoot, false),
pin: await importer.toJSON(pin, false)
};
}
createCategories(root) {
const categories = this.getElectricalComponentCategories();
categories.forEach(name => {
this.metaSheets[name] = this.createMetaSheetTab(root, name);
this.logger.debug(`Creating node category ${name}`);
const node = this.createMetaNode(root, name, '@meta:ComponentBase', name);
node.registry.isAbstract = true;
node.registry.decorator = DECORATOR_ID;
});
}
getElectricalComponentCategories() {
return ['Basic', 'Semiconductors'];
}
createMetaSheetTab(root, name) {
const sheets = root.registry[Constants.REGISTRY.META_SHEETS];
let sheet = sheets.find(sheet => sheet.title === name);
if (!sheet) {
const id = Constants.META_ASPECT_SHEET_NAME_PREFIX + generateGuid();
sheet = {
SetID: id,
order: sheets.length,
title: name
};
this.logger.debug(`Creating meta sheet "${name}"`);
sheets.push(sheet);
root.sets[id] = [];
root.member_registry[id] = {};
}
return sheet.SetID;
}
addNodeToMeta(root, node, tabName = DEFAULT_META_TAB) {
let tabId = this.metaSheets[tabName];
let position = this.getNextPositionFor(tabName);
if (!tabId) {
const err = `No meta sheet for ${tabName}`;
this.logger.error(err);
throw new Error(err);
}
const nodeId = node.id;
root.sets[Constants.META_ASPECT_SET_NAME].push(nodeId);
root.sets[tabId].push(nodeId);
const registry = {};
registry[Constants.REGISTRY.POSITION] = position;
root.member_registry[Constants.META_ASPECT_SET_NAME][nodeId] = registry;
root.member_registry[tabId][nodeId] = registry;
this.logger.debug(`added ${node.id} to the meta`);
}
async addWiresToCurrentSources() {
const currentSourcesNodes = (await this.core.loadSubTree(this.rootNode)).filter(node => {
return CURRENT_SOURCES.includes(this.core.getAttribute(node, 'name'));
});
for (let i = 0; i < currentSourcesNodes.length; i++) {
const wirePToP1 = this._addWire(currentSourcesNodes[i]);
const wireNToN1 = this._addWire(currentSourcesNodes[i]);
const pins = await this._loadChildrenOfType(
currentSourcesNodes[i],
'Pin'
);
const p1 = this._findNodeByName(pins, 'p1');
const n1 = this._findNodeByName(pins, 'n1');
const voltage = (await this._loadChildrenOfType(
currentSourcesNodes[i],
'Voltage'
)).pop();
const voltagePins = await this._loadChildrenOfType(
voltage,
'Pin'
);
const p = this._findNodeByName(voltagePins, 'p');
const n = this._findNodeByName(voltagePins, 'n');
this._setWirePointers(wirePToP1, [p, p1]);
this._setWirePointers(wireNToN1, [n, n1]);
}
}
getNextPositionFor(tabName) {
let index = this.sheetCounts[tabName] || 0,
position,
dx = 250,
dy = 160,
MAX_WIDTH = 1200,
x;
this.sheetCounts[tabName] = index + 1;
if (index === 0) {
position = {
x: MAX_WIDTH / 2,
y: 50
};
} else {
x = dx * index;
position = {
x: x % MAX_WIDTH,
y: Math.floor(x / MAX_WIDTH + 1) * dy + 150
};
}
return position;
}
createMetaNode(root, name, baseId, tabName) {
tabName = tabName || DEFAULT_META_TAB;
const node = {
id: `@meta:${name}`,
pointers: {base: baseId},
attributes: {name},
registry: {},
attribute_meta: {},
pointer_meta: {},
sets: {},
children: []
};
this.language.children.push(node);
this.addNodeToMeta(root, node, tabName);
node.registry.position = this.positionGenerator();
return node;
}
createModelicaNodesOfType(root, category) {
const nodes = this._getModelicaStateFor(category);
nodes.forEach(node => {
const base = `@meta:${category}`;
// For now just create pure components with only Pins
// This can be extended later
// if (!node.children.every(child => this._isModelicaPin(child)) && category !== 'Semiconductors') {
// return;
// }
const categoryMetaNode = this.createMetaNode(root, node.attributes.ShortName, base, category);
categoryMetaNode.registry.isAbstract = false;
node.attributes.name = node.attributes.name.replace(
MODELICA_ELECTRICAL_COMPONENTS_PREFIX + `.${category}.`,
''
);
node.children.forEach(child => {
if (this._isModelicaPin(child)) {
const pin = this._createPinNode(child.attributes.name);
categoryMetaNode.children.push(pin);
}
});
if (CURRENT_SOURCES.includes(categoryMetaNode.attributes.name)) {
categoryMetaNode.children.push({
name: '@name:Vo',
pointers: {
base: '@meta:Voltage'
}
});
}
delete node.attribute_meta.ModelicaURI;
delete node.attribute_meta.useHeatPort;
delete node.attributes.ModelicaURI;
delete node.attributes.ShortName;
delete node.attributes.useHeatPort;
categoryMetaNode.attributes = node.attributes;
categoryMetaNode.attribute_meta = node.attribute_meta;
this.addToDocumentation(categoryMetaNode);
});
}
createPySpiceNodesOfType(root, category) {
const components = this._getPySpiceStateFor(category);
components.forEach(component => {
const base = `@meta:${category}`;
const metaNode = this.createMetaNode(root, component.name, base, category);
this.logger.debug(`Created meta node of type ${component.name}`);
metaNode.registry.isAbstract = false;
component.attributes.forEach(attribute => {
metaNode.attributes[attribute.name] = attribute.default;
attribute.attribute_meta.type = this._inferAttributeType(attribute.default);
metaNode.attribute_meta[attribute.name] = attribute.attribute_meta;
});
const pinNames = ['p', 'n'];
for(let j = 0; j < (component.pins_count || 0); j++) {
metaNode.children.push(
this._createPinNode(pinNames[j])
);
}
this.addToDocumentation(metaNode);
});
}
addToDocumentation(metaNode) {
let metaDoc = [
`## ${metaNode.attributes.name}\n`,
'### Attributes:\n',
];
Object.entries(metaNode.attribute_meta).forEach(([name, attr]) => {
metaDoc.push('---');
metaDoc.push(`- Name: **${name}**`);
metaDoc.push(`- Description: ${attr.description || attr.parameter || 'N/A'}`);
metaDoc.push(`- Type: ${attr.type || 'N/A'}`);
metaDoc.push(`- Unit: ${attr.unit || attr.units || 'N/A'}`);
metaDoc.push(`- Default: ${metaNode.attributes[name] || 'N/A'}`);
metaDoc.push('\n');
});
metaDoc.push('\n');
this.documentation += metaDoc.join('\n');
}
createExtraNodes(root) {
const electricCircuits = root.children.find(child => {
return child.id === '@name:ElectricCircuits';
});
Object.entries(EXTRA_NODES).forEach(([k, v]) => {
const node = electricCircuits.children.find(child => {
return child.id === `@meta:${v}`;
});
if (node) {
const newNode = this.createMetaNode(
root, k, `@meta:${v}`, EXTRA_TAB_NAMES[k]
);
if(EXTRA_ATTRIBUTES[k]) {
EXTRA_ATTRIBUTES[k].attributes
.forEach(attr => {
Object.entries(attr).forEach(([name, defaultValue]) => {
newNode.attributes[name] = defaultValue;
});
});
EXTRA_ATTRIBUTES[k].attribute_meta
.forEach(attr => {
Object.entries(attr).forEach(([name, meta]) => {
newNode.attribute_meta[name] = meta;
});
});
}
}
});
}
createDocumentationNode() {
const docNode = this.core.createNode({
parent: this.rootNode,
base: this.META.Documentation
});
this.core.setAttribute(
docNode,
'documentation',
this.documentation
);
}
_isModelicaPin(state) {
return state.pointers.base === this.modelicaPinState.path;
}
_getModelicaStateFor(type) {
return this.modelicaState.children.filter(node => {
return (node.attributes.name.startsWith(MODELICA_ELECTRICAL_COMPONENTS_PREFIX + `.${type}`)
&& !SKIP_NODES.includes(node.attributes.ShortName));
});
}
_getPySpiceStateFor(type) {
const typeKey = PYSPICE_CATEGORIES[type];
return PySpiceElements[typeKey] || [];
}
_inferAttributeType(value) {
if (typeof value === 'number'){
return 'float';
} else if (typeof value === 'boolean') {
return 'boolean';
} else {
return 'string';
}
}
_createPinNode(name) {
return {
id: `@name:${name}`,
pointers: {base: '@meta:Pin'}
};
}
_addWire (node) {
return this.core.createNode({
parent: node,
base: this.META.Wire
});
}
_findNodeByName (arrayOfNodes, name) {
return arrayOfNodes
.find(node => this.core.getAttribute(node, 'name') === name);
}
_setWirePointers(wire, ends) {
const pointerNames = ['src', 'dst'];
ends.forEach((end, index) => {
this.core.setPointer(wire, pointerNames[index], end);
});
}
renamePinsOfTransistorMoSFET(state){
const transistors = ['NPN', 'PNP'];
const mosfets = ['NMOS', 'PMOS'];
const pinsMapTransistor = {
'C': 'Collector',
'B': 'Base',
'E': 'Emitter',
};
const pinsMapMosFET = {
'G': 'Gate',
'D': 'Drain',
'B': 'Bulk',
'S': 'Source',
};
const electricCircuits = state.children.find(child => child.id === '@name:ElectricCircuits');
const transistorNodes = electricCircuits.children.filter(node => transistors.includes(node.id.replace(/@.*:/, '')));
const mosNodes = electricCircuits.children.filter(node => mosfets.includes(node.id.replace(/@.*:/, '')));
this.renamePins(transistorNodes, pinsMapTransistor);
this.renamePins(mosNodes, pinsMapMosFET);
}
renamePins(nodes, pinsMap) {
nodes.forEach(node => {
node.children.forEach(pin => {
const pinName = pin.id.replace(/@.*:/, '');
if (pinsMap[pinName]) {
this.logger.info(`Renaming pin ${pin.id} to ${pinsMap[pinName]} for ${node.id}`);
pin.id = `@name:${pinsMap[pinName]}`;
}
});
});
}
async _loadChildrenOfType(node, type) {
return (await this.core.loadChildren(node))
.filter(child => this.core.getMetaType(child) === this.META[type]);
}
static getPositionGenerator (margin=170, maxWidth=800) {
let x = 50, y = 50;
return () => {
if (x + margin > maxWidth){
x = 50;
y += margin;
}
x += margin;
return {x, y};
};
}
}
return CreateElectricCircuitsMeta;
});
|
javascript
|
// Copyright 2021 TiKV 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,
// See the License for the specific language governing permissions and
// limitations under the License.
// NOTE: The code in this file is based on code from the
// TiDB project, licensed under the Apache License v 2.0
//
// https://github.com/pingcap/tidb/tree/cc5e161ac06827589c4966674597c137cc9e809c/store/tikv/tests/store_test.go
//
// Copyright 2016 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package tikv_test
import (
"context"
"sync"
"testing"
"time"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/stretchr/testify/suite"
"github.com/tikv/client-go/v2/oracle"
"github.com/tikv/client-go/v2/oracle/oracles"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/tikvrpc"
)
func TestStore(t *testing.T) {
suite.Run(t, new(testStoreSuite))
}
type testStoreSuite struct {
suite.Suite
store tikv.StoreProbe
}
func (s *testStoreSuite) SetupTest() {
s.store = tikv.StoreProbe{KVStore: NewTestStore(s.T())}
}
func (s *testStoreSuite) TearDownTest() {
s.Require().Nil(s.store.Close())
}
func (s *testStoreSuite) TestOracle() {
s.store.GetOracle().Close()
o := &oracles.MockOracle{}
s.store.SetOracle(o)
ctx := context.Background()
t1, err := s.store.GetTimestampWithRetry(tikv.NewBackofferWithVars(ctx, 100, nil), oracle.GlobalTxnScope)
s.Nil(err)
t2, err := s.store.GetTimestampWithRetry(tikv.NewBackofferWithVars(ctx, 100, nil), oracle.GlobalTxnScope)
s.Nil(err)
s.Less(t1, t2)
t1, err = o.GetLowResolutionTimestamp(ctx, &oracle.Option{})
s.Nil(err)
t2, err = o.GetLowResolutionTimestamp(ctx, &oracle.Option{})
s.Nil(err)
s.Less(t1, t2)
f := o.GetLowResolutionTimestampAsync(ctx, &oracle.Option{})
s.NotNil(f)
_ = o.UntilExpired(0, 0, &oracle.Option{})
// Check retry.
var wg sync.WaitGroup
wg.Add(2)
o.Disable()
go func() {
defer wg.Done()
time.Sleep(time.Millisecond * 100)
o.Enable()
}()
go func() {
defer wg.Done()
t3, err := s.store.GetTimestampWithRetry(tikv.NewBackofferWithVars(ctx, 5000, nil), oracle.GlobalTxnScope)
s.Nil(err)
s.Less(t2, t3)
expired := s.store.GetOracle().IsExpired(t2, 50, &oracle.Option{})
s.True(expired)
}()
wg.Wait()
}
type checkRequestClient struct {
tikv.Client
priority kvrpcpb.CommandPri
}
func (c *checkRequestClient) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) {
resp, err := c.Client.SendRequest(ctx, addr, req, timeout)
if c.priority != req.Priority {
if resp.Resp != nil {
if getResp, ok := resp.Resp.(*kvrpcpb.GetResponse); ok {
getResp.Error = &kvrpcpb.KeyError{
Abort: "request check error",
}
}
}
}
return resp, err
}
func (s *testStoreSuite) TestRequestPriority() {
client := &checkRequestClient{
Client: s.store.GetTiKVClient(),
}
s.store.SetTiKVClient(client)
// Cover 2PC commit.
txn, err := s.store.Begin()
s.Require().Nil(err)
client.priority = kvrpcpb.CommandPri_High
txn.SetPriority(tikv.PriorityHigh)
err = txn.Set([]byte("key"), []byte("value"))
s.Nil(err)
err = txn.Commit(context.Background())
s.Nil(err)
// Cover the basic Get request.
txn, err = s.store.Begin()
s.Require().Nil(err)
client.priority = kvrpcpb.CommandPri_Low
txn.SetPriority(tikv.PriorityLow)
_, err = txn.Get(context.TODO(), []byte("key"))
s.Nil(err)
// A counter example.
client.priority = kvrpcpb.CommandPri_Low
txn.SetPriority(tikv.PriorityNormal)
_, err = txn.Get(context.TODO(), []byte("key"))
// err is translated to "try again later" by backoffer, so doesn't check error value here.
s.NotNil(err)
// Cover Seek request.
client.priority = kvrpcpb.CommandPri_High
txn.SetPriority(tikv.PriorityHigh)
iter, err := txn.Iter([]byte("key"), nil)
s.Nil(err)
for iter.Valid() {
s.Nil(iter.Next())
}
iter.Close()
}
func (s *testStoreSuite) TestFailBusyServerKV() {
txn, err := s.store.Begin()
s.Require().Nil(err)
err = txn.Set([]byte("key"), []byte("value"))
s.Nil(err)
err = txn.Commit(context.Background())
s.Nil(err)
txn, err = s.store.Begin()
s.Require().Nil(err)
s.Nil(failpoint.Enable("tikvclient/tikvStoreSendReqResult", `1*return("busy")->return("")`))
val, err := txn.Get(context.TODO(), []byte("key"))
s.Nil(err)
s.Equal(val, []byte("value"))
}
|
go
|
export default {
namespaced: true,
state: {
player : {
url : '',
data : {
name : '',
score : 0,
},
},
},
getters: {
get_player : function( state ){
return state.player;
},
get_url : function( state ){
return state.player.url;
},
get_name : function( state ){
return state.player.data.name;
},
get_score : function( state ){
return state.player.data.score;
},
},
mutations: {
player : function( state, input ){
if( input.url !== undefined ){
state.player.url = input.url;
}
if( input.data !== undefined ){
if( input.data.name !== undefined ){
state.player.data.name = input.data.name;
basic.data.name = input.data.name;
}
if( input.data.score !== undefined ){
state.player.data.score = input.data.score;
}
}
},
},
actions: {
set_player : function( context, input ){
context.commit('player', input );
},
reset : function( context ){
context.commit('player', basic );
},
exit : function( context ){
context.commit('player', basic );
},
}
};
let basic = {
url : '',
data : {
name : '',
score : 0,
},
};
|
javascript
|
Punjab National Bank (PNB), signed a Memorandum of Understanding (MOU) with Unique Identification Authority of India (UIDAI) today in New Delhi to act as Registrar for ‘AADHAAR’ project. The MOU was signed by Shri AP Singh, DDG, UIDAI and Shri MV Tanksale, Executive Director, PNB in the presence of Chairman of the UIDAI, Shri Nandan Nilekani and Chairman & managing Director of PNB, Shri KR Kamath. PNB thus becomes sixth Bank to have entered into such MoU by which its shall provide AADHAAR (UID No.) to its existing 58 million customers as well as future customers by collecting Biometric and Demographic details as per UID norms.
Shri Kamath pointed out, “PNB already has an impressive network of banking outlets with over 5000 branches and 3175 ATMs and has a strong presence of more than 3000 rural and semi urban branches. The bank has a business of Rs. 4520 billion at end June 2010 with a deposit base of Rs 2550 billion and a credit portfolio of Rs 1970 billion”.
He also said, “PNB has already opened 57 lac No Frill accounts under financial inclusion which are being serviced by its nearly 3000 Rural/Semi urban branches. It has plans to open another 130 rural branches in the current financial year. The bank is implementing 39 ICT based projects in 15 States. PNB has plans to cover 5000 villages in next 2 years and provide services to 10 million customers through ICT model”.
The UID is developing the architecture of technical standards and ecosystem that will facilitate collection of demographic and biometric attributes by various agencies it has empanelled to support AADHAAR, based on which the UID Number will be allotted to each citizen. These UID numbers then shall be dovetailed into PNB’s present and future customer base so as to provide the facility of ANYTIME, ANYWHERE, ANYHOW banking services. The bank will use this platform not only to cover rural populace which has hitherto been deprived of financial services but also to distribute benefits under the Social Security Scheme and provide credit facilities as per PNB’s motto “BANKING FOR UNBANKED”.
|
english
|
Seeing a dozen different types of cheese congeal between the rhinestones on Paris Hilton’s serving spoon, I felt closer to the heiress-turned-influencer than ever before. Not only did I learn we both have an affinity for overly decadent macaroni and cheese, but using an obviously decorative utensil in a way sure to ruin it is the kind of kitchen shenanigan I relate to deeply.
And watching Paris shrug off the incident like it hadn’t happened at all? That’s just pure fantasy.
In Netflix’s Cooking with Paris, an unconventional cooking show that sees Hilton invite guests over for meals she only sort of knows how to make, self-confidence is key. Where the Food Network might dazzle us with a dish’s ease, speed, or creativity, Cooking with Paris boasts things made by Paris Hilton — period. The show’s purpose, Hilton repeatedly explains in the series’ intro, isn’t for Paris to become a professional chef. She just wants to “mix it up” so she’s “expanding her repertoire” with these new recipes, created by her and her friends.
Theoretically, you could join Hilton as she cooks alongside Kim Kardashian West, Demi Lovato, Nikki Glaser, Saweetie, Lele Pons, and sister Nicky and mom Kathy Hilton. But it’s immediately apparent the point of this show isn’t so much to learn from Hilton, as it is to hang out with her. Even as helpful cooking tips like “These are tongs!” fly across the screen, it’s Hilton’s kaleidoscopic personality that keeps the show feeling like a high-budget version of her YouTube showher YouTube show genuinely worth binging.
Between the edible glitter and aimless internet searching — “What is zest lemon?” Hilton earnestly asks Google in episode 2 — the pop culture icon lets her unique personality pull you into the fun of this Barbie Dreamhouse-meets-Nailed It! hybrid. In each of Cooking with Paris’ six episodes, Hilton invites over a guest who helps her cook (or try to cook) a meal that is later served against an extravagant, themed backdrop, with Hilton sporting an outfit made to match.
These culinary experiments have mixed results. But what actually happens in the series’ all-too-brief first season is fairly predictable. The Frosted Flake-encrusted french toast works great, because how could it not? Hilton breaks an industrial-grade blender, because how could she not? These hijinks are enjoyable if you’re someone fully onboard with Hilton’s brand of celebrity, but if you’re someone looking to be newly won over by the former The Simple Life star you won’t have much luck. From the jump, Cooking with Paris assumes you want to be “cooking with Paris” — and considering the star’s tumultuous Hollywood history that may not be true for all viewers.
If you are someone who wants to like Cooking with Paris, you will need to understand Hilton’s evolving personal history and complicated relationship to the modern fame economy. Her self-produced documentary This Is Paris, which was released last year free on YouTubefree on YouTube, offers a first-hand account of Hilton’s experiences with childhood abuse and toxic celebrity that provide essential context for understanding her as a pop culture figure. With that knowledge, watching Hilton crack jokes with Whitney Cummings or talk motherhood with Kardashian feels less like a flagrant display of privilege than a pleasant next chapter for a complicated person.
Though Hilton's theatrical personality can feel grating on occasion and her bedazzled collection of pandemic-era face masks a bit on the nose, Cooking with Paris is a cutesy cooking show Hilton fans will appreciate. Above all, it lets Paris be Paris — paving the way for messy cooks with completely impractical fantasies of jeweled cookware everywhere.
Cooking with Paris Cooking with Paris is now streaming on Netflix.
|
english
|
<reponame>krzkaczor/node-csharp<gh_stars>0
{
"name": "node-csharp",
"version": "0.2.4",
"description": "A simple wrapper around mono utilities that allows you to compile and run your C# app from source.",
"main": "lib/nodeCSharp.js",
"scripts": {
"compile": "babel -d lib/ src/",
"compile-test": "babel -d tests-es5/ tests/",
"test": "node tests-es5/tests.js",
"pretest": "npm run compile && npm run compile-test",
"prepublish": "npm run compile"
},
"repository": {
"type": "git",
"url": "git+https://github.com/krzkaczor/node-csharp.git"
},
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/krzkaczor/node-csharp/issues"
},
"homepage": "https://github.com/krzkaczor/node-csharp#readme",
"dependencies": {
"tmp": "0.0.28"
},
"devDependencies": {
"babel-cli": "6.3.17",
"babel-preset-es2015": "6.3.13",
"string-to-stream": "1.0.1",
"tape": "4.2.2"
}
}
|
json
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
/*--------------------------------------------------------------------
*
* To Do:
* - Write test_value()
* - Write test_literal()
* - Write test_match()
* - Write test_operator()
* - Extend test_collection() to test much more of the interface
* - Extend test_classad() to test much more of the interface
* - Test xml: roll in test_xml.C
* - Get stuff from extra_tests.C
*
*-------------------------------------------------------------------*/
#include "classad/classad_distribution.h"
#include "classad/lexerSource.h"
#include "classad/xmlSink.h"
#include <fstream>
#include <iostream>
#include <ctype.h>
#include <assert.h>
using namespace std;
#ifdef WANT_CLASSAD_NAMESPACE
using namespace classad;
#endif
#define TEST(name, test) {if (test) \
results.AddSuccessfulTest(name, __LINE__); \
else results.AddFailedTest(name, __LINE__);}
class Parameters
{
public:
bool debug;
bool verbose;
bool very_verbose;
bool check_all;
bool check_parsing;
bool check_classad;
bool check_exprlist;
bool check_value;
bool check_literal;
bool check_match;
bool check_operator;
bool check_collection;
bool check_utils;
void ParseCommandLine(int argc, char **argv);
};
class Results
{
public:
Results(const Parameters ¶meters);
void AddSuccessfulTest(const char *name, int line_number);
void AddFailedTest(const char *name, int line_number);
void GetResults(int &number_of_errors, int &number_of_tests);
private:
int _number_of_errors;
int _number_of_tests;
bool _verbose;
bool _very_verbose;
};
/*--------------------------------------------------------------------
*
* Private Functions
*
*--------------------------------------------------------------------*/
static void test_parsing(const Parameters ¶meters, Results &results);
static void test_classad(const Parameters ¶meters, Results &results);
static void test_exprlist(const Parameters ¶meters, Results &results);
static void test_value(const Parameters ¶meters, Results &results);
static void test_collection(const Parameters ¶meters, Results &results);
static void test_utils(const Parameters ¶meters, Results &results);
static bool check_in_view(ClassAdCollection *collection, string view_name, string classad_name);
static void print_version(void);
/*********************************************************************
*
* Function: Parameters::ParseCommandLine
* Purpose: This parses the command line. Note that it will exit
* if there are any problems.
*
*********************************************************************/
void Parameters::ParseCommandLine(
int argc,
char **argv)
{
bool selected_test = false;
bool help = false;
// First we set up the defaults.
help = false;
debug = false;
verbose = false;
very_verbose = false;
check_all = false;
check_parsing = false;
check_classad = false;
check_exprlist = false;
check_value = false;
check_literal = false;
check_match = false;
check_operator = false;
check_collection = false;
check_utils = false;
// Then we parse to see what the user wants.
for (int arg_index = 1; arg_index < argc; arg_index++) {
if ( !strcasecmp(argv[arg_index], "-h")
|| !strcasecmp(argv[arg_index], "-help")) {
help = true;
break;
} else if ( !strcasecmp(argv[arg_index], "-d")
|| !strcasecmp(argv[arg_index], "-debug")) {
debug = true;
} else if ( !strcasecmp(argv[arg_index], "-v")
|| !strcasecmp(argv[arg_index], "-verbose")) {
verbose = true;
} else if ( !strcasecmp(argv[arg_index], "-vv")
|| !strcasecmp(argv[arg_index], "-veryverbose")) {
verbose = true;
very_verbose = true;
} else if (!strcasecmp(argv[arg_index], "-all")){
check_all = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-parsing")){
check_parsing = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-classad")){
check_classad = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-epxrlist")){
check_exprlist = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-value")){
check_value = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-literal")){
check_literal = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-match")){
check_match = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-operator")){
check_operator = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-collection")){
check_collection = true;
selected_test = true;
} else if (!strcasecmp(argv[arg_index], "-utils")){
check_utils = true;
selected_test = true;
} else {
cout << "Unknown argument: " << argv[arg_index] << endl;
help = true;
}
}
if (help) {
cout << "Usage: classad_unit_tester [options]\n";
cout << "\n";
cout << "Basic options:\n";
cout << " -h | -help: print help\n";
cout << " -d | -debug: debug\n";
cout << " -v | -verbose: verbose output\n";
cout << " -vv | -veryverbose: very verbose output\n";
cout << "\n";
cout << "Test selectors:\n";
cout << " -all: all tests listed below (the default)\n";
cout << " -parsing: test non-ClassAd parsing.\n";
cout << " -classad: test the ClassAd class.\n";
cout << " -exprlist: test the ExprList class.\n";
cout << " -value: test the Value class.\n";
cout << " -literal: test the Literal class.\n";
cout << " -match: test the MatchClassAd class.\n";
cout << " -operator: test the Operator class.\n";
cout << " -collection: test the Collection class.\n";
cout << " -utils: test little utilities.\n";
exit(1);
}
if (!selected_test) {
check_all = true;
}
return;
}
/*********************************************************************
*
* Function:
* Purpose:
*
*********************************************************************/
Results::Results(const Parameters ¶meters)
{
_number_of_errors = 0;
_number_of_tests = 0;
_verbose = parameters.verbose;
_very_verbose = parameters.very_verbose;
return;
}
void Results::AddSuccessfulTest(const char *name, int line_number)
{
_number_of_tests++;
if (_very_verbose) {
cout << "SUCCESS: " << name << " on line " << line_number << endl;
}
return;
}
void Results::AddFailedTest(const char *name, int line_number)
{
_number_of_errors++;
_number_of_tests++;
cout << "FAILURE " << name << " on line " << line_number << endl;
return;
}
void Results::GetResults(int &number_of_errors, int &number_of_tests)
{
number_of_errors = _number_of_errors;
number_of_tests = _number_of_tests;
return;
}
/*********************************************************************
*
* Function: main
* Purpose: The main control loop.
*
*********************************************************************/
int main(
int argc,
char **argv)
{
int number_of_errors;
int number_of_tests;
bool have_errors;
string line;
Parameters parameters;
/* ----- Setup ----- */
print_version();
parameters.ParseCommandLine(argc, argv);
Results results(parameters);
/* ----- Run tests ----- */
if (parameters.check_all || parameters.check_parsing) {
test_parsing(parameters, results);
}
if (parameters.check_all || parameters.check_classad) {
test_classad(parameters, results);
}
if (parameters.check_all || parameters.check_exprlist) {
test_exprlist(parameters, results);
}
if (parameters.check_all || parameters.check_value) {
test_value(parameters, results);
}
if (parameters.check_all || parameters.check_literal) {
}
if (parameters.check_all || parameters.check_match) {
}
if (parameters.check_all || parameters.check_operator) {
}
if (parameters.check_all || parameters.check_collection) {
test_collection(parameters, results);
}
if (parameters.check_all || parameters.check_utils) {
test_utils(parameters, results);
}
/* ----- Report ----- */
cout << endl;
results.GetResults(number_of_errors, number_of_tests);
if (number_of_errors > 0) {
have_errors = true;
cout << "Finished with errors: \n";
cout << " " << number_of_errors << " errors\n";
cout << " " << number_of_tests << " tests\n";
} else {
have_errors = false;
cout << "Finished with no errors.\n";
cout << " " << number_of_tests << " tests\n";
}
return have_errors;
}
/*********************************************************************
*
* Function: test_parsing
* Purpose: Test parsing that isn't ClassAd-specific. (ClassAd-specific
* is in test_clasad
*
*********************************************************************/
static void test_parsing(const Parameters &, Results &results)
{
ClassAdParser parser;
ExprTree *tree;
// My goal is to ensure that these expressions don't crash
// They should also return a NULL tree
tree = parser.ParseExpression("true || false || ;");
TEST("Bad or doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("true && false && ;");
TEST("Bad and doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("3 | 4 | ;");
TEST("Bad and doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("3 ^ 4 ^ ;");
TEST("Bad exclusive or doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("3 & 4 & ;");
TEST("Bad bitwise and doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("3 == 4 == ;");
TEST("Bad equality doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("1 < 3 < ;");
TEST("Bad relational doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("1 << 3 << ;");
TEST("Bad shift doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("1 + 3 + ;");
TEST("Bad additive doesn't crash & isn't bogus", tree == NULL);
tree = parser.ParseExpression("1 * 3 * ;");
TEST("Bad multiplicative doesn't crash & isn't bogus", tree == NULL);
return;
}
/*********************************************************************
*
* Function: test_classad
* Purpose: Test the ClassAd class.
*
*********************************************************************/
static void test_classad(const Parameters &, Results &results)
{
ClassAdParser parser;
bool have_attribute;
bool success;
cout << "Testing the ClassAd class...\n";
string input_basic = "[ A = 3; B = 4.0; C = \"babyzilla\"; D = true; E = {1}; F = [ AA = 3; ]; G =\"deleteme\";]";
ClassAd *basic;
int i;
bool b;
double r;
string s;
ClassAd *c;
ExprList *l;
basic = parser.ParseClassAd(input_basic);
/* ----- Test EvaluateAttr* ----- */
have_attribute = basic->EvaluateAttrInt("A", i);
TEST("Have attribute A", (have_attribute == true));
TEST("A is 3", (i == 3));
have_attribute = basic->EvaluateAttrReal("B", r);
TEST("Have attribute B", (have_attribute == true));
TEST("B is 4.0", (r == 4.0));
have_attribute = basic->EvaluateAttrString("C", s);
TEST("Have attribute C", (have_attribute == true));
TEST("C is 'babyzilla'", (s.compare("babyzilla") == 0));
have_attribute = basic->EvaluateAttrBool("D", b);
TEST("Have attribute D", (have_attribute == true));
TEST("D is true", (b == true));
have_attribute = basic->EvaluateAttrList("E", l);
TEST("Have attribute E", (have_attribute == true));
TEST("E is list of size ", (l->size() == 1));
have_attribute = basic->EvaluateAttrClassAd("F", c);
TEST("Have attribute F", (have_attribute == true));
have_attribute = c->EvaluateAttrInt("AA", i);
TEST("F looks correct", (i == 3));
/* ----- Test basic insert and delete ----- */
success = basic->InsertAttr("new", 4);
TEST("InsertAttr claims to have worked", (success == true));
have_attribute = basic->EvaluateAttrInt("new", i);
TEST("Have new attribute", (have_attribute == true));
TEST("new attribute is 4", i == 4);
success = basic->Delete("new");
TEST("Delete claims to have worked", (success == true));
have_attribute = basic->EvaluateAttrInt("new", i);
TEST("New attribute was deleted", (have_attribute == false));
success = basic->Delete("G");
TEST("DELETE claims to have worked", (success == true));
have_attribute = basic->EvaluateAttrString("G", s);
TEST("Attribute G was deleted", (have_attribute == false));
delete basic;
basic = NULL;
/* ----- Test GetExternalReferences ----- */
string input_ref = "[ Rank=Member(\"LCG-2_1_0\",other.Environment) ? other.Time/seconds : other.Time/minutes; minutes=60; ]";
References refs;
References::iterator iter;
ExprTree *rank;
c = parser.ParseClassAd(input_ref);
TEST("Made classad_ref", (c != NULL));
if (c != NULL) {
rank = c->Lookup("Rank");
TEST("Rank exists", (rank != NULL));
if (rank != NULL) {
bool have_references;
if (have_references = c->GetExternalReferences(rank, refs, true)) {
TEST("have_references", (have_references == true));
if (have_references) {
bool have_environment;
bool have_time;
bool have_seconds;
bool have_other;
have_environment = false;
have_time = false;
have_seconds = false;
have_other = false;
for (iter = refs.begin(); iter != refs.end(); iter++) {
printf("%s\n",(*iter).c_str());
if ((*iter).compare("other.Environment") == 0) {
have_environment = true;
} else if ((*iter).compare("other.Time") == 0) {
have_time = true;
} else if ((*iter).compare("seconds") == 0) {
have_seconds = true;
} else {
have_other = true;
}
}
TEST("Have external reference to Environment", (have_environment == true));
TEST("Have external reference to Time", (have_time == true));
TEST("Have external reference to seconds", (have_seconds == true));
TEST("Have no other external references", (have_other != true));
}
}
}
delete c;
c = NULL;
}
// This ClassAd may cause problems. Perhaps a memory leak.
// This test is only useful when run under valgrind.
string memory_problem_classad =
"[ Updates = [status = \"request_completed\"; timestamp = absTime(\"2004-12-16T18:10:59-0600]\")] ]";
c = parser.ParseClassAd(memory_problem_classad);
delete c;
c = NULL;
/* ----- Test Parsing multiple ClassAds ----- */
char *two_classads = "[ a = 3; ][ b = 4; ]";
ClassAd classad1;
ClassAd classad2;
int offset = 0;
parser.ParseClassAd(two_classads, classad1, offset);
TEST("Have good offset #1", offset == 10);
parser.ParseClassAd(two_classads, classad2, offset);
TEST("Have good offset #2", offset == 20);
/* ----- Test chained ClassAds ----- */
//classad1 and classad2 from above test are used.
ClassAd classad3;
classad1.ChainToAd(&classad2);
TEST("classad1's parent is classad2", classad1.GetChainedParentAd() == &classad2);
have_attribute = classad1.EvaluateAttrInt("b", i);
TEST("chain has attribute b from parent", (have_attribute == true));
TEST("chain attribute b from parent is 4", (i == 4));
have_attribute = classad1.EvaluateAttrInt("a", i);
TEST("chain has attribute a from self", (have_attribute == true));
TEST("chain attribute a is 3", (i == 3));
// Now we modify classad2 (parent) to contain "a".
success = classad2.InsertAttr("a",7);
TEST("insert a into parent",(success == true));
have_attribute = classad1.EvaluateAttrInt("a", i);
TEST("chain has attribute a from self (overriding parent)", (have_attribute == true));
TEST("chain attribute a is 3 (overriding parent)", (i == 3));
have_attribute = classad2.EvaluateAttrInt("a", i);
TEST("chain parent has attribute a", (have_attribute == true));
TEST("chain parent attribute a is 7", (i == 7));
success = classad3.CopyFromChain(classad1);
TEST("copy from chain succeeded", (success == true));
have_attribute = classad3.EvaluateAttrInt("b",i);
TEST("copy of chain has attribute b",(have_attribute == true));
TEST("copy of chain has attribute b==4",(i==4));
success = classad3.InsertAttr("c", 6);
TEST("insert into copy of chain succeeded",(success==true));
classad3.CopyFromChain(classad1);
have_attribute = classad3.EvaluateAttrInt("c",i);
TEST("copy of chain is clean",(have_attribute==false));
classad3.InsertAttr("c", 6);
success = classad3.UpdateFromChain(classad1);
TEST("update from chain succeeded",(success == true));
have_attribute = classad3.EvaluateAttrInt("c",i);
TEST("update from chain is merged",(have_attribute==true));
TEST("update from chain has attribute c==6",(i==6));
return;
}
/*********************************************************************
*
* Function: test_exprlist
* Purpose: Test the ExprList class.
*
*********************************************************************/
static void test_exprlist(const Parameters &, Results &results)
{
cout << "Testing the ExprList class...\n";
Literal *literal1_0;
Literal *literal2_0;
Literal *literal2_1;
vector<ExprTree*> vector1;
vector<ExprTree*> vector2;
ExprList *list0;
ExprList *list0_copy;
ExprList *list1;
ExprList *list1_copy;
ExprList *list2;
ExprList *list2_copy;
ExprList::iterator iter;
/* ----- Setup Literals, the vectors, then ExprLists ----- */
literal1_0 = Literal::MakeReal("1.0");
literal2_0 = Literal::MakeReal("2.0");
literal2_1 = Literal::MakeReal("2.1");
vector1.push_back(literal1_0);
vector2.push_back(literal2_0);
vector2.push_back(literal2_1);
list0 = new ExprList();
list1 = new ExprList(vector1);
list2 = new ExprList(vector2);
/* ----- Did the lists get made? ----- */
TEST("Made list 0", (list0 != NULL));
TEST("Made list 1", (list1 != NULL));
TEST("Made list 2", (list2 != NULL));
/* ----- Are these lists identical to themselves? ----- */
TEST("ExprList identical 0", list0->SameAs(list0));
TEST("ExprList identical 1", list1->SameAs(list1));
TEST("ExprList identical 2", list2->SameAs(list2));
/* ----- Are they different from each other? ----- */
TEST("ExprLists different 0-1", !(list0->SameAs(list1)));
TEST("ExprLists different 1-2", !(list1->SameAs(list2)));
TEST("ExprLists different 0-2", !(list0->SameAs(list2)));
/* ----- Check the size of the ExprLists to make sure they are ok ----- */
TEST("ExprList size 0", (list0->size() == 0));
TEST("ExprList size 1", (list1->size() == 1));
TEST("ExprList size 2", (list2->size() == 2));
/* ----- Make sure the iterators work ----- */
iter = list0->begin();
TEST("Reached end of list 0", iter == list0->end());
iter = list1->begin();
TEST("Item 1.0 is as expected", (*iter)->SameAs(literal1_0));
iter++;
TEST("Reached end of list 1", iter == list1->end());
iter = list2->begin();
TEST("Item 2.0 is as expected", (*iter)->SameAs(literal2_0));
iter++;
TEST("Item 2.1 is as expected", (*iter)->SameAs(literal2_1));
iter++;
TEST("Reached end of list 2", iter == list2->end());
/* ----- Make copies of the ExprLists ----- */
list0_copy = (ExprList *) list0->Copy();
list1_copy = (ExprList *) list1->Copy();
list2_copy = (ExprList *) list2->Copy();
/* ----- Did the copies get made? ----- */
TEST("Made copy of list 0", (list0_copy != NULL));
TEST("Made copy of list 1", (list1_copy != NULL));
TEST("Made copy of list 2", (list2_copy != NULL));
/* ----- Are they identical to the originals? ----- */
TEST("ExprList self-identity 0", (list0->SameAs(list0_copy)));
TEST("ExprList self-identity 1", (list1->SameAs(list1_copy)));
TEST("ExprList self-identity 2", (list2->SameAs(list2_copy)));
/* ----- Test adding and deleting from a list ----- */
Literal *add;
add = Literal::MakeReal("2.2");
iter = list2_copy->begin();
list2_copy->insert(iter, add);
TEST("Edited list is different", !(list2->SameAs(list2_copy)));
iter = list2_copy->begin();
list2_copy->erase(iter);
TEST("Twice Edited list is same", (list2->SameAs(list2_copy)));
delete list0;
delete list1;
delete list2;
delete list0_copy;
delete list1_copy;
delete list2_copy;
// Note that we do not delete the Literals that we created, because
// they should have been deleted when the list was deleted.
/* ----- Test an ExprList bug that <NAME> found ----- */
ClassAd *classad;
ClassAdParser parser;
bool b;
bool have_attribute;
bool can_evaluate;
Value value;
string list_classad_text = "[foo = 3; have_foo = member(foo, {1, 2, 3});]";
classad = parser.ParseClassAd(list_classad_text);
have_attribute = classad->EvaluateAttrBool("have_foo", b);
TEST("Can evaluate list in member function", (have_attribute == true && b == true));
can_evaluate = classad->EvaluateExpr("member(foo, {1, 2, blah, 3})", value);
TEST("Can evaluate list in member() outside of ClassAd", can_evaluate == true);
return;
}
/*********************************************************************
*
* Function: test_value
* Purpose: Test the Value class.
*
*********************************************************************/
static void test_value(const Parameters &, Results &results)
{
Value v;
bool is_expected_type;
cout << "Testing the Value class...\n";
TEST("New value is undefined", (v.IsUndefinedValue()));
TEST("New value isn't boolean", !(v.IsBooleanValue()));
TEST("GetType gives UNDEFINED_VALUE", (v.GetType() == Value::UNDEFINED_VALUE));
v.SetErrorValue();
TEST("Is error value", (v.IsErrorValue()));
TEST("GetType gives ERROR_VALUE", (v.GetType() == Value::ERROR_VALUE));
bool b;
v.SetBooleanValue(true);
b = false;
is_expected_type = v.IsBooleanValue(b);
TEST("Value is not undefined", !(v.IsUndefinedValue()));
TEST("Value is boolean", (v.IsBooleanValue()));
TEST("Try 2: New value is boolean", (is_expected_type == true))
TEST("Boolean is true", (b == true));
TEST("GetType gives BOOLEAN_VALUE", (v.GetType() == Value::BOOLEAN_VALUE));
double r = 0.0;
v.SetRealValue(1.0);
is_expected_type = v.IsRealValue(r);
TEST("Value is real", is_expected_type);
TEST("Real is 1.0", (r == 1.0));
TEST("GetType gives REAL_VALUE", (v.GetType() == Value::REAL_VALUE));
TEST("Real is a number", v.IsNumber());
int i = 0;
v.SetIntegerValue(1);
is_expected_type = v.IsIntegerValue(i);
TEST("Value is integer", is_expected_type);
TEST("Integer is 1", (i == 1));
TEST("GetType gives INTEGER_VALUE", (v.GetType() == Value::INTEGER_VALUE));
TEST("Integer is a number", v.IsNumber());
const char *s = NULL;
v.SetStringValue("Robert-Houdin");
is_expected_type = v.IsStringValue(s);
TEST("Value is string", is_expected_type);
TEST("String is 'Robert-Houdin'", (0 == strcmp(s, "Robert-Houdin")));
TEST("GetType gives STRING_VALUE", (v.GetType() == Value::STRING_VALUE));
abstime_t at = { 10, 10 };
v.SetAbsoluteTimeValue(at);
at.secs = at.offset = 0;
is_expected_type = v.IsAbsoluteTimeValue(at);
TEST("Value is absolute time", is_expected_type);
TEST("Absolute time is 10, 0", (10 == at.secs && 10 == at.offset));
TEST("GetType gives ABSOLUTE_TIME_VALUE", (v.GetType() == Value::ABSOLUTE_TIME_VALUE));
time_t rt = 0;
v.SetRelativeTimeValue((time_t) 10);
is_expected_type = v.IsRelativeTimeValue(rt);
TEST("Value is relative time", is_expected_type);
TEST("Relative time is 10", (10 == rt));
TEST("GetType gives RELATIVE_TIME_VALUE", (v.GetType() == Value::RELATIVE_TIME_VALUE));
ExprList *l = new ExprList();
ExprList *ll = NULL;
v.SetListValue(l);
is_expected_type = v.IsListValue(ll);
TEST("Value is list value", is_expected_type);
TEST("List value is correct", l == ll);
TEST("GetType gives LIST_VALUE", (v.GetType() == Value::LIST_VALUE));
delete l;
ClassAd *c = new ClassAd();
ClassAd *cc = NULL;
v.SetClassAdValue(c);
is_expected_type = v.IsClassAdValue(cc);
TEST("Value is ClassAd value", is_expected_type);
TEST("ClassAd value is correct", c == cc);
TEST("GetType gives LIST_VALUE", (v.GetType() == Value::CLASSAD_VALUE));
delete c;
return;
}
/*********************************************************************
*
* Function: test_collection
* Purpose: Test the ClassAdCollection class. Note that we test the
* local Collections only: we don't test the server/client
* versions available in ClassAdCollectionServer and
* ClassAdCollectionClient.
*
*********************************************************************/
static void test_collection(const Parameters &, Results &results)
{
bool success;
static const char *collection_log_file_name = "collection.log";
ClassAd *machine1, *machine2, *machine3;
ClassAd *retrieved;
ClassAdParser parser;
ClassAdCollection *collection;
cout << "Testing the ClassAdCollection class...\n";
/* ----- Create the ClassAds that we'll put into the collection ----- */
machine1 = parser.ParseClassAd("[ Type = \"machine\"; OS = \"Linux\"; Memory = 5000;]", true);
machine2 = parser.ParseClassAd("[ Type = \"machine\"; OS = \"Linux\"; Memory = 3000;]", true);
machine3 = parser.ParseClassAd("[ Type = \"machine\"; OS = \"Windows\"; Memory = 6000;]", true);
TEST("Made ClassAds for Collection", ((machine1 != NULL) && (machine2 != NULL) && (machine3 != NULL)));
/* ----- Create the collection ----- */
collection = new ClassAdCollection();
TEST("Made Collection", collection != NULL);
if (collection == NULL) {
return;
}
// We delete the log file so we start with a fresh slate.
// Later on we will make a different collection from the log file
// that we create, so we can test that it does what we want.
#if defined ( WIN32 )
_unlink(collection_log_file_name);
#else
unlink(collection_log_file_name);
#endif
success = collection->InitializeFromLog(collection_log_file_name);
TEST("Initialized from empty log", success == true);
/* ----- Add the machines to the collection ----- */
success = collection->AddClassAd("machine1", machine1);
TEST("Added machine1 to collection", success == true);
success = collection->AddClassAd("machine2", machine2);
TEST("Added machine2 to collection", success == true);
success = collection->AddClassAd("machine3", machine3);
TEST("Added machine3 to collection", success == true);
/* ----- Put in one machine twice, to make sure it doesn't break ----- */
success = collection->AddClassAd("machine3", machine3);
TEST("Added machine3 to collection", success == true);
/* ----- Make sure that they are in the collection ----- */
retrieved = collection->GetClassAd("machine1");
TEST("machine1 in the collection", retrieved == machine1);
retrieved = collection->GetClassAd("machine2");
TEST("machine2 in the collection", retrieved == machine2);
retrieved = collection->GetClassAd("machine3");
TEST("machine3 in the collection", retrieved == machine3);
/* ----- Make a couple of subviews ----- */
success = collection->CreateSubView("Linux-View", "root",
"(other.OS == \"Linux\")", "", "");
TEST("Create Machine-View", success == true);
success = collection->CreateSubView("BigLinux-View", "Linux-View",
"(other.Memory >= 5000)", "", "");
TEST("Create BigMachine-View", success == true);
/* ----- Now test that the right things are in each view ----- */
TEST("machine1 in Linux-View", (check_in_view(collection, "Linux-View", "machine1") == true));
TEST("machine2 in Linux-View", (check_in_view(collection, "Linux-View", "machine2") == true));
TEST("machine3 not in Linux-View", (check_in_view(collection, "Linux-View", "machine3") == false));
TEST("machine1 not in BigLinux-View", (check_in_view(collection, "BigLinux-View", "machine1") == true));
TEST("machine2 in BigLinux-View", (check_in_view(collection, "BigLinux-View", "machine2") == false));
TEST("machine3 not in BigLinux-View", (check_in_view(collection, "BigLinux-View", "machine3") == false));
bool have_machine1, have_machine2, have_machine3, have_others;
View::const_iterator view_iterator;
/* ----- Now test the iterator for the root view ----- */
const View *root_view = collection->GetView("root");
have_machine1 = have_machine2 = have_machine3 = have_others = false;
for (view_iterator = root_view->begin();
view_iterator != root_view->end();
view_iterator++) {
string key;
view_iterator->GetKey(key);
if (key == "machine1") {
have_machine1 = true;
} else if (key == "machine2") {
have_machine2 = true;
} else if (key == "machine3") {
have_machine3 = true;
} else {
have_others = true;
}
}
TEST("machine1 found with iterator", have_machine1 == true);
TEST("machine2 found with iterator", have_machine2 == true);
TEST("machine3 found with iterator", have_machine3 == true);
TEST("No others found with iterator", have_others == false);
/* ----- Now test the iterator for a subview ----- */
const View *linux_view = collection->GetView("Linux-View");
have_machine1 = have_machine2 = have_machine3 = have_others = false;
for (view_iterator = linux_view->begin();
view_iterator != linux_view->end();
view_iterator++) {
string key;
view_iterator->GetKey(key);
if (key == "machine1") {
have_machine1 = true;
} else if (key == "machine2") {
have_machine2 = true;
} else {
have_others = true;
}
}
TEST("machine1 found with iterator", have_machine1 == true);
TEST("machine2 found with iterator", have_machine2 == true);
TEST("No others found with iterator", have_others == false);
/* ----- Reread from the collection log and see if everything is still good ----- */
delete collection;
collection = new ClassAdCollection();
TEST("Made Collection again", collection != NULL);
if (collection == NULL) {
return;
}
success = collection->InitializeFromLog(collection_log_file_name);
TEST("Initialized from full log", success == true);
TEST("machine1 in root", (check_in_view(collection, "root", "machine1") == true));
TEST("machine2 in root", (check_in_view(collection, "root", "machine2") == true));
TEST("machine3 not in root", (check_in_view(collection, "root", "machine3") == true));
TEST("machine1 in Linux-View", (check_in_view(collection, "Linux-View", "machine1") == true));
TEST("machine2 in Linux-View", (check_in_view(collection, "Linux-View", "machine2") == true));
TEST("machine3 not in Linux-View", (check_in_view(collection, "Linux-View", "machine3") == false));
TEST("machine1 not in BigLinux-View", (check_in_view(collection, "BigLinux-View", "machine1") == true));
TEST("machine2 in BigLinux-View", (check_in_view(collection, "BigLinux-View", "machine2") == false));
TEST("machine3 not in BigLinux-View", (check_in_view(collection, "BigLinux-View", "machine3") == false));
delete collection;
unlink(collection_log_file_name);
return;
}
static bool check_in_view(
ClassAdCollection *collection,
string view_name,
string classad_name)
{
bool have_view;
bool in_view;
in_view = false;
LocalCollectionQuery query;
query.Bind(collection);
have_view = query.Query(view_name, NULL);
if (have_view) {
string classad_key;
for (query.ToFirst(), query.Current(classad_key);
!query.IsAfterLast();
query.Next(classad_key)) {
if (!classad_key.compare(classad_name)) {
in_view = true;
break;
}
}
}
return in_view;
}
/*********************************************************************
*
* Function: test_utils
* Purpose: Test utils
*
*********************************************************************/
static void test_utils(const Parameters &, Results &results)
{
cout << "Testing little utilities...\n";
TEST("1800 is not a leap year", !is_leap_year(1800));
TEST("1900 is not a leap year", !is_leap_year(1900));
TEST("2000 is a leap year", is_leap_year(2000));
TEST("2001 is not a leap year", !is_leap_year(2001));
TEST("2002 is not a leap year", !is_leap_year(2002));
TEST("2003 is not a leap year", !is_leap_year(2003));
TEST("2004 is a leap year", is_leap_year(2004));
TEST("70, 9, 24 -> 25469", fixed_from_gregorian(70, 9, 24) == 25469);
TEST("135, 10, 2 -> 49217", fixed_from_gregorian(135, 10, 2) == 49217);
TEST("470, 1, 8 -> 171307", fixed_from_gregorian(470, 1, 8) == 171307);
TEST("576, 5, 20 -> 210155", fixed_from_gregorian(576, 5, 20) == 210155);
TEST("694, 11, 10 -> 253427", fixed_from_gregorian(694, 11, 10) == 253427);
TEST("1013, 4, 25 -> 369740", fixed_from_gregorian(1013, 4, 25) == 369740);
TEST("1096, 5, 24 -> 400085", fixed_from_gregorian(1096, 5, 24) == 400085);
TEST("1190, 3, 23 -> 434355", fixed_from_gregorian(1190, 3, 23) == 434355);
TEST("1240, 3, 10 -> 452605", fixed_from_gregorian(1240, 3, 10) == 452605);
TEST("1288, 4, 2 -> 470160", fixed_from_gregorian(1288, 4, 2) == 470160);
TEST("1298, 4, 27 -> 473837", fixed_from_gregorian(1298, 4, 27) == 473837);
TEST("1391, 6, 12 -> 507850", fixed_from_gregorian(1391, 6, 12) == 507850);
TEST("1436, 2, 3 -> 524156", fixed_from_gregorian(1436, 2, 3) == 524156);
TEST("1492, 4, 9 -> 544676", fixed_from_gregorian(1492, 4, 9) == 544676);
TEST("1553, 9, 19 -> 567118", fixed_from_gregorian(1553, 9, 19) == 567118);
TEST("1560, 3, 5 -> 569477", fixed_from_gregorian(1560, 3, 5) == 569477);
TEST("1648, 6, 10 -> 601716", fixed_from_gregorian(1648, 6, 10) == 601716);
TEST("1680, 6, 30 -> 613424", fixed_from_gregorian(1680, 6, 30) == 613424);
TEST("1716, 7, 24 -> 626596", fixed_from_gregorian(1716, 7, 24) == 626596);
TEST("1768, 6, 19 -> 645554", fixed_from_gregorian(1768, 6, 19) == 645554);
TEST("1819, 8, 2 -> 664224", fixed_from_gregorian(1819, 8, 2) == 664224);
TEST("1839, 3, 27 -> 671401", fixed_from_gregorian(1839, 3, 27) == 671401);
TEST("1903, 4, 19 -> 694799", fixed_from_gregorian(1903, 4, 19) == 694799);
TEST("1929, 8, 25 -> 704424", fixed_from_gregorian(1929, 8, 25) == 704424);
TEST("1941, 9, 29 -> 708842", fixed_from_gregorian(1941, 9, 29) == 708842);
TEST("1943, 4, 19 -> 709409", fixed_from_gregorian(1943, 4, 19) == 709409);
TEST("1943, 10, 7 -> 709580", fixed_from_gregorian(1943, 10, 7) == 709580);
TEST("1992, 3, 17 -> 727274", fixed_from_gregorian(1992, 3, 17) == 727274);
TEST("1996, 2, 25 -> 728714", fixed_from_gregorian(1996, 2, 25) == 728714);
TEST("2038, 11, 10 -> 744313", fixed_from_gregorian(2038, 11, 10) == 744313);
TEST("2094, 7, 18 -> 764652", fixed_from_gregorian(2094, 7, 18) == 764652);
int weekday;
int yearday;
day_numbers(2005, 1, 1, weekday, yearday);
TEST("Jan 1, 2005->6, 0", weekday==6 && yearday==0);
day_numbers(2005, 1, 2, weekday, yearday);
TEST("Jan 2, 2005->6, 1", weekday==0 && yearday==1);
day_numbers(2005, 12, 30, weekday, yearday);
TEST("Dec 30, 2005->5, 363", weekday==5 && yearday==363);
day_numbers(2005, 12, 31, weekday, yearday);
TEST("Dec 31, 2005->6, 364", weekday==6 && yearday==364);
day_numbers(2004, 12, 31, weekday, yearday);
TEST("Dec 31, 2005->5, 365", weekday==5 && yearday==365);
return;
}
/*********************************************************************
*
* Function: print_version
* Purpose:
*
*********************************************************************/
static void print_version(void)
{
string classad_version;
ClassAdLibraryVersion(classad_version);
cout << "ClassAd Unit Tester v" << classad_version << "\n\n";
return;
}
|
cpp
|
Credit cards are one of the most effective and hassle-free tools to meet financial requirements. However, if not managed properly, credit card expenses can pile up, leading to massive debt. High credit card bills can lead to additional borrowing and thereby impact the credit score of an individual.
Here are some of the best ways to pay off credit card debt faster.
Customers struggling to pay off credit card debt can use these strategies to clear the outstanding balance faster:
Individuals with outstanding bills on more than one credit card should pay off the debt on cards with higher interest rates. One might want to clear off the bills on cards with a shorter due date. However, that will lead to more expenses in the long run.
By clearing off dues on cards having higher interest rates, individuals can significantly reduce their total interest outgo. Unpaid dues on credit cards charging exorbitant interest rates will lead to a faster accumulation of interest.
To make the most of the credit-free period on a credit card, one should have a clear understanding of the card’s billing cycle (statement cycle).
The credit card issuer provides a credit-free period, which includes 30 days of the statement cycle and usually 10-15 additional days (grace period) for clearing the dues. it starts from the first day of the monthly billing cycle and not from the day of buying something.
For example, let’s say the next due date is July 4 and the statement generation date is June 18. If the cardholder buys something on June 19, this purchase will get included in the next billing cycle and not the current one. Accordingly, he/she will get a credit free period till August 4.
Many credit card holders often tend to pay only the minimum amount. This can potentially lead to mounting credit card debt that can be quite difficult to repay.
Those looking to clear credit card outstanding balance should remember that it will take much longer to pay off the dues if they pay only the minimum amount. By paying more than the minimum, one will have to pay lower interest.
Credit cards come with late payment fees and high-interest rates. So, to avoid missing bill payments, cardholders can opt for the automatic payment feature.
The bill gets deducted automatically from the account without any involvement of the cardholder. Thus, one need not worry about missing out on the payment deadlines.
While credit cards are highly useful financial tools, reckless use can push individuals into an unending cycle of debt.
Customers wondering how to pay off credit card debt faster can follow these tricks to pay off the bills quickly and manage their debt efficiently.
Disclaimer: This blog is solely for educational purposes. The securities/investments quoted here are not recommendatory.
|
english
|
Chandigarh: In a state of being upset, as the unemployed youth was not allowed to meet the Chief Minister of Punjab Parkash Singh Badal, he threw his degrees and certificates at the car of the CM in Punjab's Muktsar district.
The incident happened today, as the man identified as Dinesh Kumar, 25 years old, threw his certificates towards CM’s car as it came out of his farmhouse in Badal village of Muktsar.
Immediately, the youth was detained by the security personnel. Later, he was allowed to go with the warning and also his certificates returned to him.
|
english
|
Bhopal: Violence broke out on Tuesday during a farmers' protest in Mandsaur in Madhya Pradesh following which curfew was clamped in Pipalya Mandi area and prohibitory orders imposed in other parts of the district.
According to reports, two farmers were killed after police opened fired on violent protesters in Bhai Parshnath area, but Mandsaur Collector SK Singh denied it.
"Curfew has been clamped in Pipalya Mandi police station area and in the rest of the district section 144 of CrPC has been imposed," Singh said.
When asked about reports claiming death of two farmers, Singh said he does not have any such information. Farmers in western Madhya Pradesh are protesting since June 1 demanding minimum support price for their farm produce, among other things. Chief Minister Shivraj Singh Chouhan on Monday said his government is taking all necessary steps to address the issues of the agitating farmers.
A price stabilisation fund of Rs 1,000 crore would be set up to purchase the farm produce at the minimum support price (MSP), he had said. Mandsaur is about 325 kms from the state capital Bhopal.
|
english
|
/*IOWAN REGULAR*/
@font-face {
font-family: "Iowan Old Style W01 Roman";
src: url('https://dl.dropboxusercontent.com/s/8e732eoue2y29rn/Iowan%20Old%20Style%20W01%20Roman.ttf?raw=1') format('truetype'),
url('https://dl.dropboxusercontent.com/s/qidrfvzki29bttv/Iowan%20Old%20Style%20W01%20Roman.woff2?raw=1') format('woff2'),
url('https://dl.dropboxusercontent.com/s/539swlaas0l35o2/Iowan%20Old%20Style%20W01%20Roman.woff?raw=1') format('woff'),
url('https://dl.dropboxusercontent.com/s/wiv7spkypzrvoe6/Iowan%20Old%20Style%20W01%20Roman.eot?raw=1') format('embedded-opentype'),
url('https://dl.dropboxusercontent.com/s/y2wgd6yn3du3ri8/Iowan%20Old%20Style%20W01%20Roman.svg?raw=1') format('svg');
font-weight: 400;
font-style: normal;
}
|
css
|
This is the new iPad Pro.
It's the first iPad Pro with a larger 10 and a half inch retina display.
That still weighs just one pound.
It's the perfect size to allow us to display a full size, on screen keyboard.
It's also the perfect size to allow us to have a full size smart keyboard as well.
And when we deliver the smart keyboard, we're gonna have support for more than languages at launch, including Chinese.
And for the very first time, a Japanese JIS keyboard.
They're the best displays that we've ever made.
They're packed with incredible features like True Tone for automatic white balance, P3 wide color gamut for the best color.
Ultra low reflectivity and the best in the industry.
And they're 50% brighter with 600 niff's.
But our biggest break through is a feature we call ProMotion.
Now typically up until today, mobile displays have refreshed at 60 hertz which means they update their content 60 times every second.
While on the new, iPad Pro.
We've doubled that maximum refresh rate, to an incredible 120Hz.
[APPLAUSE] So what does that mean to you?
It means that all of your motion content on your screen is going to be smoother, crisper, more responsive.
Now the higher refresh rate also means that it works even better with the Apple Pencil.
It's more responsive and it reduces our latency to an industry best 20 milliseconds.
Inside them, they're powered by the A10X Fusion chip.
The A10X has a Six-core CPU.
And it delivers 30% faster CPU performance.
Overall, already industry leading A9X, and 40% faster graphics performance.
They're delivering an industry leading graphics performance that's more than 500 times the original iPad from just a few years ago.
|
english
|
<gh_stars>1-10
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you 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 org.apache.james.mime4j.decoder;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
/**
* This class is based on Base64 and Base64OutputStream code from Commons-Codec 1.4
*
* Provides Base64 encoding and decoding as defined by RFC 2045.
*
* <p>
* This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
* Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by <NAME> Borenstein.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @author Apache Software Foundation
* @since 1.0-dev
* @version $Id$
*/
public class Base64OutputStream extends FilterOutputStream {
/**
* Chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
static final int CHUNK_SIZE = 76;
/**
* Chunk separator per RFC 2045 section 2.1.
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
*/
static final byte[] CHUNK_SEPARATOR = {'\r','\n'};
/**
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in Table 1 of RFC 2045.
*
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*/
private static final byte[] intToBase64 = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/**
* Byte used to pad output.
*/
private static final byte PAD = '=';
/**
* This array is a lookup table that translates unicode characters
* drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
* into their 6-bit positive integer equivalents. Characters that
* are not in the Base64 alphabet but fall within the bounds of the
* array are translated to -1.
*
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*/
private static final byte[] base64ToInt = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
/** Mask used to extract 6 bits, used when encoding */
private static final int MASK_6BITS = 0x3f;
// The static final fields above are used for the original static byte[] methods on Base64.
// The private member fields below are used with the new streaming approach, which requires
// some state be preserved between calls of encode() and decode().
/**
* Line length for encoding. Not used when decoding. A value of zero or less implies
* no chunking of the base64 encoded data.
*/
private final int lineLength;
/**
* Line separator for encoding. Not used when decoding. Only used if lineLength > 0.
*/
private final byte[] lineSeparator;
/**
* Convenience variable to help us determine when our buffer is going to run out of
* room and needs resizing. <code>encodeSize = 4 + lineSeparator.length;</code>
*/
private final int encodeSize;
/**
* Buffer for streaming.
*/
private byte[] buf = new byte[1024];
/**
* Position where next character should be written in the buffer.
*/
private int pos;
/**
* Variable tracks how many characters have been written to the current line.
* Only used when encoding. We use it to make sure each encoded line never
* goes beyond lineLength (if lineLength > 0).
*/
private int currentLinePos;
/**
* Writes to the buffer only occur after every 3 reads when encoding, an
* every 4 reads when decoding. This variable helps track that.
*/
private int modulus;
/**
* Boolean flag to indicate that this Base64OutputStream has been closed.
* Once closed, this Base64 object becomes useless, and must be thrown away.
*/
private boolean closed = false;
/**
* Place holder for the 3 bytes we're dealing with for our base64 logic.
* Bitwise operations store and extract the base64 encoding or decoding from
* this variable.
*/
private int x;
/**
* Default constructor: lineLength is 76, and the lineSeparator is CRLF
* when encoding, and all forms can be decoded.
*/
public Base64OutputStream(OutputStream os) {
this(os, CHUNK_SIZE, CHUNK_SEPARATOR);
}
/**
* <p>
* Consumer can use this constructor to choose a different lineLength
* when encoding (lineSeparator is still CRLF). All forms of data can
* be decoded.
* </p><p>
* Note: lineLengths that aren't multiples of 4 will still essentially
* end up being multiples of 4 in the encoded data.
* </p>
*
* @param lineLength each line of encoded data will be at most this long
* (rounded up to nearest multiple of 4).
* If lineLength <= 0, then the output will not be divided into lines (chunks).
* Ignored when decoding.
*/
public Base64OutputStream(OutputStream os, int lineLength) {
this(os, lineLength, CHUNK_SEPARATOR);
}
/**
* <p>
* Consumer can use this constructor to choose a different lineLength
* and lineSeparator when encoding. All forms of data can
* be decoded.
* </p><p>
* Note: lineLengths that aren't multiples of 4 will still essentially
* end up being multiples of 4 in the encoded data.
* </p>
* @param lineLength Each line of encoded data will be at most this long
* (rounded up to nearest multiple of 4). Ignored when decoding.
* If <= 0, then output will not be divided into lines (chunks).
* @param lineSeparator Each line of encoded data will end with this
* sequence of bytes.
* If lineLength <= 0, then the lineSeparator is not used.
* @throws IllegalArgumentException The provided lineSeparator included
* some base64 characters. That's not going to work!
*/
public Base64OutputStream(OutputStream os, int lineLength, byte[] lineSeparator) {
super(os);
this.lineLength = lineLength;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
if (lineLength > 0) {
this.encodeSize = 4 + lineSeparator.length;
} else {
this.encodeSize = 4;
}
if (containsBase64Byte(lineSeparator)) {
String sep;
try {
sep = new String(lineSeparator, "UTF-8");
} catch (UnsupportedEncodingException uee) {
sep = new String(lineSeparator);
}
throw new IllegalArgumentException("lineSeperator must not contain base64 characters: [" + sep + "]");
}
}
/** Doubles our buffer. */
private void resizeBuf() {
byte[] b = new byte[buf.length * 2];
System.arraycopy(buf, 0, b, 0, buf.length);
buf = b;
}
/**
* Returns whether or not the <code>octet</code> is in the base 64 alphabet.
*
* @param octet
* The value to test
* @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
*/
public static boolean isBase64(byte octet) {
return octet == PAD || (octet >= 0 && octet < base64ToInt.length && base64ToInt[octet] != -1);
}
/*
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.
*
* @param arrayOctet
* byte array to test
* @return <code>true</code> if any byte is a valid character in the Base64 alphabet; false herwise
*/
private static boolean containsBase64Byte(byte[] arrayOctet) {
for (int i = 0; i < arrayOctet.length; i++) {
if (isBase64(arrayOctet[i])) {
return true;
}
}
return false;
}
// Implementation of the Encoder Interface
private final byte[] singleByte = new byte[1];
/**
* Writes the specified <code>byte</code> to this output stream.
*/
public void write(int i) throws IOException {
singleByte[0] = (byte) i;
write(singleByte, 0, 1);
}
/**
* Writes <code>len</code> bytes from the specified
* <code>b</code> array starting at <code>offset</code> to
* this output stream.
*
* @param b source byte array
* @param offset where to start reading the bytes
* @param len maximum number of bytes to write
*
* @throws IOException if an I/O error occurs.
* @throws NullPointerException if the byte array parameter is null
* @throws IndexOutOfBoundsException if offset, len or buffer size are invalid
*/
public void write(byte b[], int offset, int len) throws IOException {
if (closed) {
throw new IOException("Base64OutputStream has been closed");
}
if (b == null) {
throw new NullPointerException();
} else if (len < 0) {
// len < 0 is how we're informed of EOF in the underlying data we're
// encoding.
closed = true;
if (buf.length - pos < encodeSize) {
resizeBuf();
}
switch (modulus) {
case 1:
buf[pos++] = intToBase64[(x >> 2) & MASK_6BITS];
buf[pos++] = intToBase64[(x << 4) & MASK_6BITS];
buf[pos++] = PAD;
buf[pos++] = PAD;
break;
case 2:
buf[pos++] = intToBase64[(x >> 10) & MASK_6BITS];
buf[pos++] = intToBase64[(x >> 4) & MASK_6BITS];
buf[pos++] = intToBase64[(x << 2) & MASK_6BITS];
buf[pos++] = PAD;
break;
}
if (lineLength > 0) {
System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
pos += lineSeparator.length;
// TODO I had to add this to make it work as the quoted printable encoder.
// not sure this is generally speaking ok.
System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
pos += lineSeparator.length;
}
} else if (offset < 0 || len < 0 || offset + len < 0) {
throw new IndexOutOfBoundsException();
} else if (offset > b.length || offset + len > b.length) {
throw new IndexOutOfBoundsException();
} else if (len > 0) {
for (int i = 0; i < len; i++) {
if (buf.length - pos < encodeSize) {
resizeBuf();
}
modulus = (++modulus) % 3;
int bc = b[offset++];
if (bc < 0) { bc += 256; }
x = (x << 8) + bc;
if (0 == modulus) {
buf[pos++] = intToBase64[(x >> 18) & MASK_6BITS];
buf[pos++] = intToBase64[(x >> 12) & MASK_6BITS];
buf[pos++] = intToBase64[(x >> 6) & MASK_6BITS];
buf[pos++] = intToBase64[x & MASK_6BITS];
currentLinePos += 4;
if (lineLength > 0 && lineLength <= currentLinePos) {
System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
pos += lineSeparator.length;
currentLinePos = 0;
}
}
}
}
flushBuffer();
}
/**
* Flushes this output stream and forces any buffered output bytes
* to be written out to the stream. If propogate is true, the wrapped
* stream will also be flushed.
*
* @param propogate boolean flag to indicate whether the wrapped
* OutputStream should also be flushed.
* @throws IOException if an I/O error occurs.
*/
private void flushBuffer() throws IOException {
if (pos > 0) {
out.write(buf, 0, pos);
// buf = null;
pos = 0;
}
}
/**
* Flushes this output stream and forces any buffered output bytes
* to be written out to the stream.
*
* @throws IOException if an I/O error occurs.
*/
public void flush() throws IOException {
flushBuffer();
out.flush();
}
/**
* Terminates the BASE64 coded content and flushes the internal buffers. This method does
* NOT close the underlying output stream.
*/
public void close() throws IOException {
if (closed) {
return;
}
try {
// Notify encoder of EOF (-1).
write(singleByte, 0, -1);
flush();
} finally {
closed = true;
}
}
}
|
java
|
Former tennis star Boris Becker was on Friday jailed for two and a half years after being found guilty by a British court of charges relating to his 2017 bankruptcy.
The six-time Grand Slam champion, 54, will serve half of the term having being convicted at Southwark Crown Court in London over his transfer of huge amounts of money from his business account.
He also failed to declare a property in Germany and concealed 825,000 euros ($866,500) of debt and shares in a tech firm.
He was acquitted earlier this month of a further 20 charges, including nine counts of failing to hand over trophies and medals he won during his glittering tennis career.
Becker told jurors he did not know the whereabouts of the memorabilia, including two of his three Wimbledon men’s singles trophies.
Judge Deborah Taylor had released Becker – who won Wimbledon as an unseeded teenager – on conditional bail ahead of her sentencing decision on Friday.
Passing sentence, she told him: “You have not shown remorse, acceptance of your guilt and have sought to distance yourself from your offending and your bankruptcy.
Taylor said Becker’s previous conviction in Germany for tax offences was “a significant aggravating factor”.
Becker arrived early for the hearing, wearing a striped purple and green tie in the Wimbledon colours, a white shirt and a charcoal grey suit.
He held hands with his partner Lilian de Carvalho Monteiro as he walked into court past a bank of waiting reporters and cameras.
The star showed no emotion as he was sentenced, picking up his bag before being taken down to the cells.
There was no immediate word that Becker would appeal and he will lodge any legal challenge from behind bars.
Former world number one Becker told the jury how his $50 million (£40 million) career earnings were swallowed up by a costly divorce from his first wife Barbara Becker, child maintenance payments and “expensive lifestyle commitments”.
Becker said he was “shocked” and “embarrassed” when he was declared bankrupt in June 2017 over an unpaid loan of more than £3 million on his estate in Mallorca, Spain.
The German, who has lived in Britain since 2012, said he had cooperated with trustees trying to secure his assets, even offering his wedding ring, and relied on the advisers who managed his life away from tennis.
But the former player, who was supported in court by his partner and eldest son Noah, was found guilty of four charges.
Giving evidence, Becker said he earned a “vast amount” of money during his career, paying cash for several properties.
But the German, who went on to coach current world number one tennis player Novak Djokovic, work as a TV sports commentator and act as a brand ambassador for firms including Puma, said his income “reduced dramatically” following his retirement in 1999.
Becker, who was resident in Monte Carlo and Switzerland before moving to the UK, said his financial commitments included his £22,000-a-month rented house in Wimbledon, southwest London.
He also owed the Swiss authorities five million francs (about $5.1 million) and separately just under one million euros in liabilities over a conviction for tax evasion and attempted tax evasion in Germany in 2002.
He said bad publicity had damaged “brand Becker”, meaning he struggled to make enough money to pay off his debts.
His lawyer Jonathan Laidlaw said at the time of his bankruptcy that Becker was too “trusting and reliant” on his advisers.
Becker, with a shock of strawberry-blond hair, shook up the tennis world in 1985 when he became Wimbledon’s youngest men’s singles champion at 17 and repeated the feat the following year.
Nicknamed “Boom Boom” Becker for his ferocious serve, he won Wimbledon for a third time in 1989.
He also won the Australian Open twice and the US Open during his glittering career, becoming the top-ranked player in the world in 1991.
Becker turned to commentary after his retirement, landing a high-profile role on the BBC, but he returned to the court in 2013 to guide Djokovic, helping the Serb win six more Grand Slam trophies before the pair parted ways in 2016.
|
english
|
#!/usr/bin/env python
"""
wiggletools_commands.py
<NAME> / December 15, 2015
Writes wiggletools commands for computing mean bigwigs by tissue. Each set
of commands is numbered. They should be executed in order; some commands
in successive files depend on commands from previous files.
"""
import gzip
from collections import defaultdict
import os
import glob
import sys
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--gtex-dir', required=True,
help='path to GTEx output files; this is where the batch_* '
'subdirectories are')
parser.add_argument('--auc', required=True,
help='path to file with bigwig AUCs for normalization; '
'this script normalizes to library size 40 million 100-bp reads')
parser.add_argument('--wiggletools', required=True,
help='path to wiggletools')
parser.add_argument('--max-bw', required=False,
default=500,
help='max number of bigwig files to process at a time')
parser.add_argument('--out', required=True,
help='path to output directory')
args = parser.parse_args()
containing_dir = os.path.dirname(os.path.realpath(__file__))
# Create original sample index to new sample index map
sample_name_to_bw = {}
big_name_to_sample_name = {}
batch_numbers = []
for manifest in glob.glob(os.path.join(containing_dir, '*.manifest')):
batch_number = int(manifest.partition('.')[0].rpartition('_')[2])
batch_numbers.append(batch_number)
with open(manifest) as manifest_stream:
for j, line in enumerate(manifest_stream):
line = line.strip()
if not line: continue
sample_name = line.partition('\t')[0].partition(':')[2]
big_name_to_sample_name[line.rpartition('\t')[2]] = sample_name
sample_name_to_bw[sample_name] = os.path.join(
args.gtex_dir,
'batch_{}'.format(batch_number),
'coverage_bigwigs',
line.rpartition('\t')[2] +
'.bw'
)
sample_name_to_auc = {}
with open(args.auc) as auc_stream:
for line in auc_stream:
tokens = line.strip().split('\t')
sample_name_to_auc[tokens[0].strip()] = float(tokens[1])
sample_name_to_tissue = {}
with open(os.path.join(containing_dir, 'SraRunInfo.csv')) as sra_stream:
sra_stream.readline()
for line in sra_stream:
line = line.strip()
if not line: continue
if '_rep1' in line or '_rep2' in line: continue
tokens = line.split(',')
sample_name_to_tissue[tokens[0]] = tokens[41]
# Handle exceptions: some samples in SraRunInfo don't have tissues labeled
sample_name_to_tissue['SRR1325138'] = 'Skin'
sample_name_to_tissue['SRR1325690'] = 'Stomach'
sample_name_to_tissue['SRR1397115'] = 'Esophagus'
sample_name_to_tissue['SRR1405266'] = 'Esophagus'
sample_name_to_tissue['SRR1467633'] = 'Skin'
tissue_to_sample_names = defaultdict(list)
for sample_name in sample_name_to_auc:
tissue_to_sample_names[
sample_name_to_tissue[sample_name]
].append(sample_name)
try:
os.makedirs(args.out)
except OSError as e:
if 'File exists' not in e:
raise
file_handles = [
open(os.path.join(args.out, 'wiggletools_commands_0'), 'w')
]
more_than_one_batch = {}
for tissue in tissue_to_sample_names:
more_than_one_batch[tissue] = False
file_index = 0
divided_sample_names = [
tissue_to_sample_names[tissue][i:i+args.max_bw]
for i in xrange(0, len(tissue_to_sample_names[tissue]),
args.max_bw)
]
# Remove a lonely sample
if (len(divided_sample_names) >= 2
and len(divided_sample_names[-1]) == 1):
divided_sample_names[-2].append(divided_sample_names[-1][0])
divided_sample_names = divided_sample_names[:-1]
for i, sample_group in enumerate(divided_sample_names):
command_to_print = ' '.join([args.wiggletools, 'sum'] + [
'scale {} {}'.format(
float(40000000) * 100
/ sample_name_to_auc[sample_name],
sample_name_to_bw[sample_name]
) for sample_name in sample_group
]) + ' >{}'.format(
os.path.join(args.out,
tissue.replace(' ', '_')
+ '.sum_{}.wig'.format(i))
)
if i >= 1:
more_than_one_batch[tissue] = True
try:
print >>file_handles[i], command_to_print
except IndexError:
file_handles.append(
open(os.path.join(args.out,
'wiggletools_commands_' + str(i)), 'w')
)
print >>file_handles[i], command_to_print
next_index = len(file_handles)
file_handles.append(
open(os.path.join(args.out,
'wiggletools_commands_'
+ str(next_index)), 'w')
)
import glob
for tissue in tissue_to_sample_names:
print >>file_handles[-1], ' '.join([args.wiggletools, 'scale',
str(1./len(tissue_to_sample_names[tissue])),
('sum ' + os.path.join(args.out,
tissue.replace(' ', '_') + '.sum_*.wig'))
if more_than_one_batch[tissue]
else os.path.join(args.out,
tissue.replace(' ', '_') + '.sum_*.wig'),
'>' + os.path.join(args.out,
tissue.replace(' ', '_') + '.mean.wig')])
file_handles.append(
open(os.path.join(args.out,
'wiggletools_commands_'
+ str(next_index+1)), 'w')
)
sample_count = len(sample_name_to_auc)
print >>file_handles[-1], ' '.join([args.wiggletools, 'sum']
+ ['scale {} {}'.format(
float(
len(tissue_to_sample_names[tissue])
) / sample_count,
os.path.join(args.out,
tissue.replace(' ', '_') + '.mean.wig')
) for tissue in tissue_to_sample_names]) + (
' >{}'.format(
os.path.join(args.out,
'mean.wig')
)
)
for file_handle in file_handles:
file_handle.close()
|
python
|
<reponame>nameczz/www.zilliz.com<filename>src/pages/aboutus.js
import React from "react";
import Layout from "../components/layout";
import { graphql } from "gatsby";
import SEO from "../components/seo";
import AboutUs from "../blocks/AboutUs";
const AboutUsPage = ({ data, pageContext }) => {
const { locale } = pageContext;
const layout = data.allFile.edges[0].node.childLayoutJson.layout;
const aboutus = data.allFile.edges[0].node.childLayoutJson.aboutus;
const nav = {
current: "aboutus",
};
return (
<Layout
data={layout}
locale={locale}
nav={nav}
wrapperClass={"wrapper-about"}
hasSubNav={false}
>
<SEO title="About us" lang={locale} />
<AboutUs data={aboutus} />
</Layout>
);
};
export const Query = graphql`
query AboutQuery($locale: String) {
allFile(
filter: { name: { eq: $locale }, relativeDirectory: { in: ["layout"] } }
) {
edges {
node {
childLayoutJson {
layout {
header {
overview
analytics
milvus
product
aboutus
joinus
doc
}
footer {
contactButton
contactLeading
address
phone
email
infiniAnalytics
aboutZilliz
news
product
company
joinus
culture
socialCareer
schoolCareer
}
}
aboutus {
mission {
p
h2
}
roadmap {
p
h2
}
joinus {
p
h2
h3
button
}
}
}
}
}
}
}
`;
export default AboutUsPage;
|
javascript
|
You can update your channel preference from the Settings menu in the header menu.
You can update your channel preference from the Settings menu in the header menu.
Latest Topics For '
Asif Ali to team up with Jeethu Joseph?
Asif Ali-Namitha movie to start rolling!
Kaapa: Prithviraj, Manju Warrier, Asif Ali and Anna Ben team up!
Asif Ali's Kunjeldho gets a release date!
Actor Asif Ali hosts a grand birthday party for his little daughter!
Nivin Pauly-Asif Ali's 'Mahaveeryar' starts rolling !
|
english
|
<filename>test/Integration/Json/testNodeContextWithOperatorStringNotContain.json
{
"node": "context",
"contextName": "depositCount",
"operator": "stringNotContain",
"value": "def"
}
|
json
|
The court case between internet service provider iiNet and a number of movie studios represented by the Australian Federation Against Copyright Theft (AFACT) is grabbing attention as the pair war about who's responsible for Australians downloading pirated content on the internet. This interactive timeline presents a complete history of the trial.
In an effort to gain a wider audience for college sporting events, a South Carolina university is launching wireless live video and audio streaming of soccer and softball games, reports Campus Technology. Charleston Southern University in South Carolina - one of the first universities to create a wireless array across their campus - is expanding their wireless system from its Learning Center to its soccer and softball fields, using Xirrus technology.
|
english
|
{
"parent": "minecraft:block/brown_mushroom_block_inventory",
"overrides": [
{"predicate": {"custom_model_data": 1000}, "model": "ores:block/bauxite/bauxite"},
{"predicate": {"custom_model_data": 1001}, "model": "ores:block/uranium/uranium"},
{"predicate": {"custom_model_data": 1002}, "model": "ores:block/lead/lead"},
{"predicate": {"custom_model_data": 1003}, "model": "ores:block/lead/lead_collector_north"},
{"predicate": {"custom_model_data": 1004}, "model": "ores:block/uranium/nuclear_power_generator"}
]
}
|
json
|
---
layout: project_single
title: "Love this space idea. Can't wait to have our own place soon so we can do things like this"
slug: "love-this-space-idea-cant-wait-to-have-our-own-place-soon-so-we-can"
parent: "lego-room-designs"
---
Love this space idea. Can't wait to have our own place soon so we can do things like this
|
markdown
|
|Modified link of Web site: National Center for Biotechnology Information - GeneReviews - Classic Galactosemia and Clinical Variant Galactosemia.
|Add new Web site: MedlinePlus - Galactosemia.
|Added new Web site: How Stuff Works - Healthguide - Galactosemia.
|Article added to new online database.
|
english
|
<reponame>google-ar/chromium
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/stub_password_manager_driver.h"
namespace password_manager {
StubPasswordManagerDriver::StubPasswordManagerDriver() {
}
StubPasswordManagerDriver::~StubPasswordManagerDriver() {
}
void StubPasswordManagerDriver::FillPasswordForm(
const autofill::PasswordFormFillData& form_data) {
}
void StubPasswordManagerDriver::AllowPasswordGenerationForForm(
const autofill::PasswordForm& form) {
}
void StubPasswordManagerDriver::FormsEligibleForGenerationFound(
const std::vector<autofill::PasswordFormGenerationData>& forms) {}
void StubPasswordManagerDriver::GeneratedPasswordAccepted(
const base::string16& password) {
}
void StubPasswordManagerDriver::FillSuggestion(const base::string16& username,
const base::string16& password) {
}
void StubPasswordManagerDriver::PreviewSuggestion(
const base::string16& username,
const base::string16& password) {
}
void StubPasswordManagerDriver::ShowInitialPasswordAccountSuggestions(
const autofill::PasswordFormFillData& form_data) {}
void StubPasswordManagerDriver::ClearPreviewedForm() {
}
PasswordGenerationManager*
StubPasswordManagerDriver::GetPasswordGenerationManager() {
return nullptr;
}
PasswordManager* StubPasswordManagerDriver::GetPasswordManager() {
return nullptr;
}
PasswordAutofillManager*
StubPasswordManagerDriver::GetPasswordAutofillManager() {
return nullptr;
}
} // namespace password_manager
|
cpp
|
<reponame>xavierm02/timetable
{
"CR00": {
"name": "Structures algébriques de la réécriture et bases de Gröbner généralisées",
"teachers": "<NAME>, <NAME>"
},
"CR01": {
"name": "Fundamental Algorithms in Real Algebraic Geometry",
"teachers": "<NAME> and <NAME>"
},
"CR02": {
"name": "Resilient and Energy-Aware Scheduling Algorithms",
"teachers": "<NAME>"
},
"CR03": {
"name": "Network Algorithms for Molecular Biology",
"teachers": "<NAME>, <NAME> and <NAME>"
},
"CR04": {
"name": "Quantum Information and Computation",
"teachers": "<NAME>, <NAME> and <NAME>"
},
"CR05": {
"name": "Monadic Second Order Logic, Automata, Expressivity and Decidability",
"teachers": "<NAME> and <NAME>"
},
"CR06": {
"name": "Formal proof and Floating-Point Arithmetic",
"teachers": "<NAME>, <NAME> and <NAME>"
},
"CR07": {
"name": "Computer Science and Privacy",
"teachers": "<NAME> and <NAME>"
},
"CR08": {
"name": "Arithmetic Circuit Complexity",
"teachers": "<NAME> and <NAME>"
},
"CR09": {
"name": "Advanced Topics in Scalable Data Management",
"teachers": "<NAME> and <NAME>"
},
"CR10": {
"name": "Program Analysis, Safety Program Verification",
"teachers": "<NAME> and <NAME>"
},
"CR11": {
"name": "Mathematical Methods for Image Synthesis",
"teachers": "<NAME> and <NAME>"
},
"CR12": {
"name": "Coinductive Methods in Computer Science",
"teachers": "<NAME>, <NAME> and <NAME>"
},
"CR13": {
"name": "Computational Topology",
"teachers": "<NAME> and <NAME>"
},
"CR14": {
"name": "Network Information Theory",
"teachers": "<NAME> and <NAME>"
},
"CR15": {
"name": "Complex Networks",
"teachers": "<NAME> and <NAME>"
},
"CR16": {
"name": "Advanced Compilers",
"teachers": "<NAME> and <NAME>"
},
"CR17": {
"name": "Graph Decompositions: From Tree-Width to Perfect Graphs",
"teachers": "<NAME> and <NAME>"
}
}
|
json
|
import {ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-chip',
templateUrl: './chip.component.html',
styleUrls: ['./chip.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChipComponent implements OnInit {
@Input() value: string;
@Output() remove = new EventEmitter();
constructor() { }
ngOnInit(): void {
}
removeItem(): void {
this.remove.emit(this.value);
}
}
|
typescript
|
The farmers from Rajasthan were on their way to Delhi to join others who have been protesting against the central government's new farm laws for more than one month.
By India Today Web Desk: A group of protesting farmers from Rajasthan broke through police barricades on the Haryana-Rajasthan border on Thursday. These farmers are on their way to Delhi to join others who have been protesting against the central government's new farm laws for more than one month.
According to new agency ANI, when the farmers were attempting to break through police barricades, a clash ensued between the police and protesting farmers during which cops fired teargas shells and used water cannons.
After breaking through the barricades, a convoy of tractors marched towards Delhi.
#WATCH | A group of agitating farmers breaks through police barricades to enter Haryana via Rajasthan-Haryana border in Shahjahanpur.
Police said while farmers on around 25 tractor-trailers pushed past the barricades, others stayed behind on the Rajasthan side of the Shahjahanpur-Rewari border.
Farmers have been on a dharna at the site, blocking the road for several days in protest over the three new agri-marketing laws enacted at the Centre.
Farmer leaders at the site made clear that the protesters who forced their way into Haryana did not have their consent. Kisan Mahapanchayat president Rampal Jat said the agitation was going on peacefully but some of the farmers forcibly entered Haryana, which was not expected of them.
Haryana Police officials said a group of farmers, mostly youths, broke through the barricades set up by them in a bid to move towards Delhi.
"There were some young elements who came with tractors and broke through the barricades. We tried to stop them and gently persuade them. However, they were very aggressive and turned violent. They were not even listening to farmer leaders," Rewari Superintendent of Police Abhishek Jorwal told news agency PTI.
Meanwhile, farmer leaders at Shahjahanpur called for peace in the agitation. "We are sitting here peacefully and asking our members not to resort to violence," Kisan Mahapanchayat president Rampal Jat said. "We have sent some of our members to talk to those who entered Haryana to convince them to return," Jat added.
However, some farmers have alleged that the Haryana Police resorted to lathicharge against farmers who were trying to cross the border and reach Delhi.
In a statement, the All India Kisan Sangharsh Coordination Committee (AIKSCC) condemned the lathicharge of farmers from Rajasthan. "AIKSCC condemns the Haryana Police lathicharge on farmers at Rajasthan-Haryana border. Repression will lead to greater determination of farmers," it said, adding that Committee will "counter the repression with huge mobilisations".
"The AIKSCC severely condemns the repression (of farmers) in BJP-ruled and BJP-influenced states and has decided to counter this with huge mobilisations. It has called upon farmers to hold yatras in states and organise rallies at the district level," the statement said.
On Wednesday, the central government and farm unions reached some common ground to resolve protesting farmers' concerns over rise in power tariff and penalties for stubble burning. However, the two sides remained deadlocked over the main contentious issues of the repeal of three farm laws and a legal guarantee for MSP.
The sixth round of talks between the farmers' leaders and the government continued for nearly five hours. Agriculture Minister Narendra Singh Tomar said at least 50 per cent resolution has been reached with mutual agreement on two out of four items on the agenda and discussions would continue on the remaining two on January 4 at 2 PM.
He also hoped that the new year will herald new solutions and asserted that the Modi government has always been sensitive to farmers' issues.
"Discussions on the three farm laws and MSP are not complete and will continue in the next round of talks. . . We are hopeful that consensus would be reached for resolving the two remaining issues also," Tomar said.
Meanwhile, farmers' leaders said the government agreed to their demands of dropping the penal provisions against farmers in an ordinance relating to stubble burning and to put on hold a proposed electricity amendment law.
However, there was no concrete movement on their main demands for repeal of the three farm laws and a legal guarantee for MSP, union leaders said.
(With inputs from agencies)
|
english
|
<filename>Frontend/src/components/Commons/NavBar/index.js
import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withRouter, Link } from 'react-router-dom';
import { withStyles } from '@material-ui/core/styles';
// Actions
import { logout } from '../../../redux/actions/auth.action';
import { selectTab, cleanAppStates } from '../../../redux/actions/app.action';
import { cleanZonesStates } from '../../../redux/actions/zones.action';
// Material UI
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Button from '@material-ui/core/Button';
// Styles
import { styles } from './styles';
class NavBar extends Component {
handleChange = (event, value) => {
if(value === 0){
this.props.cleanAppStates();
this.props.cleanZonesStates();
}
this.props.selectTab(value);
};
logoutApp = (event) => {
event.preventDefault();
this.props.selectTab(0);
this.props.cleanAppStates();
this.props.cleanZonesStates();
this.props.logout();
}
render(){
const { classes, selectedLocation, isAuthenticated, tabValueSelected, servicesStatus } = this.props;
if(!isAuthenticated){
this.props.history.push('/');
}
return (
<Fragment>
{
isAuthenticated &&
<div className={classes.root}>
<AppBar position="static" color="default" className={classes.appBar}>
<div className={classes.logoCont}>
<Link to='/'><img className={classes.Logo} alt="logo" src={require('../../../assets/logo.jpg')} /></Link>
</div>
<Tabs
value={tabValueSelected}
onChange={this.handleChange}
indicatorColor="primary"
textColor="primary"
centered
>
<Tab label="Your locations" component={Link} to="/locations"/>
{
tabValueSelected > 0 && servicesStatus.insideService === true &&
<Tab label="Inside" component={Link} to="/inside"/>
}
{
tabValueSelected > 0 && servicesStatus.outsideService === true &&
<Tab label="Outside" component={Link} to="/outside"/>
}
{
tabValueSelected > 0 && servicesStatus.insideService === true &&
<Tab label="Zones" component={Link} to="/zones"/>
}
{
tabValueSelected > 0 && servicesStatus.insideService === true &&
<Tab label="Comparison" component={Link} to="/comparison"/>
}
{/* Start Weinladen and Capital Investment Insights */}
{
tabValueSelected > 0 && (selectedLocation[0].id_location === 4 || selectedLocation[0].id_location === 5 || selectedLocation[0].id_location === 7) &&
<Tab label="Insights" component={Link} to="/insights"/>
}
{/* End Weinladen and Capital Investment Insights */}
{
isAuthenticated &&
<div className={classes.logoutContainer}>
<Button variant="contained" color="primary" className={classes.button} onClick={this.logoutApp}>
Logout
</Button>
</div>
}
</Tabs>
</AppBar>
</div>
}
</Fragment>
);
}
}
NavBar.propTypes = {
classes: PropTypes.object.isRequired,
selectedLocation: PropTypes.array.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
logout: PropTypes.func.isRequired,
selectTab: PropTypes.func.isRequired,
tabValueSelected: PropTypes.number.isRequired,
cleanAppStates: PropTypes.func.isRequired,
cleanZonesStates: PropTypes.func.isRequired,
servicesStatus: PropTypes.object.isRequired
};
function mapStateToProps({ auth, app }) {
return {
selectedLocation: app.selectedLocation,
isAuthenticated: auth.isAuthenticated,
tabValueSelected: app.tabValueSelected,
servicesStatus: app.servicesStatus
}
}
export default withStyles(styles, { withTheme: true })(connect(mapStateToProps,
{
logout, selectTab, cleanAppStates, cleanZonesStates
})(withRouter(NavBar)));
|
javascript
|
According to a statement from Twitter’s owner, Elon Musk, on Tuesday, Twitter Notes, the feature that would let users write long-form content on the platform, appears to be back on track. In response to a user’s tweet claiming that the Twitter Notes project had recently been rebranded as “Articles,” the owner of Twitter acknowledged the company’s ambitions.
Prior to Musk’s purchase of Twitter, the firm first introduced Twitter Notes in June 2022 as an experiment with a select number of writers in the United States, Canada, Ghana, and the United Kingdom. The new “Write” tab on Twitter gave the writers access to write and access all of their Notes. Additionally, they would have a Notes page on their Twitter profiles where their followers and other Twitter users could access all of their long-form work.
The platform stated at the time that Twitter Notes allowed rich formatting and uploaded media, including the capability to incorporate pictures, videos, GIFs, and even tweets. After they were finished, authors could tweet out their Notes to their followers, who could then like, bookmark, retweet, or share them in DMs, just like they could with regular tweets.
However, the Twitter Notes project seemed to have been shelved since Musk took over the platform in a $44 billion deal. Notes had been placed on an indefinite “pause,” according to Platformer’s report from November 2022. Additionally, Musk has abandoned additional reading and writing-related Twitter projects, such as its newsletter platform Revue in December and ad-free articles for subscribers in November 2022.
It now seems like Notes will come back. Twitter user @FaustoChou stated on Tuesday that Notes have changed to Articles, possibly indicating Twitter’s redoubled development efforts. His screenshot included additional unreleased features, such as Twitter Coins, as well as the Notes interface, which looked quite similar to how it did before. Musk then responded to the tweet and reiterated Twitter’s intentions. Musk expressed that users will be able to upload extremely long, intricate articles with mixed media. If you wanted, you could publish a book.
Elon Musk withheld all further information regarding the company’s plans for Notes, or Articles as it may now be termed, including when users would have access to the feature or when it would be live to the public. The timing of the announcement coincides with the company’s efforts to retain creators in the face of heightened competition from Instagram Threads and other platforms. These efforts even included providing creators with a percentage of ad revenue, which resulted in payouts of up to four or five figures for some producers.
|
english
|
Department of Animal Husbandry, Ministry of Agriculture clarified that no fresh outbreak of the avian influenza was detected in any part of the country. The clarification follows reports in a section of media today about the disease being confirmed in Uchachal Taluka in Surat district of Gujarat. The samples from the area were tested positive for Avian Influenza at the High Security Animal Disease Laboratory (HSADL) in Bhopal. The Government said that farms from Uchachal Taluka adjoins the infected area of Navapur in Maharashtra from where the outbreak of disease was first detected. The Gujarat Government had sent a few samples from Uchachl Taluka after reports of large scale death of poultry in Navapura. The affected birds have already been culled in the region and Maharashtra Government has banned any outside moment of poultry products from the state. Operation cleanup and disinfection continued in both Uchachal Taluka and Navapur and measures have been taken to contain the spread of bird flu in the region. The statement from the Department of Animal Husbandry said.
|
english
|
<reponame>jameslongstaff/react-trello-clone<gh_stars>10-100
import mongoose from "mongoose";
import { Db } from "mongodb";
import config from "../config";
export default async (): Promise<Db> => {
const { databaseUser, databasePath, databasePassword } = config;
const databaseURL = `mongodb://${databaseUser}:${databasePassword}@${databasePath}`;
const connection = await mongoose.connect(databaseURL, {
useNewUrlParser: true,
useCreateIndex: true
});
return connection.connection.db;
};
|
typescript
|
In addition to their athletic characteristics, Air Jordans have developed into an important fashion statement. As a result of their streamlined aesthetics, one-of-a-kind color combinations, and recognizable silhouette, sneakerheads and fashion aficionados all over the world covet them. Because Jordans are worn both on and off the court for basketball, they are functional and fashionable accessories.
Nike typically refers to these limited edition Jordans as "retros" or "colorways." These releases are part of Nike's overall marketing strategy. The limited availability of these exclusive releases lends a sense of desirability and scarcity to the community of sneaker fans, which in turn results in increased demand overall. Moreover, this rarity means AJs can be pretty expensive for some sneakerheads.
However, every now and then, there are sales on their favorite Air Jordan sneakers. Here, we have curated a list of the top five AJs currently on sale, so that you know which ones to consider for your next shopping spree.
1) Air Jordan 1 Mid 'Lakers'
The long-awaited 'Lakers' colorway of the legendary Jordan 1 Mid sneaker is an art. Leather is used in the construction of these mid-top sneakers, which come in shades of dark purple, yellow, white, and black. The traction-enhancing sole is made of two different colors of rubber. Additionally, the original AJ1 inspired this mid-top model of the AJ1, which kept its iconic appearance. It features choice colors and crisp leather, giving it its own individual personality.
The Jordan 1 Mid 'Lakers' was released in 2022 and originally retailed for $130, currently discounted to $87 at the official Nike retail site.
2) Air Jordan 1 Mid 'Christmas/Malachite'
The Jordan Mid silhouette has a distinctive black base with embossed details. The leather overlays and the Air Jordan tongue emblem both include bold hits of red. Other identifying features of the brand can be found on the ankle and insole, while the swoosh on the panel itself is in clean white. The shoe has a white midsole and an outsole made of gum rubber, and it is held together with green laces for a consistent finish.
Another splash of color comes from the yellow heel stamp that matches the shoe's laces. The Low model also has a black foundation but features green overlays rather than red ones as a contrast. The remainder of the shoe's detailing has been preserved, including the white panel Swoosh, the red Air Jordan tongue logo, the white midsole, and the gum outsole.
The Jordan 1 Mid 'Christmas/Malachite' was released in 2022 with a retail price of $135 and is currently discounted at $94 at the official Nike retail site.
3) Air Jordan 1 Mid 'Orange Wear-Away'
The 'Wear-Away' style of the Jordan 1 Mid, which has surfaced, maintains the trend of the silhouette and has a history of being the most experimental trim of Michael Jordan's first trademark sneaker.
The pair has experienced a change from 'Infrared 23' and 'Black' color-blocking to an orange color, while keeping its cracked leather top for a worn aesthetic.
The design option resembles rusted metal, while the panels at the toe, midfoot, and collar areas opt for a clean white makeup. The mismatched tie dye finish applied to the left and right shoes' inner linings is another experiment that takes inspiration from the design that the late Peter Moore created in 1985.
The overlays across the upper of the Jordan 1 make a statement independently. The solitary unit chooses an "aged" look to fit in with the "Neo-vintage" fashion that has been growing in favor since the middle of the 2020s.
The Jordan 1 Mid 'Orange Wear-Away' was released in 2022 for $135 and is available for $94 currently at the official Nike retail site.
The 'Court Purple' outfit that was so popular in 2018 will continue to be used extensively in 2021 when the Air Jordan 1 Low Golf will release its next colorway from its extensive back catalog. The base layer and the midsole of this pair of Jordans both come in a clean white colorway.
The laces, the tongue structure, and the sock liner comes coated along the smooth leather panels of the forefoot, quarter, and heel counter.
The winged Jordan insignia is debossed at the heel and delivers a pitch-black color match. Vibrant violets are introduced into the equation through the "GOLF" marking at the tongue tab and underfoot amid the tread retooled for the green. The model's design is wrapped up with insoles that are a vibrant shade of red.
These Jordans were released in 2022 for $140 and are currently available for $98 at the official Nike retail site.
5) Jordan Jumpman Team II 'Cool Grey'
The Jordan Jumpman Team II participates in the famous 'Cool Grey' association while still dressing in the classic color blockings from the past. It debuted earlier this year as a background accent above the Air Jordan 6 and has since been released as a standalone shoe.
Before reaching its signature color, the dimpled leather mid-foot overlay, derived straight from the Jordan 13, features a pitch-black composition with color matches emerging along the laces, sock liner, vertical heel branding, and tread underfoot.
In contrast to the 'Cool Grey' that dominates the upper, the mesh tongue structure, tumbled leather vamp, and collar all come together to form this shoe's distinctive look.
These Jordans were released in 2022 for $140 and are currently discounted to $127 at the official Nike retail site.
These five Nike Air Jordans are the best at a discount. Grab them before the offers disappear, just like the limited edition Air Jordan sneakers.
|
english
|
import { words } from "../common/dict";
export class OneWord {
constructor() {
}
editDistance(s1, s2) {
var row2 = [];
if (s1 === s2) {
return 0;
} else {
var s1_len = s1.length, s2_len = s2.length;
if (s1_len && s2_len) {
var i1 = 0, i2 = 0, a, b, c, c2, row = row2;
while (i1 < s1_len)
row[i1] = ++i1;
while (i2 < s2_len) {
c2 = s2.charCodeAt(i2);
a = i2;
++i2;
b = i2;
for (i1 = 0; i1 < s1_len; ++i1) {
c = a + (s1.charCodeAt(i1) === c2 ? 0 : 1);
a = row[i1];
b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
row[i1] = b;
}
}
return b;
} else {
return s1_len + s2_len;
}
}
}
async findByRegularExpression(str, callback) {
const regularExpression = eval(`/${str}/`);
const answer = [];
if(!callback) {
callback = ()=>{};
}
for(let pattern in words) {
if(!pattern)continue;
const len = pattern.length;
for(let word of words[pattern]) {
if(regularExpression.test(word)) {
answer.push(word);
await callback(len, word);
}
}
}
return answer;
}
findByWildcard(wildcard, callback) {
let regx = '';
for(let x of wildcard) {
if(x === '#') {
regx += '.';
} else if( x === '*') {
regx += '.*';
} else {
regx += x;
}
}
return this.findByRegularExpression(`^${regx}$`, callback);
}
makeLetterSet(str) {
const letterSet = [];
for(let i = 0; i < str.length; i++) {
if(!letterSet[str[i]]) {
letterSet[str[i]] = 0;
}
letterSet[str[i]]++;
}
return letterSet;
}
async onlyContains(letters, callback) {
const answer = [];
const letterSet = this.makeLetterSet(letters);
const containsHelp = (letterSet, str) => {
const letterCount = [];
for(let i = 0; i < str.length; i++) {
if(!letterSet[str[i]]) {
return false;
}
if(!letterCount[str[i]]){
letterCount[str[i]] = 0;
}
letterCount[str[i]]++;
}
return true;
}
for(let patten in words) {
if(!patten)continue;
const len = patten.length;
for(let word of words[patten]) {
if(containsHelp(letterSet, word)) {
await callback(len, word);
answer.push(word);
}
}
}
return answer;
}
permutation(letters) {
const answer = [];
const letterSet = this.makeLetterSet(letters);
const containsHelp = (letterSet, str) => {
const letterCount = [];
for(let i = 0; i < str.length; i++) {
if(!letterSet[str[i]]) {
return false;
}
if(!letterCount[str[i]]){
letterCount[str[i]] = 0;
}
letterCount[str[i]]++;
}
for(let letter in letterSet) {
if(!letterCount[letter] || letterSet[letter] != letterCount[letter]) {
return false;
}
}
return true;
}
for(let patten in words) {
if(!patten)continue;
for(let word of words[patten]) {
if(containsHelp(letterSet, word)) {
console.info(word);
answer.push(word);
}
}
}
return answer;
}
async contains(letters, callback) {
const answers = [];
if(!callback) {
callback = ()=>{};
}
const letterSet = this.makeLetterSet(letters);
const containsHelp = (letterSet, str) => {
const letterCount = [];
for(let i = 0; i < str.length; i++) {
if(!letterSet[str[i]])continue;
if(!letterCount[str[i]]){
letterCount[str[i]] = 0;
}
letterCount[str[i]]++;
}
for(let letter in letterSet) {
if(!letterCount[letter] || letterSet[letter] > letterCount[letter]) {
return false;
}
}
return true;
}
for(let patten in words) {
if(!patten)continue;
const len = patten.length;
for(let word of words[patten]) {
if(containsHelp(letterSet, word)) {
answers.push(word);
await callback(len, word);
}
}
}
return answers;
}
async findSimilarity(str, similarityDegree, callback) {
const answer = [];
if(!similarityDegree) {
similarityDegree = 1;
}
if(!callback) {
callback = ()=>{};
}
const strLen = str.length;
for(let patten in words) {
if(!patten)continue;
const wordLen = patten.length;
if(Math.abs(wordLen-strLen) > similarityDegree)continue;
for(let word of words[patten]) {
if(this.editDistance(str, word) <= similarityDegree) {
answer.push(word);
await callback(wordLen, word);
}
}
}
return answer;
}
}
|
javascript
|
import { Button, Input, Radio, Slider, Switch, Row, Col, Tooltip } from 'antd';
import React, { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import {
useFeeDiscountKeys,
useLocallyStoredFeeDiscountKey,
useMarket,
useMarkPrice,
useSelectedBaseCurrencyAccount,
useSelectedBaseCurrencyBalances,
useSelectedOpenOrdersAccount,
useSelectedQuoteCurrencyAccount,
useSelectedQuoteCurrencyBalances,
} from '../utils/markets';
import { useWallet } from '../utils/wallet';
import { notify } from '../utils/notifications';
import { floorToDecimal, getDecimalCount, roundToDecimal, } from '../utils/utils';
import { useSendConnection } from '../utils/connection';
import FloatingElement from './layout/FloatingElement';
import { getUnixTs, placeOrder } from '../utils/send';
import { SwitchChangeEventHandler } from 'antd/es/switch';
import { refreshCache } from '../utils/fetch-loop';
import tuple from 'immutable-tuple';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faInfoCircle } from '@fortawesome/free-solid-svg-icons'
import { PracticeProvider, usePractice, PracticeContext } from '../utils/practice'
import { HistoryAdviceWallet2 } from '../components/History/HistoryAdviceWallet'
const RowBox = styled(Row)`
padding-bottom: 20px;
`;
const ActionButton = styled(Button)`
color: #f23b69;
background-color: #212734;
border-width: 0px;
`;
const ActionButton2 = styled(Button)`
color: #02bf76;
background-color: #212734;
border-width: 0px;
`;
const ActionButton3 = styled(Button)`
color: #868f92;
background-color: #212734;
border-width: 0px;
`;
const sliderMarks = {
0: '0%',
25: '25%',
50: '50%',
75: '75%',
100: '100%',
};
export default function TradeForm({
style,
setChangeOrderRef,
}: {
style?: any;
setChangeOrderRef?: (
ref: ({ size, price }: { size?: number; price?: number }) => void,
) => void;
}) {
const [side, setSide] = useState<'buy' | 'sell'>('buy');
const { baseCurrency, quoteCurrency, market } = useMarket();
const baseCurrencyBalances = useSelectedBaseCurrencyBalances();
const quoteCurrencyBalances = useSelectedQuoteCurrencyBalances();
const baseCurrencyAccount = useSelectedBaseCurrencyAccount();
const quoteCurrencyAccount = useSelectedQuoteCurrencyAccount();
const openOrdersAccount = useSelectedOpenOrdersAccount(true);
const { wallet, connected } = useWallet();
const sendConnection = useSendConnection();
const markPrice = useMarkPrice();
useFeeDiscountKeys();
const {
storedFeeDiscountKey: feeDiscountKey,
} = useLocallyStoredFeeDiscountKey();
const [postOnly, setPostOnly] = useState(false);
const [ioc, setIoc] = useState(false);
const [baseSize, setBaseSize] = useState<number | undefined>(undefined);
const [quoteSize, setQuoteSize] = useState<number | undefined>(undefined);
const [price, setPrice] = useState<number | undefined>(undefined);
const [submitting, setSubmitting] = useState(false);
const [sizeFraction, setSizeFraction] = useState(0);
const availableQuote =
openOrdersAccount && market
? market.quoteSplSizeToNumber(openOrdersAccount.quoteTokenFree)
: 0;
let quoteBalance = (quoteCurrencyBalances || 0) + (availableQuote || 0);
let baseBalance = baseCurrencyBalances || 0;
let sizeDecimalCount =
market?.minOrderSize && getDecimalCount(market.minOrderSize);
let priceDecimalCount = market?.tickSize && getDecimalCount(market.tickSize);
const publicKey = wallet?.publicKey;
useEffect(() => {
setChangeOrderRef && setChangeOrderRef(doChangeOrder);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [setChangeOrderRef]);
useEffect(() => {
baseSize && price && onSliderChange(sizeFraction);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [side]);
useEffect(() => {
updateSizeFraction();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [price, baseSize]);
useEffect(() => {
const warmUpCache = async () => {
try {
if (!wallet || !publicKey || !market) {
console.log(`Skipping refreshing accounts`);
return;
}
const startTime = getUnixTs();
console.log(`Refreshing accounts for ${market.address}`);
await market?.findOpenOrdersAccountsForOwner(sendConnection, publicKey);
await market?.findBestFeeDiscountKey(sendConnection, publicKey);
const endTime = getUnixTs();
console.log(
`Finished refreshing accounts for ${market.address} after ${endTime - startTime
}`,
);
} catch (e) {
console.log(`Encountered error when refreshing trading accounts: ${e}`);
}
};
warmUpCache();
const id = setInterval(warmUpCache, 30_000);
return () => clearInterval(id);
}, [market, sendConnection, wallet, publicKey]);
const onSetBaseSize = (baseSize: number | undefined) => {
setBaseSize(baseSize);
if (!baseSize) {
setQuoteSize(undefined);
return;
}
let usePrice = price || markPrice;
if (!usePrice) {
setQuoteSize(undefined);
return;
}
const rawQuoteSize = baseSize * usePrice;
const quoteSize =
baseSize && roundToDecimal(rawQuoteSize, sizeDecimalCount);
setQuoteSize(quoteSize);
};
const onSetQuoteSize = (quoteSize: number | undefined) => {
setQuoteSize(quoteSize);
if (!quoteSize) {
setBaseSize(undefined);
return;
}
let usePrice = price || markPrice;
if (!usePrice) {
setBaseSize(undefined);
return;
}
const rawBaseSize = quoteSize / usePrice;
const baseSize = quoteSize && roundToDecimal(rawBaseSize, sizeDecimalCount);
setBaseSize(baseSize);
};
const doChangeOrder = ({
size,
price,
}: {
size?: number;
price?: number;
}) => {
const formattedSize = size && roundToDecimal(size, sizeDecimalCount);
const formattedPrice = price && roundToDecimal(price, priceDecimalCount);
formattedSize && onSetBaseSize(formattedSize);
formattedPrice && setPrice(formattedPrice);
};
const updateSizeFraction = () => {
const rawMaxSize =
side === 'buy' ? quoteBalance / (price || markPrice || 1) : baseBalance;
const maxSize = floorToDecimal(rawMaxSize, sizeDecimalCount);
const sizeFraction = Math.min(((baseSize || 0) / maxSize) * 100, 100);
setSizeFraction(sizeFraction);
};
const onSliderChange = (value) => {
if (!price && markPrice) {
let formattedMarkPrice: number | string = priceDecimalCount
? markPrice.toFixed(priceDecimalCount)
: markPrice;
setPrice(
typeof formattedMarkPrice === 'number'
? formattedMarkPrice
: parseFloat(formattedMarkPrice),
);
}
let newSize;
if (side === 'buy') {
if (price || markPrice) {
newSize = ((quoteBalance / (price || markPrice || 1)) * value) / 100;
}
} else {
newSize = (baseBalance * value) / 100;
}
// round down to minOrderSize increment
let formatted = floorToDecimal(newSize, sizeDecimalCount);
onSetBaseSize(formatted);
};
const postOnChange: SwitchChangeEventHandler = (checked) => {
if (checked) {
setIoc(false);
}
setPostOnly(checked);
};
const iocOnChange: SwitchChangeEventHandler = (checked) => {
if (checked) {
setPostOnly(false);
}
setIoc(checked);
};
async function onSubmit() {
if (!price) {
console.warn('Missing price');
notify({
message: 'Missing price',
type: 'error',
});
return;
} else if (!baseSize) {
console.warn('Missing size');
notify({
message: 'Missing size',
type: 'error',
});
return;
}
setSubmitting(true);
try {
if (!wallet) {
return null;
}
await placeOrder({
side,
price,
size: baseSize,
orderType: ioc ? 'ioc' : postOnly ? 'postOnly' : 'limit',
market,
connection: sendConnection,
wallet,
baseCurrencyAccount: baseCurrencyAccount?.pubkey,
quoteCurrencyAccount: quoteCurrencyAccount?.pubkey,
feeDiscountPubkey: feeDiscountKey,
});
refreshCache(tuple('getTokenAccounts', wallet, connected));
setPrice(undefined);
onSetBaseSize(undefined);
} catch (e) {
console.warn(e);
notify({
message: 'Error placing order',
//@ts-ignore
description: e.message,
type: 'error',
});
} finally {
setSubmitting(false);
}
}
//const {practice, setPractice} = useContext(PracticeContext)
const { practice, setPractice, skip, predict, conected_api, setConected_api } = useContext(PracticeContext)
if (connected){
return (
<FloatingElement
style={{ display: 'flex', flexDirection: 'column', ...style }}
>
<RowBox align="middle" justify="space-between">
<div style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
<h1> Escoja una opción</h1>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
<Tooltip
placement="bottomLeft"
title="Aquí se puede escoger la opción de predicción del ejercicio, donde se puede seleccionar: Sube, si es que la tendencia es alcista, Baja si es que la tendencia es bajista u Omitir para saltar a otro ejercicio">
<span style={{ color: "#1ce6d2" }}>
<FontAwesomeIcon size='lg' icon={faInfoCircle} />
</span>
</Tooltip>
</div>
</RowBox>
<div style={{ flex: 1 }}>
<RowBox align="middle" justify="space-around">
<Col style={{ width: 150 }}>
<ActionButton2
block
size="large"
onClick={() => {
connected ? predict(true, publicKey, practice.modality) :
notify({
message: "Aviso",
description: "Se necesita conectar una wallet para usar esta funcionalidad",
type: "warning"
})
}
}
>
Sube
</ActionButton2>
</Col>
<Col style={{ width: 150 }}>
<ActionButton block size="large" onClick={() => connected ? predict(false, publicKey, practice.modality) :
notify({
message: "Aviso",
description: "Se necesita conectar una wallet para usar esta funcionalidad",
type: "warning"
})} >
Baja
</ActionButton>
</Col>
</RowBox>
<RowBox align="middle" justify="space-around">
<Col style={{ width: 325 }}>
<ActionButton3 onClick={() => connected ? skip() :
notify({
message: "Aviso",
description: "Se necesita conectar una wallet para usar esta funcionalidad",
type: "warning"
})} block size="large">
Omitir
</ActionButton3>
</Col>
</RowBox>
</div>
</FloatingElement >
);
} else{
return <HistoryAdviceWallet2></HistoryAdviceWallet2>
;
}
}
|
typescript
|
<filename>src/app/plugins/account/components/userManagement/users/EditUserPage.js
import { setActiveRegion } from 'api-client/helpers'
import ValidatedForm from 'core/components/validatedForm/ValidatedForm'
import TextField from 'core/components/validatedForm/TextField'
import React, { useMemo, useEffect, useState } from 'react'
import clsx from 'clsx'
import TenantRolesTableField from 'account/components/userManagement/users/TenantRolesTableField'
import useDataUpdater from 'core/hooks/useDataUpdater'
import { mngmTenantActions } from 'account/components/userManagement/tenants/actions'
import useDataLoader from 'core/hooks/useDataLoader'
import {
mngmUserActions,
mngmUserRoleAssignmentsLoader,
} from 'account/components/userManagement/users/actions'
import { TextField as BaseTextField } from '@material-ui/core'
import { emptyObj, pathStr } from 'utils/fp'
import useReactRouter from 'use-react-router'
import FormWrapper from 'core/components/FormWrapper'
import { propEq, prop } from 'ramda'
import Wizard from 'core/components/wizard/Wizard'
import WizardStep from 'core/components/wizard/WizardStep'
import UserPasswordField from 'account/components/userManagement/users/UserPasswordField'
import useToggler from 'core/hooks/useToggler'
import SimpleLink from 'core/components/SimpleLink'
import makeStyles from '@material-ui/styles/makeStyles'
import { requiredValidator } from 'core/utils/fieldValidators'
import Progress from 'core/components/progress/Progress'
import { routes } from 'core/utils/routes'
import { sessionActions, sessionStoreKey } from 'core/session/sessionReducers'
import { useDispatch, useSelector } from 'react-redux'
import useScopedPreferences from 'core/session/useScopedPreferences'
import ApiClient from 'api-client/ApiClient'
import { loadUserTenants } from 'openstack/components/tenants/actions'
const listUrl = routes.userManagement.users.path()
const useStyles = makeStyles((theme) => ({
togglableFieldContainer: {
display: 'flex',
flex: 1,
alignItems: 'center',
'& .Mui-disabled': {
color: theme.palette.text.primary,
},
},
togglableField: {
width: '50%',
},
togglableFieldBtn: {
marginLeft: theme.spacing(2),
},
}))
const TogglableTextField = ({
id,
label,
initialValue,
value,
required = false,
TextFieldComponent = TextField,
}) => {
const classes = useStyles()
const [showingField, toggleField] = useToggler()
return (
<div className={clsx('togglableFieldContainer', classes.togglableFieldContainer)}>
{showingField ? (
<TextFieldComponent id={id} label={label} value={value} required={required} />
) : (
<BaseTextField
className={classes.togglableField}
label={label}
value={initialValue}
disabled
/>
)}
<SimpleLink className={classes.togglableFieldBtn} onClick={toggleField} label={label}>
{showingField ? 'Cancel' : 'Change'}
</SimpleLink>
</div>
)
}
const tenantRolesValidations = [requiredValidator.withMessage('Must select at least one tenant')]
const EditUserPage = () => {
const { match, history } = useReactRouter()
const dispatch = useDispatch()
const userId = match.params.id
const [users, loadingUsers] = useDataLoader(mngmUserActions.list)
const user = useMemo(() => users.find(propEq('id', userId)) || emptyObj, [users, userId])
const [tenants, loadingTenants] = useDataLoader(mngmTenantActions.list)
const [update, updating] = useDataUpdater(mngmUserActions.update)
const [roleAssignments, loadingRoleAssignments] = useDataLoader(mngmUserRoleAssignmentsLoader, {
userId,
})
const [, , reloadTenants] = useDataLoader(loadUserTenants)
const session = useSelector(prop(sessionStoreKey))
const { userDetails } = session
const { id: activeUserId, email: activeUserEmail } = userDetails
const { prefs, updatePrefs } = useScopedPreferences()
const [oldUserPrefs, setOldUserPrefs] = useState(prefs)
const [activeUserUpdated, setActiveUserUpdated] = useState(false)
const loadingSomething = loadingUsers || loadingTenants || loadingRoleAssignments || updating
const isActiveUser = userId === activeUserId
const showPasswordField = !isActiveUser
const initialContext = useMemo(
() => ({
id: userId,
username: user.username || user.email,
displayname: user.displayname || '',
roleAssignments: roleAssignments.reduce(
(acc, roleAssignment) => ({
...acc,
[pathStr('scope.project.id', roleAssignment)]: pathStr('role.id', roleAssignment),
}),
{},
),
}),
[user, roleAssignments],
)
useEffect(() => {
// When the active user's email gets updated, transfer their old prefs over to the new email
if (activeUserUpdated) {
updatePrefs(oldUserPrefs)
if (oldUserPrefs.currentRegion) {
setActiveRegion(oldUserPrefs.currentRegion)
}
history.push(listUrl)
}
}, [activeUserEmail])
const handleUserUpdate = async (values) => {
const [updated, updatedUser] = await update(values)
if (updated && isActiveUser) {
setActiveUserUpdated(true)
dispatch(
sessionActions.updateSession({
username: updatedUser.email,
userDetails: {
...userDetails,
username: updatedUser.email,
name: updatedUser.email,
email: updatedUser.email,
displayName: updatedUser.displayname, // displayName is a UI variable
displayname: updatedUser.displayname, // displayname is what we get from the api
},
}),
)
reloadTenants(true)
history.push(listUrl)
} else {
history.push(listUrl)
}
}
return (
<FormWrapper
title={`Edit User ${user.displayname || user.username || ''}`}
loading={loadingSomething}
renderContentOnMount={!loadingSomething}
message={updating ? 'Submitting form...' : 'Loading User...'}
backUrl={listUrl}
>
<Wizard onComplete={handleUserUpdate} context={initialContext}>
{({ wizardContext, setWizardContext, onNext }) => (
<>
<WizardStep stepId="basic" label="Basic Info">
<ValidatedForm
initialValues={wizardContext}
onSubmit={setWizardContext}
triggerSubmit={onNext}
>
{({ values }) => (
<>
<TogglableTextField
id="username"
label="Username or Email"
initialValue={user.username}
required
/>
<TogglableTextField
id="displayname"
label="Display Name"
initialValue={user.displayname}
/>
{showPasswordField && (
<TogglableTextField
id="password"
label="Password"
initialValue={'********'}
value={values.password}
TextFieldComponent={UserPasswordField}
/>
)}
</>
)}
</ValidatedForm>
</WizardStep>
<WizardStep stepId="tenants" label="Tenants and Roles">
<ValidatedForm
fullWidth
initialValues={wizardContext}
onSubmit={setWizardContext}
triggerSubmit={onNext}
>
<Progress
renderContentOnMount={!loadingTenants}
loading={loadingTenants}
message={'Loading Tenants...'}
>
<TenantRolesTableField
validations={tenantRolesValidations}
id="roleAssignments"
tenants={tenants}
/>
</Progress>
</ValidatedForm>
</WizardStep>
</>
)}
</Wizard>
</FormWrapper>
)
}
export default EditUserPage
|
javascript
|
import * as React from 'react';
import { Link } from 'react-router-dom';
import { Icon } from '@rmwc/icon';
import { Fab } from '@rmwc/fab';
import { Tree } from '../tree';
import './home.styles.css';
export const Home = () => (
<div className="home">
<Tree className="home__tree" />
<div>
<h1 className="home__title">Redux StateBranch</h1>
<h2 className="home__subtitle">
A library for simplified Redux development.
</h2>
<code className="home__npm-install">
npm install
<wbr /> redux-state-branch
</code>
<ul>
<li>
<Icon icon="check" /> Zero Dependencies
</li>
<li>
<Icon icon="check" /> < 5 KB
</li>
<li>
<Icon icon="check" /> Typescript Support
</li>
</ul>
<Fab
tag={Link}
{...{ to: '/getting-started' }}
label="Get Started"
trailingIcon="keyboard_arrow_right"
/>
</div>
</div>
);
|
typescript
|
<filename>aws/cache.go
package aws
import (
"github.com/patrickmn/go-cache"
"reflect"
"time"
)
const DEFAULT_EXP_TIME = 10 * time.Second
var generalCache = cache.New(DEFAULT_EXP_TIME, DEFAULT_EXP_TIME)
type Any interface{}
//
// Provide a general caching mechanism for any function that lasts a few seconds.
//
func GetAndCache(key string, input Any, f Any, cacheTime time.Duration) (Any, error) {
vf := reflect.ValueOf(f)
vinput := reflect.ValueOf(input)
result, found := generalCache.Get(key)
if !found {
caller := vf.Call([]reflect.Value{vinput})
output := caller[0].Interface()
err, _ := caller[1].Interface().(error)
if err == nil {
generalCache.Set(key, output, cacheTime)
return output, nil
}
return nil, err
}
return result, nil
}
func AddToCache(key string, value Any, cacheTime time.Duration) {
generalCache.Set(key, value, cacheTime)
}
// RemoveKeyFromCache : Delete any entry cache in the cache for this key
func RemoveKeyFromCache(key string) {
generalCache.Delete(key)
}
|
go
|
{"rows":[{"OrderID":"11058","RequiredDate":"1998-05-27 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"31.1400"},{"OrderID":"10956","RequiredDate":"1998-04-28 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"44.6500"},{"OrderID":"10853","RequiredDate":"1998-02-24 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"53.8300"},{"OrderID":"10614","RequiredDate":"1997-08-26 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"1.9300"},{"OrderID":"10582","RequiredDate":"1997-07-25 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"27.7100"},{"OrderID":"10509","RequiredDate":"1997-05-15 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"0.1500"},{"OrderID":"10501","RequiredDate":"1997-05-07 00:00:00","ShipName":"<NAME>","ShipCity":"Mannheim","Freight":"8.8500"}]}
|
json
|
The question wasn't exactly clear: Why do you think you're here? The query was posed to Utah Jazz rookie forward Taylor Hendricks ahead of his first preseason game in October and was meant to elicit a response about why the talented forward believed the Jazz drafted him. Hendricks, though, took it in a much different direction. "God put me in this position for a reason, so I'm gonna do my best and work hard to spread his word," Hendricks said.
Last night the Utah Jazz had one of their more impressive wins this year and certainly the best effort they've shown in a handful of games. Talen Horton-Tucker's early 4th quarter barrage was a big part of extending the lead. Walker Kessler's defense and rim pressure were difficult for the Knicks to handle.
Keyonte George clearly has been the most productive of the Utah Jazz's trio of rookies thus far this season, with his 30-point outburst on Monday night in Oklahoma City just the latest example of his impressive progress. George would soon be ruled out for the remainder of the game with what the team generically referred to as a “left foot” injury, though Hardy referenced the guard's ankle in his postgame media session. George's status is to be determined. Utah picked up its eighth victory of the season, 117-113 against the Knicks.
|
english
|
A subscription to JoVE is required to view this content.
You will only be able to see the first 2 minutes.
The JoVE video player is compatible with HTML5 and Adobe Flash. Older browsers that do not support HTML5 and the H.264 video codec will still use a Flash-based video player. We recommend downloading the newest version of Flash here, but we support all versions 10 and above.
If that doesn't help, please let us know.
Please note that all translations are automatically generated.
यह काम लेजर-विकिरणित सोने के नैनोकणों से टीबीएलएमएस तक हीट ट्रांसफर की गतिशील, गैर-आक्रामक निगरानी प्राप्त करने के लिए एक प्रोटोकॉल की रूपरेखा तैयार करता है। यह प्रणाली टीबीएलएमएस में आचरण परिवर्तनों के वास्तविक समय के माप के लिए बाधा स्पेक्ट्रोस्कोपी को जोड़ती है, जिसमें एक क्षैतिज रूप से केंद्रित लेजर बीम है जो गर्मी उत्पादन के लिए सोने की नैनोपार्टिकल रोशनी को चलाता है।
|
english
|
U. S. President Joe Biden has nominated former Mastercard CEO Ajay Banga to lead the World Bank as its next president, a week after its current President David Malpass announced his intention to step down in June this year.
Biden expects India-born Ajay Banga's ties to the private sector and emerging markets to jump-start the World Bank's overhaul to better address climate change.
Biden's nomination of 63-year-old Ajay Banga, who is now a US citizen, all but assures that he will assume a job that oversees billions of dollars of funding as it races to help developing countries address climate change.
The World Bank said recently that it expects to select a new president by early May 2023 to replace David Malpass, who announced his resignation last week after months of controversy sparked by his initial refusal to say if he accepted the scientific consensus on climate change, and pressure from Treasury Secretary Janet Yellen for him to adopt "bolder" reforms.
"I think the speed of the nomination (of Ajay Banga), less than 48 hours after the World Bank board launched the process, reflects a desire to discourage any challengers and wrap it up quickly," said Scott Morris, a senior fellow at the Center for Global Development and a former U. S. Treasury official, as per a Reuters report.
US President Biden mentioned Ajay Banga's decades of experience building global companies and public-private partnerships to fund responses to climate change and migration and said he had a proven track record working with global leaders.
"Ajay is uniquely equipped to lead the World Bank at this critical moment in history," Biden said in a statement, as per the report, hailing the former Mastercard CEO's Indian roots, knowledge of the challenges facing developing countries, and ability to mobilise private capital to tackle big problems.
Ajay Banga's work in India and other emerging markets, his "obsession" with expanding financial inclusion, and his deep knowledge of new technologies could help bridge the divide between rich countries and emerging markets, said Luis Alberto Moreno, who worked closely with Banga while serving as president of the Inter-American Development Bank.
"He can really be a force for change," Moreno said, as per the report, noting that Banga enjoyed the trust of financial markets.
India was expected to support Banga's candidacy, according to Krishnamurthy Subramanian, the former top economic adviser to the Indian government who now serves as India's executive director at the International Monetary Fund. "It's an elegant solution. "
The World Bank has historically been headed by someone from the United States, its largest shareholder, while a European heads the International Monetary Fund (IMF), but developing countries and emerging markets have pushed to widen those choices.
Banga's nomination is the first to be made public, but the bank will accept nominations from other member countries through March 29. Germany, another major shareholder, this week said the job should go to a woman since the bank has never been headed by a woman.
Reuters reported that a senior U. S. administration official said they did not know if other countries would nominate candidates for the post.
Asked about Washington's decision not to nominate a woman, the official said Banga had "a personal conviction and excellent track record promoting diversity, equity, and inclusion in the work that he does" and would bring that view to the bank.
Pune-born Ajay Banga is currently the vice chair of General Atlantic, a U. S. private equity firm that administration officials said has invested over $800 million in EV charging solutions, solar power, and sustainable farming.
He retired in December 2021 after 12 years at the helm of Mastercard, where administration officials noted that he helped 500 million unbanked people join the digital economy, averted layoffs of the bank's 19,000 employees during the COVID-19 pandemic, and led work on climate, gender, and sustainable agriculture.
US' Vice President Kamala Harris said Ajay Banga brought great insight, energy, and persistence to his role as co-chair of the Partnership for Central America, which has mobilised $4. 2 billion in public, private, and nonprofit funds to advance economic opportunity in northern Central America.
For the latest and interesting financial news, keep reading Indiatimes Worth. Click here.
|
english
|
Chat & Instant Messaging (133 programs)
PROS: Saves phone storage space. Uses much less data and battery. Functional even in 2G. Features all the main Messenger functions.CONS: Lacks extras - GIFs, stories.
PROS: Easy to join group chats. Supports up to 8 people in a group call. Allows simultaneous group calls. Allows users to play games while on the call.CONS: Lots of call dropouts. Some games do not work. Can be too invasive. Uses an excessive amount of battery.
PROS: Extremely fast and easy to use. Supports both emojis and stickers. Preserves past conversations automatically. Optional end-to-end encryption.CONS: Heavily designed for phones rather than other devices. Privacy may be an issue.
PROS: Free to download and use. Lots of funny filters to choose from.CONS: Requires a strong internet connection. May glitch from time to time.
PROS: Find easily friends. Familiar messaging app interface. Dictionaries and translators. Many languages to choose from.CONS: Connection issues. Sometimes struggle to detect microphone for chat.
PROS: Free text and calls across Canada and the US. Easy-to-use interface. Can sync across multiple devices. Earn international credits by watching ads.CONS: Below average call quality. May experience calls dropping. Can lose phone number due to inactivity. Might receive scam calls.
PROS: Good selection of emojis. Very funny animated gifs. Compatible with all messaging apps.CONS: Not a great keyboard. It doesn't send imojis but created images.
PROS: Helps avoid text messages from unwanted contacts. Free app.CONS: Only available on Android. Depends on Truecaller’s database.
PROS: Safe and secure. Quality audio and video.CONS: Another messaging app. Convincing your friends to use it.
PROS: Tons of content. Easy to use. Shares to many apps.CONS: Can't share others' Kongs. Gimmicky premise.
PROS: Simple but useful addition to main Go SMS Pro app. Better than no emojis.CONS: Limited amount of average emojis.
PROS: Great concept. Can be both fun and practical to use. Customizable chat background. Lets you personalize your profile.CONS: Confusing to use at first. No group messaging support. User interface looks outdated.
PROS: Attractive, Material Design interface. Handy Quick Reply feature. Night mode. Lots of notification settings.CONS: Still has some bugs. No location sharing option.
PROS: Slick, attractive user interface. Fast and simple to use. Integrates well with your contacts. Lets you block SMS from pre-defined contacts.CONS: Needs more customization options. Not as fully featured as Hangouts.
PROS: TLS and SRTP encryption. Instant messaging and voice calling capabilities. Real-time collaboration on MS Office apps.CONS: Limited to Microsoft applications.
|
english
|
var GSAP = function() {
var pineconeTl = new TimelineLite(),
pineconeLogo = $('.powered_by_pinecone svg'),
pineconeEls = pineconeLogo.find('path[id*="cone"]'),
pineconeType = pineconeLogo.find('path[id*="type"]'),
pineconePlay = pineconeLogo.find('path[id="play"]'),
pineconeSpan = $('.powered_by_pinecone span');
TweenLite.set([pineconeLogo, pineconeSpan], {
visibility: 'visible'
});
TweenLite.set(pineconeSpan, {
x: 7
});
// timeline animations pines, type and "powered by"
pineconeTl.timeScale(0.65);
pineconeTl.staggerFrom(pineconeEls, 0.2, {
transformOrigin: 'center',
scale: 0,
autoAlpha: 0,
y: 150,
ease: Back.easeOut.config(3)
}, 0.05);
pineconeTl.staggerFrom(pineconeType, 0.2, {
transformOrigin: 'center',
scale: 0,
autoAlpha: 0,
rotationX: -180,
y: 150,
ease: Back.easeOut.config(4)
}, 0.05, '-=0.25');
pineconeTl.from(pineconeSpan, 0.8, {
autoAlpha: 0,
y: 30,
scaleY: 0,
ease: Elastic.easeOut.config(1.5, 0.4)
}, '-=0.45');
pineconeLogo.on('mouseenter', function() {
TweenLite.to(pineconePlay, 0.3, {
transformOrigin: 'center',
autoAlpha: 1,
scale: 1,
ease: Back.easeOut.config(3)
});
TweenLite.to([pineconeType, pineconeSpan, pineconeEls], 0.5, {
opacity: 0.5
});
pineconeLogo.click(function() {
TweenLite.set([pineconeType, pineconeSpan, pineconeEls], {
opacity: 1
});
pineconeTl.restart();
TweenLite.to(pineconePlay, 0.3, {
transformOrigin: 'center',
autoAlpha: 0,
scale: 0
});
});
});
pineconeLogo.on('mouseleave', function() {
TweenLite.to(pineconePlay, 0.3, {
transformOrigin: 'center',
autoAlpha: 0,
scale: 0
});
TweenLite.to([pineconeType, pineconeSpan, pineconeEls], 0.3, {
opacity: 1
});
});
};
$(document).on('ready', function() {
GSAP();
});
|
javascript
|
Teen Titans Go! To the Movies Movie Streaming Watch Online. All the major DC superheroes are starring in their own films, all but the Teen Titans, so Robin is determined to remedy this situation by getting over his role as a sidekick and becoming a movie star. Thus, with a few madcap ideas and an inspirational song in their hearts, the Teen Titans head to Hollywood to fulfill their dreams.
|
english
|
<reponame>abyr/take-care-client-js
{
"name": "take-care-client-js",
"version": "0.0.1",
"homepage": "https://github.com/abyr/take-care-client-js",
"authors": [
"<NAME> <<EMAIL>>"
],
"description": "Js error logger for take care",
"main": "grabber.js",
"license": "MIT",
"private": true,
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"chance": "~0.5.6",
"gremlins.js": "~0.1.0",
"bowser": "~0.7.1"
}
}
|
json
|
<gh_stars>0
import { Component } from '@angular/core';
import {GameService} from '../services/game.service';
@Component({
selector: 'objectprops',
template: `
<div style="height:50%;width:100%">
Props:
<!--<button (click)="refresh()">Refresh</button>-->
<div *ngIf="gameservice.selectobject">
Object: {{gameservice.selectobject.uuid}}<button (click)="meshdelete()">Delete</button>
<br><label>px:<input type="number" ng-model='val | number: 2' [ngModel]="gameservice.selectobject.position.x" value="{{gameservice.selectobject.position.x}}" (ngModelChange)="objposx($event)" step ="0.000001" /></label>
<br><label>py:<input type="number" [ngModel]="gameservice.selectobject.position.y" value="{{gameservice.selectobject.position.y}}" (ngModelChange)="objposy($event)" step ="0.000001" /></label>
<br><label>pz:<input type="number" [ngModel]="gameservice.selectobject.position.z" value="{{gameservice.selectobject.position.z}}" (ngModelChange)="objposz($event)" step ="0.000001" /></label>
</div>
</div>
`
})
export class Objectprops {
posx = 0;
constructor(gameservice:GameService){
//console.log(gameservice);
this.gameservice = gameservice;
}
objposx(value){
console.log(value);
console.log("pos x");
if(this.gameservice.selectobject !=null){
this.gameservice.selectobject.position.x = value;
}
}
objposy(value){
console.log(value);
console.log("pos y");
if(this.gameservice.selectobject !=null){
this.gameservice.selectobject.position.y = value;
}
}
objposz(value){
console.log(value);
console.log("pos z");
if(this.gameservice.selectobject !=null){
this.gameservice.selectobject.position.z = value;
}
}
meshdelete(){
console.log("delete");
if(this.gameservice.selectobject !=null){
//this.gameservice.selectobject.dispose();
this.gameservice.scene.remove(this.gameservice.selectobject);
this.gameservice.selectobject = null;
}
}
refresh(){
//console.log("refresh");
//console.log(this.gameservice);
//console.log(this.gameservice.scene.children[0]);
}
}
|
javascript
|
Vicky Kauhsal and Sara Ali Khan's latest release 'Zara Hatke Zara Bachke' received a great opening day response and had collected Rs 5. 49 crore at the box-office.
According to reports, the film was well received by audience as well critics and had earned Rs 7. 20 crore on the second day.
As per the latest resources, the highly-anticipated movie had collected more than Rs 22 crore in the first weekend.
The family drama 'Zara Hatke Zara Bachke' is directed by Laxman Utekar , marks first on-screen collaboration of actor Vicky Kaushal and Sara Ali Khan.
According to reports, the film was made on a budget of 50 crores and it includes production costs, cast salary and advertising expenses.
Zara Hatke Zara Bachke was released on June 2, had received good responses from audience. As per latest reports, the movie would be released on the OTT platform in August 2023.
|
english
|
package eu.thesystems.cloud;
/*
* Created by derrop on 09.12.2019
*/
import org.bukkit.plugin.java.JavaPlugin;
public class CloudNet2Emulator extends JavaPlugin {
@Override
public void onEnable() {
this.getLogger().info("This plugin does nothing, except that it lets all plugins that depend on the \"CloudNetAPI\" plugin of CloudNet 2 load after the \"CloudSupport\" plugin to support CloudNet 2 plugins on CloudNet 3");
}
@Override
public void onDisable() {
}
}
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.