text stringlengths 1 1.04M | language stringclasses 25 values |
|---|---|
/* Copyright (C) 2003 <NAME>. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/cpl-v10.html
*
* $Id: ByteArrayOStream.java,v 1.1.1.1 2004/05/09 16:57:52 vlad_r Exp $
*/
package com.vladium.util;
import java.io.IOException;
import java.io.OutputStream;
import com.vladium.util.asserts.$assert;
// ----------------------------------------------------------------------------
/**
* An unsynchronized version of java.io.ByteArrayOutputStream that can expose
* the underlying byte array without a defensive clone and can also be converted
* to a {@link ByteArrayIStream} without intermediate array copies.<p>
*
* All argument validation is disabled in release mode.<p>
*
* NOTE: copy-on-write not supported
*
* @author (C) 2001, <NAME>
*/
public
final class ByteArrayOStream extends OutputStream
{
// public: ................................................................
/**
* Callee takes ownership of 'buf'.
*/
public ByteArrayOStream (final int initialCapacity)
{
if ($assert.ENABLED)
$assert.ASSERT (initialCapacity >= 0, "negative initial capacity: " + initialCapacity);
m_buf = new byte [initialCapacity];
}
public final ByteArrayIStream toByteIStream ()
{
return new ByteArrayIStream (m_buf, m_pos);
}
public final void write2 (final int b1, final int b2)
{
final int pos = m_pos;
final int capacity = pos + 2;
byte [] mbuf = m_buf;
final int mbuflen = mbuf.length;
if (mbuflen < capacity)
{
final byte [] newbuf = new byte [Math.max (mbuflen << 1, capacity)];
if (pos < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < pos; ++ i) newbuf [i] = mbuf [i];
else
System.arraycopy (mbuf, 0, newbuf, 0, pos);
m_buf = mbuf = newbuf;
}
mbuf [pos] = (byte) b1;
mbuf [pos + 1] = (byte) b2;
m_pos = capacity;
}
public final void write3 (final int b1, final int b2, final int b3)
{
final int pos = m_pos;
final int capacity = pos + 3;
byte [] mbuf = m_buf;
final int mbuflen = mbuf.length;
if (mbuflen < capacity)
{
final byte [] newbuf = new byte [Math.max (mbuflen << 1, capacity)];
if (pos < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < pos; ++ i) newbuf [i] = mbuf [i];
else
System.arraycopy (mbuf, 0, newbuf, 0, pos);
m_buf = mbuf = newbuf;
}
mbuf [pos] = (byte) b1;
mbuf [pos + 1] = (byte) b2;
mbuf [pos + 2] = (byte) b3;
m_pos = capacity;
}
public final void write4 (final int b1, final int b2, final int b3, final int b4)
{
final int pos = m_pos;
final int capacity = pos + 4;
byte [] mbuf = m_buf;
final int mbuflen = mbuf.length;
if (mbuflen < capacity)
{
final byte [] newbuf = new byte [Math.max (mbuflen << 1, capacity)];
if (pos < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < pos; ++ i) newbuf [i] = mbuf [i];
else
System.arraycopy (mbuf, 0, newbuf, 0, pos);
m_buf = mbuf = newbuf;
}
mbuf [pos] = (byte) b1;
mbuf [pos + 1] = (byte) b2;
mbuf [pos + 2] = (byte) b3;
mbuf [pos + 3] = (byte) b4;
m_pos = capacity;
}
public final void writeTo (final OutputStream out)
throws IOException
{
out.write (m_buf, 0, m_pos);
}
// public final void readFully (final InputStream in)
// throws IOException
// {
// while (true)
// {
// int chunk = in.available ();
//
// System.out.println ("available = " + chunk);
//
// // TODO: this case is handled poorly (on EOF)
// if (chunk == 0) chunk = READ_CHUNK_SIZE;
//
// // read at least 'available' bytes: extend the capacity as needed
//
// int free = m_buf.length - m_pos;
//
// final int read;
// if (free > chunk)
// {
// // try reading more than 'chunk' anyway:
// read = in.read (m_buf, m_pos, free);
// }
// else
// {
// // extend the capacity to match 'chunk':
// {
// System.out.println ("reallocation");
// final byte [] newbuf = new byte [m_pos + chunk];
//
// if (m_pos < NATIVE_COPY_THRESHOLD)
// for (int i = 0; i < m_pos; ++ i) newbuf [i] = m_buf [i];
// else
// System.arraycopy (m_buf, 0, newbuf, 0, m_pos);
//
// m_buf = newbuf;
// }
//
// read = in.read (m_buf, m_pos, chunk);
// }
//
// if (read < 0)
// break;
// else
// m_pos += read;
// }
// }
// public final void addCapacity (final int extraCapacity)
// {
// final int pos = m_pos;
// final int capacity = pos + extraCapacity;
// byte [] mbuf = m_buf;
// final int mbuflen = mbuf.length;
//
// if (mbuflen < capacity)
// {
// final byte [] newbuf = new byte [Math.max (mbuflen << 1, capacity)];
//
// if (pos < NATIVE_COPY_THRESHOLD)
// for (int i = 0; i < pos; ++ i) newbuf [i] = mbuf [i];
// else
// System.arraycopy (mbuf, 0, newbuf, 0, pos);
//
// m_buf = newbuf;
// }
// }
public final byte [] getByteArray ()
{
return m_buf;
}
/**
*
* @return [result.length = size()]
*/
public final byte [] copyByteArray ()
{
final int pos = m_pos;
final byte [] result = new byte [pos];
final byte [] mbuf = m_buf;
if (pos < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < pos; ++ i) result [i] = mbuf [i];
else
System.arraycopy (mbuf, 0, result, 0, pos);
return result;
}
public final int size ()
{
return m_pos;
}
public final int capacity ()
{
return m_buf.length;
}
/**
* Does not reduce the current capacity.
*/
public final void reset ()
{
m_pos = 0;
}
// OutputStream:
public final void write (final int b)
{
final int pos = m_pos;
final int capacity = pos + 1;
byte [] mbuf = m_buf;
final int mbuflen = mbuf.length;
if (mbuflen < capacity)
{
final byte [] newbuf = new byte [Math.max (mbuflen << 1, capacity)];
if (pos < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < pos; ++ i) newbuf [i] = mbuf [i];
else
System.arraycopy (mbuf, 0, newbuf, 0, pos);
m_buf = mbuf = newbuf;
}
mbuf [pos] = (byte) b;
m_pos = capacity;
}
public final void write (final byte [] buf, final int offset, final int length)
{
if ($assert.ENABLED)
$assert.ASSERT ((offset >= 0) && (offset <= buf.length) &&
(length >= 0) && ((offset + length) <= buf.length),
"invalid input (" + buf.length + ", " + offset + ", " + length + ")");
final int pos = m_pos;
final int capacity = pos + length;
byte [] mbuf = m_buf;
final int mbuflen = mbuf.length;
if (mbuflen < capacity)
{
final byte [] newbuf = new byte [Math.max (mbuflen << 1, capacity)];
if (pos < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < pos; ++ i) newbuf [i] = mbuf [i];
else
System.arraycopy (mbuf, 0, newbuf, 0, pos);
m_buf = mbuf = newbuf;
}
if (length < NATIVE_COPY_THRESHOLD)
for (int i = 0; i < length; ++ i) mbuf [pos + i] = buf [offset + i];
else
System.arraycopy (buf, offset, mbuf, pos, length);
m_pos = capacity;
}
/**
* Equivalent to {@link #reset()}.
*/
public final void close ()
{
reset ();
}
// protected: .............................................................
// package: ...............................................................
// private: ...............................................................
private byte [] m_buf;
private int m_pos;
// private static final int READ_CHUNK_SIZE = 16 * 1024;
private static final int NATIVE_COPY_THRESHOLD = 9;
} // end of class
// ---------------------------------------------------------------------------- | java |
Laal Singh Chaddha, starring Aamir Khan and Kareena Kapoor Khan, will be their third collaboration together.
Laal Singh Chaddha is a Hindi remake of Robert Zemeckis' classic Forrest Gump, which starred Tom Hanks in the lead role.
Aamir Khan suffered a rib injury while filming Laal Singh Chaddha, but he didn't stop the action.
Some fans were utterly enamoured with Aamir Khan's work after hearing the movie's songs.
On his 54th birthday, Aamir Khan released the poster of Laal Singh Chaddha. | english |
{"nom":"Eschbourg","circ":"7ème circonscription","dpt":"Bas-Rhin","inscrits":381,"abs":173,"votants":208,"blancs":10,"nuls":7,"exp":191,"res":[{"nuance":"LR","nom":"<NAME>","voix":115},{"nuance":"REM","nom":"<NAME>","voix":76}]} | json |
import numpy as np
from math import ceil
from scipy.stats import norm
from TaPR import compute_precision_recall
from data_loader import _count_anomaly_segments
n_thresholds = 1000
def _simulate_thresholds(rec_errors, n, verbose):
# maximum value of the anomaly score for all time steps in the test data
thresholds, step_size = [], abs(np.max(rec_errors) - np.min(rec_errors)) / n
th = np.min(rec_errors)
if verbose:
print(f'Threshold Range: ({np.max(rec_errors)}, {np.min(rec_errors)}) with Step Size: {step_size}')
for i in range(n):
thresholds.append(float(th))
th = th + step_size
return thresholds
def _flatten_anomaly_scores(values, stride, flatten=False):
flat_seq = []
if flatten:
for i, x in enumerate(values):
if i == len(values) - 1:
flat_seq = flat_seq + list(np.ravel(x).astype(float))
else:
flat_seq = flat_seq + list(np.ravel(x[:stride]).astype(float))
else:
flat_seq = list(np.ravel(values).astype(float))
return flat_seq
def compute_anomaly_scores(x, rec_x, scoring='square', x_val=None, rec_val=None):
# average anomaly scores from different sensors/channels/metrics/variables (in case of multivariate time series)
if scoring == 'absolute':
return np.mean(np.abs(x - rec_x), axis=-1)
elif scoring == 'square':
return np.mean(np.square(x - rec_x), axis=-1)
elif scoring == 'normal':
if x_val is not None and rec_val is not None:
val_rec_err = x_val - rec_val
test_rec_err = x - rec_x
mu, std = norm.fit(val_rec_err)
return (test_rec_err - mu).T * std ** -1 * (test_rec_err - mu)
def compute_metrics(anomaly_scores, labels, label_segments=None, n=n_thresholds, delta=0.01, alpha=0.5, theta=0.5, stride=1, verbose=False):
if label_segments is None:
label_segments = []
thresholds = _simulate_thresholds(anomaly_scores, n, verbose)
correct_count, correct_ratio = [], []
precision, recall, f1 = [], [], []
flat_seq = _flatten_anomaly_scores(anomaly_scores, stride, flatten=len(anomaly_scores.shape) == 2)
print('here1', len(thresholds))
for th in thresholds:
pred_anomalies = np.zeros(len(flat_seq)).astype(int) # default with no anomaly
pred_anomalies[np.where(np.array(flat_seq) > th)[0]] = 1 # assign 1 if scores > threshold
_, pred_segments = _count_anomaly_segments(pred_anomalies)
if len(labels) != len(pred_anomalies):
print(f'evaluating with unmatch shape: Labels: {len(labels)} vs. Preds: {len(pred_anomalies)}')
labels = labels[-len(pred_anomalies):] # ref. OmniAnomaly
print(f'evaluating with unmatch shape: Labels: {len(labels)} vs. Preds: {len(pred_anomalies)}')
anomaly_lengths = []
for seg in label_segments:
anomaly_lengths.append(len(seg))
TaD = 0 if len(anomaly_lengths) == 0 else np.ceil(np.mean(anomaly_lengths) * delta).astype(int)
TaP, TaR = compute_precision_recall(pred_anomalies, labels, theta=theta, delta=TaD, alpha=alpha, verbose=verbose)
count, ratio = compute_accuracy(pred_segments, label_segments, delta)
precision.append(float(TaP))
recall.append(float(TaR))
f1.append(float(2 * (TaP * TaR) / (TaP + TaR + 1e-7)))
correct_count.append(int(count))
correct_ratio.append(float(ratio))
return {
'precision': np.mean(precision),
'recall': np.mean(recall),
'f1': np.max(f1),
'count': correct_count,
'ratio': correct_ratio,
'thresholds': thresholds,
'anomaly_scores': flat_seq
}
def visualization(anomaly_scores, x_test, labels):
# TODO: visualize original data + label and anomaly_scores side-by-side
return
def compute_accuracy(pred_segments, anomaly_segments, delta):
correct = 0
for seg in anomaly_segments:
L = seg[-1] - seg[0] # length of anomaly
d = ceil(L * delta)
for pred in pred_segments:
P = pred[len(pred) // 2] # center location as an integer
if min([seg[0] - L, seg[0] - d]) < P < max([seg[-1] + L, seg[-1] + d]):
correct = correct + 1
break
return correct, correct / (len(anomaly_segments) + 1e-7)
| python |
<filename>DataStructures/src/streams/DS_Stream.cpp
#include "CommonTypeDefines.h"
#include "streams/DS_FileStream.h"
#include "fileUtils/_fileExists.h"
#include <algorithm>
using std::min;
namespace DataStructures
{
//------------------------------------------------------------------- Stream ------------------------------------------------------------------------
#if __WORDSIZE == 64
template <>
size_t Stream::Write(const unsigned int &buffer)
{
if (mForce32bitCompatable)
{
__u32 val = buffer;
return this->Write(&val, sizeof(__u32));
}
else
return this->Write(&buffer, sizeof(unsigned int));
}
template <>
size_t Stream::Write(const int &buffer)
{
if (mForce32bitCompatable)
{
__s32 val = buffer;
return this->Write(&val, sizeof(__s32));
}
else
return this->Write(&buffer, sizeof(int));
}
template <>
size_t Stream::Write(const unsigned long &buffer)
{
if (mForce32bitCompatable)
{
__u32 val = buffer;
return this->Write(&val, sizeof(__u32));
}
else
return this->Write(&buffer, sizeof(unsigned long));
}
template <>
size_t Stream::Write(const long &buffer)
{
if (mForce32bitCompatable)
{
__s32 val = buffer;
return this->Write(&val, sizeof(__s32));
}
else
return this->Write(&buffer, sizeof(long));
}
template <>
bool Stream::Read(unsigned int &dst)
{
if (mForce32bitCompatable)
{
__u32 t;
bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(unsigned int)) == sizeof(unsigned int);
}
template <>
bool Stream::Read(int &dst)
{
if (mForce32bitCompatable)
{
__s32 t;
bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(int)) == sizeof(int);
}
template <>
bool Stream::Read(unsigned long &dst)
{
if (mForce32bitCompatable)
{
__u32 t;
bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(unsigned long)) == sizeof(unsigned long);
}
template <>
bool Stream::Read(long &dst)
{
if (mForce32bitCompatable)
{
__s32 t;
bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(long)) == sizeof(long);
}
#endif
size_t Stream::WriteString(const char *buffer, size_t maxsize)
{
if (!CanWrite())
return 0;
__u16 size = min(strlen(buffer), maxsize + sizeof(__u16));
size_t actSize = this->Write(&size, sizeof(size));
actSize += this->Write(buffer, size);
return actSize;
}
size_t Stream::ReadString(char *dst, size_t maxsize)
{
if (Eof() || !dst || !CanRead())
return 0;
__u16 size;
size_t readIn = this->Read(&size, sizeof(size));
readIn += this->Read(dst, min((size_t)size, maxsize));
dst[size] = 0;
return readIn;
}
size_t Stream::CopyFrom(Stream *stream, size_t count)
{
const size_t _max_buffer_size = 0xf0000;
size_t size = count;
if (count == 0)
{
stream->Seek(0, SEEK_SET);
size = stream->Length();
}
size_t result = size;
size_t bufferSize;
if (size > _max_buffer_size)
bufferSize = _max_buffer_size;
else
bufferSize = size;
char *buffer = (char *)malloc(bufferSize);
size_t n;
while (size != 0)
{
if (size > bufferSize)
n = bufferSize;
else
n = size;
stream->Read(buffer, n);
Write(buffer, n);
size -= n;
}
free(buffer);
return result;
}
bool Stream::SaveToStream(Stream *stream)
{
if (!stream)
return false;
__s64 oldPos = Position();
__s64 oldPos1 = stream->Position();
bool res = stream->CopyFrom(this, 0) == Length();
Seek(oldPos, SEEK_SET);
stream->Seek(oldPos1, SEEK_SET);
return res;
}
bool Stream::LoadFromStream(Stream *stream)
{
if (!stream)
return false;
__s64 oldPos = Position();
__s64 oldPos1 = stream->Position();
size_t size = stream->Length();
SetLength(size);
Seek(0, SEEK_SET);
bool res = CopyFrom(stream, 0) == size;
Seek(oldPos, SEEK_SET);
stream->Seek(oldPos1, SEEK_SET);
return res;
}
bool Stream::SaveToFile(const char *fileName)
{
FileStream *stream = new FileStream(fileName, "wb+");
bool result = SaveToStream(stream);
stream->Close();
delete stream;
return result;
}
bool Stream::LoadFromFile(const char *fileName)
{
if (!_fileExists(fileName))
return false;
FileStream *stream = new FileStream(fileName, "rb");
bool result = LoadFromStream(stream);
stream->Close();
delete stream;
return result;
}
__s64 Stream::Length()
{
__s64 oldPos = Seek(0, SEEK_CUR);
__s64 length = Seek(0, SEEK_END);
Seek(oldPos, SEEK_SET);
return length;
}
__s64 Stream::Position()
{
return Seek(0, SEEK_CUR);
}
char *Stream::ReadLine(char *str, int num)
{
if (num <= 0)
return NULL;
char c = 0;
size_t maxCharsToRead = num - 1;
for (size_t i = 0; i < maxCharsToRead; ++i)
{
size_t result = Read(&c, 1);
if (result != 1)
{
str[i] = '\0';
break;
}
if (c == '\n')
{
str[i] = c;
str[i + 1] = '\0';
break;
}
else if(c == '\r')
{
str[i] = c;
// next may be '\n'
size_t pos = Position();
char nextChar = 0;
if (Read(&nextChar, 1) != 1)
{
// no more characters
str[i + 1] = '\0';
break;
}
if (nextChar == '\n')
{
if (i == maxCharsToRead - 1)
{
str[i + 1] = '\0';
break;
}
else
{
str[i + 1] = nextChar;
str[i + 2] = '\0';
break;
}
}
else
{
Seek(pos, SEEK_SET);
str[i + 1] = '\0';
break;
}
}
str[i] = c;
}
return str; // what if first read failed?
}
bool Stream::Eof()
{
return Position() >= Length();
}
bool Stream::Rewind()
{
if (!CanSeek())
return 0;
else
return Seek(0, SEEK_SET) == 0;
}
std::string Stream::GetAsString()
{
char *buffer;
__s64 fileLen = Length();
__s64 oldPosition = Position();
buffer = (char *)malloc(fileLen + 1);
Seek(0, SEEK_SET);
Read(buffer, fileLen);
Seek(oldPosition, SEEK_SET);
buffer[fileLen] = 0;
std::string result(buffer);
free(buffer);
return result;
}
__u32 Stream::GetMemoryCost()
{
//this value is not very accurate because of class HexString's cache using
return static_cast<__u32>(sizeof(*this) + strlen(mFileName));
}
} | cpp |
<reponame>asdqwe12011/Medical-Datasets-Classification<filename>code/Dist.py
import numpy as np
euclidean = lambda x1, x2: np.sqrt(np.sum((x1 - x2) ** 2, axis=-1))
manhattan = lambda x1, x2: np.sum(np.abs(x1 - x2), axis=-1)
| python |
<reponame>joiellantero/codeforasia-scheduler
{% extends 'scheduler/base.html' %}
{% block header %}
<h1 class="title has-text-centered mt-6">Login</h1>
{% endblock %}
{% block body %}
<div class="container login">
{% if form.errors %}
<div class="notification is-danger">
<button class="delete"></button>
<strong>Oh snap!</strong> <br>
Invalid Credentials!
</div>
{% endif %}
<div class="card">
<div class="card-body">
<form action="" method="post">
{% csrf_token %}
<div class="field mb-4">
<label for="username" class="mb-0">{{ form.username.label }}</label>
{{ form.username }}
<p class="help text-danger">{{ form.username.errors }}</p>
</div>
<div class="field">
<label for="password" class="mb-0">{{ form.password.label }}</label>
{{ form.password }}
<p class="help text-danger">{{ form.password.errors }}</p>
</div>
<div class="field my-4">
<input type="checkbox" class="is-checkradio is-small is-info" id="rememberme" name="remember_me">
<label class="form-check-label" for="rememberme">Remember me</label><br>
</div>
<button type="submit" class="button is-info is-fullwidth my-4">Login</button>
</form>
</div>
<p class="has-text-centered is-small">Don't have an account? Signup <a href="{% url 'scheduler-signup' %}">here.</a></p>
</div>
</div>
{% endblock %} | html |
/* special css for amafatt */
.yellow {
color: #FBF462 !important;
}
.preservewhitespace {
white-space: pre-wrap;
}
/* html elements by name because is easier to change css then tho compile rust code */
#reqbody {
height: 450px;
}
#respbody {
height: 450px;
} | css |
module.exports = function(data, helper) {
data = data || {};
helper = helper || {};
var __t;
var __p = '';
var __j = Array.prototype.join;
var print = function() {
__p += __j.call(arguments, '');
};
return (function(name) {
__p += '<div class="node-label">' +
((__t = (name)) == null ? '' : __t) +
'</div>\n';;
return __p;
})(data.name);
}; | javascript |
<filename>DataSources/raw/zeronet/1BLogC9LN4oPDcruNz3qo1ysa133E9AGg8/data/users/1KSgrKLRS1Y47h77wAqs2NwoQbNuX6ttrJ/content.json
{
"address": "1BLogC9LN4oPDcruNz3qo1ysa133E9AGg8",
"cert_auth_type": "web",
"cert_sign": "<KEY>
"cert_user_id": "<EMAIL>",
"files": {
"data.json": {
"sha512": "7a7c2acb049bffea078a7f9498a0aedd3efeafe0e989d273e62a3b1920c3dfb5",
"size": 92
}
},
"inner_path": "data/users/1KSgrKLRS1Y47h77wAqs2NwoQbNuX6ttrJ/content.json",
"modified": 1469940805.925,
"signs": {
"<KEY>": "<KEY>
}
} | json |
<reponame>lukaschoebel/bed
#!/usr/bin/python
import time
import random
import RPi.GPIO as GPIO
import firebase_admin
from firebase_admin import credentials, firestore
cred = credentials.Certificate("secrets/firestore-creds.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# reference to the firestore document
doc_ref = db.collection(u'current_measure').document(u'0')
count = 0
prev_inp = 1
def random_number(infested):
"""
This function mocks the functionality of the detection.
If tree is infested, generate number between 50-100.
If tree is not infested, generate number between 0-50.
Args:
infested (bool): [description]
"""
if infested:
return random.randint(51, 100)
return random.randint(0, 50)
def trigger_detection(PIN_NO):
"""
On button press, trigger the send process of the message.
Args:
PIN_NO (int): Pin number on raspi zero board
"""
global prev_inp
global count
t1 = time.time()
inp = GPIO.input(PIN_NO)
duration = time.time() - t1
if ((not prev_inp) and inp):
count = count + 1
print("Button pressed")
print(round(duration, 2))
if duration > 0.8:
print("befallen")
else:
print("cool")
print(count)
# only update degree of infestiation and duration
doc_ref.update({
u'duration': 5,
u'infestation': random_number(infested=True),
u'status': u'completed'
})
prev_inp = inp
time.sleep(0.05)
@DeprecationWarning
if __name__ == "__main__":
print("+++ borki initialized +++")
try:
while True:
trigger_detection(18)
except KeyboardInterrupt:
GPIO.cleanup()
| python |
Wednesday September 16, 2015,
There are so many startups today who want to position themselves as the equivalent of companies like Uber or AirBnB in completely different sectors. Cross-industry innovation is on the rise as never before, thanks to the global growth of entrepreneurship, deeper understanding of innovation processes, and the ready availability of online resources for innovators.
What can a restaurant learn from an airport, a car manufacturer from the games industry, a hospital from a hotel or theme park, or a chemical company from a festival organiser? A wide range of tips and case studies for such cross-industry innovation are offered in the new book ‘Not Invented Here,’ by Ramon Vullings and Marc Heleven of innovation consultancy 21 Lobsterstreet.
The compact 224-page book is designed almost like a cookbook, with plenty of photographs, illustrations and checklists on how innovators can frame contexts, unpack insights from other industries and transfer them to their own companies. See also my book reviews of ‘Peers Inc.’ (Robin Chase), ‘Four Lenses of Innovation’ (Rowan Gibson), ‘Innovators’ DNA’ (Clayton Christensen), and ‘Steal Like an Artist’ (Austin Kleon).
“Cross-industry innovation is the commitment we make to the process of asking questions, combining elements, finding patterns and testing concepts,” the authors begin.
Here are my four key sets of takeaways and tips from the book, on how to effectively see and use analogies from other industries. There is also an online companion for effective ‘conceptualise-combine-create’ techniques with interactive tools, maps and examples.
“You need to go through craziness to be able to jump out of the limiting box of best practices to enter the world of next practices,” the authors explain. A huge pool of case studies has been gathered on cross-industry innovation. The key is to go beyond ‘copy and paste’ to ‘adapt and paste,’ via enrichment, customisation, modification, blending and fusion.
BMW’s iDrive system is inspired by a video console. Nike Shox shoes draw on the springiness of shock absorbers from Formula One racing, and the Waffle shoe was inspired by the waffle iron of Founder Bill Bowerman’s wife. The Worx automatic screwdriver is shaped like a revolver where drill bits can be loaded like bullets.
Doug Dietz of GE Healthcare redesigned CT scan rooms like game parks to make them less scary for children. Sushi restaurants use airport-style conveyor belts to provide diners a wide range of fresh dishes.
KLM borrowed social media concepts for its ‘Meet and Seat’ facility to let passengers choose their flight companions. The NeoNurture affordable incubator in Indonesia is designed from car parts.
Nature itself offers innovation models for industry. Japan’s high-speed train engines are designed to look like a kingfisher beak. Velcro design is based on seeds of plants that cling to animal fur. Speedo Fastskin swimsuits mimic a shark’s skin.
Sectors that have fertilised other segments with concepts, practices and metaphors include airlines (foldable prams, hub, payloads, frequent flyer miles, parachute, safety check, double check), aerospace (capsules, satellites, aliens, launchpads, lift-off, touchdown), military (boot camp, commando teams, laser focus, drills), Formula One (pit stop, dashboard), and fashion (catwalk, connected clothing, fashion wearables, fast fashion, fashion statement).
However, there are a wide range of obstacles, mental blocks and attitudes which prevent people from learning from other industries, as identified by the authors. Our customers won’t accept it. We are not Apple. We have our own R&D department. We can’t change the rules. That won’t work here.
Successful innovators constantly change things by asking questions like why, what if, and how as they frame their offerings and their companies. Innovative companies have a culture of inquiry, of asking deep and powerful questions. Setting an innovation challenge is a good way to get started and focused.
Looking “sideways” helps see how others have solve related problems or components of problems – which can include products, services and even internal processes. Company visits, international travel, science fiction, history, patent databases, crowd platforms, curated sites, social media and hackathons are some good sources of outside ideas.
The authors offer a useful visioning exercise: WWXD (‘what would X do’ in your company, eg. Steve Jobs, Google, AliBaba, NetFlix, Zara). Lego is a good company to study for its modular and compatible approach to products, processes, channels and brands. Apple Stores offer good lessons in design, multi-sensory experiences and sales staff diversity. IKEA stands out for its products which can be easily transported and assembled, management style by ‘walking around,’ and naming conventions.
Companies which strongly focus on customer interaction and business value will migrate across the full value chain: commodities, products, services, solutions, experience and engagement. Growth leaps come from techniques such as simplification, digital channels (eg. e-commerce, IoT), higher level positioning, and effective business models (eg sharing economy, green economy).
Based on cross-industry research, the authors offer a practical checklist of 21 innovation principles for companies to adopt and operationalise, eg. hybridisation, transparency, P2P, co-branding, frugality, storytelling, community building, DIY, crowdsourcing and bio-mimicry.
Once the applicable innovation patterns from other industries have been indentified, they can be used to transform a company in a number of ways: finding shortcuts, reducing complexity, changing rules, removing some elements, cutting prices, flipping to opposite positions, vaulting to previously impossible levels, and blending business models.
‘Shortcut’ principles are exemplified in price comparison sites, P2P lending and crowdfunding. Companies like Tesla are ‘challenging the rules’ of the car industry. ‘Removing some elements’ is shown by Cirque du Soleil (circus with no animals). Examples of ‘doing the opposite’ are reverse graffiti (selectively removing dirt from a surface, instead of adding new material).
In all, there are around 55 business model patterns that companies can experiment with, as identified by researchers at the University of St. Gallen (see PDF). They include add-on, crowdsourcing, fractional ownership, freemium, hidden revenue, ingredient branding, layer player, orchestrator, pay per use and trash-to-cash.
Overall, the book is a practical yet delightful exploration of cross-industry innovation, with lots of insights and humour blended in, eg. why can you easily test-drive a car – yet not test-sleep a house you want to buy; why can’t road tarmacs be designed as solar panels.
The authors also offer a number of creative word games to trigger out-of-the-box thinking, eg. synonyms for service or reduction; terms for combinations (dual, hybrid, smart, mixed); prefixes for experience (emotional, retro), dimensions (nano, pocket, flexible), and sustainability (eco, fair).
The authors also identify some disappearing objects (eg. fax machines, answering machines, pagers, subway tokens) and disappearing jobs (typist, meter reader) – as well as emerging jobs, eg. garbage designer, nostalgist, gamification designer, ideaDJ!
“It’s time to disrupt your industry or maybe even better – disrupt another industry,” the authors provocatively conclude.
| english |
Will Seth Rollins Defend His Title on August 14, 2023, Episode of WWE Raw?
Seth Rollins isn’t scheduled to defend his title on the August 14, 2023, episode of Monday Night Raw. However, he might defend his championship in the episode.
Previously, on WWE Raw last week, Seth Rollins, Cody Rhodes, and Sami Zayn were all set to face The Judgment Day (Dominik Mysterio, Damian Priest, and Finn Balor) in a tag team match. However, during the episode, JD McDonagh attacked Sami Zayn causing him to drop out of the scheduled match. Shinsuke Nakamura then replaced Zayn in the Six Man Tag Team Match.
In the main event of Monday Night Raw, Seth Rollins, Shinsuke Nakamura, and Cody Rhodes successfully defeated The Judgment Day. However, as they were celebrating their win, Shinsuke Nakamura nailed a Kinshasa to Rollins and walked away.
With that, now on WWE Raw this week, Nakamura is all set to appear and explain the cause of his actions. There’s a possibility that Nakamura might challenge Rollins to a title match or Rollins might attack Nakamura during the segment, ultimately leading to a match between the two. Thus, though Seth Rollins doesn’t have a match scheduled on the upcoming episode of Raw, he might defend his title against Shinsuke Nakamura on August 14, 2023.
| english |
{
"author": {
"id": "t2_ccdto",
"name": "FastSniperfox"
},
"date": {
"day": 1496275200,
"full": 1496328378,
"month": 1496275200,
"week": 1495929600
},
"id": "t3_6en71n",
"misc": {
"postHint": "link"
},
"picture": {
"filesize": 92212,
"fullUrl": "https://external-preview.redd.it/Nvn6P_BtV5jevTSvKXHOAD2Vr3-BtSqtGCQQCTW8NmQ.jpg?auto=webp&s=a95302f26161eeddcdcfa532cf68f0b158b65e37",
"hash": "7a0c6a9691",
"height": 409,
"lqip": "data:image/jpg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAKABADASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAABgEE/8QAIhAAAgEDBAIDAAAAAAAAAAAAAQIDERIhAAQFMRMUIkJR/8QAFQEBAQAAAAAAAAAAAAAAAAAABAX/xAAYEQACAwAAAAAAAAAAAAAAAAAAAQIRQf/aAAwDAQACEQMRAD8ARy+7JycyHcmJ0N4UMxLKaVKg4IAPXers9zLKyCKXzWuEJB+Xf2BP5nSHkUVg1yqba0qOtY+GRTvLiq3YzTOpLlgij//Z",
"thumbnailUrl": "https://b.thumbs.redditmedia.com/3S_-e5ezsD6Q0P-JeseW2NZMvDZY5pdWxqBxrzSD-ww.jpg",
"url": "https://external-preview.redd.it/Nvn6P_BtV5jevTSvKXHOAD2Vr3-BtSqtGCQQCTW8NmQ.jpg?width=640&crop=smart&auto=webp&s=765c75e5ec012a857ea7ae45679ec0a9011662c7",
"width": 640
},
"score": {
"comments": 6,
"downs": 0,
"isCurated": false,
"ratio": 0.98,
"ups": 48,
"value": 48
},
"subreddit": {
"id": "t5_3isai",
"name": "dndmaps"
},
"tags": ["Region"],
"title": "A blank fantasy map for your use!",
"url": "https://www.reddit.com/r/dndmaps/comments/6en71n/a_blank_fantasy_map_for_your_use/"
}
| json |
{
"templates": {
"repository": "lowcodeunit-devkit/lcu-cli-templates-core",
"scope": "@lcu",
"workspace": "reference-architecture"
}
}
| json |
<filename>package.json
{
"name": "simple-blockchain-service",
"private": false,
"version": "0.1.0",
"description": "Web Service of Simple Private Blockchain | Project @ Udacity's Blockchain Developer Nanodegree",
"keywords": [],
"dependencies": {
"@sailshq/lodash": "^3.10.3",
"async": "2.0.1",
"crypto-js": "^3.1.9-1",
"level": "^4.0.0",
"sails": "^1.0.2",
"sails-hook-orm": "^2.0.0-16",
"sails-hook-sockets": "^1.4.0"
},
"devDependencies": {
"@sailshq/eslint": "^4.19.3"
},
"scripts": {
"start": "NODE_ENV=production node app.js",
"test": "npm run lint && npm run custom-tests && echo 'Done.'",
"lint": "eslint . --max-warnings=0 --report-unused-disable-directives && echo '✔ Your .js files look good.'",
"custom-tests": "echo \"(No other custom tests yet.)\" && echo"
},
"main": "app.js",
"repository": {
"type": "git",
"url": "git://github.com/nlknguyen/simple-blockchain-service.git"
},
"author": "<NAME>",
"license": "MIT",
"engines": {
"node": ">=10.10"
}
}
| json |
{"word":"bog","definition":"1. A quagmire filled with decayed moss and other vegetable matter; wet spongy ground where a heavy body is apt to sink; a marsh; a morass. Appalled with thoughts of bog, or caverned pit, Of treacherous earth, subsiding where they tread. <NAME>. 2. A little elevated spot or clump of earth, roots, and grass, in a marsh or swamp. [Local, U. S.] Bog bean. See Buck bean. -- Bog bumper (bump, to make a loud noise), Bog blitter, Bog bluiter, Bog jumper, the bittern. [Prov.] -- Bog butter, a hydrocarbon of butterlike consistence found in the peat bogs of Ireland. -- Bog earth (Min.), a soil composed for the most part of silex and partially decomposed vegetable fiber. P. Cyc. -- Bog moss. (Bot.) Same as Sphagnum. -- Bog myrtle (Bot.), the sweet gale. -- Bog ore. (Min.) (a) An ore of iron found in boggy or swampy land; a variety of brown iron ore, or limonite. (b) Bog manganese, the hydrated peroxide of manganese. -- Bog rush (Bot.), any rush growing in bogs; saw grass. -- Bog spavin. See under Spavin.\n\nTo sink, as into a bog; to submerge in a bog; to cause to sink and stick, as in mud and mire. At another time, he was bogged up to the middle in the slough of Lochend. Sir <NAME>."} | json |
/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionCommandUIInfo.h"
#include "MissionController.h"
#include "MultiVehicleManager.h"
#include "MissionManager.h"
#include "FlightPathSegment.h"
#include "FirmwarePlugin.h"
#include "QGCApplication.h"
#include "SimpleMissionItem.h"
#include "SurveyComplexItem.h"
#include "FixedWingLandingComplexItem.h"
#include "VTOLLandingComplexItem.h"
#include "StructureScanComplexItem.h"
#include "CorridorScanComplexItem.h"
#include "JsonHelper.h"
#include "ParameterManager.h"
#include "QGroundControlQmlGlobal.h"
#include "SettingsManager.h"
#include "AppSettings.h"
#include "MissionSettingsItem.h"
#include "QGCQGeoCoordinate.h"
#include "PlanMasterController.h"
#include "KMLPlanDomDocument.h"
#include "QGCCorePlugin.h"
#include "TakeoffMissionItem.h"
#include "PlanViewSettings.h"
#define UPDATE_TIMEOUT 5000 ///< How often we check for bounding box changes
QGC_LOGGING_CATEGORY(MissionControllerLog, "MissionControllerLog")
const char* MissionController::_settingsGroup = "MissionController";
const char* MissionController::_jsonFileTypeValue = "Mission";
const char* MissionController::_jsonItemsKey = "items";
const char* MissionController::_jsonPlannedHomePositionKey = "plannedHomePosition";
const char* MissionController::_jsonFirmwareTypeKey = "firmwareType";
const char* MissionController::_jsonVehicleTypeKey = "vehicleType";
const char* MissionController::_jsonCruiseSpeedKey = "cruiseSpeed";
const char* MissionController::_jsonHoverSpeedKey = "hoverSpeed";
const char* MissionController::_jsonParamsKey = "params";
const char* MissionController::_jsonGlobalPlanAltitudeModeKey = "globalPlanAltitudeMode";
// Deprecated V1 format keys
const char* MissionController::_jsonComplexItemsKey = "complexItems";
const char* MissionController::_jsonMavAutopilotKey = "MAV_AUTOPILOT";
const int MissionController::_missionFileVersion = 2;
MissionController::MissionController(PlanMasterController* masterController, QObject *parent)
: PlanElementController (masterController, parent)
, _controllerVehicle (masterController->controllerVehicle())
, _managerVehicle (masterController->managerVehicle())
, _missionManager (masterController->managerVehicle()->missionManager())
, _visualItems (new QmlObjectListModel(this))
, _planViewSettings (qgcApp()->toolbox()->settingsManager()->planViewSettings())
, _appSettings (qgcApp()->toolbox()->settingsManager()->appSettings())
{
_resetMissionFlightStatus();
_updateTimer.setSingleShot(true);
connect(&_updateTimer, &QTimer::timeout, this, &MissionController::_updateTimeout);
connect(_planViewSettings->takeoffItemNotRequired(), &Fact::rawValueChanged, this, &MissionController::_takeoffItemNotRequiredChanged);
connect(this, &MissionController::missionDistanceChanged, this, &MissionController::recalcTerrainProfile);
// The follow is used to compress multiple recalc calls in a row to into a single call.
connect(this, &MissionController::_recalcMissionFlightStatusSignal, this, &MissionController::_recalcMissionFlightStatus, Qt::QueuedConnection);
connect(this, &MissionController::_recalcFlightPathSegmentsSignal, this, &MissionController::_recalcFlightPathSegments, Qt::QueuedConnection);
qgcApp()->addCompressedSignal(QMetaMethod::fromSignal(&MissionController::_recalcMissionFlightStatusSignal));
qgcApp()->addCompressedSignal(QMetaMethod::fromSignal(&MissionController::_recalcFlightPathSegmentsSignal));
qgcApp()->addCompressedSignal(QMetaMethod::fromSignal(&MissionController::recalcTerrainProfile));
}
MissionController::~MissionController()
{
}
void MissionController::_resetMissionFlightStatus(void)
{
_missionFlightStatus.totalDistance = 0.0;
_missionFlightStatus.maxTelemetryDistance = 0.0;
_missionFlightStatus.totalTime = 0.0;
_missionFlightStatus.hoverTime = 0.0;
_missionFlightStatus.cruiseTime = 0.0;
_missionFlightStatus.hoverDistance = 0.0;
_missionFlightStatus.cruiseDistance = 0.0;
_missionFlightStatus.cruiseSpeed = _controllerVehicle->defaultCruiseSpeed();
_missionFlightStatus.hoverSpeed = _controllerVehicle->defaultHoverSpeed();
_missionFlightStatus.vehicleSpeed = _controllerVehicle->multiRotor() || _managerVehicle->vtol() ? _missionFlightStatus.hoverSpeed : _missionFlightStatus.cruiseSpeed;
_missionFlightStatus.vehicleYaw = qQNaN();
_missionFlightStatus.gimbalYaw = qQNaN();
_missionFlightStatus.gimbalPitch = qQNaN();
_missionFlightStatus.mAhBattery = 0;
_missionFlightStatus.hoverAmps = 0;
_missionFlightStatus.cruiseAmps = 0;
_missionFlightStatus.ampMinutesAvailable = 0;
_missionFlightStatus.hoverAmpsTotal = 0;
_missionFlightStatus.cruiseAmpsTotal = 0;
_missionFlightStatus.batteryChangePoint = -1;
_missionFlightStatus.batteriesRequired = -1;
_missionFlightStatus.vtolMode = _missionContainsVTOLTakeoff ? QGCMAVLink::VehicleClassMultiRotor : QGCMAVLink::VehicleClassFixedWing;
_controllerVehicle->firmwarePlugin()->batteryConsumptionData(_controllerVehicle, _missionFlightStatus.mAhBattery, _missionFlightStatus.hoverAmps, _missionFlightStatus.cruiseAmps);
if (_missionFlightStatus.mAhBattery != 0) {
double batteryPercentRemainingAnnounce = qgcApp()->toolbox()->settingsManager()->appSettings()->batteryPercentRemainingAnnounce()->rawValue().toDouble();
_missionFlightStatus.ampMinutesAvailable = static_cast<double>(_missionFlightStatus.mAhBattery) / 1000.0 * 60.0 * ((100.0 - batteryPercentRemainingAnnounce) / 100.0);
}
emit missionDistanceChanged(_missionFlightStatus.totalDistance);
emit missionTimeChanged();
emit missionHoverDistanceChanged(_missionFlightStatus.hoverDistance);
emit missionCruiseDistanceChanged(_missionFlightStatus.cruiseDistance);
emit missionHoverTimeChanged();
emit missionCruiseTimeChanged();
emit missionMaxTelemetryChanged(_missionFlightStatus.maxTelemetryDistance);
emit batteryChangePointChanged(_missionFlightStatus.batteryChangePoint);
emit batteriesRequiredChanged(_missionFlightStatus.batteriesRequired);
}
void MissionController::start(bool flyView)
{
qCDebug(MissionControllerLog) << "start flyView" << flyView;
_managerVehicleChanged(_managerVehicle);
connect(_masterController, &PlanMasterController::managerVehicleChanged, this, &MissionController::_managerVehicleChanged);
PlanElementController::start(flyView);
_init();
}
void MissionController::_init(void)
{
// We start with an empty mission
_addMissionSettings(_visualItems);
_initAllVisualItems();
}
// Called when new mission items have completed downloading from Vehicle
void MissionController::_newMissionItemsAvailableFromVehicle(bool removeAllRequested)
{
qCDebug(MissionControllerLog) << "_newMissionItemsAvailableFromVehicle flyView:count" << _flyView << _missionManager->missionItems().count();
// Fly view always reloads on _loadComplete
// Plan view only reloads if:
// - Load was specifically requested
// - There is no current Plan
if (_flyView || removeAllRequested || _itemsRequested || isEmpty()) {
// Fly Mode (accept if):
// - Always accepts new items from the vehicle so Fly view is kept up to date
// Edit Mode (accept if):
// - Remove all was requested from Fly view (clear mission on flight end)
// - A load from vehicle was manually requested
// - The initial automatic load from a vehicle completed and the current editor is empty
_deinitAllVisualItems();
_visualItems->deleteLater();
_visualItems = nullptr;
_settingsItem = nullptr;
_takeoffMissionItem = nullptr;
_updateContainsItems(); // This will clear containsItems which will be set again below. This will re-pop Start Mission confirmation.
QmlObjectListModel* newControllerMissionItems = new QmlObjectListModel(this);
const QList<MissionItem*>& newMissionItems = _missionManager->missionItems();
qCDebug(MissionControllerLog) << "loading from vehicle: count"<< newMissionItems.count();
_missionItemCount = newMissionItems.count();
emit missionItemCountChanged(_missionItemCount);
MissionSettingsItem* settingsItem = _addMissionSettings(newControllerMissionItems);
int i=0;
if (_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle() && newMissionItems.count() != 0) {
// First item is fake home position
MissionItem* fakeHomeItem = newMissionItems[0];
if (fakeHomeItem->coordinate().latitude() != 0 || fakeHomeItem->coordinate().longitude() != 0) {
settingsItem->setInitialHomePosition(fakeHomeItem->coordinate());
}
i = 1;
}
for (; i < newMissionItems.count(); i++) {
const MissionItem* missionItem = newMissionItems[i];
SimpleMissionItem* simpleItem = new SimpleMissionItem(_masterController, _flyView, *missionItem, this);
if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(simpleItem->command()))) {
// This needs to be a TakeoffMissionItem
_takeoffMissionItem = new TakeoffMissionItem(*missionItem, _masterController, _flyView, settingsItem, this);
simpleItem->deleteLater();
simpleItem = _takeoffMissionItem;
}
newControllerMissionItems->append(simpleItem);
}
_visualItems = newControllerMissionItems;
_settingsItem = settingsItem;
MissionController::_scanForAdditionalSettings(_visualItems, _masterController);
_initAllVisualItems();
_updateContainsItems();
emit newItemsFromVehicle();
}
_itemsRequested = false;
}
void MissionController::loadFromVehicle(void)
{
if (_masterController->offline()) {
qCWarning(MissionControllerLog) << "MissionControllerLog::loadFromVehicle called while offline";
} else if (syncInProgress()) {
qCWarning(MissionControllerLog) << "MissionControllerLog::loadFromVehicle called while syncInProgress";
} else {
_itemsRequested = true;
_managerVehicle->missionManager()->loadFromVehicle();
}
}
void MissionController::sendToVehicle(void)
{
if (_masterController->offline()) {
qCWarning(MissionControllerLog) << "MissionControllerLog::sendToVehicle called while offline";
} else if (syncInProgress()) {
qCWarning(MissionControllerLog) << "MissionControllerLog::sendToVehicle called while syncInProgress";
} else {
qCDebug(MissionControllerLog) << "MissionControllerLog::sendToVehicle";
if (_visualItems->count() == 1) {
// This prevents us from sending a possibly bogus home position to the vehicle
QmlObjectListModel emptyModel;
sendItemsToVehicle(_managerVehicle, &emptyModel);
} else {
sendItemsToVehicle(_managerVehicle, _visualItems);
}
setDirty(false);
}
}
/// Converts from visual items to MissionItems
/// @param missionItemParent QObject parent for newly allocated MissionItems
/// @return true: Mission end action was added to end of list
bool MissionController::_convertToMissionItems(QmlObjectListModel* visualMissionItems, QList<MissionItem*>& rgMissionItems, QObject* missionItemParent)
{
if (visualMissionItems->count() == 0) {
return false;
}
bool endActionSet = false;
int lastSeqNum = 0;
for (int i=0; i<visualMissionItems->count(); i++) {
VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(visualMissionItems->get(i));
lastSeqNum = visualItem->lastSequenceNumber();
visualItem->appendMissionItems(rgMissionItems, missionItemParent);
qCDebug(MissionControllerLog) << "_convertToMissionItems seqNum:lastSeqNum:command"
<< visualItem->sequenceNumber()
<< lastSeqNum
<< visualItem->commandName();
}
// Mission settings has a special case for end mission action
MissionSettingsItem* settingsItem = visualMissionItems->value<MissionSettingsItem*>(0);
if (settingsItem) {
endActionSet = settingsItem->addMissionEndAction(rgMissionItems, lastSeqNum + 1, missionItemParent);
}
return endActionSet;
}
void MissionController::addMissionToKML(KMLPlanDomDocument& planKML)
{
QObject* deleteParent = new QObject();
QList<MissionItem*> rgMissionItems;
_convertToMissionItems(_visualItems, rgMissionItems, deleteParent);
planKML.addMission(_controllerVehicle, _visualItems, rgMissionItems);
deleteParent->deleteLater();
}
void MissionController::sendItemsToVehicle(Vehicle* vehicle, QmlObjectListModel* visualMissionItems)
{
if (vehicle) {
QList<MissionItem*> rgMissionItems;
_convertToMissionItems(visualMissionItems, rgMissionItems, vehicle);
// PlanManager takes control of MissionItems so no need to delete
vehicle->missionManager()->writeMissionItems(rgMissionItems);
}
}
int MissionController::_nextSequenceNumber(void)
{
if (_visualItems->count() == 0) {
qWarning() << "Internal error: Empty visual item list";
return 0;
} else {
VisualMissionItem* lastItem = _visualItems->value<VisualMissionItem*>(_visualItems->count() - 1);
return lastItem->lastSequenceNumber() + 1;
}
}
VisualMissionItem* MissionController::_insertSimpleMissionItemWorker(QGeoCoordinate coordinate, MAV_CMD command, int visualItemIndex, bool makeCurrentItem)
{
int sequenceNumber = _nextSequenceNumber();
SimpleMissionItem * newItem = new SimpleMissionItem(_masterController, _flyView, false /* forLoad */, this);
newItem->setSequenceNumber(sequenceNumber);
newItem->setCoordinate(coordinate);
newItem->setCommand(command);
_initVisualItem(newItem);
if (newItem->specifiesAltitude()) {
if (!qgcApp()->toolbox()->missionCommandTree()->isLandCommand(command)) {
double prevAltitude;
int prevAltitudeMode;
if (_findPreviousAltitude(visualItemIndex, &prevAltitude, &prevAltitudeMode)) {
newItem->altitude()->setRawValue(prevAltitude);
if (globalAltitudeMode() == QGroundControlQmlGlobal::AltitudeModeNone) {
// We are in mixed altitude modes, so copy from previous. Otherwise alt mode will be set from global setting.
newItem->setAltitudeMode(static_cast<QGroundControlQmlGlobal::AltitudeMode>(prevAltitudeMode));
}
}
}
}
if (visualItemIndex == -1) {
_visualItems->append(newItem);
} else {
_visualItems->insert(visualItemIndex, newItem);
}
// We send the click coordinate through here to be able to set the planned home position from the user click location if needed
_recalcAllWithCoordinate(coordinate);
if (makeCurrentItem) {
setCurrentPlanViewSeqNum(newItem->sequenceNumber(), true);
}
_firstItemAdded();
return newItem;
}
VisualMissionItem* MissionController::insertSimpleMissionItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem)
{
return _insertSimpleMissionItemWorker(coordinate, MAV_CMD_NAV_WAYPOINT, visualItemIndex, makeCurrentItem);
}
VisualMissionItem* MissionController::insertTakeoffItem(QGeoCoordinate /*coordinate*/, int visualItemIndex, bool makeCurrentItem)
{
int sequenceNumber = _nextSequenceNumber();
_takeoffMissionItem = new TakeoffMissionItem(_controllerVehicle->vtol() ? MAV_CMD_NAV_VTOL_TAKEOFF : MAV_CMD_NAV_TAKEOFF, _masterController, _flyView, _settingsItem, this);
_takeoffMissionItem->setSequenceNumber(sequenceNumber);
_initVisualItem(_takeoffMissionItem);
if (_takeoffMissionItem->specifiesAltitude()) {
double prevAltitude;
int prevAltitudeMode;
if (_findPreviousAltitude(visualItemIndex, &prevAltitude, &prevAltitudeMode)) {
_takeoffMissionItem->altitude()->setRawValue(prevAltitude);
_takeoffMissionItem->setAltitudeMode(static_cast<QGroundControlQmlGlobal::AltitudeMode>(prevAltitudeMode));
}
}
if (visualItemIndex == -1) {
_visualItems->append(_takeoffMissionItem);
} else {
_visualItems->insert(visualItemIndex, _takeoffMissionItem);
}
_recalcAll();
if (makeCurrentItem) {
setCurrentPlanViewSeqNum(_takeoffMissionItem->sequenceNumber(), true);
}
_firstItemAdded();
return _takeoffMissionItem;
}
VisualMissionItem* MissionController::insertLandItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem)
{
if (_controllerVehicle->fixedWing()) {
FixedWingLandingComplexItem* fwLanding = qobject_cast<FixedWingLandingComplexItem*>(insertComplexMissionItem(FixedWingLandingComplexItem::name, coordinate, visualItemIndex, makeCurrentItem));
return fwLanding;
} else if (_controllerVehicle->vtol()) {
VTOLLandingComplexItem* vtolLanding = qobject_cast<VTOLLandingComplexItem*>(insertComplexMissionItem(VTOLLandingComplexItem::name, coordinate, visualItemIndex, makeCurrentItem));
return vtolLanding;
} else {
return _insertSimpleMissionItemWorker(coordinate, _controllerVehicle->vtol() ? MAV_CMD_NAV_VTOL_LAND : MAV_CMD_NAV_RETURN_TO_LAUNCH, visualItemIndex, makeCurrentItem);
}
}
VisualMissionItem* MissionController::insertROIMissionItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem)
{
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_insertSimpleMissionItemWorker(coordinate, MAV_CMD_DO_SET_ROI_LOCATION, visualItemIndex, makeCurrentItem));
if (!_controllerVehicle->firmwarePlugin()->supportedMissionCommands(QGCMAVLink::VehicleClassGeneric).contains(MAV_CMD_DO_SET_ROI_LOCATION)) {
simpleItem->setCommand(MAV_CMD_DO_SET_ROI) ;
simpleItem->missionItem().setParam1(MAV_ROI_LOCATION);
}
_recalcROISpecialVisuals();
return simpleItem;
}
VisualMissionItem* MissionController::insertCancelROIMissionItem(int visualItemIndex, bool makeCurrentItem)
{
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_insertSimpleMissionItemWorker(QGeoCoordinate(), MAV_CMD_DO_SET_ROI_NONE, visualItemIndex, makeCurrentItem));
if (!_controllerVehicle->firmwarePlugin()->supportedMissionCommands(QGCMAVLink::VehicleClassGeneric).contains(MAV_CMD_DO_SET_ROI_NONE)) {
simpleItem->setCommand(MAV_CMD_DO_SET_ROI) ;
simpleItem->missionItem().setParam1(MAV_ROI_NONE);
}
_recalcROISpecialVisuals();
return simpleItem;
}
VisualMissionItem* MissionController::insertComplexMissionItem(QString itemName, QGeoCoordinate mapCenterCoordinate, int visualItemIndex, bool makeCurrentItem)
{
ComplexMissionItem* newItem = nullptr;
if (itemName == SurveyComplexItem::name) {
newItem = new SurveyComplexItem(_masterController, _flyView, QString() /* kmlFile */, _visualItems /* parent */);
newItem->setCoordinate(mapCenterCoordinate);
} else if (itemName == FixedWingLandingComplexItem::name) {
newItem = new FixedWingLandingComplexItem(_masterController, _flyView, _visualItems /* parent */);
} else if (itemName == VTOLLandingComplexItem::name) {
newItem = new VTOLLandingComplexItem(_masterController, _flyView, _visualItems /* parent */);
} else if (itemName == StructureScanComplexItem::name) {
newItem = new StructureScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, _visualItems /* parent */);
} else if (itemName == CorridorScanComplexItem::name) {
newItem = new CorridorScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, _visualItems /* parent */);
} else {
qWarning() << "Internal error: Unknown complex item:" << itemName;
return nullptr;
}
_insertComplexMissionItemWorker(mapCenterCoordinate, newItem, visualItemIndex, makeCurrentItem);
return newItem;
}
VisualMissionItem* MissionController::insertComplexMissionItemFromKMLOrSHP(QString itemName, QString file, int visualItemIndex, bool makeCurrentItem)
{
ComplexMissionItem* newItem = nullptr;
if (itemName == SurveyComplexItem::name) {
newItem = new SurveyComplexItem(_masterController, _flyView, file, _visualItems);
} else if (itemName == StructureScanComplexItem::name) {
newItem = new StructureScanComplexItem(_masterController, _flyView, file, _visualItems);
} else if (itemName == CorridorScanComplexItem::name) {
newItem = new CorridorScanComplexItem(_masterController, _flyView, file, _visualItems);
} else {
qWarning() << "Internal error: Unknown complex item:" << itemName;
return nullptr;
}
_insertComplexMissionItemWorker(QGeoCoordinate(), newItem, visualItemIndex, makeCurrentItem);
return newItem;
}
void MissionController::_insertComplexMissionItemWorker(const QGeoCoordinate& mapCenterCoordinate, ComplexMissionItem* complexItem, int visualItemIndex, bool makeCurrentItem)
{
int sequenceNumber = _nextSequenceNumber();
bool surveyStyleItem = qobject_cast<SurveyComplexItem*>(complexItem) ||
qobject_cast<CorridorScanComplexItem*>(complexItem) ||
qobject_cast<StructureScanComplexItem*>(complexItem);
if (surveyStyleItem) {
bool rollSupported = false;
bool pitchSupported = false;
bool yawSupported = false;
// If the vehicle is known to have a gimbal then we automatically point the gimbal straight down if not already set
MissionSettingsItem* settingsItem = _visualItems->value<MissionSettingsItem*>(0);
CameraSection* cameraSection = settingsItem->cameraSection();
// Set camera to photo mode (leave alone if user already specified)
if (cameraSection->cameraModeSupported() && !cameraSection->specifyCameraMode()) {
cameraSection->setSpecifyCameraMode(true);
cameraSection->cameraMode()->setRawValue(CAMERA_MODE_IMAGE_SURVEY);
}
// Point gimbal straight down
if (_controllerVehicle->firmwarePlugin()->hasGimbal(_controllerVehicle, rollSupported, pitchSupported, yawSupported) && pitchSupported) {
// If the user already specified a gimbal angle leave it alone
if (!cameraSection->specifyGimbal()) {
cameraSection->setSpecifyGimbal(true);
cameraSection->gimbalPitch()->setRawValue(-90.0);
}
}
}
complexItem->setSequenceNumber(sequenceNumber);
complexItem->setWizardMode(true);
_initVisualItem(complexItem);
if (visualItemIndex == -1) {
_visualItems->append(complexItem);
} else {
_visualItems->insert(visualItemIndex, complexItem);
}
//-- Keep track of bounding box changes in complex items
if(!complexItem->isSimpleItem()) {
connect(complexItem, &ComplexMissionItem::boundingCubeChanged, this, &MissionController::_complexBoundingBoxChanged);
}
_recalcAllWithCoordinate(mapCenterCoordinate);
if (makeCurrentItem) {
setCurrentPlanViewSeqNum(complexItem->sequenceNumber(), true);
}
_firstItemAdded();
}
void MissionController::removeVisualItem(int viIndex)
{
if (viIndex <= 0 || viIndex >= _visualItems->count()) {
qWarning() << "MissionController::removeVisualItem called with bad index - count:index" << _visualItems->count() << viIndex;
return;
}
bool removeSurveyStyle = _visualItems->value<SurveyComplexItem*>(viIndex) || _visualItems->value<CorridorScanComplexItem*>(viIndex);
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->removeAt(viIndex));
if (item == _takeoffMissionItem) {
_takeoffMissionItem = nullptr;
}
_deinitVisualItem(item);
item->deleteLater();
if (removeSurveyStyle) {
// Determine if the mission still has another survey style item in it
bool foundSurvey = false;
for (int i=1; i<_visualItems->count(); i++) {
if (_visualItems->value<SurveyComplexItem*>(i) || _visualItems->value<CorridorScanComplexItem*>(i)) {
foundSurvey = true;
break;
}
}
// If there is no longer a survey item in the mission remove added commands
if (!foundSurvey) {
bool rollSupported = false;
bool pitchSupported = false;
bool yawSupported = false;
CameraSection* cameraSection = _settingsItem->cameraSection();
if (_controllerVehicle->firmwarePlugin()->hasGimbal(_controllerVehicle, rollSupported, pitchSupported, yawSupported) && pitchSupported) {
if (cameraSection->specifyGimbal() && cameraSection->gimbalPitch()->rawValue().toDouble() == -90.0 && cameraSection->gimbalYaw()->rawValue().toDouble() == 0.0) {
cameraSection->setSpecifyGimbal(false);
}
}
if (cameraSection->cameraModeSupported() && cameraSection->specifyCameraMode() && cameraSection->cameraMode()->rawValue().toInt() == 0) {
cameraSection->setSpecifyCameraMode(false);
}
}
}
_recalcAll();
// Adjust current item
int newVIIndex;
if (viIndex >= _visualItems->count()) {
newVIIndex = _visualItems->count() - 1;
} else {
newVIIndex = viIndex;
}
setCurrentPlanViewSeqNum(_visualItems->value<VisualMissionItem*>(newVIIndex)->sequenceNumber(), true);
setDirty(true);
if (_visualItems->count() == 1) {
_allItemsRemoved();
}
}
void MissionController::removeAll(void)
{
if (_visualItems) {
_deinitAllVisualItems();
_visualItems->clearAndDeleteContents();
_visualItems->deleteLater();
_settingsItem = nullptr;
_takeoffMissionItem = nullptr;
_visualItems = new QmlObjectListModel(this);
_addMissionSettings(_visualItems);
_initAllVisualItems();
setDirty(true);
_resetMissionFlightStatus();
_allItemsRemoved();
}
}
bool MissionController::_loadJsonMissionFileV1(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString)
{
// Validate root object keys
QList<JsonHelper::KeyValidateInfo> rootKeyInfoList = {
{ _jsonPlannedHomePositionKey, QJsonValue::Object, true },
{ _jsonItemsKey, QJsonValue::Array, true },
{ _jsonMavAutopilotKey, QJsonValue::Double, true },
{ _jsonComplexItemsKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(json, rootKeyInfoList, errorString)) {
return false;
}
setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeModeNone); // Mixed mode
// Read complex items
QList<SurveyComplexItem*> surveyItems;
QJsonArray complexArray(json[_jsonComplexItemsKey].toArray());
qCDebug(MissionControllerLog) << "Json load: complex item count" << complexArray.count();
for (int i=0; i<complexArray.count(); i++) {
const QJsonValue& itemValue = complexArray[i];
if (!itemValue.isObject()) {
errorString = QStringLiteral("Mission item is not an object");
return false;
}
SurveyComplexItem* item = new SurveyComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems /* parent */);
const QJsonObject itemObject = itemValue.toObject();
if (item->load(itemObject, itemObject["id"].toInt(), errorString)) {
surveyItems.append(item);
} else {
return false;
}
}
// Read simple items, interspersing complex items into the full list
int nextSimpleItemIndex= 0;
int nextComplexItemIndex= 0;
int nextSequenceNumber = 1; // Start with 1 since home is in 0
QJsonArray itemArray(json[_jsonItemsKey].toArray());
MissionSettingsItem* settingsItem = _addMissionSettings(visualItems);
if (json.contains(_jsonPlannedHomePositionKey)) {
SimpleMissionItem* item = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems);
if (item->load(json[_jsonPlannedHomePositionKey].toObject(), 0, errorString)) {
settingsItem->setInitialHomePositionFromUser(item->coordinate());
item->deleteLater();
} else {
return false;
}
}
qCDebug(MissionControllerLog) << "Json load: simple item loop start simpleItemCount:ComplexItemCount" << itemArray.count() << surveyItems.count();
do {
qCDebug(MissionControllerLog) << "Json load: simple item loop nextSimpleItemIndex:nextComplexItemIndex:nextSequenceNumber" << nextSimpleItemIndex << nextComplexItemIndex << nextSequenceNumber;
// If there is a complex item that should be next in sequence add it in
if (nextComplexItemIndex < surveyItems.count()) {
SurveyComplexItem* complexItem = surveyItems[nextComplexItemIndex];
if (complexItem->sequenceNumber() == nextSequenceNumber) {
qCDebug(MissionControllerLog) << "Json load: injecting complex item expectedSequence:actualSequence:" << nextSequenceNumber << complexItem->sequenceNumber();
visualItems->append(complexItem);
nextSequenceNumber = complexItem->lastSequenceNumber() + 1;
nextComplexItemIndex++;
continue;
}
}
// Add the next available simple item
if (nextSimpleItemIndex < itemArray.count()) {
const QJsonValue& itemValue = itemArray[nextSimpleItemIndex++];
if (!itemValue.isObject()) {
errorString = QStringLiteral("Mission item is not an object");
return false;
}
const QJsonObject itemObject = itemValue.toObject();
SimpleMissionItem* item = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems);
if (item->load(itemObject, itemObject["id"].toInt(), errorString)) {
if (TakeoffMissionItem::isTakeoffCommand(item->mavCommand())) {
// This needs to be a TakeoffMissionItem
TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_masterController, _flyView, settingsItem, true /* forLoad */, visualItems);
takeoffItem->load(itemObject, itemObject["id"].toInt(), errorString);
item->deleteLater();
item = takeoffItem;
}
qCDebug(MissionControllerLog) << "Json load: adding simple item expectedSequence:actualSequence" << nextSequenceNumber << item->sequenceNumber();
nextSequenceNumber = item->lastSequenceNumber() + 1;
visualItems->append(item);
} else {
return false;
}
}
} while (nextSimpleItemIndex < itemArray.count() || nextComplexItemIndex < surveyItems.count());
return true;
}
bool MissionController::_loadJsonMissionFileV2(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString)
{
// Validate root object keys
QList<JsonHelper::KeyValidateInfo> rootKeyInfoList = {
{ _jsonPlannedHomePositionKey, QJsonValue::Array, true },
{ _jsonItemsKey, QJsonValue::Array, true },
{ _jsonFirmwareTypeKey, QJsonValue::Double, true },
{ _jsonVehicleTypeKey, QJsonValue::Double, false },
{ _jsonCruiseSpeedKey, QJsonValue::Double, false },
{ _jsonHoverSpeedKey, QJsonValue::Double, false },
{ _jsonGlobalPlanAltitudeModeKey, QJsonValue::Double, false },
};
if (!JsonHelper::validateKeys(json, rootKeyInfoList, errorString)) {
return false;
}
setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeModeNone); // Mixed mode
qCDebug(MissionControllerLog) << "MissionController::_loadJsonMissionFileV2 itemCount:" << json[_jsonItemsKey].toArray().count();
AppSettings* appSettings = qgcApp()->toolbox()->settingsManager()->appSettings();
// Get the firmware/vehicle type from the plan file
MAV_AUTOPILOT planFileFirmwareType = static_cast<MAV_AUTOPILOT>(json[_jsonFirmwareTypeKey].toInt());
MAV_TYPE planFileVehicleType = static_cast<MAV_TYPE> (QGCMAVLink::vehicleClassToMavType(appSettings->offlineEditingVehicleClass()->rawValue().toInt()));
if (json.contains(_jsonVehicleTypeKey)) {
planFileVehicleType = static_cast<MAV_TYPE>(json[_jsonVehicleTypeKey].toInt());
}
// Update firmware/vehicle offline settings if we aren't connect to a vehicle
if (_masterController->offline()) {
appSettings->offlineEditingFirmwareClass()->setRawValue(QGCMAVLink::firmwareClass(static_cast<MAV_AUTOPILOT>(json[_jsonFirmwareTypeKey].toInt())));
if (json.contains(_jsonVehicleTypeKey)) {
appSettings->offlineEditingVehicleClass()->setRawValue(QGCMAVLink::vehicleClass(planFileVehicleType));
}
}
// The controller vehicle always tracks the Plan file firmware/vehicle types so update it
_controllerVehicle->stopTrackingFirmwareVehicleTypeChanges();
_controllerVehicle->_offlineFirmwareTypeSettingChanged(planFileFirmwareType);
_controllerVehicle->_offlineVehicleTypeSettingChanged(planFileVehicleType);
if (json.contains(_jsonCruiseSpeedKey)) {
appSettings->offlineEditingCruiseSpeed()->setRawValue(json[_jsonCruiseSpeedKey].toDouble());
}
if (json.contains(_jsonHoverSpeedKey)) {
appSettings->offlineEditingHoverSpeed()->setRawValue(json[_jsonHoverSpeedKey].toDouble());
}
if (json.contains(_jsonGlobalPlanAltitudeModeKey)) {
setGlobalAltitudeMode(json[_jsonGlobalPlanAltitudeModeKey].toVariant().value<QGroundControlQmlGlobal::AltitudeMode>());
}
QGeoCoordinate homeCoordinate;
if (!JsonHelper::loadGeoCoordinate(json[_jsonPlannedHomePositionKey], true /* altitudeRequired */, homeCoordinate, errorString)) {
return false;
}
MissionSettingsItem* settingsItem = new MissionSettingsItem(_masterController, _flyView, visualItems);
settingsItem->setCoordinate(homeCoordinate);
visualItems->insert(0, settingsItem);
qCDebug(MissionControllerLog) << "plannedHomePosition" << homeCoordinate;
// Read mission items
int nextSequenceNumber = 1; // Start with 1 since home is in 0
const QJsonArray rgMissionItems(json[_jsonItemsKey].toArray());
for (int i=0; i<rgMissionItems.count(); i++) {
// Convert to QJsonObject
const QJsonValue& itemValue = rgMissionItems[i];
if (!itemValue.isObject()) {
errorString = tr("Mission item %1 is not an object").arg(i);
return false;
}
const QJsonObject itemObject = itemValue.toObject();
// Load item based on type
QList<JsonHelper::KeyValidateInfo> itemKeyInfoList = {
{ VisualMissionItem::jsonTypeKey, QJsonValue::String, true },
};
if (!JsonHelper::validateKeys(itemObject, itemKeyInfoList, errorString)) {
return false;
}
QString itemType = itemObject[VisualMissionItem::jsonTypeKey].toString();
if (itemType == VisualMissionItem::jsonTypeSimpleItemValue) {
SimpleMissionItem* simpleItem = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems);
if (simpleItem->load(itemObject, nextSequenceNumber, errorString)) {
if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(simpleItem->command()))) {
// This needs to be a TakeoffMissionItem
TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_masterController, _flyView, settingsItem, true /* forLoad */, this);
takeoffItem->load(itemObject, nextSequenceNumber, errorString);
simpleItem->deleteLater();
simpleItem = takeoffItem;
}
qCDebug(MissionControllerLog) << "Loading simple item: nextSequenceNumber:command" << nextSequenceNumber << simpleItem->command();
nextSequenceNumber = simpleItem->lastSequenceNumber() + 1;
visualItems->append(simpleItem);
} else {
return false;
}
} else if (itemType == VisualMissionItem::jsonTypeComplexItemValue) {
QList<JsonHelper::KeyValidateInfo> complexItemKeyInfoList = {
{ ComplexMissionItem::jsonComplexItemTypeKey, QJsonValue::String, true },
};
if (!JsonHelper::validateKeys(itemObject, complexItemKeyInfoList, errorString)) {
return false;
}
QString complexItemType = itemObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();
if (complexItemType == SurveyComplexItem::jsonComplexItemTypeValue) {
qCDebug(MissionControllerLog) << "Loading Survey: nextSequenceNumber" << nextSequenceNumber;
SurveyComplexItem* surveyItem = new SurveyComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems);
if (!surveyItem->load(itemObject, nextSequenceNumber++, errorString)) {
return false;
}
nextSequenceNumber = surveyItem->lastSequenceNumber() + 1;
qCDebug(MissionControllerLog) << "Survey load complete: nextSequenceNumber" << nextSequenceNumber;
visualItems->append(surveyItem);
} else if (complexItemType == FixedWingLandingComplexItem::jsonComplexItemTypeValue) {
qCDebug(MissionControllerLog) << "Loading Fixed Wing Landing Pattern: nextSequenceNumber" << nextSequenceNumber;
FixedWingLandingComplexItem* landingItem = new FixedWingLandingComplexItem(_masterController, _flyView, visualItems);
if (!landingItem->load(itemObject, nextSequenceNumber++, errorString)) {
return false;
}
nextSequenceNumber = landingItem->lastSequenceNumber() + 1;
qCDebug(MissionControllerLog) << "FW Landing Pattern load complete: nextSequenceNumber" << nextSequenceNumber;
visualItems->append(landingItem);
} else if (complexItemType == VTOLLandingComplexItem::jsonComplexItemTypeValue) {
qCDebug(MissionControllerLog) << "Loading VTOL Landing Pattern: nextSequenceNumber" << nextSequenceNumber;
VTOLLandingComplexItem* landingItem = new VTOLLandingComplexItem(_masterController, _flyView, visualItems);
if (!landingItem->load(itemObject, nextSequenceNumber++, errorString)) {
return false;
}
nextSequenceNumber = landingItem->lastSequenceNumber() + 1;
qCDebug(MissionControllerLog) << "VTOL Landing Pattern load complete: nextSequenceNumber" << nextSequenceNumber;
visualItems->append(landingItem);
} else if (complexItemType == StructureScanComplexItem::jsonComplexItemTypeValue) {
qCDebug(MissionControllerLog) << "Loading Structure Scan: nextSequenceNumber" << nextSequenceNumber;
StructureScanComplexItem* structureItem = new StructureScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems);
if (!structureItem->load(itemObject, nextSequenceNumber++, errorString)) {
return false;
}
nextSequenceNumber = structureItem->lastSequenceNumber() + 1;
qCDebug(MissionControllerLog) << "Structure Scan load complete: nextSequenceNumber" << nextSequenceNumber;
visualItems->append(structureItem);
} else if (complexItemType == CorridorScanComplexItem::jsonComplexItemTypeValue) {
qCDebug(MissionControllerLog) << "Loading Corridor Scan: nextSequenceNumber" << nextSequenceNumber;
CorridorScanComplexItem* corridorItem = new CorridorScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems);
if (!corridorItem->load(itemObject, nextSequenceNumber++, errorString)) {
return false;
}
nextSequenceNumber = corridorItem->lastSequenceNumber() + 1;
qCDebug(MissionControllerLog) << "Corridor Scan load complete: nextSequenceNumber" << nextSequenceNumber;
visualItems->append(corridorItem);
} else {
errorString = tr("Unsupported complex item type: %1").arg(complexItemType);
}
} else {
errorString = tr("Unknown item type: %1").arg(itemType);
return false;
}
}
// Fix up the DO_JUMP commands jump sequence number by finding the item with the matching doJumpId
for (int i=0; i<visualItems->count(); i++) {
if (visualItems->value<VisualMissionItem*>(i)->isSimpleItem()) {
SimpleMissionItem* doJumpItem = visualItems->value<SimpleMissionItem*>(i);
if (doJumpItem->command() == MAV_CMD_DO_JUMP) {
bool found = false;
int findDoJumpId = static_cast<int>(doJumpItem->missionItem().param1());
for (int j=0; j<visualItems->count(); j++) {
if (visualItems->value<VisualMissionItem*>(j)->isSimpleItem()) {
SimpleMissionItem* targetItem = visualItems->value<SimpleMissionItem*>(j);
if (targetItem->missionItem().doJumpId() == findDoJumpId) {
doJumpItem->missionItem().setParam1(targetItem->sequenceNumber());
found = true;
break;
}
}
}
if (!found) {
errorString = tr("Could not find doJumpId: %1").arg(findDoJumpId);
return false;
}
}
}
}
return true;
}
bool MissionController::_loadItemsFromJson(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString)
{
// V1 file format has no file type key and version key is string. Convert to new format.
if (!json.contains(JsonHelper::jsonFileTypeKey)) {
json[JsonHelper::jsonFileTypeKey] = _jsonFileTypeValue;
}
int fileVersion;
JsonHelper::validateExternalQGCJsonFile(json,
_jsonFileTypeValue, // expected file type
1, // minimum supported version
2, // maximum supported version
fileVersion,
errorString);
if (fileVersion == 1) {
return _loadJsonMissionFileV1(json, visualItems, errorString);
} else {
return _loadJsonMissionFileV2(json, visualItems, errorString);
}
}
bool MissionController::_loadTextMissionFile(QTextStream& stream, QmlObjectListModel* visualItems, QString& errorString)
{
bool firstItem = true;
bool plannedHomePositionInFile = false;
QString firstLine = stream.readLine();
const QStringList& version = firstLine.split(" ");
bool versionOk = false;
if (version.size() == 3 && version[0] == "QGC" && version[1] == "WPL") {
if (version[2] == "110") {
// ArduPilot file, planned home position is already in position 0
versionOk = true;
plannedHomePositionInFile = true;
} else if (version[2] == "120") {
// Old QGC file, no planned home position
versionOk = true;
plannedHomePositionInFile = false;
}
}
if (versionOk) {
MissionSettingsItem* settingsItem = _addMissionSettings(visualItems);
while (!stream.atEnd()) {
SimpleMissionItem* item = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems);
if (item->load(stream)) {
if (firstItem && plannedHomePositionInFile) {
settingsItem->setInitialHomePositionFromUser(item->coordinate());
} else {
if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(item->command()))) {
// This needs to be a TakeoffMissionItem
TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_masterController, _flyView, settingsItem, true /* forLoad */, visualItems);
takeoffItem->load(stream);
item->deleteLater();
item = takeoffItem;
}
visualItems->append(item);
}
firstItem = false;
} else {
errorString = tr("The mission file is corrupted.");
return false;
}
}
} else {
errorString = tr("The mission file is not compatible with this version of %1.").arg(qgcApp()->applicationName());
return false;
}
if (!plannedHomePositionInFile) {
// Update sequence numbers in DO_JUMP commands to take into account added home position in index 0
for (int i=1; i<visualItems->count(); i++) {
SimpleMissionItem* item = qobject_cast<SimpleMissionItem*>(visualItems->get(i));
if (item && item->command() == MAV_CMD_DO_JUMP) {
item->missionItem().setParam1(static_cast<int>(item->missionItem().param1()) + 1);
}
}
}
return true;
}
void MissionController::_initLoadedVisualItems(QmlObjectListModel* loadedVisualItems)
{
if (_visualItems) {
_deinitAllVisualItems();
_visualItems->deleteLater();
}
_settingsItem = nullptr;
_takeoffMissionItem = nullptr;
_visualItems = loadedVisualItems;
if (_visualItems->count() == 0) {
_addMissionSettings(_visualItems);
} else {
_settingsItem = _visualItems->value<MissionSettingsItem*>(0);
}
MissionController::_scanForAdditionalSettings(_visualItems, _masterController);
_initAllVisualItems();
if (_visualItems->count() > 1) {
_firstItemAdded();
} else {
_allItemsRemoved();
}
}
bool MissionController::load(const QJsonObject& json, QString& errorString)
{
QString errorStr;
QString errorMessage = tr("Mission: %1");
QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this);
if (!_loadJsonMissionFileV2(json, loadedVisualItems, errorStr)) {
errorString = errorMessage.arg(errorStr);
return false;
}
_initLoadedVisualItems(loadedVisualItems);
return true;
}
bool MissionController::loadJsonFile(QFile& file, QString& errorString)
{
QString errorStr;
QString errorMessage = tr("Mission: %1");
QJsonDocument jsonDoc;
QByteArray bytes = file.readAll();
if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorStr)) {
errorString = errorMessage.arg(errorStr);
return false;
}
QJsonObject json = jsonDoc.object();
QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this);
if (!_loadItemsFromJson(json, loadedVisualItems, errorStr)) {
errorString = errorMessage.arg(errorStr);
return false;
}
_initLoadedVisualItems(loadedVisualItems);
return true;
}
bool MissionController::loadTextFile(QFile& file, QString& errorString)
{
QString errorStr;
QString errorMessage = tr("Mission: %1");
QByteArray bytes = file.readAll();
QTextStream stream(bytes);
setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeModeNone); // Mixed mode
QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this);
if (!_loadTextMissionFile(stream, loadedVisualItems, errorStr)) {
errorString = errorMessage.arg(errorStr);
return false;
}
_initLoadedVisualItems(loadedVisualItems);
return true;
}
int MissionController::readyForSaveState(void) const
{
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
if (visualItem->readyForSaveState() != VisualMissionItem::ReadyForSave) {
return visualItem->readyForSaveState();
}
}
return VisualMissionItem::ReadyForSave;
}
void MissionController::save(QJsonObject& json)
{
json[JsonHelper::jsonVersionKey] = _missionFileVersion;
// Mission settings
MissionSettingsItem* settingsItem = _visualItems->value<MissionSettingsItem*>(0);
if (!settingsItem) {
qWarning() << "First item is not MissionSettingsItem";
return;
}
QJsonValue coordinateValue;
JsonHelper::saveGeoCoordinate(settingsItem->coordinate(), true /* writeAltitude */, coordinateValue);
json[_jsonPlannedHomePositionKey] = coordinateValue;
json[_jsonFirmwareTypeKey] = _controllerVehicle->firmwareType();
json[_jsonVehicleTypeKey] = _controllerVehicle->vehicleType();
json[_jsonCruiseSpeedKey] = _controllerVehicle->defaultCruiseSpeed();
json[_jsonHoverSpeedKey] = _controllerVehicle->defaultHoverSpeed();
json[_jsonGlobalPlanAltitudeModeKey] = _globalAltMode;
// Save the visual items
QJsonArray rgJsonMissionItems;
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
visualItem->save(rgJsonMissionItems);
}
// Mission settings has a special case for end mission action
if (settingsItem) {
QList<MissionItem*> rgMissionItems;
if (_convertToMissionItems(_visualItems, rgMissionItems, this /* missionItemParent */)) {
QJsonObject saveObject;
MissionItem* missionItem = rgMissionItems[rgMissionItems.count() - 1];
missionItem->save(saveObject);
rgJsonMissionItems.append(saveObject);
}
for (int i=0; i<rgMissionItems.count(); i++) {
rgMissionItems[i]->deleteLater();
}
}
json[_jsonItemsKey] = rgJsonMissionItems;
}
void MissionController::_calcPrevWaypointValues(VisualMissionItem* currentItem, VisualMissionItem* prevItem, double* azimuth, double* distance, double* altDifference)
{
QGeoCoordinate currentCoord = currentItem->coordinate();
QGeoCoordinate prevCoord = prevItem->exitCoordinate();
// Convert to fixed altitudes
*altDifference = currentItem->amslEntryAlt() - prevItem->amslExitAlt();
*distance = prevCoord.distanceTo(currentCoord);
*azimuth = prevCoord.azimuthTo(currentCoord);
}
double MissionController::_calcDistanceToHome(VisualMissionItem* currentItem, VisualMissionItem* homeItem)
{
QGeoCoordinate currentCoord = currentItem->coordinate();
QGeoCoordinate homeCoord = homeItem->exitCoordinate();
bool distanceOk = false;
distanceOk = true;
return distanceOk ? homeCoord.distanceTo(currentCoord) : 0.0;
}
FlightPathSegment* MissionController::_createFlightPathSegmentWorker(VisualItemPair& pair)
{
QGeoCoordinate coord1 = pair.first->isSimpleItem() ? pair.first->coordinate() : pair.first->exitCoordinate();
QGeoCoordinate coord2 = pair.second->coordinate();
double coord1Alt = pair.first->isSimpleItem() ? pair.first->amslEntryAlt() : pair.first->amslExitAlt();
double coord2Alt = pair.second->amslEntryAlt();
FlightPathSegment* segment = new FlightPathSegment(coord1, coord1Alt, coord2, coord2Alt, !_flyView /* queryTerrainData */, this);
auto coord1Notifier = pair.first->isSimpleItem() ? &VisualMissionItem::coordinateChanged : &VisualMissionItem::exitCoordinateChanged;
auto coord2Notifier = &VisualMissionItem::coordinateChanged;
auto coord1AltNotifier = pair.first->isSimpleItem() ? &VisualMissionItem::amslEntryAltChanged : &VisualMissionItem::amslExitAltChanged;
auto coord2AltNotifier = &VisualMissionItem::amslEntryAltChanged;
connect(pair.first, coord1Notifier, segment, &FlightPathSegment::setCoordinate1);
connect(pair.second, coord2Notifier, segment, &FlightPathSegment::setCoordinate2);
connect(pair.first, coord1AltNotifier, segment, &FlightPathSegment::setCoord1AMSLAlt);
connect(pair.second, coord2AltNotifier, segment, &FlightPathSegment::setCoord2AMSLAlt);
connect(pair.second, &VisualMissionItem::coordinateChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(segment, &FlightPathSegment::totalDistanceChanged, this, &MissionController::recalcTerrainProfile, Qt::QueuedConnection);
connect(segment, &FlightPathSegment::coord1AMSLAltChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(segment, &FlightPathSegment::coord2AMSLAltChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(segment, &FlightPathSegment::amslTerrainHeightsChanged, this, &MissionController::recalcTerrainProfile, Qt::QueuedConnection);
connect(segment, &FlightPathSegment::terrainCollisionChanged, this, &MissionController::recalcTerrainProfile, Qt::QueuedConnection);
return segment;
}
FlightPathSegment* MissionController::_addFlightPathSegment(FlightPathSegmentHashTable& prevItemPairHashTable, VisualItemPair& pair)
{
FlightPathSegment* segment = nullptr;
if (prevItemPairHashTable.contains(pair)) {
// Pair already exists and connected, just re-use
_flightPathSegmentHashTable[pair] = segment = prevItemPairHashTable.take(pair);
} else {
segment = _createFlightPathSegmentWorker(pair);
_flightPathSegmentHashTable[pair] = segment;
}
_simpleFlightPathSegments.append(segment);
return segment;
}
void MissionController::_recalcROISpecialVisuals(void)
{
return;
VisualMissionItem* lastCoordinateItem = qobject_cast<VisualMissionItem*>(_visualItems->get(0));
bool roiActive = false;
for (int i=1; i<_visualItems->count(); i++) {
VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);
VisualItemPair viPair;
if (simpleItem) {
if (roiActive) {
if (_isROICancelItem(simpleItem)) {
roiActive = false;
}
} else {
if (_isROIBeginItem(simpleItem)) {
roiActive = true;
}
}
}
if (visualItem->specifiesCoordinate() && !visualItem->isStandaloneCoordinate()) {
viPair = VisualItemPair(lastCoordinateItem, visualItem);
if (_flightPathSegmentHashTable.contains(viPair)) {
_flightPathSegmentHashTable[viPair]->setSpecialVisual(roiActive);
}
lastCoordinateItem = visualItem;
}
}
}
void MissionController::_recalcFlightPathSegments(void)
{
VisualItemPair lastSegmentVisualItemPair;
int segmentCount = 0;
bool firstCoordinateNotFound = true;
VisualMissionItem* lastFlyThroughVI = qobject_cast<VisualMissionItem*>(_visualItems->get(0));
bool linkEndToHome = false;
bool linkStartToHome = _controllerVehicle->rover() ? true : false;
bool foundRTL = false;
bool homePositionValid = _settingsItem->coordinate().isValid();
bool roiActive = false;
bool previousItemIsIncomplete = false;
qCDebug(MissionControllerLog) << "_recalcFlightPathSegments homePositionValid" << homePositionValid;
FlightPathSegmentHashTable oldSegmentTable = _flightPathSegmentHashTable;
_missionContainsVTOLTakeoff = false;
_flightPathSegmentHashTable.clear();
_waypointPath.clear();
// Note: Although visual support for _incompleteComplexItemLines is still in the codebase. The support for populating the list is not.
// This is due to the initial implementation being buggy and incomplete with respect to correctly generating the line set.
// So for now we leave the code for displaying them in, but none are ever added until we have time to implement the correct support.
_simpleFlightPathSegments.beginReset();
_directionArrows.beginReset();
_incompleteComplexItemLines.beginReset();
_simpleFlightPathSegments.clear();
_directionArrows.clear();
_incompleteComplexItemLines.clearAndDeleteContents();
// Mission Settings item needs to start with no segment
lastFlyThroughVI->setSimpleFlighPathSegment(nullptr);
// Grovel through the list of items keeping track of things needed to correctly draw waypoints lines
for (int i=1; i<_visualItems->count(); i++) {
VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);
ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(visualItem);
visualItem->setSimpleFlighPathSegment(nullptr);
if (simpleItem) {
if (roiActive) {
if (_isROICancelItem(simpleItem)) {
roiActive = false;
}
} else {
if (_isROIBeginItem(simpleItem)) {
roiActive = true;
}
}
MAV_CMD command = simpleItem->mavCommand();
switch (command) {
case MAV_CMD_NAV_TAKEOFF:
case MAV_CMD_NAV_VTOL_TAKEOFF:
_missionContainsVTOLTakeoff = command == MAV_CMD_NAV_VTOL_TAKEOFF;
if (!linkEndToHome) {
// If we still haven't found the first coordinate item and we hit a takeoff command this means the mission starts from the ground.
// Link the first item back to home to show that.
if (firstCoordinateNotFound) {
linkStartToHome = true;
}
}
break;
case MAV_CMD_NAV_RETURN_TO_LAUNCH:
linkEndToHome = true;
foundRTL = true;
break;
default:
break;
}
}
// No need to add waypoint segments after an RTL.
if (foundRTL) {
break;
}
if (visualItem->specifiesCoordinate() && !visualItem->isStandaloneCoordinate()) {
// Incomplete items are complex items which are waiting for the user to complete setup before there visuals can become valid.
// They may not yet have valid entry/exit coordinates associated with them while in the incomplete state.
// For examples a Survey item which has no polygon set yet.
if (complexItem && complexItem->isIncomplete()) {
// We don't link lines from a valid item to an incomplete item
previousItemIsIncomplete = true;
} else if (previousItemIsIncomplete) {
// We also don't link lines from an incomplete item to a valid item.
previousItemIsIncomplete = false;
firstCoordinateNotFound = false;
lastFlyThroughVI = visualItem;
} else {
if (lastFlyThroughVI != _settingsItem || (homePositionValid && linkStartToHome)) {
bool addDirectionArrow = false;
if (i != 1) {
// Direction arrows are added to the second segment and every 5 segments thereafter.
// The reason for start with second segment is to prevent an arrow being added in between the home position
// and a takeoff item which may be right over each other. In that case the arrow points in a random direction.
if (firstCoordinateNotFound || !lastFlyThroughVI->isSimpleItem() || !visualItem->isSimpleItem()) {
addDirectionArrow = true;
} else if (segmentCount > 5) {
segmentCount = 0;
addDirectionArrow = true;
}
segmentCount++;
}
lastSegmentVisualItemPair = VisualItemPair(lastFlyThroughVI, visualItem);
if (!_flyView || addDirectionArrow) {
FlightPathSegment* segment = _addFlightPathSegment(oldSegmentTable, lastSegmentVisualItemPair);
segment->setSpecialVisual(roiActive);
if (addDirectionArrow) {
_directionArrows.append(segment);
}
lastFlyThroughVI->setSimpleFlighPathSegment(segment);
}
}
firstCoordinateNotFound = false;
_waypointPath.append(QVariant::fromValue(visualItem->coordinate()));
lastFlyThroughVI = visualItem;
}
}
}
if (linkStartToHome && homePositionValid) {
_waypointPath.prepend(QVariant::fromValue(_settingsItem->coordinate()));
}
if (linkEndToHome && lastFlyThroughVI != _settingsItem && homePositionValid) {
lastSegmentVisualItemPair = VisualItemPair(lastFlyThroughVI, _settingsItem);
if (_flyView) {
_waypointPath.append(QVariant::fromValue(_settingsItem->coordinate()));
}
FlightPathSegment* segment = _addFlightPathSegment(oldSegmentTable, lastSegmentVisualItemPair);
segment->setSpecialVisual(roiActive);
lastFlyThroughVI->setSimpleFlighPathSegment(segment);
}
// Add direction arrow to last segment
if (lastSegmentVisualItemPair.first) {
FlightPathSegment* coordVector = nullptr;
// The pair may not be in the hash, this can happen in the fly view where only segments with arrows on them are added to hash.
// check for that first and add if needed
if (_flightPathSegmentHashTable.contains(lastSegmentVisualItemPair)) {
// Pair exists in the new table already just reuse it
coordVector = _flightPathSegmentHashTable[lastSegmentVisualItemPair];
} else if (oldSegmentTable.contains(lastSegmentVisualItemPair)) {
// Pair already exists in old table, pull from old to new and reuse
_flightPathSegmentHashTable[lastSegmentVisualItemPair] = coordVector = oldSegmentTable.take(lastSegmentVisualItemPair);
} else {
// Create a new segment. Since this is the fly view there is no need to wire change signals.
coordVector = new FlightPathSegment(lastSegmentVisualItemPair.first->isSimpleItem() ? lastSegmentVisualItemPair.first->coordinate() : lastSegmentVisualItemPair.first->exitCoordinate(),
lastSegmentVisualItemPair.first->isSimpleItem() ? lastSegmentVisualItemPair.first->amslEntryAlt() : lastSegmentVisualItemPair.first->amslExitAlt(),
lastSegmentVisualItemPair.second->coordinate(),
lastSegmentVisualItemPair.second->amslEntryAlt(),
!_flyView /* queryTerrainData */,
this);
_flightPathSegmentHashTable[lastSegmentVisualItemPair] = coordVector;
}
_directionArrows.append(coordVector);
}
_simpleFlightPathSegments.endReset();
_directionArrows.endReset();
_incompleteComplexItemLines.endReset();
// Anything left in the old table is an obsolete line object that can go
qDeleteAll(oldSegmentTable);
emit _recalcMissionFlightStatusSignal();
if (_waypointPath.count() == 0) {
// MapPolyLine has a bug where if you change from a path which has elements to an empty path the line drawn
// is not cleared from the map. This hack works around that since it causes the previous lines to be remove
// as then doesn't draw anything on the map.
_waypointPath.append(QVariant::fromValue(QGeoCoordinate(0, 0)));
_waypointPath.append(QVariant::fromValue(QGeoCoordinate(0, 0)));
}
emit waypointPathChanged();
emit recalcTerrainProfile();
}
void MissionController::_updateBatteryInfo(int waypointIndex)
{
if (_missionFlightStatus.mAhBattery != 0) {
_missionFlightStatus.hoverAmpsTotal = (_missionFlightStatus.hoverTime / 60.0) * _missionFlightStatus.hoverAmps;
_missionFlightStatus.cruiseAmpsTotal = (_missionFlightStatus.cruiseTime / 60.0) * _missionFlightStatus.cruiseAmps;
_missionFlightStatus.batteriesRequired = ceil((_missionFlightStatus.hoverAmpsTotal + _missionFlightStatus.cruiseAmpsTotal) / _missionFlightStatus.ampMinutesAvailable);
// FIXME: Battery change point code pretty much doesn't work. The reason is that is treats complex items as a black box. It needs to be able to look
// inside complex items in order to determine a swap point that is interior to a complex item. Current the swap point display in PlanToolbar is
// disabled to do this problem.
if (waypointIndex != -1 && _missionFlightStatus.batteriesRequired == 2 && _missionFlightStatus.batteryChangePoint == -1) {
_missionFlightStatus.batteryChangePoint = waypointIndex - 1;
}
}
}
void MissionController::_addHoverTime(double hoverTime, double hoverDistance, int waypointIndex)
{
_missionFlightStatus.totalTime += hoverTime;
_missionFlightStatus.hoverTime += hoverTime;
_missionFlightStatus.hoverDistance += hoverDistance;
_missionFlightStatus.totalDistance += hoverDistance;
_updateBatteryInfo(waypointIndex);
}
void MissionController::_addCruiseTime(double cruiseTime, double cruiseDistance, int waypointIndex)
{
_missionFlightStatus.totalTime += cruiseTime;
_missionFlightStatus.cruiseTime += cruiseTime;
_missionFlightStatus.cruiseDistance += cruiseDistance;
_missionFlightStatus.totalDistance += cruiseDistance;
_updateBatteryInfo(waypointIndex);
}
/// Adds the specified time to the appropriate hover or cruise time values.
/// @param vtolInHover true: vtol is currrent in hover mode
/// @param hoverTime Amount of time tp add to hover
/// @param cruiseTime Amount of time to add to cruise
/// @param extraTime Amount of additional time to add to hover/cruise
/// @param seqNum Sequence number of waypoint for these values, -1 for no waypoint associated
void MissionController::_addTimeDistance(bool vtolInHover, double hoverTime, double cruiseTime, double extraTime, double distance, int seqNum)
{
if (_controllerVehicle->vtol()) {
if (vtolInHover) {
_addHoverTime(hoverTime, distance, seqNum);
_addHoverTime(extraTime, 0, -1);
} else {
_addCruiseTime(cruiseTime, distance, seqNum);
_addCruiseTime(extraTime, 0, -1);
}
} else {
if (_controllerVehicle->multiRotor()) {
_addHoverTime(hoverTime, distance, seqNum);
_addHoverTime(extraTime, 0, -1);
} else {
_addCruiseTime(cruiseTime, distance, seqNum);
_addCruiseTime(extraTime, 0, -1);
}
}
}
void MissionController::_recalcMissionFlightStatus()
{
if (!_visualItems->count()) {
return;
}
bool firstCoordinateItem = true;
VisualMissionItem* lastFlyThroughVI = qobject_cast<VisualMissionItem*>(_visualItems->get(0));
bool homePositionValid = _settingsItem->coordinate().isValid();
qCDebug(MissionControllerLog) << "_recalcMissionFlightStatus";
// If home position is valid we can calculate distances between all waypoints.
// If home position is not valid we can only calculate distances between waypoints which are
// both relative altitude.
// No values for first item
lastFlyThroughVI->setAltDifference(0);
lastFlyThroughVI->setAzimuth(0);
lastFlyThroughVI->setDistance(0);
lastFlyThroughVI->setDistanceFromStart(0);
_minAMSLAltitude = _maxAMSLAltitude = _settingsItem->coordinate().altitude();
_resetMissionFlightStatus();
bool linkStartToHome = false;
bool foundRTL = false;
double totalHorizontalDistance = 0;
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(item);
ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(item);
if (simpleItem && simpleItem->mavCommand() == MAV_CMD_NAV_RETURN_TO_LAUNCH) {
foundRTL = true;
}
// Assume the worst
item->setAzimuth(0);
item->setDistance(0);
item->setDistanceFromStart(0);
// Gimbal states reflect the state AFTER executing the item
// ROI commands cancel out previous gimbal yaw/pitch
if (simpleItem) {
switch (simpleItem->command()) {
case MAV_CMD_NAV_ROI:
case MAV_CMD_DO_SET_ROI_LOCATION:
case MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET:
_missionFlightStatus.gimbalYaw = qQNaN();
_missionFlightStatus.gimbalPitch = qQNaN();
break;
default:
break;
}
}
// Look for specific gimbal changes
double gimbalYaw = item->specifiedGimbalYaw();
if (!qIsNaN(gimbalYaw) || _planViewSettings->showGimbalOnlyWhenSet()->rawValue().toBool()) {
_missionFlightStatus.gimbalYaw = gimbalYaw;
}
double gimbalPitch = item->specifiedGimbalPitch();
if (!qIsNaN(gimbalPitch) || _planViewSettings->showGimbalOnlyWhenSet()->rawValue().toBool()) {
_missionFlightStatus.gimbalPitch = gimbalPitch;
}
// We don't need to do any more processing if:
// Mission Settings Item
// We are after an RTL command
if (i != 0 && !foundRTL) {
// We must set the mission flight status prior to querying for any values from the item. This is because things like
// current speed, gimbal, vtol state impact the values.
item->setMissionFlightStatus(_missionFlightStatus);
// Link back to home if first item is takeoff and we have home position
if (firstCoordinateItem && simpleItem && (simpleItem->mavCommand() == MAV_CMD_NAV_TAKEOFF || simpleItem->mavCommand() == MAV_CMD_NAV_VTOL_TAKEOFF)) {
if (homePositionValid) {
linkStartToHome = true;
if (_controllerVehicle->multiRotor() || _controllerVehicle->vtol()) {
// We have to special case takeoff, assuming vehicle takes off straight up to specified altitude
double azimuth, distance, altDifference;
_calcPrevWaypointValues(_settingsItem, simpleItem, &azimuth, &distance, &altDifference);
double takeoffTime = qAbs(altDifference) / _appSettings->offlineEditingAscentSpeed()->rawValue().toDouble();
_addHoverTime(takeoffTime, 0, -1);
}
}
}
_addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, 0, 0, item->additionalTimeDelay(), 0, -1);
if (item->specifiesCoordinate()) {
// Keep track of the min/max AMSL altitude for entire mission so we can calculate altitude percentages in terrain status display
if (simpleItem) {
double amslAltitude = item->amslEntryAlt();
_minAMSLAltitude = std::min(_minAMSLAltitude, amslAltitude);
_maxAMSLAltitude = std::max(_maxAMSLAltitude, amslAltitude);
} else {
// Complex item
double complexMinAMSLAltitude = complexItem->minAMSLAltitude();
double complexMaxAMSLAltitude = complexItem->maxAMSLAltitude();
_minAMSLAltitude = std::min(_minAMSLAltitude, complexMinAMSLAltitude);
_maxAMSLAltitude = std::max(_maxAMSLAltitude, complexMaxAMSLAltitude);
}
if (!item->isStandaloneCoordinate()) {
firstCoordinateItem = false;
// Update vehicle yaw assuming direction to next waypoint and/or mission item change
if (simpleItem) {
double newVehicleYaw = simpleItem->specifiedVehicleYaw();
if (qIsNaN(newVehicleYaw)) {
// No specific vehicle yaw set. Current vehicle yaw is determined from flight path segment direction.
if (simpleItem != lastFlyThroughVI) {
_missionFlightStatus.vehicleYaw = lastFlyThroughVI->exitCoordinate().azimuthTo(simpleItem->coordinate());
}
} else {
_missionFlightStatus.vehicleYaw = newVehicleYaw;
}
simpleItem->setMissionVehicleYaw(_missionFlightStatus.vehicleYaw);
}
if (lastFlyThroughVI != _settingsItem || linkStartToHome) {
// This is a subsequent waypoint or we are forcing the first waypoint back to home
double azimuth, distance, altDifference;
_calcPrevWaypointValues(item, lastFlyThroughVI, &azimuth, &distance, &altDifference);
totalHorizontalDistance += distance;
item->setAltDifference(altDifference);
item->setAzimuth(azimuth);
item->setDistance(distance);
item->setDistanceFromStart(totalHorizontalDistance);
_missionFlightStatus.maxTelemetryDistance = qMax(_missionFlightStatus.maxTelemetryDistance, _calcDistanceToHome(item, _settingsItem));
// Calculate time/distance
double hoverTime = distance / _missionFlightStatus.hoverSpeed;
double cruiseTime = distance / _missionFlightStatus.cruiseSpeed;
_addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, hoverTime, cruiseTime, 0, distance, item->sequenceNumber());
}
if (complexItem) {
// Add in distance/time inside complex items as well
double distance = complexItem->complexDistance();
_missionFlightStatus.maxTelemetryDistance = qMax(_missionFlightStatus.maxTelemetryDistance, complexItem->greatestDistanceTo(complexItem->exitCoordinate()));
double hoverTime = distance / _missionFlightStatus.hoverSpeed;
double cruiseTime = distance / _missionFlightStatus.cruiseSpeed;
_addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, hoverTime, cruiseTime, 0, distance, item->sequenceNumber());
totalHorizontalDistance += distance;
}
lastFlyThroughVI = item;
}
}
}
// Speed, VTOL states changes are processed last since they take affect on the next item
double newSpeed = item->specifiedFlightSpeed();
if (!qIsNaN(newSpeed)) {
if (_controllerVehicle->multiRotor()) {
_missionFlightStatus.hoverSpeed = newSpeed;
} else if (_controllerVehicle->vtol()) {
if (_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor) {
_missionFlightStatus.hoverSpeed = newSpeed;
} else {
_missionFlightStatus.cruiseSpeed = newSpeed;
}
} else {
_missionFlightStatus.cruiseSpeed = newSpeed;
}
_missionFlightStatus.vehicleSpeed = newSpeed;
}
// Update VTOL state
if (simpleItem && _controllerVehicle->vtol()) {
switch (simpleItem->command()) {
case MAV_CMD_NAV_TAKEOFF: // This will do a fixed wing style takeoff
case MAV_CMD_NAV_VTOL_TAKEOFF: // Vehicle goes straight up and then transitions to FW
case MAV_CMD_NAV_LAND:
_missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassFixedWing;
break;
case MAV_CMD_NAV_VTOL_LAND:
_missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassMultiRotor;
break;
case MAV_CMD_DO_VTOL_TRANSITION:
{
int transitionState = simpleItem->missionItem().param1();
if (transitionState == MAV_VTOL_STATE_MC) {
_missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassMultiRotor;
} else if (transitionState == MAV_VTOL_STATE_FW) {
_missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassFixedWing;
}
}
break;
default:
break;
}
}
}
lastFlyThroughVI->setMissionVehicleYaw(_missionFlightStatus.vehicleYaw);
// Add the information for the final segment back to home
if (foundRTL && lastFlyThroughVI != _settingsItem && homePositionValid) {
double azimuth, distance, altDifference;
_calcPrevWaypointValues(lastFlyThroughVI, _settingsItem, &azimuth, &distance, &altDifference);
// Calculate time/distance
double hoverTime = distance / _missionFlightStatus.hoverSpeed;
double cruiseTime = distance / _missionFlightStatus.cruiseSpeed;
double landTime = qAbs(altDifference) / _appSettings->offlineEditingDescentSpeed()->rawValue().toDouble();
_addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, hoverTime, cruiseTime, distance, landTime, -1);
}
if (_missionFlightStatus.mAhBattery != 0 && _missionFlightStatus.batteryChangePoint == -1) {
_missionFlightStatus.batteryChangePoint = 0;
}
emit missionMaxTelemetryChanged (_missionFlightStatus.maxTelemetryDistance);
emit missionDistanceChanged (_missionFlightStatus.totalDistance);
emit missionHoverDistanceChanged (_missionFlightStatus.hoverDistance);
emit missionCruiseDistanceChanged (_missionFlightStatus.cruiseDistance);
emit missionTimeChanged ();
emit missionHoverTimeChanged ();
emit missionCruiseTimeChanged ();
emit batteryChangePointChanged (_missionFlightStatus.batteryChangePoint);
emit batteriesRequiredChanged (_missionFlightStatus.batteriesRequired);
emit minAMSLAltitudeChanged (_minAMSLAltitude);
emit maxAMSLAltitudeChanged (_maxAMSLAltitude);
// Walk the list again calculating altitude percentages
double altRange = _maxAMSLAltitude - _minAMSLAltitude;
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
if (item->specifiesCoordinate()) {
double amslAlt = item->amslEntryAlt();
if (altRange == 0.0) {
item->setAltPercent(0.0);
item->setTerrainPercent(qQNaN());
item->setTerrainCollision(false);
} else {
item->setAltPercent((amslAlt - _minAMSLAltitude) / altRange);
double terrainAltitude = item->terrainAltitude();
if (qIsNaN(terrainAltitude)) {
item->setTerrainPercent(qQNaN());
item->setTerrainCollision(false);
} else {
item->setTerrainPercent((terrainAltitude - _minAMSLAltitude) / altRange);
item->setTerrainCollision(amslAlt < terrainAltitude);
}
}
}
}
_updateTimer.start(UPDATE_TIMEOUT);
emit recalcTerrainProfile();
}
// This will update the sequence numbers to be sequential starting from 0
void MissionController::_recalcSequence(void)
{
if (_inRecalcSequence) {
// Don't let this call recurse due to signalling
return;
}
// Setup ascending sequence numbers for all visual items
_inRecalcSequence = true;
int sequenceNumber = 0;
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
item->setSequenceNumber(sequenceNumber);
sequenceNumber = item->lastSequenceNumber() + 1;
}
_inRecalcSequence = false;
}
// This will update the child item hierarchy
void MissionController::_recalcChildItems(void)
{
VisualMissionItem* currentParentItem = qobject_cast<VisualMissionItem*>(_visualItems->get(0));
currentParentItem->childItems()->clear();
for (int i=1; i<_visualItems->count(); i++) {
VisualMissionItem* item = _visualItems->value<VisualMissionItem*>(i);
item->setParentItem(nullptr);
item->setHasCurrentChildItem(false);
// Set up non-coordinate item child hierarchy
if (item->specifiesCoordinate()) {
item->childItems()->clear();
currentParentItem = item;
} else if (item->isSimpleItem()) {
item->setParentItem(currentParentItem);
currentParentItem->childItems()->append(item);
if (item->isCurrentItem()) {
currentParentItem->setHasCurrentChildItem(true);
}
}
}
}
void MissionController::_setPlannedHomePositionFromFirstCoordinate(const QGeoCoordinate& clickCoordinate)
{
bool foundFirstCoordinate = false;
QGeoCoordinate firstCoordinate;
if (_settingsItem->coordinate().isValid()) {
return;
}
// Set the planned home position to be a delta from first coordinate
for (int i=1; i<_visualItems->count(); i++) {
VisualMissionItem* item = _visualItems->value<VisualMissionItem*>(i);
if (item->specifiesCoordinate() && item->coordinate().isValid()) {
foundFirstCoordinate = true;
firstCoordinate = item->coordinate();
break;
}
}
// No item specifying a coordinate was found, in this case it we have a clickCoordinate use that
if (!foundFirstCoordinate) {
firstCoordinate = clickCoordinate;
}
if (firstCoordinate.isValid()) {
QGeoCoordinate plannedHomeCoord = firstCoordinate.atDistanceAndAzimuth(30, 0);
plannedHomeCoord.setAltitude(0);
_settingsItem->setInitialHomePositionFromUser(plannedHomeCoord);
}
}
void MissionController::_recalcAllWithCoordinate(const QGeoCoordinate& coordinate)
{
if (!_flyView) {
_setPlannedHomePositionFromFirstCoordinate(coordinate);
}
_recalcSequence();
_recalcChildItems();
emit _recalcFlightPathSegmentsSignal();
_updateTimer.start(UPDATE_TIMEOUT);
}
void MissionController::_recalcAll(void)
{
QGeoCoordinate emptyCoord;
_recalcAllWithCoordinate(emptyCoord);
}
/// Initializes a new set of mission items
void MissionController::_initAllVisualItems(void)
{
// Setup home position at index 0
if (!_settingsItem) {
_settingsItem = qobject_cast<MissionSettingsItem*>(_visualItems->get(0));
if (!_settingsItem) {
qWarning() << "First item not MissionSettingsItem";
return;
}
}
connect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::_recalcAll);
connect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::plannedHomePositionChanged);
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
_initVisualItem(item);
TakeoffMissionItem* takeoffItem = qobject_cast<TakeoffMissionItem*>(item);
if (takeoffItem) {
_takeoffMissionItem = takeoffItem;
}
}
_recalcAll();
connect(_visualItems, &QmlObjectListModel::dirtyChanged, this, &MissionController::_visualItemsDirtyChanged);
connect(_visualItems, &QmlObjectListModel::countChanged, this, &MissionController::_updateContainsItems);
emit visualItemsChanged();
emit containsItemsChanged(containsItems());
emit plannedHomePositionChanged(plannedHomePosition());
if (!_flyView) {
setCurrentPlanViewSeqNum(0, true);
}
setDirty(false);
}
void MissionController::_deinitAllVisualItems(void)
{
disconnect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::_recalcAll);
disconnect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::plannedHomePositionChanged);
for (int i=0; i<_visualItems->count(); i++) {
_deinitVisualItem(qobject_cast<VisualMissionItem*>(_visualItems->get(i)));
}
disconnect(_visualItems, &QmlObjectListModel::dirtyChanged, this, &MissionController::dirtyChanged);
disconnect(_visualItems, &QmlObjectListModel::countChanged, this, &MissionController::_updateContainsItems);
}
void MissionController::_initVisualItem(VisualMissionItem* visualItem)
{
setDirty(false);
connect(visualItem, &VisualMissionItem::specifiesCoordinateChanged, this, &MissionController::_recalcFlightPathSegmentsSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::specifiedFlightSpeedChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::specifiedGimbalYawChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::specifiedGimbalPitchChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::specifiedVehicleYawChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::terrainAltitudeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::additionalTimeDelayChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::currentVTOLModeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(visualItem, &VisualMissionItem::lastSequenceNumberChanged, this, &MissionController::_recalcSequence);
if (visualItem->isSimpleItem()) {
// We need to track commandChanged on simple item since recalc has special handling for takeoff command
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);
if (simpleItem) {
connect(&simpleItem->missionItem()._commandFact, &Fact::valueChanged, this, &MissionController::_itemCommandChanged);
} else {
qWarning() << "isSimpleItem == true, yet not SimpleMissionItem";
}
} else {
ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(visualItem);
if (complexItem) {
connect(complexItem, &ComplexMissionItem::complexDistanceChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(complexItem, &ComplexMissionItem::greatestDistanceToChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(complexItem, &ComplexMissionItem::minAMSLAltitudeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(complexItem, &ComplexMissionItem::maxAMSLAltitudeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(complexItem, &ComplexMissionItem::isIncompleteChanged, this, &MissionController::_recalcFlightPathSegmentsSignal, Qt::QueuedConnection);
} else {
qWarning() << "ComplexMissionItem not found";
}
}
}
void MissionController::_deinitVisualItem(VisualMissionItem* visualItem)
{
// Disconnect all signals
disconnect(visualItem, nullptr, nullptr, nullptr);
}
void MissionController::_itemCommandChanged(void)
{
_recalcChildItems();
emit _recalcFlightPathSegmentsSignal();
}
void MissionController::_managerVehicleChanged(Vehicle* managerVehicle)
{
if (_managerVehicle) {
_missionManager->disconnect(this);
_managerVehicle->disconnect(this);
_managerVehicle = nullptr;
_missionManager = nullptr;
}
_managerVehicle = managerVehicle;
if (!_managerVehicle) {
qWarning() << "MissionController::managerVehicleChanged managerVehicle=NULL";
return;
}
_missionManager = _managerVehicle->missionManager();
connect(_missionManager, &MissionManager::newMissionItemsAvailable, this, &MissionController::_newMissionItemsAvailableFromVehicle);
connect(_missionManager, &MissionManager::sendComplete, this, &MissionController::_managerSendComplete);
connect(_missionManager, &MissionManager::removeAllComplete, this, &MissionController::_managerRemoveAllComplete);
connect(_missionManager, &MissionManager::inProgressChanged, this, &MissionController::_inProgressChanged);
connect(_missionManager, &MissionManager::progressPct, this, &MissionController::_progressPctChanged);
connect(_missionManager, &MissionManager::currentIndexChanged, this, &MissionController::_currentMissionIndexChanged);
connect(_missionManager, &MissionManager::lastCurrentIndexChanged, this, &MissionController::resumeMissionIndexChanged);
connect(_missionManager, &MissionManager::resumeMissionReady, this, &MissionController::resumeMissionReady);
connect(_missionManager, &MissionManager::resumeMissionUploadFail, this, &MissionController::resumeMissionUploadFail);
connect(_managerVehicle, &Vehicle::defaultCruiseSpeedChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(_managerVehicle, &Vehicle::defaultHoverSpeedChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection);
connect(_managerVehicle, &Vehicle::vehicleTypeChanged, this, &MissionController::complexMissionItemNamesChanged);
emit complexMissionItemNamesChanged();
emit resumeMissionIndexChanged();
}
void MissionController::_inProgressChanged(bool inProgress)
{
emit syncInProgressChanged(inProgress);
}
bool MissionController::_findPreviousAltitude(int newIndex, double* prevAltitude, int* prevAltitudeMode)
{
bool found = false;
double foundAltitude = 0;
int foundAltitudeMode = QGroundControlQmlGlobal::AltitudeModeNone;
if (newIndex > _visualItems->count()) {
return false;
}
newIndex--;
for (int i=newIndex; i>0; i--) {
VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
if (visualItem->specifiesCoordinate() && !visualItem->isStandaloneCoordinate()) {
if (visualItem->isSimpleItem()) {
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);
if (simpleItem->specifiesAltitude()) {
foundAltitude = simpleItem->altitude()->rawValue().toDouble();
foundAltitudeMode = simpleItem->altitudeMode();
found = true;
break;
}
}
}
}
if (found) {
*prevAltitude = foundAltitude;
*prevAltitudeMode = foundAltitudeMode;
}
return found;
}
double MissionController::_normalizeLat(double lat)
{
// Normalize latitude to range: 0 to 180, S to N
return lat + 90.0;
}
double MissionController::_normalizeLon(double lon)
{
// Normalize longitude to range: 0 to 360, W to E
return lon + 180.0;
}
/// Add the Mission Settings complex item to the front of the items
MissionSettingsItem* MissionController::_addMissionSettings(QmlObjectListModel* visualItems)
{
qCDebug(MissionControllerLog) << "_addMissionSettings";
MissionSettingsItem* settingsItem = new MissionSettingsItem(_masterController, _flyView, visualItems);
visualItems->insert(0, settingsItem);
if (visualItems == _visualItems) {
_settingsItem = settingsItem;
}
return settingsItem;
}
void MissionController::_centerHomePositionOnMissionItems(QmlObjectListModel *visualItems)
{
qCDebug(MissionControllerLog) << "_centerHomePositionOnMissionItems";
if (visualItems->count() > 1) {
double north = 0.0;
double south = 0.0;
double east = 0.0;
double west = 0.0;
bool firstCoordSet = false;
for (int i=1; i<visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(visualItems->get(i));
if (item->specifiesCoordinate()) {
if (firstCoordSet) {
double lat = _normalizeLat(item->coordinate().latitude());
double lon = _normalizeLon(item->coordinate().longitude());
north = fmax(north, lat);
south = fmin(south, lat);
east = fmax(east, lon);
west = fmin(west, lon);
} else {
firstCoordSet = true;
north = _normalizeLat(item->coordinate().latitude());
south = north;
east = _normalizeLon(item->coordinate().longitude());
west = east;
}
}
}
if (firstCoordSet) {
_settingsItem->setInitialHomePositionFromUser(QGeoCoordinate((south + ((north - south) / 2)) - 90.0, (west + ((east - west) / 2)) - 180.0, 0.0));
}
}
}
int MissionController::resumeMissionIndex(void) const
{
int resumeIndex = 0;
if (_flyView) {
resumeIndex = _missionManager->lastCurrentIndex() + (_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle() ? 0 : 1);
if (resumeIndex > 1 && resumeIndex != _visualItems->value<VisualMissionItem*>(_visualItems->count() - 1)->sequenceNumber()) {
// Resume at the item previous to the item we were heading towards
resumeIndex--;
} else {
resumeIndex = 0;
}
}
return resumeIndex;
}
int MissionController::currentMissionIndex(void) const
{
if (!_flyView) {
return -1;
} else {
int currentIndex = _missionManager->currentIndex();
if (!_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle()) {
currentIndex++;
}
return currentIndex;
}
}
void MissionController::_currentMissionIndexChanged(int sequenceNumber)
{
if (_flyView) {
if (!_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle()) {
sequenceNumber++;
}
for (int i=0; i<_visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
item->setIsCurrentItem(item->sequenceNumber() == sequenceNumber);
}
emit currentMissionIndexChanged(currentMissionIndex());
}
}
bool MissionController::syncInProgress(void) const
{
return _missionManager->inProgress();
}
bool MissionController::dirty(void) const
{
return _visualItems ? _visualItems->dirty() : false;
}
void MissionController::setDirty(bool dirty)
{
if (_visualItems) {
_visualItems->setDirty(dirty);
}
}
void MissionController::_scanForAdditionalSettings(QmlObjectListModel* visualItems, PlanMasterController* masterController)
{
// First we look for a Landing Patterns which are at the end
if (!FixedWingLandingComplexItem::scanForItem(visualItems, _flyView, masterController)) {
VTOLLandingComplexItem::scanForItem(visualItems, _flyView, masterController);
}
int scanIndex = 0;
while (scanIndex < visualItems->count()) {
VisualMissionItem* visualItem = visualItems->value<VisualMissionItem*>(scanIndex);
qCDebug(MissionControllerLog) << "MissionController::_scanForAdditionalSettings count:scanIndex" << visualItems->count() << scanIndex;
if (!_flyView) {
MissionSettingsItem* settingsItem = qobject_cast<MissionSettingsItem*>(visualItem);
if (settingsItem) {
scanIndex++;
settingsItem->scanForMissionSettings(visualItems, scanIndex);
continue;
}
}
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);
if (simpleItem) {
scanIndex++;
simpleItem->scanForSections(visualItems, scanIndex, masterController);
} else {
// Complex item, can't have sections
scanIndex++;
}
}
}
void MissionController::_updateContainsItems(void)
{
emit containsItemsChanged(containsItems());
}
bool MissionController::containsItems(void) const
{
return _visualItems ? _visualItems->count() > 1 : false;
}
void MissionController::removeAllFromVehicle(void)
{
if (_masterController->offline()) {
qCWarning(MissionControllerLog) << "MissionControllerLog::removeAllFromVehicle called while offline";
} else if (syncInProgress()) {
qCWarning(MissionControllerLog) << "MissionControllerLog::removeAllFromVehicle called while syncInProgress";
} else {
_itemsRequested = true;
_missionManager->removeAll();
}
}
QStringList MissionController::complexMissionItemNames(void) const
{
QStringList complexItems;
complexItems.append(SurveyComplexItem::name);
complexItems.append(CorridorScanComplexItem::name);
if (_controllerVehicle->multiRotor() || _controllerVehicle->vtol()) {
complexItems.append(StructureScanComplexItem::name);
}
// Note: The landing pattern items are not added here since they have there own button which adds them
return qgcApp()->toolbox()->corePlugin()->complexMissionItemNames(_controllerVehicle, complexItems);
}
void MissionController::resumeMission(int resumeIndex)
{
if (!_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle()) {
resumeIndex--;
}
_missionManager->generateResumeMission(resumeIndex);
}
QGeoCoordinate MissionController::plannedHomePosition(void) const
{
if (_settingsItem) {
return _settingsItem->coordinate();
} else {
return QGeoCoordinate();
}
}
void MissionController::applyDefaultMissionAltitude(void)
{
double defaultAltitude = _appSettings->defaultMissionItemAltitude()->rawValue().toDouble();
for (int i=1; i<_visualItems->count(); i++) {
VisualMissionItem* item = _visualItems->value<VisualMissionItem*>(i);
item->applyNewAltitude(defaultAltitude);
}
}
void MissionController::_progressPctChanged(double progressPct)
{
if (!QGC::fuzzyCompare(progressPct, _progressPct)) {
_progressPct = progressPct;
emit progressPctChanged(progressPct);
}
}
void MissionController::_visualItemsDirtyChanged(bool dirty)
{
// We could connect signal to signal and not need this but this is handy for setting a breakpoint on
emit dirtyChanged(dirty);
}
bool MissionController::showPlanFromManagerVehicle (void)
{
qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle _flyView" << _flyView;
if (_masterController->offline()) {
qCWarning(MissionControllerLog) << "MissionController::showPlanFromManagerVehicle called while offline";
return true; // stops further propagation of showPlanFromManagerVehicle due to error
} else {
if (!_managerVehicle->initialPlanRequestComplete()) {
// The vehicle hasn't completed initial load, we can just wait for newMissionItemsAvailable to be signalled automatically
qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle: !initialPlanRequestComplete, wait for signal";
return true;
} else if (syncInProgress()) {
// If the sync is already in progress, newMissionItemsAvailable will be signalled automatically when it is done. So no need to do anything.
qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle: syncInProgress wait for signal";
return true;
} else {
// Fake a _newMissionItemsAvailable with the current items
qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle: sync complete simulate signal";
_itemsRequested = true;
_newMissionItemsAvailableFromVehicle(false /* removeAllRequested */);
return false;
}
}
}
void MissionController::_managerSendComplete(bool error)
{
// Fly view always reloads on send complete
if (!error && _flyView) {
showPlanFromManagerVehicle();
}
}
void MissionController::_managerRemoveAllComplete(bool error)
{
if (!error) {
// Remove all from vehicle so we always update
showPlanFromManagerVehicle();
}
}
bool MissionController::_isROIBeginItem(SimpleMissionItem* simpleItem)
{
return simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI_LOCATION ||
simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET ||
(simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI &&
static_cast<int>(simpleItem->missionItem().param1()) == MAV_ROI_LOCATION);
}
bool MissionController::_isROICancelItem(SimpleMissionItem* simpleItem)
{
return simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI_NONE ||
(simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI &&
static_cast<int>(simpleItem->missionItem().param1()) == MAV_ROI_NONE);
}
void MissionController::setCurrentPlanViewSeqNum(int sequenceNumber, bool force)
{
if (_visualItems && (force || sequenceNumber != _currentPlanViewSeqNum)) {
bool foundLand = false;
int takeoffSeqNum = -1;
int landSeqNum = -1;
int lastFlyThroughSeqNum = -1;
_splitSegment = nullptr;
_currentPlanViewItem = nullptr;
_currentPlanViewSeqNum = -1;
_currentPlanViewVIIndex = -1;
_onlyInsertTakeoffValid = !_planViewSettings->takeoffItemNotRequired()->rawValue().toBool() && _visualItems->count() == 1; // First item must be takeoff
_isInsertTakeoffValid = true;
_isInsertLandValid = true;
_isROIActive = false;
_isROIBeginCurrentItem = false;
_flyThroughCommandsAllowed = true;
_previousCoordinate = QGeoCoordinate();
for (int viIndex=0; viIndex<_visualItems->count(); viIndex++) {
VisualMissionItem* pVI = qobject_cast<VisualMissionItem*>(_visualItems->get(viIndex));
SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(pVI);
int currentSeqNumber = pVI->sequenceNumber();
if (sequenceNumber != 0 && currentSeqNumber <= sequenceNumber) {
if (pVI->specifiesCoordinate() && !pVI->isStandaloneCoordinate()) {
// Coordinate based flight commands prior to where the takeoff would be inserted
_isInsertTakeoffValid = false;
}
}
if (qobject_cast<TakeoffMissionItem*>(pVI)) {
takeoffSeqNum = currentSeqNumber;
_isInsertTakeoffValid = false;
}
if (!foundLand) {
if (simpleItem) {
switch (simpleItem->mavCommand()) {
case MAV_CMD_NAV_LAND:
case MAV_CMD_NAV_VTOL_LAND:
case MAV_CMD_DO_LAND_START:
case MAV_CMD_NAV_RETURN_TO_LAUNCH:
foundLand = true;
landSeqNum = currentSeqNumber;
break;
default:
break;
}
} else {
FixedWingLandingComplexItem* fwLanding = qobject_cast<FixedWingLandingComplexItem*>(pVI);
if (fwLanding) {
foundLand = true;
landSeqNum = currentSeqNumber;
}
}
}
if (simpleItem) {
// Remember previous coordinate
if (currentSeqNumber < sequenceNumber && simpleItem->specifiesCoordinate() && !simpleItem->isStandaloneCoordinate()) {
_previousCoordinate = simpleItem->coordinate();
}
// ROI state handling
if (currentSeqNumber <= sequenceNumber) {
if (_isROIActive) {
if (_isROICancelItem(simpleItem)) {
_isROIActive = false;
}
} else {
if (_isROIBeginItem(simpleItem)) {
_isROIActive = true;
}
}
}
if (currentSeqNumber == sequenceNumber && _isROIBeginItem(simpleItem)) {
_isROIBeginCurrentItem = true;
}
}
if (viIndex != 0) {
// Complex items are assumed to be fly through
if (!simpleItem || (simpleItem->specifiesCoordinate() && !simpleItem->isStandaloneCoordinate())) {
lastFlyThroughSeqNum = currentSeqNumber;
}
}
if (currentSeqNumber == sequenceNumber) {
pVI->setIsCurrentItem(true);
pVI->setHasCurrentChildItem(false);
_currentPlanViewItem = pVI;
_currentPlanViewSeqNum = sequenceNumber;
_currentPlanViewVIIndex = viIndex;
if (pVI->specifiesCoordinate()) {
if (!pVI->isStandaloneCoordinate()) {
// Determine split segment used to display line split editing ui.
for (int j=viIndex-1; j>0; j--) {
VisualMissionItem* pPrev = qobject_cast<VisualMissionItem*>(_visualItems->get(j));
if (pPrev->specifiesCoordinate() && !pPrev->isStandaloneCoordinate()) {
VisualItemPair splitPair(pPrev, pVI);
if (_flightPathSegmentHashTable.contains(splitPair)) {
_splitSegment = _flightPathSegmentHashTable[splitPair];
}
}
}
}
} else if (pVI->parentItem()) {
pVI->parentItem()->setHasCurrentChildItem(true);
}
} else {
pVI->setIsCurrentItem(false);
}
}
if (takeoffSeqNum != -1) {
// Takeoff item was found which means mission starts from ground
if (sequenceNumber < takeoffSeqNum) {
// Land is only valid after the takeoff item.
_isInsertLandValid = false;
// Fly through commands are not allowed prior to the takeoff command
_flyThroughCommandsAllowed = false;
}
}
if (lastFlyThroughSeqNum != -1) {
// Land item must be after any fly through coordinates
if (sequenceNumber < lastFlyThroughSeqNum) {
_isInsertLandValid = false;
}
}
if (foundLand) {
// Can't have more than one land sequence
_isInsertLandValid = false;
if (sequenceNumber >= landSeqNum) {
// Can't have fly through commands after a land item
_flyThroughCommandsAllowed = false;
}
}
// These are not valid when only takeoff is allowed
_isInsertLandValid = _isInsertLandValid && !_onlyInsertTakeoffValid;
_flyThroughCommandsAllowed = _flyThroughCommandsAllowed && !_onlyInsertTakeoffValid;
emit currentPlanViewSeqNumChanged();
emit currentPlanViewVIIndexChanged();
emit currentPlanViewItemChanged();
emit splitSegmentChanged();
emit onlyInsertTakeoffValidChanged();
emit isInsertTakeoffValidChanged();
emit isInsertLandValidChanged();
emit isROIActiveChanged();
emit isROIBeginCurrentItemChanged();
emit flyThroughCommandsAllowedChanged();
emit previousCoordinateChanged();
}
}
void MissionController::_updateTimeout()
{
QGeoCoordinate firstCoordinate;
QGeoCoordinate takeoffCoordinate;
QGCGeoBoundingCube boundingCube;
double north = 0.0;
double south = 180.0;
double east = 0.0;
double west = 360.0;
double minAlt = QGCGeoBoundingCube::MaxAlt;
double maxAlt = QGCGeoBoundingCube::MinAlt;
for (int i = 1; i < _visualItems->count(); i++) {
VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
if(item->isSimpleItem()) {
SimpleMissionItem* pSimpleItem = qobject_cast<SimpleMissionItem*>(item);
if(pSimpleItem) {
switch(pSimpleItem->command()) {
case MAV_CMD_NAV_TAKEOFF:
case MAV_CMD_NAV_WAYPOINT:
case MAV_CMD_NAV_LAND:
if(pSimpleItem->coordinate().isValid()) {
if((MAV_CMD)pSimpleItem->command() == MAV_CMD_NAV_TAKEOFF) {
takeoffCoordinate = pSimpleItem->coordinate();
} else if(!firstCoordinate.isValid()) {
firstCoordinate = pSimpleItem->coordinate();
}
double lat = pSimpleItem->coordinate().latitude() + 90.0;
double lon = pSimpleItem->coordinate().longitude() + 180.0;
double alt = pSimpleItem->coordinate().altitude();
north = fmax(north, lat);
south = fmin(south, lat);
east = fmax(east, lon);
west = fmin(west, lon);
minAlt = fmin(minAlt, alt);
maxAlt = fmax(maxAlt, alt);
}
break;
default:
break;
}
}
} else {
ComplexMissionItem* pComplexItem = qobject_cast<ComplexMissionItem*>(item);
if(pComplexItem) {
QGCGeoBoundingCube bc = pComplexItem->boundingCube();
if(bc.isValid()) {
if(!firstCoordinate.isValid() && pComplexItem->coordinate().isValid()) {
firstCoordinate = pComplexItem->coordinate();
}
north = fmax(north, bc.pointNW.latitude() + 90.0);
south = fmin(south, bc.pointSE.latitude() + 90.0);
east = fmax(east, bc.pointNW.longitude() + 180.0);
west = fmin(west, bc.pointSE.longitude() + 180.0);
minAlt = fmin(minAlt, bc.pointNW.altitude());
maxAlt = fmax(maxAlt, bc.pointSE.altitude());
}
}
}
}
//-- Figure out where this thing is taking off from
if(!takeoffCoordinate.isValid()) {
if(firstCoordinate.isValid()) {
takeoffCoordinate = firstCoordinate;
} else {
takeoffCoordinate = plannedHomePosition();
}
}
//-- Build bounding "cube"
boundingCube = QGCGeoBoundingCube(
QGeoCoordinate(north - 90.0, west - 180.0, minAlt),
QGeoCoordinate(south - 90.0, east - 180.0, maxAlt));
if(_travelBoundingCube != boundingCube || _takeoffCoordinate != takeoffCoordinate) {
_takeoffCoordinate = takeoffCoordinate;
_travelBoundingCube = boundingCube;
emit missionBoundingCubeChanged();
qCDebug(MissionControllerLog) << "Bounding cube:" << _travelBoundingCube.pointNW << _travelBoundingCube.pointSE;
}
}
void MissionController::_complexBoundingBoxChanged()
{
_updateTimer.start(UPDATE_TIMEOUT);
}
bool MissionController::isEmpty(void) const
{
return _visualItems->count() <= 1;
}
void MissionController::_takeoffItemNotRequiredChanged(void)
{
// Force a recalc of allowed bits
setCurrentPlanViewSeqNum(_currentPlanViewSeqNum, true /* force */);
}
QString MissionController::surveyComplexItemName(void) const
{
return SurveyComplexItem::name;
}
QString MissionController::corridorScanComplexItemName(void) const
{
return CorridorScanComplexItem::name;
}
QString MissionController::structureScanComplexItemName(void) const
{
return StructureScanComplexItem::name;
}
void MissionController::_allItemsRemoved(void)
{
// When there are no mission items we track changes to firmware/vehicle type. This allows a vehicle connection
// to adjust these items.
_controllerVehicle->trackFirmwareVehicleTypeChanges();
}
void MissionController::_firstItemAdded(void)
{
// As soon as the first item is added we lock the firmware/vehicle type to current values. So if you then connect a vehicle
// it will not affect these values.
_controllerVehicle->stopTrackingFirmwareVehicleTypeChanges();
}
MissionController::SendToVehiclePreCheckState MissionController::sendToVehiclePreCheck(void)
{
if (_managerVehicle->isOfflineEditingVehicle()) {
return SendToVehiclePreCheckStateNoActiveVehicle;
}
if (_managerVehicle->armed() && _managerVehicle->flightMode() == _managerVehicle->missionFlightMode()) {
return SendToVehiclePreCheckStateActiveMission;
}
if (_controllerVehicle->firmwareType() != _managerVehicle->firmwareType() || QGCMAVLink::vehicleClass(_controllerVehicle->vehicleType()) != QGCMAVLink::vehicleClass(_managerVehicle->vehicleType())) {
return SendToVehiclePreCheckStateFirwmareVehicleMismatch;
}
return SendToVehiclePreCheckStateOk;
}
QGroundControlQmlGlobal::AltitudeMode MissionController::globalAltitudeMode(void)
{
return _globalAltMode;
}
QGroundControlQmlGlobal::AltitudeMode MissionController::globalAltitudeModeDefault(void)
{
if (_globalAltMode == QGroundControlQmlGlobal::AltitudeModeNone) {
return QGroundControlQmlGlobal::AltitudeModeRelative;
} else {
return _globalAltMode;
}
}
void MissionController::setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeMode altMode)
{
if (_globalAltMode != altMode) {
_globalAltMode = altMode;
emit globalAltitudeModeChanged();
}
}
| cpp |
<reponame>gregarndt/gaia
// Tests the keyboard_helper.js from shared
'use strict';
require('/shared/test/unit/mocks/mock_manifest_helper.js');
require('/shared/test/unit/mocks/mock_navigator_moz_apps.js');
require('/shared/test/unit/mocks/mock_navigator_moz_settings.js');
require('/shared/js/keyboard_helper.js');
suite('KeyboardHelper', function() {
var mocksHelper = new MocksHelper(['ManifestHelper']).init();
mocksHelper.attachTestHelpers();
var realMozSettings;
var realMozApps;
var appEvents = ['applicationinstall', 'applicationinstallsuccess',
'applicationuninstall'];
var DEFAULT_KEY = 'keyboard.default-layouts';
var ENABLED_KEY = 'keyboard.enabled-layouts';
var THIRD_PARTY_APP_ENABLED_KEY = 'keyboard.3rd-party-app.enabled';
var keyboardAppOrigin = 'app://keyboard.gaiamobile.org';
var keyboardAppManifestURL =
'app://keyboard.gaiamobile.org/manifest.webapp';
var standardKeyboards = [
{
manifestURL: keyboardAppManifestURL,
manifest: {
role: 'input',
inputs: {
en: {
types: ['url', 'text'],
launch_path: '/index.html#en'
},
es: {
types: ['url', 'text'],
launch_path: '/index.html#es'
},
fr: {
types: ['url', 'text'],
launch_path: '/index.html#fr'
},
pl: {
types: ['url', 'text'],
launch_path: '/index.html#pl'
},
number: {
types: ['number'],
launch_path: '/index.html#number'
}
}
}
}
];
var defaultSettings = {
oldEnabled: [
{
layoutId: 'en',
appOrigin: keyboardAppOrigin,
enabled: true
},
{
layoutId: 'es',
appOrigin: keyboardAppOrigin,
enabled: false
},
{
layoutId: 'fr',
appOrigin: keyboardAppOrigin,
enabled: false
},
{
layoutId: 'pl',
appOrigin: keyboardAppOrigin,
enabled: false
},
{
layoutId: 'number',
appOrigin: keyboardAppOrigin,
enabled: true
}
],
'default': {}
};
defaultSettings['default'][keyboardAppManifestURL] = {en: true};
defaultSettings.enabled = defaultSettings['default'];
var DEPRECATE_KEYBOARD_SETTINGS = {
en: 'keyboard.layouts.english',
'en-Dvorak': 'keyboard.layouts.dvorak',
cs: 'keyboard.layouts.czech',
fr: 'keyboard.layouts.french',
de: 'keyboard.layouts.german',
hu: 'keyboard.layouts.hungarian',
nb: 'keyboard.layouts.norwegian',
my: 'keyboard.layouts.myanmar',
sl: 'keyboard.layouts.slovak',
tr: 'keyboard.layouts.turkish',
ro: 'keyboard.layouts.romanian',
ru: 'keyboard.layouts.russian',
ar: 'keyboard.layouts.arabic',
he: 'keyboard.layouts.hebrew',
'zh-Hant-Zhuyin': 'keyboard.layouts.zhuyin',
'zh-Hans-Pinyin': 'keyboard.layouts.pinyin',
el: 'keyboard.layouts.greek',
'jp-kanji': 'keyboard.layouts.japanese',
pl: 'keyboard.layouts.polish',
'pt-BR': 'keyboard.layouts.portuguese',
sr: 'keyboard.layouts.serbian',
es: 'keyboard.layouts.spanish',
ca: 'keyboard.layouts.catalan'
};
function trigger(event) {
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, true, false, {});
window.dispatchEvent(evt);
}
suiteSetup(function() {
realMozApps = navigator.mozApps;
navigator.mozApps = MockNavigatormozApps;
realMozSettings = navigator.mozSettings;
navigator.mozSettings = MockNavigatorSettings;
// ensure the default settings are indeed default
assert.deepEqual(KeyboardHelper.settings['default'],
defaultSettings['default']);
});
suiteTeardown(function() {
navigator.mozApps = realMozApps;
navigator.mozSettings = realMozSettings;
});
setup(function() {
MockNavigatorSettings.mSyncRepliesOnly = true;
// reset KeyboardHelper each time
KeyboardHelper.settings.enabled = {};
KeyboardHelper.settings['default'] = defaultSettings['default'];
KeyboardHelper.keyboardSettings = [];
KeyboardHelper.init();
});
teardown(function() {
MockNavigatorSettings.mTeardown();
});
test('observes settings', function() {
assert.equal(MockNavigatorSettings.mObservers[ENABLED_KEY].length, 1);
assert.equal(MockNavigatorSettings.mObservers[DEFAULT_KEY].length, 1);
});
test('requests initial settings', function() {
var requests = MockNavigatorSettings.mRequests;
assert.equal(requests.length, 26);
assert.ok(DEFAULT_KEY in requests[0].result, 'requested defaults');
assert.ok(ENABLED_KEY in requests[1].result, 'requested enabled');
assert.ok(THIRD_PARTY_APP_ENABLED_KEY in requests[2].result,
'requested 3rd-party keyboard app enabled');
var i = 0;
for (var key in DEPRECATE_KEYBOARD_SETTINGS) {
assert.ok(DEPRECATE_KEYBOARD_SETTINGS[key] in requests[3 + i].result,
'requested deprecated settings - ' +
DEPRECATE_KEYBOARD_SETTINGS[key]);
i++;
}
});
suite('getApps', function() {
setup(function() {
this.apps = [
{
origin: 'app://keyboard.gaiamobile.org',
manifestURL: 'app://keyboard.gaiamobile.org/manifest.webapp',
manifest: {
type: 'privileged',
role: 'input',
inputs: {},
permissions: {
input: {}
}
}
}, {
origin: 'app://keyboard2.gaiamobile.org',
manifestURL: 'app://keyboard2.gaiamobile.org/manifest.webapp',
manifest: {
type: 'certified',
role: 'input',
inputs: {},
permissions: {
input: {}
}
}
},
// vaild only if 3rd-party keyboard app support is enabled
{
origin: 'app://keyboard.notgaiamobile.org',
manifestURL: 'app://keyboard.notgaiamobile.org/manifest.webapp',
manifest: {
type: 'privileged',
role: 'input',
inputs: {},
permissions: {
input: {}
}
}
},
// vaild only if 3rd-party keyboard app support is enabled
{
origin: 'app://keyboard.notgaiamobile.org',
manifestURL:
'app://keyboard.example.com/hello.gaiamobile.org/manifest.webapp',
manifest: {
type: 'privileged',
role: 'input',
inputs: {},
permissions: {
input: {}
}
}
},
// invalid because there aren't inputs
{
origin: 'app://keyboard.gaiamobile.org',
manifestURL: 'app://keyboard.gaiamobile.org/manifest.webapp',
manifest: {
type: 'certified',
role: 'input',
permissions: {
input: {}
}
}
},
// invalid because it's not input role
{
origin: 'app://keyboard.gaiamobile.org',
manifestURL: 'app://keyboard.gaiamobile.org/manifest.webapp',
manifest: {
type: 'privileged',
role: 'notinput',
inputs: {},
permissions: {
input: {}
}
}
},
// invalid because it's not privileged, nor certified
{
origin: 'app://keyboard-no.gaiamobile.org',
manifestURL: 'app://keyboard-no.gaiamobile.org/manifest.webapp',
manifest: {
role: 'input',
inputs: {},
permissions: {
input: {}
}
}
},
// invalid because it does not have input permission
{
origin: 'app://keyboard-no.gaiamobile.org',
manifestURL: 'app://keyboard-no.gaiamobile.org/manifest.webapp',
manifest: {
type: 'privileged',
role: 'input',
inputs: {},
permissions: {
notinput: {}
}
}
}
];
this.callback = this.sinon.spy();
this.sinon.stub(navigator.mozApps.mgmt, 'getAll', function() {
return {};
});
KeyboardHelper.setLayoutEnabled('app://not-an-app', 'en', true);
KeyboardHelper.getApps(this.callback);
});
test('requests all apps from mozApps', function() {
assert.isTrue(navigator.mozApps.mgmt.getAll.called);
});
test('never calls back if no response', function() {
assert.isFalse(this.callback.called);
});
test('never calls back if no valid apps', function() {
var request = navigator.mozApps.mgmt.getAll.returnValues[0];
request.result = [];
request.onsuccess({ target: request });
assert.isFalse(this.callback.called);
});
suite('valid response', function() {
setup(function() {
var request = navigator.mozApps.mgmt.getAll.returnValues[0];
request.result = this.apps;
request.onsuccess({ target: request });
});
test('correctly filters test data', function() {
// only the first 4 are valid (including 2 third-party keyboard apps).
var filtered = this.apps.slice(0, 4);
var results = this.callback.args[0][0];
assert.deepEqual(results, filtered);
});
test('removed illegal app from settings', function() {
assert.isFalse(
KeyboardHelper.getLayoutEnabled('app://not-an-app', 'en'),
'correctly disabled the missing app origin'
);
});
suite('second request', function() {
setup(function() {
this.lastResult = this.callback.args[0][0];
this.callback.reset();
navigator.mozApps.mgmt.getAll.reset();
KeyboardHelper.getApps(this.callback);
});
test('does not request apps again', function() {
assert.isFalse(navigator.mozApps.mgmt.getAll.called);
});
test('re-uses same results', function() {
assert.equal(this.callback.args[0][0], this.lastResult);
});
});
appEvents.forEach(function eventSuite(event) {
suite(event + ' event clears cache', function() {
setup(function() {
trigger(event);
this.callback.reset();
navigator.mozApps.mgmt.getAll.reset();
KeyboardHelper.getApps(this.callback);
});
test('requests apps again', function() {
assert.isTrue(navigator.mozApps.mgmt.getAll.called);
});
test('does not immediately call callback', function() {
assert.isFalse(this.callback.called);
});
});
});
});
});
suite('isKeyboardType', function() {
['text', 'url', 'email', 'password', 'number', 'option']
.forEach(function(type) {
test(type + ': true', function() {
assert.isTrue(KeyboardHelper.isKeyboardType(type));
});
});
['not', 'base', 'type', undefined, 1]
.forEach(function(type) {
test(type + ': false', function() {
assert.isFalse(KeyboardHelper.isKeyboardType(type));
});
});
});
suite('checkDefaults', function() {
setup(function() {
this.defaultLayouts = [];
this.getLayouts = this.sinon.stub(KeyboardHelper, 'getLayouts',
function(options, callback) {
if (options.enabled) {
return callback([]);
}
if (options.default) {
var layout = { type: options.type };
this.defaultLayouts.push(layout);
return callback([layout]);
}
}.bind(this));
this.callback = this.sinon.spy();
KeyboardHelper.checkDefaults(this.callback);
});
test('enabled default layouts', function() {
assert.equal(this.defaultLayouts.length, 2);
});
['text', 'url'].forEach(function(type) {
test('enabled a "' + type + '" layout', function() {
assert.ok(this.defaultLayouts.some(function(layout) {
return layout.type === type && layout.enabled;
}));
});
});
test('called with default layouts', function() {
assert.deepEqual(this.callback.args[0][0], this.defaultLayouts);
});
});
suite('getLayouts', function() {
setup(function() {
MockNavigatorSettings.mRequests[0].result[DEFAULT_KEY] =
defaultSettings['default'];
MockNavigatorSettings.mRequests[1].result[ENABLED_KEY] =
defaultSettings.enabled;
this.sinon.stub(KeyboardHelper, 'getApps');
this.sinon.spy(window, 'ManifestHelper');
this.apps = [{
origin: keyboardAppOrigin,
manifestURL: keyboardAppManifestURL,
manifest: {
role: 'input',
inputs: {
en: {
types: ['text', 'url']
},
number: {
types: ['number']
},
noType: {}
}
}
}, {
origin: 'app://keyboard2.gaiamobile.org',
manifestURL: 'app://keyboard2.gaiamobile.org/manifest.webapp',
manifest: {
role: 'input',
inputs: {
number: {
types: ['number', 'url']
}
}
}
}];
});
suite('waits for settings to load to reply', function() {
setup(function() {
this.callback = this.sinon.spy();
KeyboardHelper.getLayouts(this.callback);
KeyboardHelper.getApps.yield(this.apps);
});
test('callback not called', function() {
assert.isFalse(this.callback.called);
});
test('called after reply', function() {
MockNavigatorSettings.mReplyToRequests();
assert.isTrue(this.callback.called);
});
});
suite('basic operation', function() {
setup(function() {
MockNavigatorSettings.mReplyToRequests();
delete this.result;
KeyboardHelper.settings.enabled = defaultSettings.enabled;
KeyboardHelper.getLayouts(function(result) {
this.result = result;
}.bind(this));
KeyboardHelper.getApps.yield(this.apps);
});
test('3 layouts found', function() {
assert.equal(this.result.length, 3);
});
test('Created ManifestHelpers', function() {
assert.ok(ManifestHelper.calledWith(this.apps[0].manifest));
assert.ok(ManifestHelper.calledWith(this.apps[1].manifest));
});
test('Correct info', function() {
assert.equal(this.result[0].app, this.apps[0]);
assert.equal(this.result[0].layoutId, 'en');
assert.equal(this.result[0].enabled, true);
assert.equal(this.result[0]['default'], true);
assert.equal(this.result[1].app, this.apps[0]);
assert.equal(this.result[1].layoutId, 'number');
assert.equal(this.result[1].enabled, false);
assert.equal(this.result[1]['default'], false);
assert.equal(this.result[2].app, this.apps[1]);
assert.equal(this.result[2].layoutId, 'number');
assert.equal(this.result[2].enabled, false);
assert.equal(this.result[2]['default'], false);
});
});
suite('{ default: true }', function() {
setup(function() {
MockNavigatorSettings.mReplyToRequests();
delete this.result;
KeyboardHelper.getLayouts({ 'default': true }, function(result) {
this.result = result;
}.bind(this));
KeyboardHelper.settings.enabled = defaultSettings.enabled;
KeyboardHelper.getApps.yield(this.apps);
});
test('1 layout found', function() {
assert.equal(this.result.length, 1);
});
test('only default keyboards', function() {
assert.ok(this.result.every(function(layout) {
return layout['default'];
}));
});
test('sorts layouts by number of types', function() {
// most specific layouts first
assert.ok(this.result.reduce(function(inOrder, layout) {
if (!inOrder) {
return false;
}
if (layout.inputManifest.types.length < inOrder) {
return false;
}
return layout.inputManifest.types.length;
}, 1));
});
});
suite('{ enabled: true }', function() {
setup(function() {
MockNavigatorSettings.mReplyToRequests();
delete this.result;
KeyboardHelper.getLayouts({ enabled: true }, function(result) {
this.result = result;
}.bind(this));
KeyboardHelper.settings.enabled = defaultSettings.enabled;
KeyboardHelper.getApps.yield(this.apps);
});
test('1 layout found', function() {
assert.equal(this.result.length, 1);
});
test('only enabled keyboards', function() {
assert.ok(this.result.every(function(layout) {
return layout.enabled;
}));
});
});
suite('{ type: "number" }', function() {
setup(function() {
MockNavigatorSettings.mReplyToRequests();
delete this.result;
KeyboardHelper.getLayouts({ type: 'number' }, function(result) {
this.result = result;
}.bind(this));
KeyboardHelper.settings.enabled = defaultSettings.enabled;
KeyboardHelper.getApps.yield(this.apps);
});
test('2 layouts found', function() {
assert.equal(this.result.length, 2);
});
test('only number keyboards', function() {
assert.ok(this.result.every(function(layout) {
return layout.inputManifest.types.indexOf('number') !== -1;
}));
});
});
suite('{ type: "url" }', function() {
setup(function() {
MockNavigatorSettings.mReplyToRequests();
delete this.result;
KeyboardHelper.getLayouts({ type: 'url' }, function(result) {
this.result = result;
}.bind(this));
KeyboardHelper.settings.enabled = defaultSettings.enabled;
KeyboardHelper.getApps.yield(this.apps);
});
test('2 layouts found', function() {
assert.equal(this.result.length, 2);
});
test('only url keyboards', function() {
assert.ok(this.result.every(function(layout) {
return layout.inputManifest.types.indexOf('url') !== -1;
}));
});
});
});
suite('Fallback layout with getLayouts', function() {
var oldFallbackLayoutNames;
var oldFallbackLayouts;
setup(function() {
MockNavigatorSettings.mRequests[0].result[DEFAULT_KEY] =
defaultSettings['default'];
MockNavigatorSettings.mRequests[1].result[ENABLED_KEY] =
defaultSettings.enabled;
this.sinon.stub(KeyboardHelper, 'getApps');
this.sinon.spy(window, 'ManifestHelper');
// since defaultSettings.default does not include fr layout,
// fallback with password-type should be set with fr layout
this.apps = [{
origin: keyboardAppOrigin,
manifestURL: keyboardAppManifestURL,
manifest: {
role: 'input',
inputs: {
en: {
types: ['text', 'url']
},
fr: {
types: ['password']
},
number: {
types: ['number']
}
}
}
}];
MockNavigatorSettings.mReplyToRequests();
oldFallbackLayoutNames = KeyboardHelper.fallbackLayoutNames;
oldFallbackLayouts = KeyboardHelper.fallbackLayouts;
KeyboardHelper.fallbackLayoutNames = {
password: 'fr'
};
KeyboardHelper.getLayouts({ 'default': true }, function() {}.bind(this));
KeyboardHelper.settings.enabled = defaultSettings.enabled;
KeyboardHelper.getApps.yield(this.apps);
});
teardown(function() {
KeyboardHelper.fallbackLayoutNames = oldFallbackLayoutNames;
KeyboardHelper.fallbackLayouts = oldFallbackLayouts;
});
test('fallback layout test', function() {
assert.isTrue('password' in KeyboardHelper.fallbackLayouts,
'"password" type is not in fallback layouts');
assert.equal('fr', KeyboardHelper.fallbackLayouts.password.layoutId,
'fallback layout for "password" is not "fr"');
});
});
suite('watchLayouts', function() {
setup(function() {
MockNavigatorSettings.mRequests[0].result[DEFAULT_KEY] =
defaultSettings['default'];
MockNavigatorSettings.mRequests[1].result[ENABLED_KEY] =
defaultSettings.enabled;
MockNavigatorSettings.mReplyToRequests();
this.callback = this.sinon.spy();
this.getApps = this.sinon.stub(KeyboardHelper, 'getApps');
this.getLayouts = this.sinon.stub(KeyboardHelper, 'getLayouts');
this.layouts = [];
});
suite('watch {}', function() {
setup(function() {
this.options = {};
KeyboardHelper.watchLayouts(this.options, this.callback);
this.getLayouts.yield(this.layouts);
});
test('getLayouts', function() {
assert.ok(this.getLayouts.calledWith(this.options));
});
test('called callback', function() {
assert.ok(this.callback.calledWith(this.layouts));
});
test('callback second arg apps', function() {
assert.ok(this.callback.args[0][1].apps);
});
test('callback second arg settings', function() {
assert.ok(this.callback.args[0][1].settings);
});
appEvents.forEach(function(event) {
suite(event + ' sends new apps', function() {
setup(function() {
this.getApps.reset();
this.getLayouts.reset();
this.callback.reset();
trigger(event);
});
test('requests apps', function() {
assert.ok(this.getApps.called);
});
test('does not request layouts', function() {
assert.isFalse(this.getLayouts.called);
});
test('callback not called', function() {
assert.isFalse(this.callback.called);
});
suite('after apps loaded', function() {
setup(function() {
this.getApps.yield();
});
test('requests layouts', function() {
this.getLayouts.calledWith(this.options);
});
test('callback not called', function() {
assert.isFalse(this.callback.called);
});
suite('got layouts', function() {
setup(function() {
this.callback.reset();
this.getLayouts.yield(this.layouts);
});
test('called callback', function() {
assert.ok(this.callback.calledWith(this.layouts));
});
test('callback second arg apps', function() {
assert.ok(this.callback.args[0][1].apps);
});
});
});
});
});
suite('changing settings', function() {
setup(function() {
this.callback.reset();
this.getApps.reset();
this.getLayouts.reset();
var settings = {};
settings[ENABLED_KEY] = defaultSettings.enabled;
// changing a setting triggers reading settings
MockNavigatorSettings.createLock().set(settings);
// reply to the read requests
MockNavigatorSettings.mReplyToRequests();
// and finally yield data to the getApps/getLayout
this.getApps.yield();
this.getLayouts.yield(this.layouts);
});
test('called callback', function() {
assert.ok(this.callback.calledWith(this.layouts));
});
test('callback second arg settings', function() {
assert.ok(this.callback.args[0][1].settings);
});
});
});
});
suite('empty settings (create defaults)', function() {
setup(function() {
this.sinon.stub(KeyboardHelper, 'saveToSettings');
MockNavigatorSettings.mReplyToRequests();
});
test('default settings loaded', function() {
assert.deepEqual(KeyboardHelper.settings.enabled,
defaultSettings.enabled);
});
test('saves settings', function() {
assert.isTrue(KeyboardHelper.saveToSettings.called);
});
});
suite('bad json settings (create defaults)', function() {
setup(function() {
this.sinon.stub(KeyboardHelper, 'saveToSettings');
MockNavigatorSettings.mRequests[1].result[ENABLED_KEY] =
'notjson';
MockNavigatorSettings.mReplyToRequests();
});
test('default settings loaded', function() {
assert.deepEqual(KeyboardHelper.settings.enabled,
defaultSettings.enabled);
});
test('saves settings', function() {
assert.isTrue(KeyboardHelper.saveToSettings.called);
});
});
suite('default settings (old string format)', function() {
setup(function() {
this.sinon.spy(KeyboardHelper, 'saveToSettings');
MockNavigatorSettings.mRequests[1].result[ENABLED_KEY] =
JSON.stringify(defaultSettings.oldEnabled);
MockNavigatorSettings.mReplyToRequests();
});
test('loaded settings properly', function() {
assert.deepEqual(KeyboardHelper.settings.enabled,
defaultSettings.enabled);
});
test('does not save settings', function() {
assert.isFalse(KeyboardHelper.saveToSettings.called);
});
test('es layout disabled (sanity check)', function() {
assert.isFalse(KeyboardHelper.getLayoutEnabled(keyboardAppManifestURL,
'es'));
});
suite('setLayoutEnabled', function() {
setup(function() {
KeyboardHelper.setLayoutEnabled(keyboardAppManifestURL, 'es', true);
KeyboardHelper.saveToSettings();
});
test('es layout enabled', function() {
assert.isTrue(KeyboardHelper.getLayoutEnabled(keyboardAppManifestURL,
'es'));
});
test('saves', function() {
assert.isTrue(KeyboardHelper.saveToSettings.called);
// with the right data
var data = {};
data[keyboardAppManifestURL] = { en: true, es: true };
assert.deepEqual(MockNavigatorSettings.mSettings[ENABLED_KEY],
data);
assert.deepEqual(MockNavigatorSettings.mSettings[DEFAULT_KEY],
defaultSettings['default']);
// and we requested to read it
assert.ok(MockNavigatorSettings.mRequests.length);
});
suite('save reloads settings', function() {
setup(function() {
this.oldSettings = KeyboardHelper.settings.enabled;
MockNavigatorSettings.mReplyToRequests();
});
test('new settings object', function() {
assert.notEqual(KeyboardHelper.settings.enabled, this.oldSettings);
});
test('same data', function() {
assert.deepEqual(KeyboardHelper.settings.enabled, this.oldSettings);
});
});
});
});
suite('migrate old settings', function() {
var expectedSettings = {
'default': {},
enabled: {}
};
suite('old settings: cs enabled', function() {
setup(function() {
this.sinon.stub(KeyboardHelper, 'saveToSettings');
MockNavigatorSettings.mRequests[3].
result[DEPRECATE_KEYBOARD_SETTINGS.en] = false;
MockNavigatorSettings.mRequests[5].
result[DEPRECATE_KEYBOARD_SETTINGS.cs] = true;
MockNavigatorSettings.mReplyToRequests();
});
test('default settings loaded with cs', function() {
expectedSettings['enabled'][keyboardAppManifestURL] =
{cs: true};
assert.deepEqual(KeyboardHelper.settings.enabled,
expectedSettings.enabled);
});
test('saves settings', function() {
assert.isTrue(KeyboardHelper.saveToSettings.called);
});
});
suite('old settings: serbian enabled', function() {
setup(function() {
this.sinon.stub(KeyboardHelper, 'saveToSettings');
MockNavigatorSettings.mRequests[3].
result[DEPRECATE_KEYBOARD_SETTINGS.en] = false;
MockNavigatorSettings.mRequests[23].
result[DEPRECATE_KEYBOARD_SETTINGS.sr] = true;
MockNavigatorSettings.mReplyToRequests();
});
test('default settings loaded with cs', function() {
expectedSettings['enabled'][keyboardAppManifestURL] =
{'sr-Cyrl': true, 'sr-Latn': true};
assert.deepEqual(KeyboardHelper.settings.enabled,
expectedSettings.enabled);
});
test('saves settings', function() {
assert.isTrue(KeyboardHelper.saveToSettings.called);
});
});
});
suite('default settings', function() {
setup(function() {
this.sinon.spy(KeyboardHelper, 'saveToSettings');
MockNavigatorSettings.mRequests[1].result[ENABLED_KEY] =
defaultSettings.enabled;
MockNavigatorSettings.mReplyToRequests();
});
test('loaded settings properly', function() {
assert.deepEqual(KeyboardHelper.settings.enabled,
defaultSettings.enabled);
});
test('does not save settings', function() {
assert.isFalse(KeyboardHelper.saveToSettings.called);
});
});
suite('change default settings', function() {
var expectedSettings = {
'default': {},
enabled: {}
};
suiteSetup(function(done) {
KeyboardHelper.getDefaultLayoutConfig(function(configData) {
done();
});
});
setup(function() {
// reset KeyboardHelper each time
KeyboardHelper.settings['default'] = defaultSettings['default'];
KeyboardHelper.settings['enabled'] = defaultSettings['default'];
});
test('change default settings, keeping the enabled layouts', function() {
expectedSettings['default'][keyboardAppManifestURL] = {fr: true};
expectedSettings['enabled'][keyboardAppManifestURL] = {en: true,
fr: true};
KeyboardHelper.changeDefaultLayouts('fr', false);
assert.deepEqual(KeyboardHelper.settings.default,
expectedSettings['default']);
assert.deepEqual(KeyboardHelper.settings.enabled,
expectedSettings.enabled);
});
test('change default settings and reset enabled layouts', function() {
expectedSettings['default'][keyboardAppManifestURL] = {es: true};
expectedSettings['enabled'][keyboardAppManifestURL] = {es: true};
KeyboardHelper.changeDefaultLayouts('es', true);
assert.deepEqual(KeyboardHelper.settings.default,
expectedSettings['default']);
assert.deepEqual(KeyboardHelper.settings.enabled,
expectedSettings.enabled);
});
test('change default settings and reset for nonLatin', function() {
expectedSettings['default'][keyboardAppManifestURL] = {
'zh-Hant-Zhuyin': true, en: true};
expectedSettings['enabled'][keyboardAppManifestURL] = {
'zh-Hant-Zhuyin': true, en: true};
KeyboardHelper.changeDefaultLayouts('zh-TW', true);
assert.deepEqual(KeyboardHelper.settings.default,
expectedSettings['default']);
assert.deepEqual(KeyboardHelper.settings.enabled,
expectedSettings.enabled);
});
});
});
| javascript |
{
"latest_version": [
"0.0.1"
],
"meta": {
"description": "Add real HTML punctuation",
"homepage": "https://github.com/honza/punctuation"
},
"versions": {}
} | json |
{"inferno-component.js":"<KEY>,"inferno-component.min.js":"<KEY>,"inferno-create-element.js":"<KEY>,"inferno-create-element.min.js":"sha512-237zrDAh0oBxqf+khtO0AFsgixugHEOBqrMv05tUxiKDryTPuwI8UqNupOhV9T59vASbaoNLSrGOI7WBJxwStw==","inferno-dom.js":"<KEY>,"inferno-dom.min.js":"<KEY>,"inferno-router.js":"<KEY>CNgg==","inferno-router.min.js":"<KEY>,"inferno-server.js":"<KEY>,"inferno-server.min.js":"<KEY>,"inferno-test-utils.js":"sha512-s1W3uIByGloz21r4Vvsgi+GT7AfI5/EIIZILUdhgMkv2jZbdQOlSZM1xVmDwOcZtg33OD9V/fQoBqnhEnErHrQ==","inferno-test-utils.min.js":"sha512-CNDuKI0r17I1NijrTlsW/0fvGB1eaBYKvOj++ZHULQ3bYsP/ncfHotP+0i7VDq3yHA8wpadoCBz8W5P+5dxRJg==","inferno.js":"<KEY>,"inferno.min.js":"<KEY>} | json |
<gh_stars>0
{"id":248,"series":"QT","title":"(NOUVEAU QT) Tutoriel de l'assistant de configuration","tagline":"","steps":[{"step_id":1966,"number":1,"true_number":0,"step_type":"Step","step":"[bold]Pour prévenir l'affichage de l'assistant après chaque redémarrage :[/bold][br]décochez l'option[blue]Activer l'assistant la prochaine fois.[/blue][br]Cliquez sur [red]Configuration avec l'assistant[/red] pour commencer.","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw1.PNG?1463673545"},{"step_id":1967,"number":2,"true_number":1,"step_type":"Step","step":"Sélectionnez la [blue]Langue[/blue] pour votre système.[br]Cliquez sur [red]Suivant[/red]","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw2.PNG?1463673690"},{"step_id":1968,"number":3,"true_number":2,"step_type":"Step","step":"À l'aide du clavier visuel, saisissez le [blue]Nouveau mot de passe[/blue] pour votre système.[br]Retapez ce mot dans le champ [blue]Confirmer le mot de passe[/blue].[br][br]Cliquez sur [red]Modifier une question de sécurité[/red] pour configurer l'outil de récupération du mot de passe.","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw3.PNG?1463674091"},{"step_id":1969,"number":4,"true_number":3,"step_type":"Step","step":"Saisissez la [blue]Question[/blue] de sécurité que vous souhaitez utiliser, puis la [blue]Réponse[/blue].[br]Cliquez sur [red]Ajouter[/red][br][note]Répétez cette étape pour ajouter d'autres questions.[/note]","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw4.PNG?1463674504"},{"step_id":1970,"number":5,"true_number":4,"step_type":"Step","step":"Cliquez sur [red]OK[/red]","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw5.PNG?1463674554"},{"step_id":1971,"number":6,"true_number":5,"step_type":"Step","step":"Cliquez sur [red]Suivant[/red]","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw6.PNG?1463674584"},{"step_id":1972,"number":7,"true_number":6,"step_type":"Step","step":"[blue]Réglez la date et l'heure [/blue]:[br][br] Préférences de fuseau horaire[br][bold]Terre-Neuve [/bold]: -03:30[br][bold]Heure de l'Atlantique [/bold]: -04:00[br][bold]Heure normale de l'Est [/bold]: -05:00[br][bold]Heure normale du Centre [/bold]: -06:00[br][bold]Heure normale des Rocheuses [/bold]: -07:00[br][bold]Heure normale du Pacifique [/bold]: -08:00[br][bold]Alaska [/bold]: -09:00[br][bold]Hawaii [/bold]: -10:00[br][br]Cliquez sur [red]Suivant[/red]","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw7.PNG?1463752897"},{"step_id":1973,"number":8,"true_number":7,"step_type":"Step","step":"Cliquez sur [red]Suivant[/red] pour passer à la configuration du réseau.","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw8.PNG?1463675386"},{"step_id":1974,"number":9,"true_number":8,"step_type":"Step","step":"Notez votre [blue]Numéro de série[/blue].[br][bold]Vous en aurez besoin pour accéder à votre système depuis vos appareils mobiles et vos ordinateurs.[/bold][br]Cliquez sur [red]OK[/red] pour mettre fin à l'assistant.","image":"http://q-see.s3.amazonaws.com/content/support/howto/qtngw9.PNG?1463675685"}]} | json |
<filename>app.json
{
"name": "dns",
"description": "Deploy dns on Heroku.",
"keywords": [""],
"website": "https://github.com/DNSCrypt/",
"repository": "https://github.com/DNSCrypt/dnscrypt-server-docker",
"stack": "container"
}
| json |
<filename>data/nixpkgs/outputs/php80Extensions.ldap.json
{
"dev": [
"/include/config.h",
"/include/ldap_arginfo.h",
"/include/php_ldap.h",
"/nix-support/propagated-build-inputs"
],
"out": [
"/lib/php/extensions/ldap.so"
]
} | json |
<filename>test/setup.js
// mute some warnings and make everything else an error
console.error = function (message) { // eslint-disable-line no-console
throw new Error(message)
}
console.warning = function (message) { // eslint-disable-line no-console
throw new Error(message)
}
// configure test suite
const unexpected = require('unexpected')
const unexpectedImmutable = require('unexpected-immutable')
const unexpectedReact = require('unexpected-react')
const unexpectedSinon = require('unexpected-sinon')
unexpected.use(unexpectedImmutable)
unexpected.use(unexpectedReact)
unexpected.use(unexpectedSinon)
| javascript |
<gh_stars>0
import { commonCSS } from './common.css';
export const mailTemplate = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>${commonCSS}</style>
</head>
<body>
<div class="body">
<div class="content">
<div>Xin chào {{username}},</div>
<br>
<div class="description">Kết quả xet nghiệm đã có, vui lòng truy cập website để xem kết quả</div>
<br>
<div>
</div>
</body>
</html>
`;
| typescript |
<reponame>CharmaineKarlsen/dummy_recommender<gh_stars>0
'''
testing test
'''
import pandas as pd
from recommender import recommend_random
# testing the recommend_random function to check length equals 10
def test_recommender():
"""
testing recommender
"""
movies = pd.read_csv('./data/movies.csv')
recommendations = recommend_random(movies=movies,k=10)
assert len(recommendations)==10
| python |
In a clear demonstration of her immense popularity with advertisers and audiences, the young and talented actor Mithila Palkar has signed two strong endorsement deals in a span of just one month with pizza brand, EatFit and cosmetics brand, Plum.
In a clear demonstration of her immense popularity with advertisers and audiences, the young and talented actor Mithila Palkar has signed two strong endorsement deals in a span of just one month with pizza brand, EatFit and cosmetics brand, Plum.
This commendable feat comes on the back of the beautiful actor's great success in her film with Kajol, Tribhanga and the much-loved fourth season of hot series Little Things.
Says Alok Damani, Business Head at Exceed Entertainment, "We're seeing a clear shift with advertisers preferring stars who demonstrate a strong and genuine connect with their fans and followers. With trends shifting towards D2C brands and digital marketing, celebrities that have a big appeal in these areas are in big demand. These endorsements are a clear testimony that Mithila's equity is soaring among millennial audiences based on her unmatched and genuine appeal in this segment. "
Speaking on her massive connect with Gen Z, Gokul Kandhi, Business Head, EatFit, said, "Mithila is the perfect ambassador to resonate with our target groups. She portrays authenticity and is truly Indian at heart, much like the EatFit brand. "
This view was further endorsed by Shankar Prasad, CEO and founder at Plum, "Plum is a youthful brand that resonates with the confident woman of today. So, on boarding a millennial youth icon like Mithila Palkar seemed to be a natural fit. She reflects Plum's values of being honest and real. "
Mithila currently enjoys being the face of 4 dynamic brands like Plum Goodness, Eat. fit, Mia by Tanishq and Carmesi. Having successfully made her mark on the Hindi and Marathi mediums, Mithila is widening her pan India appeal with setting foot in India's growing South entertainment market. Her upcoming Telugu debut release opposite Vishwak Sen is touted as one of the most anticipated film of Mithila Palkar. We watch the journey of this star with great interest!
This story is provided by NewsVoir. will not be responsible in any way for the content of this article. (ANI/NewsVoir)
( With inputs from ANI ) | english |
Things got heated between Kyrie Irving and Xavier Tillman during the Memphis Grizzlies‘ 120-103 over the Dallas Mavericks on Tuesday. The two got into a verbal altercation after a foul on Irving, and X (formerly Twitter) user Legend_Z decoded the trash talk between the duo.
Obviously, Tillman had the last laugh as the Grizzlies pulled off a surprise win over the Mavericks. He finished the game with 14 points and 11 rebounds. Irving also had a spectacular outing. He scored 33 points, grabbed eight rebounds, and dished four assists. Desmond Bane was the star of the show for the Grizzlies with a team-high 32 points, nine rebounds, and four assists.
The trash-talking fired up both Irving and Tillman as they were excellent for their respective teams. Neither player resorted to personal jibes and instead only boasted about their ability. Healthy competition between two elite athletes soothes the soul.
Fans on X had plenty to say about the verbal altercation between Kyrie Irving and Xavier Tillman. One fan questioned whether the Grizzlies star even has the authority to engage in trash-talking with the Mavericks superstar.
Another fan was kind enough to give the entire context of the play, which led to the trash-talking. Tillman played excellent defense against Irving, but the Mavericks superstar was too crafty and eventually found a way to draw a foul and earn two free throws.
Another fan showed a clip of Tillman fending off Irving with stellar defense. However, despite the Grizzlies forward and his teammates’ best effort, the Mavericks superstar scored 33 points.
While most fans were focused on the trash-talking, one couldn’t get past Irving reminding the world that he’s in his 13th NBA season. It doesn’t feel real that the Mavericks superstar is now a senior statesman in the NBA. Irving will turn 32 in March but it feels like it was only a couple of years ago when he was touted as a future MVP. Things haven’t panned out how many envisioned, but Irving has built an incredible resume.
This was the fourth and final meeting between the two sides this season unless they face off in the playoffs. They split the season series 2-2. This marks the first time since the 2016-17 series that the season series between these two teams has finished in a 2-2 tie.
Surprisingly, neither team won their home against but had a 100% win record on the road. The Mavericks will look to bounce back when they host the New York Knicks on Thursday, while the Grizzlies will eye a fourth-straight win when they host the red-hot Los Angeles Clippers.
| english |
package fakekube.io.model;
import fakekube.io.model.IoK8sApiDiscoveryV1beta1Endpoint;
import fakekube.io.model.IoK8sApiDiscoveryV1beta1EndpointPort;
import fakekube.io.model.IoK8sApimachineryPkgApisMetaV1ObjectMeta;
import io.swagger.annotations.ApiModel;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.*;
import javax.validation.Valid;
import io.swagger.annotations.ApiModelProperty;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* EndpointSlice represents a subset of the endpoints that implement a service. For a given service there may be multiple EndpointSlice objects, selected by labels, which must be joined to produce the full set of endpoints.
**/
@ApiModel(description="EndpointSlice represents a subset of the endpoints that implement a service. For a given service there may be multiple EndpointSlice objects, selected by labels, which must be joined to produce the full set of endpoints.")
public class IoK8sApiDiscoveryV1beta1EndpointSlice {
@ApiModelProperty(required = true, value = "addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name.")
/**
* addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name.
**/
private String addressType = null;
@ApiModelProperty(value = "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources")
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
**/
private String apiVersion = null;
@ApiModelProperty(required = true, value = "endpoints is a list of unique endpoints in this slice. Each slice may include a maximum of 1000 endpoints.")
@Valid
/**
* endpoints is a list of unique endpoints in this slice. Each slice may include a maximum of 1000 endpoints.
**/
private List<IoK8sApiDiscoveryV1beta1Endpoint> endpoints = new ArrayList<IoK8sApiDiscoveryV1beta1Endpoint>();
@ApiModelProperty(value = "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds")
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
**/
private String kind = null;
@ApiModelProperty(value = "Standard object's metadata.")
@Valid
/**
* Standard object's metadata.
**/
private IoK8sApimachineryPkgApisMetaV1ObjectMeta metadata = null;
@ApiModelProperty(value = "ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. When ports is empty, it indicates that there are no defined ports. When a port is defined with a nil port value, it indicates \"all ports\". Each slice may include a maximum of 100 ports.")
@Valid
/**
* ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. When ports is empty, it indicates that there are no defined ports. When a port is defined with a nil port value, it indicates \"all ports\". Each slice may include a maximum of 100 ports.
**/
private List<IoK8sApiDiscoveryV1beta1EndpointPort> ports = null;
/**
* addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name.
* @return addressType
**/
@JsonProperty("addressType")
@NotNull
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice addressType(String addressType) {
this.addressType = addressType;
return this;
}
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
* @return apiVersion
**/
@JsonProperty("apiVersion")
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/**
* endpoints is a list of unique endpoints in this slice. Each slice may include a maximum of 1000 endpoints.
* @return endpoints
**/
@JsonProperty("endpoints")
@NotNull
public List<IoK8sApiDiscoveryV1beta1Endpoint> getEndpoints() {
return endpoints;
}
public void setEndpoints(List<IoK8sApiDiscoveryV1beta1Endpoint> endpoints) {
this.endpoints = endpoints;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice endpoints(List<IoK8sApiDiscoveryV1beta1Endpoint> endpoints) {
this.endpoints = endpoints;
return this;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice addEndpointsItem(IoK8sApiDiscoveryV1beta1Endpoint endpointsItem) {
this.endpoints.add(endpointsItem);
return this;
}
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
* @return kind
**/
@JsonProperty("kind")
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice kind(String kind) {
this.kind = kind;
return this;
}
/**
* Standard object's metadata.
* @return metadata
**/
@JsonProperty("metadata")
public IoK8sApimachineryPkgApisMetaV1ObjectMeta getMetadata() {
return metadata;
}
public void setMetadata(IoK8sApimachineryPkgApisMetaV1ObjectMeta metadata) {
this.metadata = metadata;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice metadata(IoK8sApimachineryPkgApisMetaV1ObjectMeta metadata) {
this.metadata = metadata;
return this;
}
/**
* ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. When ports is empty, it indicates that there are no defined ports. When a port is defined with a nil port value, it indicates \"all ports\". Each slice may include a maximum of 100 ports.
* @return ports
**/
@JsonProperty("ports")
public List<IoK8sApiDiscoveryV1beta1EndpointPort> getPorts() {
return ports;
}
public void setPorts(List<IoK8sApiDiscoveryV1beta1EndpointPort> ports) {
this.ports = ports;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice ports(List<IoK8sApiDiscoveryV1beta1EndpointPort> ports) {
this.ports = ports;
return this;
}
public IoK8sApiDiscoveryV1beta1EndpointSlice addPortsItem(IoK8sApiDiscoveryV1beta1EndpointPort portsItem) {
this.ports.add(portsItem);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class IoK8sApiDiscoveryV1beta1EndpointSlice {\n");
sb.append(" addressType: ").append(toIndentedString(addressType)).append("\n");
sb.append(" apiVersion: ").append(toIndentedString(apiVersion)).append("\n");
sb.append(" endpoints: ").append(toIndentedString(endpoints)).append("\n");
sb.append(" kind: ").append(toIndentedString(kind)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n");
sb.append(" ports: ").append(toIndentedString(ports)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private static String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| java |
Bray Wyatt recently surpassed 600 days without having wrestled a match, and fans on Twitter aren't thrilled one bit.
Wyatt made his surprise return at Extreme Rules 2022. The comeback garnered massive coverage on Wrestling Twitter, and fans were quite excited over what was next for the former WWE Champion.
It has been a while since Bray's return, and he has yet to step into the squared circle for a match. The excitement surrounding his comeback has seemingly died down, and fans are growing impatient.
Wrestling World CC recently shared a tweet pointing out that Bray Wyatt has now completed a whopping 620 days without having wrestled a match.
Fans' reactions to the tweet weren't positive in the least.
Check out some of the replies below:
At WrestleMania 37 in 2021, Wyatt's months-long feud with his arch-enemy Randy Orton finally ended. On Night 2 of 'Mania, The Viper defeated The Fiend in a contest that didn't even last six minutes.
Alexa Bliss' betrayal cost Wyatt the match that night, thus marking the end of their alliance.
Wyatt was let go by WWE a few months later. He didn't step back into the ring after his WWE release and occasionally shared cryptic messages via his Twitter handle. Earlier this year, Wyatt hinted that he would return to the ring somewhere down the line:
"I will always love wrestling. I couldn’t imagine spending the rest of my life without stepping in the ring again and hearing that roar again. I think about it often. Everything has to be in place though. Like I said, timing is everything. "
When Vince McMahon retired from WWE, fans were hopeful in regards to a Bray Wyatt return. Their wishes finally came true when Triple H brought Wyatt back at Extreme Rules.
Wyatt went on to kick off a feud with LA Knight on WWE SmackDown. Wyatt's first match in more than 600 days will likely be against LA Knight, and it might take place at the upcoming Royal Rumble PLE.
How has Bray Wyatt been handled ever since his WWE return? Are you still excited to see him back in the ring? Share your thoughts in the comments below:
What's next for The Bloodline? | english |
<reponame>Zealen408/Bike_registry
{% extends 'main/base.html' %}
{% block content %}
{% if object_list %}
<div class="row">
{% for object in object_list %}
<div class="col s12">
<div class="card hover">
<a href="{% url 'main:post_detail' object.slug %}">
<div class="card-content black-text">
<span class="btn teal white-text">{{ object.publish_date }}</span>
<span class="card-title center"><strong>{{ object.title|title}}</strong></span>
<p>{{ object.post | linebreaks | truncatewords:20 }}</p>
</div>
</a>
<div class="card-action teal lighten-2">
{% if user.is_staff %}
<a class="white-text" href="{% url 'main:post_update' object.slug %}">Edit</a>
<a class="white-text" href="{% url 'main:post_delete' object.slug %}">Delete</a>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
{% lorem 12 p random %}
{% endif %}
{% endblock content %} | html |
valor = input("Digite algo: ")
print("É do tipo", type(valor))
print("Valor numérico:", valor.isnumeric())
print("Valor Alfa:", valor.isalpha())
print("Valor Alfanumérico:", valor.isalnum())
print("Valor ASCII:", valor.isascii())
print("Valor Decimal", valor.isdecimal())
print("Valor Printavel", valor.isprintable()) | python |
Even as it sets eyes on garnering a sizable space in a segment where it has no presence at the moment, Japanese car maker Nissan Motor Company is betting big on “the well-balanced pyramid in India” to make a success out of its soon-to-be tested Datsun strategy.
Couple of months ago, Nissan resurrected the heritage brand Datsun, discontinued way back in 1981. While doing so, it signalled its decision to cut deep into the fast growing small car markets such as India, Indonesia and Russia with Datsun.
In a free-wheeling chat with this correspondent, Ashwani Gupta, Programme Director, Control Corporate Plan Group, Datsun Business Unit, Nissan Motor, asserted that “India is a key strategy market for us. ” A combination of factors ranging from high level of education to spirit of entrepreneurship and the huge contingent of youth in the total population had all been a tempting invitation for Nissan to “offer an affordable value proposition product,” he said.
Mr. Gupta said Nissan at present had no products in around 40-50 per cent of TIV (total industry volume) in India.
“Any value proposition you offer in this space, provides one a great opportunity,” he added.
“Datsun brand of products have the right proposition to deliver this core offer at a price point below Rs. 4 lakh,” he asserted.
Each target markets — India, Indonesia and Russia — would have a Datsun branded locally-made product tailored to local needs, he added. | english |
package defs
const (
INVITE string = "INVITE"
BYE string = "BYE"
)
| go |
Baroda vs Haryana Fantasy Cricket, Captain And Vice Captain For Today Group A, Super League, Syed Mushtaq Ali Trophy 2019 Between BRD vs HAR at CB Patel Stadium, Surat 1:30 PM IST:
As the tournament rolls on – Haryana and Baroda – the two most successful teams thus far will lock horns. Both the teams are enjoying a seven-match winning streak. With big names in both the sides, it is expected to be a cracker of a contest on Monday.
TOSS – The toss between Baroda vs Haryana will take place at 1:00 PM (IST).
Time: 1.30 PM IST.
Venue: CB Patel International Cricket Stadium, Surat.
Keeper Kedar Devdhar (C)
Check Dream11 Prediction/ BRD Dream11 Team/ HAR Dream11 Team/ Baroda Dream11 Team/ Haryana Dream11 Team/ Dream11 Guru Tips And Prediction/ Online Cricket Tips and more.
| english |
WWE’s Royal Rumble 2017 is now in the history books and it offered plenty to make any wrestling fan happy. Roman Reigns and Kevin Owens beat the tar out of each other under No DQ rules, there was plenty of solid women’s action, and Cena vs. Styles might’ve put on the best match of the year.
Like usual, WWE will always find a way for a mistake or two to make its way onto the broadcast and it’s my job to find these moments. I document them in the convenient medium of the . gif, ready to be seen endlessly by the masses.
Royal Rumble had its fair share of these moments, including a bloody mouth from the Raw Women’s Champion, a goofy amount of makeup from The Deadman and a certain member of New Day, who weighs slightly more than the limits of Cesaro’s swing.
I’ll accept if I’m alone on this one but The Undertaker looks awful when he tries to cover up how old he is. It’s not that he’s super old, but with the pencil thin black eyeliner, the hair-do that looks like a wig, and the dyed goatee, he just looks like your dad’s older brother who still wants to hang out with you and your college friends, rather than a man who can fight alongside Brock Lesnar.
It might be good to go ahead and get this booking botch out of the way. I understand the point in using Roman’s rocky relationship with the audience as a way to get the crowd more sympathetic to Randy Orton in the final moments of the Rumble, but this soured many people on the entire show.
It doesn’t take long to figure out why the crowd was so upset about Roman entering at #30. There were strong rumours that Kurt Angle might be in the Rumble. There were also hopes that somebody like Samoa Joe or Shinsuke Nakamura might make their debut in the 30-man contest.
Perhaps it was due to a lack of surprises that fans were so disappointed with Roman when he made his way to the ring but WWE should’ve anticipated this a little better.
When Cesaro entered the Rumble at Number 20, he immediately began swinging everyone. First up was Miz, then Sami Zayn, then Dean Ambrose, then Kofi Kingston, then. . . he experienced trouble. Big E was next up and try as he might, Cesaro couldn’t swing the man.
Cesaro resumed swinging after this failure against Baron Corbin. He then seriously considered swinging his tag partner Sheamus, The Swiss Superman was finally stopped with a kick by this point, stopping a big mistake against his sort of buddy.
If it wasn’t for Braun Strowman, Roman Reigns would be Universal Champion right now. Braun got involved in this No DQ Match, specifically targeting Roman Reigns.
One of the big moments in his attack was when he Chokeslammed The Big Dog onto an announce table that just did not give way. In addition to that, nobody cleared the monitors off the table before the big bump. Roman’s head clearly landed on a TV.
I’m not sure how Charlotte did this, but her mouth suffered the most legitimate injury of the night. Bayley is not exactly known for being a stiff worker, but there’s a good chance she landed something a tad too snug on the Queen of Pay-Per-View.
This Figure Four reversal by Bayley offers one of the better glimpses of Charlotte’s bloody mouth. She’s screaming in pain while sporting crimson in her mouth. | english |
<gh_stars>0
# Copyright 2016 Google 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,
# 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.
"""Defines external repositories needed by rules_webtesting."""
load("//web/internal:platform_http_file.bzl", "platform_http_file")
load("@bazel_gazelle//:deps.bzl", "go_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:java.bzl", "java_import_external")
# NOTE: URLs are mirrored by an asynchronous review process. They must
# be greppable for that to happen. It's OK to submit broken mirror
# URLs, so long as they're correctly formatted. Bazel's downloader
# has fast failover.
def web_test_repositories(**kwargs):
"""Defines external repositories required by Webtesting Rules.
This function exists for other Bazel projects to call from their WORKSPACE
file when depending on rules_webtesting using http_archive. This function
makes it easy to import these transitive dependencies into the parent
workspace. This will check to see if a repository has been previously defined
before defining a new repository.
Alternatively, individual dependencies may be excluded with an
"omit_" + name parameter. This is useful for users who want to be rigorous
about declaring their own direct dependencies, or when another Bazel project
is depended upon (e.g. rules_closure) that defines the same dependencies as
this one (e.g. com_google_guava.) Alternatively, a whitelist model may be
used by calling the individual functions this method references.
Please note that while these dependencies are defined, they are not actually
downloaded, unless a target is built that depends on them.
Args:
**kwargs: omit_... parameters used to prevent importing specific
dependencies.
"""
if should_create_repository("bazel_skylib", kwargs):
bazel_skylib()
if should_create_repository("com_github_blang_semver", kwargs):
com_github_blang_semver()
if should_create_repository("com_github_gorilla_context", kwargs):
com_github_gorilla_context()
if should_create_repository("com_github_gorilla_mux", kwargs):
com_github_gorilla_mux()
if should_create_repository("com_github_tebeka_selenium", kwargs):
com_github_tebeka_selenium()
if should_create_repository("com_github_urllib3", kwargs):
com_github_urllib3()
if should_create_repository("com_google_code_findbugs_jsr305", kwargs):
com_google_code_findbugs_jsr305()
if should_create_repository("com_google_code_gson", kwargs):
com_google_code_gson()
if should_create_repository(
"com_google_errorprone_error_prone_annotations",
kwargs,
):
com_google_errorprone_error_prone_annotations()
if should_create_repository("com_google_guava", kwargs):
com_google_guava()
if should_create_repository("com_squareup_okhttp3_okhttp", kwargs):
com_squareup_okhttp3_okhttp()
if should_create_repository("com_squareup_okio", kwargs):
com_squareup_okio()
if should_create_repository("commons_codec", kwargs):
commons_codec()
if should_create_repository("commons_logging", kwargs):
commons_logging()
if should_create_repository("junit", kwargs):
junit()
if should_create_repository("net_bytebuddy", kwargs):
net_bytebuddy()
if should_create_repository("org_apache_commons_exec", kwargs):
org_apache_commons_exec()
if should_create_repository("org_apache_httpcomponents_httpclient", kwargs):
org_apache_httpcomponents_httpclient()
if should_create_repository("org_apache_httpcomponents_httpcore", kwargs):
org_apache_httpcomponents_httpcore()
if should_create_repository("org_hamcrest_core", kwargs):
org_hamcrest_core()
if should_create_repository("org_jetbrains_kotlin_stdlib", kwargs):
org_jetbrains_kotlin_stdlib()
if should_create_repository("org_json", kwargs):
org_json()
if should_create_repository("org_seleniumhq_py", kwargs):
org_seleniumhq_py()
if should_create_repository("org_seleniumhq_selenium_api", kwargs):
org_seleniumhq_selenium_api()
if should_create_repository("org_seleniumhq_selenium_remote_driver", kwargs):
org_seleniumhq_selenium_remote_driver()
if kwargs.keys():
print("The following parameters are unknown: " + str(kwargs.keys()))
def should_create_repository(name, args):
"""Returns whether the name repository should be created.
This allows creation of a repository to be disabled by either an
"omit_" _+ name parameter or by previously defining a rule for the repository.
The args dict will be mutated to remove "omit_" + name.
Args:
name: The name of the repository that should be checked.
args: A dictionary that contains "omit_...": bool pairs.
Returns:
boolean indicating whether the repository should be created.
"""
key = "omit_" + name
if key in args:
val = args.pop(key)
if val:
return False
if native.existing_rule(name):
return False
return True
def browser_repositories(firefox = False, chromium = False, sauce = False):
"""Sets up repositories for browsers defined in //browsers/....
This should only be used on an experimental basis; projects should define
their own browsers.
Args:
firefox: Configure repositories for //browsers:firefox-native.
chromium: Configure repositories for //browsers:chromium-native.
sauce: Configure repositories for //browser/sauce:chrome-win10.
"""
if chromium:
org_chromium_chromedriver()
org_chromium_chromium()
if firefox:
org_mozilla_firefox()
org_mozilla_geckodriver()
if sauce:
com_saucelabs_sauce_connect()
def bazel_skylib():
http_archive(
name = "bazel_skylib",
sha256 = "",
strip_prefix = "bazel-skylib-e9fc4750d427196754bebb0e2e1e38d68893490a",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/archive/e9fc4750d427196754bebb0e2e1e38d68893490a.tar.gz",
"https://github.com/bazelbuild/bazel-skylib/archive/e9fc4750d427196754bebb0e2e1e38d68893490a.tar.gz",
],
)
def com_github_blang_semver():
go_repository(
name = "com_github_blang_semver",
importpath = "github.com/blang/semver",
sha256 = "3d9da53f4c2d3169bfa9b25f2f36f301a37556a47259c870881524c643c69c57",
strip_prefix = "semver-3.5.1",
urls = [
"https://mirror.bazel.build/github.com/blang/semver/archive/v3.5.1.tar.gz",
"https://github.com/blang/semver/archive/v3.5.1.tar.gz",
],
)
def com_github_gorilla_context():
go_repository(
name = "com_github_gorilla_context",
importpath = "github.com/gorilla/context",
sha256 = "2dfdd051c238695bf9ebfed0bf6a8c533507ac0893bce23be5930e973736bb03",
strip_prefix = "context-1.1.1",
urls = [
"https://mirror.bazel.build/github.com/gorilla/context/archive/v1.1.1.tar.gz",
"https://github.com/gorilla/context/archive/v1.1.1.tar.gz",
],
)
def com_github_gorilla_mux():
go_repository(
name = "com_github_gorilla_mux",
importpath = "github.com/gorilla/mux",
sha256 = "0dc18fb09413efea7393e9c2bd8b5b442ce08e729058f5f7e328d912c6c3d3e3",
strip_prefix = "mux-1.6.2",
urls = [
"https://mirror.bazel.build/github.com/gorilla/mux/archive/v1.6.2.tar.gz",
"https://github.com/gorilla/mux/archive/v1.6.2.tar.gz",
],
)
def com_github_tebeka_selenium():
go_repository(
name = "com_github_tebeka_selenium",
importpath = "github.com/tebeka/selenium",
sha256 = "c506637fd690f4125136233a3ea405908b8255e2d7aa2aa9d3b746d96df50dcd",
strip_prefix = "selenium-a49cf4b98a36c2b21b1ccb012852bd142d5fc04a",
urls = [
"https://mirror.bazel.build/github.com/tebeka/selenium/archive/a49cf4b98a36c2b21b1ccb012852bd142d5fc04a.tar.gz",
"https://github.com/tebeka/selenium/archive/a49cf4b98a36c2b21b1ccb012852bd142d5fc04a.tar.gz",
],
)
def com_github_urllib3():
http_archive(
name = "com_github_urllib3",
build_file = str(Label("//build_files:com_github_urllib3.BUILD")),
sha256 = "a68ac5e15e76e7e5dd2b8f94007233e01effe3e50e8daddf69acfd81cb686baf",
strip_prefix = "urllib3-1.23",
urls = [
"https://files.pythonhosted.org/packages/3c/d2/dc5471622bd200db1cd9319e02e71bc655e9ea27b8e0ce65fc69de0dac15/urllib3-1.23.tar.gz",
],
)
def com_google_code_findbugs_jsr305():
java_import_external(
name = "com_google_code_findbugs_jsr305",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar",
"https://repo1.maven.org/maven2/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar",
],
jar_sha256 =
"766ad2a0783f2687962c8ad74ceecc38a28b9f72a2d085ee438b7813e928d0c7",
licenses = ["notice"], # BSD 3-clause
)
def com_google_code_gson():
java_import_external(
name = "com_google_code_gson",
jar_sha256 =
"233a0149fc365c9f6edbd683cfe266b19bdc773be98eabdaf6b3c924b48e7d81",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar",
"https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar",
],
licenses = ["notice"], # The Apache Software License, Version 2.0
)
def com_google_errorprone_error_prone_annotations():
java_import_external(
name = "com_google_errorprone_error_prone_annotations",
jar_sha256 =
"10a5949aa0f95c8de4fd47edfe20534d2acefd8c224f8afea1f607e112816120",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.3.1/error_prone_annotations-2.3.1.jar",
"https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.3.1/error_prone_annotations-2.3.1.jar",
],
licenses = ["notice"], # Apache 2.0
)
def com_google_guava():
java_import_external(
name = "com_google_guava",
jar_sha256 = "a0e9cabad665bc20bcd2b01f108e5fc03f756e13aea80abaadb9f407033bea2c",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/com/google/guava/guava/26.0-jre/guava-26.9-jre.jar",
"https://repo1.maven.org/maven2/com/google/guava/guava/26.0-jre/guava-26.0-jre.jar",
],
licenses = ["notice"], # Apache 2.0
exports = [
"@com_google_code_findbugs_jsr305",
"@com_google_errorprone_error_prone_annotations",
],
)
def com_saucelabs_sauce_connect():
platform_http_file(
name = "com_saucelabs_sauce_connect",
licenses = ["by_exception_only"], # SauceLabs EULA
amd64_sha256 = "dd53f2cdcec489fbc2443942b853b51bf44af39f230600573119cdd315ddee52",
amd64_urls = [
"https://saucelabs.com/downloads/sc-4.5.1-linux.tar.gz",
],
macos_sha256 = "920ae7bd5657bccdcd27bb596593588654a2820486043e9a12c9062700697e66",
macos_urls = [
"https://saucelabs.com/downloads/sc-4.5.1-osx.zip",
],
windows_sha256 =
"ec11b4ee029c9f0cba316820995df6ab5a4f394053102e1871b9f9589d0a9eb5",
windows_urls = [
"https://saucelabs.com/downloads/sc-4.4.12-win32.zip",
],
)
def com_squareup_okhttp3_okhttp():
java_import_external(
name = "com_squareup_okhttp3_okhttp",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.9.1/okhttp-3.9.1.jar",
"https://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.9.1/okhttp-3.9.1.jar",
],
jar_sha256 =
"a0d01017a42bba26e507fc6d448bb36e536f4b6e612f7c42de30bbdac2b7785e",
licenses = ["notice"], # Apache 2.0
deps = [
"@com_squareup_okio",
"@com_google_code_findbugs_jsr305",
],
)
def com_squareup_okio():
java_import_external(
name = "com_squareup_okio",
jar_sha256 = "79b948cf77504750fdf7aeaf362b5060415136ab6635e5113bd22925e0e9e737",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/com/squareup/okio/okio/2.0.0/okio-2.0.0.jar",
"https://repo1.maven.org/maven2/com/squareup/okio/okio/2.0.0/okio-2.0.0.jar",
],
licenses = ["notice"], # Apache 2.0
deps = [
"@com_google_code_findbugs_jsr305",
"@org_jetbrains_kotlin_stdlib",
],
)
def commons_codec():
java_import_external(
name = "commons_codec",
jar_sha256 =
"e599d5318e97aa48f42136a2927e6dfa4e8881dff0e6c8e3109ddbbff51d7b7d",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar",
"https://repo1.maven.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar",
],
licenses = ["notice"], # Apache License, Version 2.0
)
def commons_logging():
java_import_external(
name = "commons_logging",
jar_sha256 =
"daddea1ea0be0f56978ab3006b8ac92834afeefbd9b7e4e6316fca57df0fa636",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar",
"https://repo1.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar",
],
licenses = ["notice"], # The Apache Software License, Version 2.0
)
def junit():
java_import_external(
name = "junit",
jar_sha256 =
"59721f0805e223d84b90677887d9ff567dc534d7c502ca903c0c2b17f05c116a",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.jar",
"https://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.jar",
],
licenses = ["reciprocal"], # Eclipse Public License 1.0
testonly_ = 1,
deps = ["@org_hamcrest_core"],
)
def net_bytebuddy():
java_import_external(
name = "net_bytebuddy",
jar_sha256 = "4b87ad52a8f64a1197508e176e84076584160e3d65229ff757efee870cd4a8e2",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/net/bytebuddy/byte-buddy/1.8.19/byte-buddy-1.8.19.jar",
"https://repo1.maven.org/maven2/net/bytebuddy/byte-buddy/1.8.19/byte-buddy-1.8.19.jar",
],
licenses = ["notice"], # Apache 2.0
deps = ["@com_google_code_findbugs_jsr305"],
)
def org_apache_commons_exec():
java_import_external(
name = "org_apache_commons_exec",
jar_sha256 =
"cb49812dc1bfb0ea4f20f398bcae1a88c6406e213e67f7524fb10d4f8ad9347b",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/apache/commons/commons-exec/1.3/commons-exec-1.3.jar",
"https://repo1.maven.org/maven2/org/apache/commons/commons-exec/1.3/commons-exec-1.3.jar",
],
licenses = ["notice"], # Apache License, Version 2.0
)
def org_apache_httpcomponents_httpclient():
java_import_external(
name = "org_apache_httpcomponents_httpclient",
jar_sha256 =
"c03f813195e7a80e3608d0ddd8da80b21696a4c92a6a2298865bf149071551c7",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/apache/httpcomponents/httpclient/4.5.6/httpclient-4.5.6.jar",
"https://repo1.maven.org/maven2/org/apache/httpcomponents/httpclient/4.5.6/httpclient-4.5.6.jar",
],
licenses = ["notice"], # Apache License, Version 2.0
deps = [
"@org_apache_httpcomponents_httpcore",
"@commons_logging",
"@commons_codec",
],
)
def org_apache_httpcomponents_httpcore():
java_import_external(
name = "org_apache_httpcomponents_httpcore",
jar_sha256 =
"1b4a1c0b9b4222eda70108d3c6e2befd4a6be3d9f78ff53dd7a94966fdf51fc5",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/apache/httpcomponents/httpcore/4.4.9/httpcore-4.4.9.jar",
"https://repo1.maven.org/maven2/org/apache/httpcomponents/httpcore/4.4.9/httpcore-4.4.9.jar",
],
licenses = ["notice"], # Apache License, Version 2.0
)
def org_chromium_chromedriver():
platform_http_file(
name = "org_chromium_chromedriver",
licenses = ["reciprocal"], # BSD 3-clause, ICU, MPL 1.1, libpng (BSD/MIT-like), Academic Free License v. 2.0, BSD 2-clause, MIT
amd64_sha256 =
"71eafe087900dbca4bc0b354a1d172df48b31a4a502e21f7c7b156d7e76c95c7",
amd64_urls = [
"https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip",
],
macos_sha256 =
"fd32a27148f44796a55f5ce3397015c89ebd9f600d9dda2bcaca54575e2497ae",
macos_urls = [
"https://chromedriver.storage.googleapis.com/2.41/chromedriver_mac64.zip",
],
windows_sha256 =
"a8fa028acebef7b931ef9cb093f02865f9f7495e49351f556e919f7be77f072e",
windows_urls = [
"https://chromedriver.storage.googleapis.com/2.38/chromedriver_win32.zip",
],
)
def org_chromium_chromium():
platform_http_file(
name = "org_chromium_chromium",
licenses = ["notice"], # BSD 3-clause (maybe more?)
amd64_sha256 =
"6933d0afce6e17304b62029fbbd246cbe9e130eb0d90d7682d3765d3dbc8e1c8",
amd64_urls = [
"https://commondatastorage.googleapis.com/chromium-browser-snapshots/Linux_x64/561732/chrome-linux.zip",
],
macos_sha256 =
"084884e91841a923d7b6e81101f0105bbc3b0026f9f6f7a3477f5b313ee89e32",
macos_urls = [
"https://commondatastorage.googleapis.com/chromium-browser-snapshots/Mac/561733/chrome-mac.zip",
],
windows_sha256 =
"d1bb728118c12ea436d8ea07dba980789e7d860aa664dd1fad78bc20e8d9391c",
windows_urls = [
"https://commondatastorage.googleapis.com/chromium-browser-snapshots/Win_x64/540270/chrome-win32.zip",
],
)
def org_hamcrest_core():
java_import_external(
name = "org_hamcrest_core",
jar_sha256 =
"66fdef91e9739348df7a096aa384a5685f4e875584cce89386a7a47251c4d8e9",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar",
"https://repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar",
],
licenses = ["notice"], # New BSD License
testonly_ = 1,
)
def org_jetbrains_kotlin_stdlib():
java_import_external(
name = "org_jetbrains_kotlin_stdlib",
jar_sha256 = "62eaf9cc6e746cef4593abe7cdb4dd48694ef5f817c852e0d9fbbd11fcfc564e",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-stdlib/1.2.61/kotlin-stdlib-1.2.61.jar",
"https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-stdlib/1.2.61/kotlin-stdlib-1.2.61.jar",
],
licenses = ["notice"], # The Apache Software License, Version 2.0
)
def org_json():
java_import_external(
name = "org_json",
jar_sha256 = "518080049ba83181914419d11a25d9bc9833a2d729b6a6e7469fa52851356da8",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/json/json/20180813/json-20180813.jar",
"https://repo1.maven.org/maven2/org/json/json/20180813/json-20180813.jar",
],
licenses = ["notice"], # MIT-style license
)
def org_mozilla_firefox():
platform_http_file(
name = "org_mozilla_firefox",
licenses = ["reciprocal"], # MPL 2.0
amd64_sha256 =
"3a729ddcb1e0f5d63933177a35177ac6172f12edbf9fbbbf45305f49333608de",
amd64_urls = [
"https://mirror.bazel.build/ftp.mozilla.org/pub/firefox/releases/61.0.2/linux-x86_64/en-US/firefox-61.0.2.tar.bz2",
"https://ftp.mozilla.org/pub/firefox/releases/61.0.2/linux-x86_64/en-US/firefox-61.0.2.tar.bz2",
],
macos_sha256 =
"bf23f659ae34832605dd0576affcca060d1077b7bf7395bc9874f62b84936dc5",
macos_urls = [
"https://mirror.bazel.build/ftp.mozilla.org/pub/firefox/releases/61.0.2/mac/en-US/Firefox%2061.0.2.dmg",
"https://ftp.mozilla.org/pub/firefox/releases/61.0.2/mac/en-US/Firefox%2061.0.2.dmg",
],
)
def org_mozilla_geckodriver():
platform_http_file(
name = "org_mozilla_geckodriver",
licenses = ["reciprocal"], # MPL 2.0
amd64_sha256 =
"c9ae92348cf00aa719be6337a608fae8304691a95668e8e338d92623ba9e0ec6",
amd64_urls = [
"https://mirror.bazel.build/github.com/mozilla/geckodriver/releases/download/v0.21.0/geckodriver-v0.21.0-linux64.tar.gz",
"https://github.com/mozilla/geckodriver/releases/download/v0.21.0/geckodriver-v0.21.0-linux64.tar.gz",
],
macos_sha256 =
"ce4a3e9d706db94e8760988de1ad562630412fa8cf898819572522be584f01ce",
macos_urls = [
"https://mirror.bazel.build/github.com/mozilla/geckodriver/releases/download/v0.21.0/geckodriver-v0.21.0-macos.tar.gz",
"https://github.com/mozilla/geckodriver/releases/download/v0.21.0/geckodriver-v0.21.0-macos.tar.gz",
],
)
def org_seleniumhq_py():
http_archive(
name = "org_seleniumhq_py",
build_file = str(Label("//build_files:org_seleniumhq_py.BUILD")),
sha256 = "f9ca21919b564a0a86012cd2177923e3a7f37c4a574207086e710192452a7c40",
strip_prefix = "selenium-3.14.0",
urls = [
"https://files.pythonhosted.org/packages/af/7c/3f76140976b1c8f8a6b437ccd1f04efaed37bdc2600530e76ba981c677b9/selenium-3.14.0.tar.gz",
],
)
def org_seleniumhq_selenium_api():
java_import_external(
name = "org_seleniumhq_selenium_api",
jar_sha256 = "1fc941f86ba4fefeae9a705c1468e65beeaeb63688e19ad3fcbda74cc883ee5b",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/seleniumhq/selenium/selenium-api/3.14.0/selenium-api-3.14.0.jar",
"https://repo1.maven.org/maven2/org/seleniumhq/selenium/selenium-api/3.14.0/selenium-api-3.14.0.jar",
],
licenses = ["notice"], # The Apache Software License, Version 2.0
testonly_ = 1,
)
def org_seleniumhq_selenium_remote_driver():
java_import_external(
name = "org_seleniumhq_selenium_remote_driver",
jar_sha256 =
"284cb4ea043539353bd5ecd774cbd726b705d423ea4569376c863d0b66e5eaf2",
jar_urls = [
"https://mirror.bazel.build/repo1.maven.org/maven2/org/seleniumhq/selenium/selenium-remote-driver/3.14.0/selenium-remote-driver-3.14.0.jar",
"https://repo1.maven.org/maven2/org/seleniumhq/selenium/selenium-remote-driver/3.14.0/selenium-remote-driver-3.14.0.jar",
],
licenses = ["notice"], # The Apache Software License, Version 2.0
testonly_ = 1,
deps = [
"@com_google_code_gson",
"@com_google_guava",
"@net_bytebuddy",
"@com_squareup_okhttp3_okhttp",
"@com_squareup_okio",
"@commons_codec",
"@commons_logging",
"@org_apache_commons_exec",
"@org_apache_httpcomponents_httpclient",
"@org_apache_httpcomponents_httpcore",
"@org_seleniumhq_selenium_api",
],
)
| python |
<reponame>geraldofigueiredo/video-place
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { plainToClass } from 'class-transformer';
import { MovieDTO } from '../dto/movie.dto';
import { DeleteResult, In, Repository } from 'typeorm';
import { Movie } from './movie.entity';
import { MovieRental } from 'src/movieRental/movieRental.entity';
@Injectable()
export class MovieService {
constructor(
@InjectRepository(Movie) private movieRepository: Repository<Movie>,
) {}
async findAll(): Promise<Movie[]> {
return this.movieRepository.find();
}
async findOneById(id: number): Promise<Movie> {
return this.movieRepository.findOne({ where: { id: id } });
}
async findById(ids: number[]): Promise<Movie[]> {
return this.movieRepository.find({ where: { id: In(ids) } });
}
async insertMovie(movieDTO: MovieDTO): Promise<Movie> {
const newMovie = plainToClass(Movie, movieDTO);
newMovie.availableQuantity = newMovie.quantity;
await this.movieRepository.save(newMovie);
return newMovie;
}
async updateMovie(movieDTO: MovieDTO): Promise<Movie> {
const { id } = movieDTO;
const updatedMovie = plainToClass(Movie, movieDTO);
const oldMovie = await this.findOneById(id);
const quantityDiffInterval = updatedMovie.quantity - oldMovie.quantity;
updatedMovie.availableQuantity = oldMovie.availableQuantity + quantityDiffInterval;
await this.movieRepository.update({ id }, updatedMovie);
return this.findOneById(id);
}
async deleteMovie(id: number): Promise<DeleteResult> {
return await this.movieRepository.delete({ id: id });
}
async rentMovies(movies: MovieRental[]) {
for (const [idx, movieRental] of movies.entries()) {
const movie = await this.findOneById(movieRental.movieId);
movie.availableQuantity -= movieRental.quantity;
await this.movieRepository.update({ id: movieRental.movieId }, movie);
}
}
async devolveMovies(movies: MovieRental[]) {
for (const [idx, movieRental] of movies.entries()) {
const movie = await this.findOneById(movieRental.movieId);
movie.availableQuantity += movieRental.quantity;
await this.movieRepository.update({ id: movieRental.movieId }, movie);
}
}
async checkAvailability(rental: MovieRental[]) {
for (const [idx, movieRental] of rental.entries()) {
const movie = await this.findOneById(movieRental.movieId);
if (movie === undefined) {
throw new BadRequestException(`movies.[${idx}] does not exist`);
}
if (movieRental.quantity > movie.availableQuantity) {
throw new BadRequestException(
`movies.[${idx}] does not have this requested quantity available`,
);
}
}
}
}
| typescript |
New Delhi: Google on Saturday celebrated with a cool animated doodle the 155th birth anniversary of leading Bengali poet, social worker and the country’s first woman to graduate with honours, Kamini Roy.
Known for voicing and advocating women’s rights, Kamini helped advance feminism in the Indian subcontinent.
Born on October 12, 1864, in the village of Basanda, she joined Bethune School in 1883 and was one of the first girls to attend school in British India.
She earned a bachelor of arts degree with Sanskrit honours from Bethune College of the University of Calcutta in 1886 and started teaching there in the same year.
alleviating the condition of widows. Her friendship with Bose would inspire her interest in advocating for women’s rights,” Google said.
Hailing from a typical Bengali family, her father Chandi Charan Sen was a judge and a writer. In 1894 she married Kedarnath Roy.
By forming organizations to champion causes she believed in, she helped advance feminism in the Indian subcontinent.
She also worked to help Bengali women win the right to vote in 1926.
Kamini won several accolades including Jagattarini Gold Medal and was also made the vice-president of the Bangiya Sahitya Parishad in 1932-33.
Kamini breathed her last on 27 September 1933 while she was staying in Hazaribagh with her family. | english |
<filename>_posts/2016/2016-04-25-little-room-review-softpedia.md
---
id: 144
title: 'Little Room Review – Softpedia'
date: 2016-04-25T23:12:01+00:00
author: Arzola
layout: post
permalink: /little-room-review-softpedia/
image: /wp-content/uploads/2016/04/Little-Room-Review.png
categories:
- Announcements
- "Arzola's Games"
- Little Room
- Reviews
tags:
- "Arzola's"
- Game
- Game Release
- Image
- Little Room
- Review
- Unity3D
---
<p class="nv_desc col-blue">
<a href="/images/posts/2016/04/Little-Room-Review.png" target="_blank" rel="noopener"><img class="aligncenter wp-image-147 size-large" src="/images/posts/2016/04/Little-Room-Review.png" alt="Little Room Review - Softpedia" /></a>
</p>
* * *
<p class="nv_desc col-blue">
Yesterday, <a href="/little-room-is-free-to-download-on-itch-io/" target="_blank" rel="noopener">Little Room became available to download for free</a>. Some downloads were expected, given it got front-paged to the “new” section in <a href="https://arzola.itch.io/little-room" target="_blank" rel="noopener">itch.io</a> after it became available to public.
</p>
<p class="nv_desc col-blue">
To my surprise, after a couple of hours I received an email I wasn’t actually expecting:
</p>
> * * *
>
> <p class="nv_desc col-blue">
> Little Room, one of your products, has been added to Softpedia’s database<br /> of games and gaming tools. It is featured with a description text,<br /> screenshots, download links and technical details on this page:<br /> <a href="http://games.softpedia.com/get/Freeware-Games/Little-Room.shtml" target="_blank" rel="noopener noreferrer">http://games.softpedia.com/<wbr />get/Freeware-Games/Little-<wbr />Room.shtml</a>
> </p>
>
> * * *
<p class="nv_desc col-blue">
At first I thought the one that sent the email simply uploaded the game to their website without my permission. But once I opened the link, wow was I wrong:
</p>
> * * *
>
> #### A few rooms to explore at will
>
>
>
> <div class="storybox1 posrel">
> <p class="mgbot_10">
> Little Room is not your typical game, at least not from a gameplay point of view. It features mechanics that have been extinct ever since text-based adventure game were around, but it should be of little consequence in the grand scheme of things. In essence, this is a game that encourages you to dream and enjoy your life as much as possible.
> </p>
>
> <p class="mgbot_10">
> It all begins in a room with a clock, a plant and a window. Not much is known about the main character, and it fact it would seem like she doesn’t know very much about herself either. Your goal is to look around the room and find a way to more forward, which is actually a recurring theme in the game. To do so, you have to type specific commands in the text box and wait for the results.
> </p>
>
> <hr />
>
> </div>
<p class="mgbot_10">
<a href="/images/posts/2016/04/Little-Room-Softpedia.png" target="_blank" rel="noopener"><img class="alignleft wp-image-148 size-medium" src="/images/posts/2016/04/Little-Room-Softpedia.png" alt="Little Room - Softpedia" /></a>
</p>
<p class="mgbot_10">
This is but a fragment of the review, but as I kept reading I was amazed by how someone else described the little game I made.
</p>
<p class="mgbot_10">
I’m not going to lie, I was angry at the beginning for not asking for my permission from the start.
</p>
<p class="mgbot_10">
But my did they persuade me with their writing. Not only am I flattered, but I’m glad that someone got to enjoy Little Room.
</p>
There is actually no other reason for this post other than to showcase this <a href="http://games.softpedia.com/get/Freeware-Games/Little-Room.shtml" target="_blank" rel="noopener">fantastic review</a>.
That being said, thank you to however wrote it or made it possible for such an article to be written.
And of course, thank you to you too, for your support, and for reading my blog 🙂
<!-- AddThis Advanced Settings generic via filter on the_content -->
<!-- AddThis Share Buttons generic via filter on the_content --> | markdown |
Posted On:
Exercise Harimau Shakti 2018 between Indian and Malaysian Armies concluded with a Closing Ceremony at the tropical rainforests of Hulu Langat on 11 May 2018. The grand finale of the Exercise was a tactical operation on conduct of attack on enemy camp.
The Closing Ceremony marked the successful conclusion of Exercise Harimau Shakti 2018. The event began with customary salute to Brigadier General Abdul Malik Bin Jiran, Commander 12 Infantry Brigade, followed by national anthem of both the nations. Exercise arm bands were taken off from the exercise appointments and the Regimental flag of GRENADIERS was handed back to Col SN Karthikeyan, CO 4 GRENADIERS by Lt Col Irwan Bin Ibrahim, CO 1 Royal Ranger Regiment symbolising the handing over of the troops back to the Indian Contingent Commander at the end of the Exercise.
In his closing address, the Commander complimented the troops from both the contingents for their exemplary conduct, high morale and tactical acumen throughout the Exercise. He also remarked that the Contingents would have learned by sharing their knowledge and experiences. He also complimented the Indian contingent for assimilating and understanding the nuances of jungle operations as per Malaysian doctrine and fighting shoulder to shoulder with their Malaysian Counterparts. The ceremony came to a close with the war cries of both the contingent and customary recital of prayers by the Malaysian Army.
His Excellency Shri Mridul Kumar, Indian High Commissioner to Malaysia, also visited the Exercise contingents at the Exercise area and complimented the troops on successful completion of the joint training exercise. He was highly appreciative of the high spirits and exemplary drills shown by the Contingents under challenging conditions and inclement weather.
The professional acumen, operational abilities, battle drills and physical endurance displayed by the contingents over the last fortnight, were of extremely high standard and an apt reflection of the level of interoperability achieved during the Exercise. The contingents from Indian and Malaysian Armies have been able to share their experiences in counter insurgency operations and learn from each other. The future editions of Exercise Harimau Shakti will surely take this legacy forward and will ensure that the two nations continue to maintain close defence ties in ensuring peace and security in the region.
APRO (Army)
| english |
The latest thriller drama Reborn Rich starring Song Joong Ki overtakes Park Eun Bin’s Extraordinary Attorney Woo as it passes 20% viewer ratings.
According to the Korean ratings survey company on December 5th, the 8th episode of JTBC's Friday-Saturday drama Reborn Rich, which aired on December 4th, recorded 19.4% of households nationwide. This is a figure that has increased by 3.3 percentage points from the 16.1% obtained for the last broadcast, and corresponds to its own highest viewership rating.
The drama ratings:
With this, Reborn Rich surpassed 17.5% of ENA's Extraordinary Attorney Woo, in which Park Eun Bin played the lead role, and became the highest viewership rating for a mini-series aired this year. In the metropolitan area, it exceeded 21.8%.
About Reborn Rich:
Reborn Rich is a fantasy recurrence of Yoon Hyeon Woo (Song Joong Ki), a secretary who manages the owner risk of the chaebol family, reverts to Jin Do Joon (Song Joong Ki), the youngest son of the chaebol family, and lives for the second time in his life. Song Joong Ki, Lee Sung Min, Shin Hyun Been, Yoon Je Moon, Kim Jeong Nan, Jo Han Chul, Seo Jae Hee, Kim Young Jae, Jung Hye Young, Kim Hyun, Kim Shin Rok, Kim Do Hyun, Park Hyuk Kwon, Kim Nam Hee, Park Ji Hyun, and Tiffany Young appear.
The two dramas:
It has once again broken its own highest viewership rating of close to 20%. Reborn Rich has been renewing its own highest ratings every episode since its first broadcast with 6.058%. The ratings rose more than three times compared to the first broadcast. In particular, it drew attention by surpassing the 17.534% of the drama Extraordinary Attorney Woo, which recorded the highest viewership rating for a mini-series during the week this year.
About the latest episode:
In the 8th episode, Jin Yang Chul (Lee Sung Min) declared that he would not succeed to the eldest son at the wedding of Jin Seong Joon (Kim Nam Hee) and Mo Hyun Min (Park Ji Hyun). Jin Do Joon decided to run the DMC business by home shopping, and took revenge on Jin Hwa Yeong (Kim Shin Rok) for insulting his mother, Lee Hae In (Jung Hye Young) in front of him, by using stocks.
What do you think of the achievement? Let us know in the comments below.
NET Worth: ~ 41.7 MN USD (RS 345 cr)
| english |
<gh_stars>1-10
from bokeh.charts import BoxPlot, output_file, show
from bokeh.sampledata.autompg import autompg as df
# origin = the source of the data that makes up the autompg dataset
title = "MPG by Cylinders and Data Source, Colored by Cylinders"
# color by one dimension and label by two dimensions
# coloring by one of the columns visually groups them together
box_plot = BoxPlot(df, label=['cyl', 'origin'], values='mpg',
color='cyl', title=title)
output_file("boxplot_single.html", title="boxplot_single.py example")
show(box_plot)
| python |
{
"home": "Etusivu",
"unread": "Lukemattomat aiheet",
"popular": "Suositut aiheet",
"recent": "Viimeisimmät aiheet",
"users": "Rekisteröityneet käyttäjät",
"notifications": "Ilmoitukset",
"tags": "Topics tagged under \"%1\"",
"user.edit": "Muokataan \"%1\"",
"user.following": "Käyttäjät, joita %1 seuraa",
"user.followers": "Käyttäjät, jotka seuraavat käyttäjää %1",
"user.posts": "Käyttäjän %1 kirjoittamat viestit",
"user.topics": "Käyttäjän %1 aloittamat aiheet",
"user.favourites": "Käyttäjän %1 suosikkiviestit",
"user.settings": "Käyttäjän asetukset"
} | json |
<filename>data_collection/Basque/layer3/EU101346.json
{
"authors": [],
"doi": "",
"publication_date": "",
"id": "EU101346",
"url": "",
"source": "Wikipedia",
"source_url": "https://eu.wikipedia.org/",
"licence": "CC-BY",
"language": "eu",
"type": "other",
"description": "Annual conferences",
"text": "Tortikoli.\n| Ohar medikoa.\nizena = Tortikoli.\nirudia = Gray1194.png.\nalt = 150px.\noina = Tortikoliarekin lotura duten giharrak.\nGNS10 =.\nGNS10|M|43|6|m|40.\nGNS9 =.\nGNS9|723.5.\nOMIM =.\nMedlinePlus = 000749.\neMedicineSubj = emerg.\neMedicineTopic = 597.\neMedicine_mult =.\nMeshID = D014103.\nTortikoli lepoko gihar baten kontraktura da, bereziki mingarria eta lepoaren mugimendu normala eragozten duena.\nArrazoi traumatiko, neurologiko eta infekziosoengatik sor daiteke.\nKategoria:Erreumatologia Kategoria:Sintomak."
} | json |
Smart locks can make your life a lot more convenient. For one, you don’t have to remember to carry your keys. They also make it so that you can unlock your door seamlessly at night as you won’t have to hunt for the keyhole. And, you can further improve your experience by integrating your smart lock with a voice assistant. In fact, if you’re in the Apple ecosystem, you might want to take a look at the best HomeKit-compatible smart door locks.
By integrating your lock with HomeKit, you can lock and unlock the door using Siri or even automate schedules. You can also cook up a bunch of interesting scenarios by incorporating HomeKit-compatible smart door locks. These include (but are not limited to) having the house lights turn on as soon as your door is opened, or the AC automatically turning off when you leave for work.
- Don’t want to remember passcodes? A smart lock with a fingerprint scanner is the way to go.
- Monitor the outside of your door using a smart lock with a built-in camera.
- Keep your home safe via security cameras with local storage.
Let’s get to the products now.
Some users may want to use a physical key since it is construed more secure than a digital lock. If you find yourself in the same boat, then the Premis smart lock has you covered. You can also leverage a multitude of features via the companion smartphone app.
What’s more, you can use the HomeKit integration to lock/unlock the door using your HomePod. You can even check the lock status on your Apple TV and use voice commands to control it via Siri. That’s not all, as the companion app can be used to generate one-time passwords for guest entry.
Speaking of the app, it’s important to note that the companion app for the Kwikset Premis lock isn’t available for Android. If you have an iPhone — which you probably do since you’re looking for HomeKit-compatible locks — you’re good to go.
Most smart locks are quite big and bulky. However, the Yale Assure Lock sports a tiny form factor that won’t take away from your door’s aesthetics. It’s not without its faults though and the smart door lock omits a few features like an extra keyhole and RFID card unlock in lieu of its slender frame. As such, you’ll have to stick to unlocking the door via a PIN or using the app/Siri.
Buyers who have been using the Assure Lock have no issues with the product. In fact, per several reviews, the lock has been going strong and it is quick to register a voice command too. It’s also easy to install thanks to the way it’s designed. Another aspect related to the installation is that the lock fits on most doors with standard levels of thickness.
Yale’s Assure lock is the only one on this list that can use a 9V battery in times of emergency to power the lock. If the built-in battery runs out, you can quickly grab a cell from your local grocery store and make your way into the house.
- Unlocking mechanisms: Physical keys, Smartphone app, HomeKit devices, PIN (optional)
Some smart locks offer a lot of enticing features but they miss out on a good-looking design. Others may look attractive but skimp out on features. The best way to tackle this issue is to get a standard lock of your choice and pair it with a retrofit smart lock. The Level Bolt, for instance, fits into the cavity of the door lock and isn’t visible to the naked eye.
This way, it adds Wi-Fi connectivity and Apple HomeKit support to your existing lock. While you can use voice commands and Siri automation to unlock your door, the best part about retaining your old lock is you can also use physical keys.
Since the Level Bolt lock doesn’t replace the entire locking system on your door, you might need a professional’s help to install it. This is pretty much the only downside of what is otherwise a great product. Lest we forget, you can also pick up an additional keypad to pair with the Level Bolt lock if you want to unlock your door using a PIN.
The fact that you can use it parallelly with your existing lock means you get an additional layer of security. Interestingly, per the brand’s claims, you can install the lock into your door in just ten minutes. There’s not a lot of work involved so you should be able to do it by yourself.
August also provides a chique keypad from Yale in the box. And, if the reviews are anything to go by, then the August home lock is seemingly quite reliable. To that end, buyers cite that the smart lock doesn’t disconnect from the Wi-Fi network and it works well with HomeKit, Alexa, and Google Assistant.
To that end, Apple Home Keys allows you to store a copy of your key on your iPhone and Apple Watch. When you tap the lock, the key is read via NFC. For those who don’t want to use this feature, Schlage also offers conventional unlocking methods like a PIN or even a physical key.
Understandably, the Schlage BE499WB With Apple Home costs a pretty penny. In fact, it’s almost double the price of the August home lock prefaced above. However, several reviews say that the lock is worth its weight in gold and it features a polished companion app. What’s more, it is superbly convenient to use as it supports Apple’s Home Keys feature.
Another point to note is that the lock responds quicker to voice commands. In fact, the response time is almost instantaneous, which is great considering the alternatives prefaced above take a couple of seconds to register a voice command.
Yes, you can use a smart lock without HomeKit support if you have an iPhone. However, you won’t be able to use voice commands with Siri to control your lock. Plus, you can’t use automation schedules or other devices like HomePods to control the lock.
Smart locks need a Wi-Fi connection only to act upon receiving voice commands or for remote access/control. If you’re going to unlock the door using a PIN or a key, Wi-Fi isn’t necessary.
Several smart locks on this list allow you to retain your existing lock with a key. Some even have a keyhole built-in. So yes, you can use both a smart lock and a key in tandem.
The Apple ecosystem works beautifully with all devices in sync. So if you have multiple Apple devices spread across your home, it only makes sense to get an Apple HomeKit-compatible smart door lock. This way, you can use your iPhone, Apple Watch, HomePod, or even your Apple TV to lock and unlock your door.
The above article may contain affiliate links which help support Guiding Tech. However, it does not affect our editorial integrity. The content remains unbiased and authentic.
| english |
Bangladesh’s ODI captain, Mashrafe Mortaza, was involved in a road accident and incurred minor injuries on Thursday. He sustained skin lacerations on both his hands and knee after a bus clipped a cycle-rickshaw on which Mashrafe was travelling, on his way to the Sher-e-Bangla National Stadium.
"When I saw the bus approaching towards my rickshaw, I jumped out in anticipation," Mashrafe said. "The tyre was broken and I tried to save my legs by diving out of the rickshaw. I am very lucky to have escaped with only some skin damage.
“My own car was taking my child to the doctor for vaccination so I took the rickshaw to the ground. It is a 10-minute ride from my house. "
The police immediately took the offending driver into custody. The cycle-rickshaw puller was unhurt. The on-duty traffic police wanted to take Mortaza to the hospital for treatment. Mortaza opted to come to the ground and receive first-aid treatment instead.
Bangladesh physio Bayjedul Islam Khan said, "Mashrafe was injured in a road accident while coming to the ground this morning. These are minor injuries. He has suffered lacerations on his hands and his right knee has swollen slightly. I think he will recover quickly. "
The coach, Chandika Hathurasingha, said that the team skipper will be monitored closely until the start of the upcoming series against India on June 10th.
"This is unfortunate. We are concerned about his palm," Bangladesh coach Chandika Hathurasingha told ESPNcricinfo. "But we will give him maximum chance to recover in time for the ODI series. " | english |
<gh_stars>1-10
{"Id":1987,"Name":"Mad Cat (Timber Wolf) U","GroupName":null,"Class":"Mad Cat (Timber Wolf)","Variant":"U","Tonnage":75,"BattleValue":2627,"Technology":{"Id":2,"Name":"Clan","Image":null,"SortOrder":0},"Cost":25180313,"Rules":"Experimental","TROId":436,"TRO":"TRCI","RSId":257,"RS":"RS3085u-ONN","EraIcon":"https://i.ibb.co/4jf2wfz/era7-jihad.png","DateIntroduced":"3077","EraId":14,"EraStart":3068,"ImageUrl":"https://i.ibb.co/WtNS1pR/mad-cat-timber-wolf-ks.png","IsFeatured":false,"IsPublished":true,"Release":1.00,"Type":{"Id":18,"Name":"BattleMech","Image":"BattleMech.gif","SortOrder":0},"Role":{"Id":111,"Name":"Sniper","Image":null,"SortOrder":7},"BFType":"BM","BFSize":3,"BFMove":"10\"/8\"s","BFTMM":2,"BFArmor":8,"BFStructure":4,"BFThreshold":0,"BFDamageShort":3,"BFDamageMedium":2,"BFDamageLong":2,"BFDamageExtreme":0,"BFOverheat":0,"BFPointValue":46,"BFAbilities":"BHJ,CASE,OMNI,TOR2/2/2,UMU,SUBW1","Skill":4,"FormatedTonnage":"75"} | json |
package pacoteteste;
import recursoshumanos.Funcionario;
import recursoshumanos.Monitor;
import recursoshumanos.Vendedor;
public class Principal {
public static void main(String[] args) {
Funcionario funcionario = new Funcionario();
funcionario.setCpf(1234567891);
funcionario.setSalario(1209.75);
funcionario.setDesconto(102.35);
System.out.println("Salário líquido: " + funcionario.calcularSalario());
Vendedor vendedor = new Vendedor(1234567892, 1620.50, 120.45, 50.55);
System.out.println("Salário líquido: " +vendedor.calcularSalario());
Monitor monitor = new Monitor("123", "Biologia");
System.out.println("A matrícula é: " +monitor.getMatricula());
monitor.acesso();
}
}
| java |
#!/usr/bin/env python3
import argparse
import pandas as pd
import os
from tree import *
import copy
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--json',
help='auspice json')
parser.add_argument('--ids',
help='Drop all ids in the list.',
)
parser.add_argument('--output',
help='Output file. If none, the format will be'
' COUNTY_SCALE.json',
)
args = parser.parse_args()
au = Auspice(args.json)
with open(args.ids, 'r') as fp:
names_to_drop = fp.read().splitlines()
au.tree.drop_by_name(names_to_drop, verbose=True)
au.write(args.output)
if __name__ == '__main__':
main()
| python |
{"t":"tadanca","h":[{"d":[{"f":"太軟弱,太虛弱;太沒有魄力,能力太差。","e":["(否定詞的最高級)`Tada~`n~`ca~ `ko~ `faloco'~ `niyam~.我們的心太軟弱。","`Tada~`n~`ca~ `to~ `ko~ `tireng~ `ni~ `ina~.媽媽的身體很虛弱了。","`Tada~`n~`ca~ `ko~ `tayal~ `ako~, `ca~ `pakafilo~ `kako~ `toni~ `a~ `demak~.我的能力差,難以勝任這項工作。"],"s":["`tadaca~"]}]}]} | json |
There has been a hustle in the students across the country ever since the University final year exams have been announced by the state governments. They are now demanding the cancellation of final semester exams for all undergraduate and postgraduate courses. Various posts tagged with #StudentLivesMatter have been doing rounds on social media demanding institutions to scrap exams and promote students.
Students have also raised issues of No vaccine No exams in various parts of the country. There has been a petition on change. org for the exam cancellation. The petition runs under #StudentLivesMatter.
The decision to conduct final year exams and scrap the intermediate semester papers came after HRD Minister Ramesh Pokhriyal established a UGC Task Force in order to frame guidelines for exams focussing on social distancing and various safety arrangements to be made.
Moreover, the concern of the students also includes no books available with them for preparation. They said that since the pandemic outbreak many had travelled back to their home towns to be safe and do not have their books and notes in possession. They need those to prepare for the exams. Moreover, they are facing issues such as the no internet and other resources required to prepare for exams and attend online exams. Following these issues, the students have demanded the cancellation of papers and are counting the number of supporters now. | english |
{"meta": {"code": 200, "requestId": "595b386c6a60711438c1acb6"}, "notifications": [{"item": {"unreadCount": 0}, "type": "notificationTray"}], "response": {"photos": {"items": [{"height": 720, "source": {"url": "https://foursquare.com/download/#/iphone", "name": "Foursquare for iOS"}, "tip": {"agreeCount": 5, "canonicalUrl": "https://foursquare.com/item/4d152d03cc216ea83fc761d3", "todo": {"count": 3}, "logView": true, "disagreeCount": 0, "createdAt": 1293233411, "id": "4d152d03cc216ea83fc761d3", "text": "Whampoa prawn noodle is damn good. Must try..... And soup is good.", "likes": {"groups": [{"items": [{"photo": {"prefix": "https://igx.4sqi.net/img/user/", "suffix": "/UFJN3KAFEF0AVAWI.jpg"}, "id": "13569916", "firstName": "Jimmy", "gender": "male", "lastName": "Teo"}, {"photo": {"prefix": "https://igx.4sqi.net/img/user/", "suffix": "/83121470-PJXNLDA2TXWJSWSR.jpg"}, "id": "83121470", "firstName": "Nanz", "gender": "female", "lastName": "Twig"}, {"photo": {"prefix": "https://igx.4sqi.net/img/user/", "suffix": "/3685758_rJM41yGB_1UnZ90yRKMCxnZctSJeYxbGpDspecFmFNW294z8KraYGVQpQoVnrc4Y4mZLfUUgJ.jpg"}, "id": "3685758", "firstName": "Jessie", "gender": "female", "lastName": "Soh"}, {"photo": {"prefix": "https://igx.4sqi.net/img/user/", "suffix": "/12305570-J3K4UGYLG55R2V4G.jpg"}, "id": "12305570", "firstName": "Saudade", "gender": "female"}], "count": 5, "type": "others"}], "count": 5, "summary": "5 likes"}, "like": false, "type": "user"}, "width": 537, "prefix": "https://igx.4sqi.net/img/general/", "createdAt": 1293233421, "id": "4d152d0de9032da1179403d3", "venue": {"like": false, "location": {"formattedAddress": ["90, 91, 92 Whampoa Dr.", "320090", "Singapore"], "city": "Singapore", "lng": 103.85478641275074, "cc": "SG", "country": "Singapore", "lat": 1.3232305355665008, "address": "90, 91, 92 Whampoa Dr.", "labeledLatLngs": [{"label": "display", "lat": 1.3232305355665008, "lng": 103.85478641275074}], "postalCode": "320090"}, "categories": [{"icon": {"prefix": "https://ss3.4sqi.net/img/categories_v2/shops/food_foodcourt_", "suffix": ".png"}, "name": "Food Court", "id": "4bf58dd8d48988d120951735", "pluralName": "Food Courts", "primary": true, "shortName": "Food Court"}], "verified": false, "contact": {}, "allowMenuUrlEdit": true, "stats": {"tipCount": 223, "usersCount": 7774, "checkinsCount": 22953}, "id": "4b107e74f964a520af7123e3", "name": "<NAME> & <NAME>", "beenHere": {"lastCheckinExpiredAt": 0}}, "suffix": "/4Z4LB1MHXNMGL1ATCYQBA2YOOXZ2E2QO0LNWOZHPVGECTFPG.jpg", "visibility": "public"}], "count": 1}, "totalCount": 1}} | json |
{
"id": 4322,
"surahNumber": "042",
"ayatNumber": "050",
"arabic": "أَوْ يُزَوِّجُهُمْ ذُكْرَانًا وَإِنَاثًا ۖ وَيَجْعَلُ مَنْ يَشَاءُ عَقِيمًا ۚ إِنَّهُ عَلِيمٌ قَدِيرٌ",
"english": "Or He bestows both males and females, and He renders barren whom He wills. Verily, He is the All-Knower and is Able to do all things.",
"bengali": "অথবা তাদেরকে দান করেন পুত্র ও কন্যা উভয়ই এবং যাকে ইচ্ছা বন্ধ্যা করে দেন। নিশ্চয় তিনি সর্বজ্ঞ, ক্ষমতাশীল।"
}
| json |
Reading with the Grain of Scripture (Hardcover)
Christianity Today Book Award in Biblical Studies (2021)
"All these essays illustrate, in one way or another, how I have sought to carry out scholarly work as an aspect of discipleship--as a process of faith seeking exegetical clarity."
Richard Hays has been a giant in the field of New Testament studies since the 1989 publication of his Echoes of Scripture in the Letters of Paul. His most significant essays of the past twenty-five years are now collected in this volume, representing the full fruition of major themes from his body of work:
Readers will find themselves guided toward Hays's "hermeneutic of trust" rather than the "hermeneutic of suspicion" that has loomed large in recent biblical studies.
Richard B. Hays is George Washington Ivey Professor Emeritus of New Testament and former dean at Duke Divinity School. He is internationally recognized for his work on the letters of Paul and New Testament ethics. His book The Moral Vision of the New Testament was selected by Christianity Today as one of the 100 most important religious books of the twentieth century.
| english |
It's the middle of November and fall is finally, fully here. All the leaves are brown, and the sky is grey. It's just the right weather for a song, perhaps, or maybe to just sit inside and stare at the Internet where it's warmer, thanks to the fires of indignation. What's fueling those fires this week? Well, bad hair choices, bad advertising slogans, and the return of Shia LeBeouf to everyone's hearts, thanks to a three-day livestream where he said nothing at all. Oh, Internet. Never change. Here, as ever: the highlights of the last seven days on the World Wide Web.
What Happened: The Internet loves a comeback, but when it's as fun as Missy Elliott's return, who can blame it?
What Really Happened: If you didn't spend all Thursday playing the new Missy Elliott, I don't know what you were doing with your time. It was her first release in three years, and it quickly overwhelmed the Internet with its greatness. It was "everything we crave," it was "brilliant, because she is brilliant", and unsurprisingly, it was the song of the week. Probably thanks to it being "a bruising hip-hop banger," as well as being "pure rhythmic pleasure." Suffice to say, the media really liked it. But what about Twitter, that most reliable of Internet barometers?
...Yeah, people liked it.
The Takeaway: Oh, sorry, we're too busy watching the video.
What Happened: Starbucks thought that going with a simple, restrained design for its holiday season cups was a good idea. Some people didn't agree.
What Really Happened: You might think that a change in the design of a to-go coffee cup isn't a big deal, but apparently you'd be wrong, as Starbucks discovered this week. After unveiling its new holiday season cup design last month and boasting of its "purity of design that welcomes all our stories," the coffee giant found itself embroiled in a manufactured controversy that refused to go away.
The first sign came when right-wing site Breitbart announced that the cups were, quote, "emblematic of the Christian culture cleansing of the west," writing with appropriate umbrage that "the only thing that can redeem them from this whitewashing of Christmas is to print Bible verses on their cups next year." Things didn't really go viral until one Joshua Feuerstein (who describes himself as "an American evangelist, Internet and social media personality") took to Facebook to complain about the design, and spread some seasonal... joy...? (He also spread some things that weren't true, like saying that Starbucks employees are banned from saying "Merry Christmas." But, hey, what does the truth matter when you're ranting on Facebook?)
Feuerstein told his followers to use the hashtag #MerryChristmasStarbucks to get the story trending, and well, they did:
Even as the backlash got underway the story grew bigger when Donald Trump and Sarah Palin weighed in, and the media got involved. With a new Twitter hashtag, #ItsJustACup, bemoaning the ridiculousness of the discussion, analysts began to wonder if the entire thing was actually a PR coup for the chain, which would explain why Dunkin' Donuts tried to muscle in with its own holiday cups midway through the whole thing.
The Takeaway: It's as if the War on the War on Christmas starts earlier every year, isn't it?
What Happened: Shia LeBeouf shared the ultimate indignity with the Internet this week: having to watch all of his movies.
What Really Happened: While Shia LaBeouf's career shift from actor to art world provocateur means that cinema has lost a Transformers-level great, it does mean that the world has gained a performance art genius. At least, that seems to be the case following #AllMyMovies, a performance piece in which LaBeouf livestreamed himself watching, as the name suggests, all his movies in reverse order, in a theater filled with his fans.
I know, you're sad you missed it; don't worry, you can watch it all here, or read up on the many, many stories pieces online tracking it.
As weird as it might seem, #AllMyMovies was a genuine online phenomenon, with Twitter filled with Shias reacting to himself for days:
The Takeaway: Has... Has Shia LaBeouf managed to redeem himself in the eyes of the Internet? Affection for him seems to be at an all-time high right now, with all past controversies forgotten. Hopefully no one comes out of the woodwork to claim #AllMyMovies was their idea.
What Happened: Because style knows no bounds, this was the week when the Internet at large discovered the existence of clip-on man buns—for the man who has everything, except a man bun of his own.
What Really Happened: Remember Groupon? It's something that most people don't really think about anymore, but that changed this week when the site offered a "clip in man bun" for just $9.99. (Astonishingly, the monstrosities are traditionally $65, apparently.) According to the site, a clip-on man bun is "one of the hottest trends in men's fashion" that "oozes with fashion sense," while being detachable so that you can "blend in with your surroundings, putting it on when you smell fair-trade coffee or hear a banjo, and taking it off when someone utters the word bro."
Thankfully, the Internet responded in exactly the appropriate manner: "Clip-on man buns aren't a joke, but we wish they were," ran one headline. "Clip-on man buns are real and it's too late to do anything," went another. The offer went viral online, as everyone struggled with the horror.
The Takeaway: In a world where we rightfully disdain Donald Trump for hair that might be fake (as much as he denies it; by the way, in related news), how could we have allowed this atrocity to happen, and why have we not taken steps to ensure it never happens again?
What Happened: Bloomingdale's holiday ad campaign contained an almost impressive lack of awareness when it came to one piece of troublesome advice.
What Really Happened: Ah, the holiday season! A time for family, friends, and accidental date rape jokes, at least according to the Bloomingdale's catalog:
...the damage was done, with countless reports ensuring that, when you think about Bloomingdale's this holiday season, you'll think "date rape."
The Takeaway: How did no one at Bloomingdale's notice how bad that slogan was before the catalog was released? Do we need to ensure that there are people in charge of Avoiding Creepy Rapey Suggestions in ad companies? Really?
| english |
Bharath is ready for the race. After a mediocre show in 'Aarumugam', the actor is confident that he can pull it off with 'Thambikku Indha Ooru', which would hit screens soon.
Directed by Badri, the shooting for the movie was recently completed and the audio was launched. Prabhu plays Bharath's elder brother in the film which is touted to be a racy commercial entertainer.
Produced by VK Media, this entertainer features a song sung by Bharath himself. "The movie is about a guy who is in search of his love. It has come out well with rich and vibrant colours. One can expect the unexpected in 'Thambikku Indha Ooru'," the actor says.
He adds: "After doing a series of off-beat films, I decided to try my luck doing some light-hearted commercial ventures. When Badri narrated the story to me, I accepted it immediately. It has action, romance and humour. Also sharing the screen with a versatile actor like Prabhu is a big delight. It has been a great learning curve for me".
Follow us on Google News and stay updated with the latest! | english |
<gh_stars>1-10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="{% block meta_description %}{% endblock %}">
<meta name="author" content="{% block meta_author %}{% endblock %}">
<link rel="icon" href="../static/favicon.ico">
<title>{% block page_title %} WerSav {% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='libs/font-awesome4/css/font-awesome.min.css') }}"> {% assets "css_all" %}
<link rel="stylesheet" href="{{ ASSET_URL }}"> {% endassets %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/cover.css') }}"> {% block css %}{% endblock %}
</head>
<body>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
{% with form=form %} {% include "nav.html" %} {% endwith %}
<div class="inner cover">
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %}
<div class="row">
<div class="col-md-12">
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
<a class="close" title="Close" href="#" data-dismiss="alert">×</a> {{message}}
</div>
<!-- end .alert -->
{% endfor %}
</div>
<!-- end col-md -->
</div>
<!-- end row -->
{% endif %} {% endwith %}
{% block content %}{% endblock %}
</div>
{% include "footer.html" %}
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="<KEY>"
crossorigin="anonymous"></script>
<script>
window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="<KEY>"
crossorigin="anonymous"></script>
<!-- JavaScript at the bottom for fast page loading -->
{% assets "js_all" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %} {% block js %}{% endblock %}
<!-- end scripts -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html> | html |
The Motorola One Fusion+ is easily one of the nicest phones you can buy for less than Rs 20,000 today. Except for the build quality, this is a phone that outdoes the Poco X2 in many ways.
- The Motorola One Fusion+ sells at a price of Rs 16,999.
- Battery life is one of the key highlights on the Fusion+, stretching up to two days.
- Motorola is offering a stock Android experience with the Fusion+.
By Amritanshu Mukherjee: The Poco X2 is a great phone for its price and brings a couple of segment-first features, which other phones are yet to offer. In fact, in terms of features, the Poco X2 is unbeatable. But how often do features make for a satisfying purchase alone? I have used the phone for a long time and while it has all the flashy features, the user experience is far from nice. It has the same bloated MIUI interface that’s loaded with ad-infested apps. Nonetheless, it is still a benchmark for a sub-Rs 20,000 smartphone.
That’s why every other phone manufacturer wants to beat Poco and after Realme, as well as Samsung, tried their best, it’s time for Motorola to have a go. Yes, Motorola, the one brand that has drifted out of relevance in the last few years. It came up with the One Vision last year but it did not have enough to capture people’s fancy. For 2020, Motorola has revised its strategy and come up with the One Fusion+.
For once, the One Fusion+ is exactly what Indians want in a midrange phone: a powerful Snapdragon 730G chipset, nice cameras, massive display and a battery that does not wish to die easily Unlike the Motorolas of the past, this one even costs a sensible Rs 16,999. On paper, nothing seems wrong.
So is the Motorola One Fusion+ the ultimate one you can buy for less than Rs 20,000 today? Is this the one that dethrones the Poco X2 we have regarded so high for long?
I will cut the crap here - the Motorola One Fusion+ looks and feels dated. Dated in the sense that it has all the elements you expect from a smartphone in 2019, not 2020. A plastic body, a pop-up camera and re-used design from 2019 Motorola phones - this is what the One Fusion+ is all about.
Xiaomi and Realme have been pushing the boundaries for smartphone designs in thsi segment and Motorola is not willing to be a part of that club yet. The One Fusion+ has a design inspired from the Moto G8 Plus, with the same vertically stacked camera design that looks a lot like those expensive Huawei phones. The plastic body tries to emulate glass with a glossy finish but it only ends up looking cheap.
In fact, when compared to the Redmi Note 9 Pro Max and Poco X2, the One Fusion+ feels a class lower. The plastic itself isn’t of the highest quality and you can see the uneven textures from some angles. Motorola has tried to jazz it up with some nice texture but it does so little to make it look upmarket. This clearly feels as if Motorola has cut costs drastically on this one.
Speaking of cutting costs, the display itself has no scratch or shatter protection. The buttons on the side are small and they don’t have enough travel to make for a satisfactory feel.
Sounds bad, right? Well, it’s not all bad. Having a plastic body means you can avoid putting an ugly case on the phone, which Motorola ships with the box. The display fared well in my usage and it did not pick up any scratches so far. Also, there’s a pop-up camera mechanism that avoids a display notch or cutout, thereby making for an uninterrupted viewing experience.
Yes, Motorola hasn’t done a good job with the design and build quality on the phone, especially when you consider that its last year’s One Vision was so impeccably built. That said, one can live with the compromises here, given the rest of the package is so good.
A 6. 5-inch display sounds reasonably good for a midrange phone in 2020. More so when you consider that we aren’t dealing with a notch or punch-hole cutout here. The display has narrow bezels on the sides, which is impressive given that this is an LCD panel. However, you do get the characteristic fat chin, which also is the case with the Poco X2.
The LCD panel is a very good one. It has a resolution of Full HD+ with a standard refresh rate of 60Hz and support for DCI-P3 colours. To decode the tech gibberish, this is theoretically a nicer looking display than any other phone in this price range, except for the Realme X2’s AMOLED panel.
In the real world, the display looks amazing and I can say that it is one of the best screens you will find on a phone for less than Rs 20,000. The DCI-P3 colours make everything look alive with vibrant colours and high contrasts. The Android UI itself looks amazing while watching videos on YouTube in an amazing experience, especially since there’s no notch or camera cutout to distract. I even re-watched a few seasons of The Office on Amazon Prime in HD resolution and it was enjoyable, save for the occasional network drops from Jio.
The standard 60Hz refresh rate isn’t much of a deal-breaker here but Motorola could have bumped up the touch-refresh rate to make for a quicker responding display. This is just me nitpicking and I can assure that you will love the display on the One Fusion+.
As days go by, phones with stock Android interfaces are getting rarer. The Motorola One Fusion+ is one of those very few phones that ships with a Motorola-tweaked stock version of Android 10. I say Motorola-tweaked because the interface here is more polished than what you see on a Xiaomi Mi A3 or a Nokia smartphone. Additionally, this is not an Android One phone and when I reached out to Motorola regarding this, they said they wanted to provide a better experience with some of their personal additions.
Motorola assures at least one Android upgrade and two years of security patches, which is not much of good news. However, I was told that the company will try to push more Android upgrades and patches, if the next version of Android allows for it.
Does this affect the user experience? All I can say is that the One Fusion+ feels like a Google Pixel device and with those Motorola tweakings, it only feels better. For a change, there are no pre-loaded apps, save for Facebook, that keep throwing vulgar ads in the notifications. This is Android at its purest and you get to decide what you want on your phone. Google’s entire app suite is present here and you can remove some of them.
The phone is fast and smooth in daily usage. Whether I was juggling between email apps and Chrome or others, the One Fusion+ did not show any lag or stutter. All of Android 10’s features are present here and they work as intended. The Moto app is present with some classic Motorola touches such as the Moto Peek Display, the gesture shortcuts to flashlight and camera, and more.
The My UX is new to the Motorola family and it allows users to tweak the UI in meaningful ways. You can change icon shapes, accent colours, fonts and more from here but do note that you cannot use third-party icons packs with this app. This is more on the lines of customisation options you get in OnePlus phones. I tried a few of custom presets and it was nice on the whole. Oh, Motorola also adds a live wallpaper of its own for the first time and it looks nice but isn’t of the highest resolution.
Part of that fluid performance is due to the Snapdragon 730G chip that is accompanied by 6GB RAM and 128GB of UFS 2. 1 storage. Good specifications on a Motorola phone after a long time.
Since the software is tuned well to get the most out of the hardware, the One Fusion+ is a delight to use. After using the Oppo Find X2 Pro and Xiaomi Mi 10, the One Fusion+ felt as fast and smooth - I don’t think I can word a better compliment for this phone. Gaming was as good as expected from phones with Snapdragon 730G. PUBG MOBILE latched to High Settings with high frame rates and throughout some matches, the performance remained unaffected. Asphalt 9 also ran nicely and so did Call of Duty Mobile. Mobile gamers will find the One Fusion+ a nice device to try out the latest titles.
The One Fusion+ also adds to the experience with its amazingly loud main speaker. There’s a single speaker at the bottom that is quite loud, which is helpful during gaming. Not only loud, but the audio quality that comes out of it is nicer than what I have heard on a Poco X2 or a Redmi Note 9 Pro Max. Motorola lets you tune the audio profile too to get the best out of the speaker.
Remember the old days when the Moto G phones had the best cameras of any midrange smartphone? I think Motorola has got those people back on its product development team. The One Fusion+ has cameras to exchange blows with the Poco X2 all-day long.
Let’s start with the rear camera, of which there are four. The main one is a 64-megapixel Samsung sensor with F1. 8 aperture lens, which is accompanied by a combination of an 8-megapixel ultra-wide camera with a 118-degree FOV, a 5-megapixel macro camera and a 2-megapixel depth camera. The front 16-megapixel camera sits in the pop-up mechanism. This pop-up module isn’t the fastest one and it takes a full second to come out.
The cameras, on the whole, are impressive. With the main camera, I was consistently getting highly detailed photos with vibrant colours and oodles of sharpness in brightly-lit situations. The pixel binning technology works nicely to capture as much details as possible and it does so without affecting the colours. The colour profile is closer to the natural tones and photos from the One Fusion+ look better than the ones taken from the Poco X2 and Redmi Note 9 Pro Max. There’s a slight warm tint visible in some scenarios but needless to say, the photos look always eye-pleasing to me.
As light levels drop, the One Fusion+ keeps the colours right but starts struggling with details. Subjects loose sharpness in cloudy conditions and indoors. In night conditions, I was impressed to see how well the One Fusion+ manages to keep the colours look closer to what my eyes saw but details take a hit badly. Switch on the Night Vision and you get to see a lot of the stuff in the darkness but colours take a slight hit. In fact, during dusk, the Night Vision mode helped me get some stunning photos of the landscape without causing exposure issues or grains.
The ultra-wide camera lets you take in more of the surrounding without distortion on the edges. However, this camera is good enough only in daylight. The colour profile isn’t the same as the main camera and hence, photos always look a tad dull when compared to the same shot with the main camera. The wide-angle photos also lose out on details a lot and as light levels fall, it struggles to deliver useable photos.
Same is the case with the macro camera. It lets you go closer to your subject but you will get decent photos as long as the sun is up. If it’s cloudy or if you are shooting indoors, you will end up with a blurry photo devoid of the details that the macro camera is supposed to capture in the first place.
The depth camera performs well in portrait mode photo, providing great subject separation. The background does not blur out of proportion and on the whole, you get some nice photos you can use on social media.
The front camera also impresses with its selfie quality. In the pixel-binned mode, the One Fusion+ kept snapping highly detailed selfies with vibrant colours and decent exposure management of the background. There’s a characteristic Motorola warm tint that makes skin tones and other lighter surfaces appear reddish.
Video quality is average at its best, be it 4K or 1080p at 60fps. The colours are decent and so are the details. Stability is average as it is based on EIS. It would have been nice if Motorola decided to bring the OIS from last year’s One Vision to the main camera.
Motorola has made the 5000mAh battery a standard feature for all its smartphones in 2020. The One Fusion+ gets the same and is coupled with an 18W TurboPower fast charger. Motorola has optimised the software well and along with Android 10’s adaptive battery, I was able to push the phone to two days easily. Mind you, this two-day battery was with both of my SIM cards inside with mobile data switched ON, lots of web and social media browsing, more than 50 calls per day, endless texting and considerable photography sessions. With gaming included, the battery life takes a hit but on the whole, this is easily a phone that can last more than a day.
Sadly, the 18W fast charging feels slower on such a big battery and it could have been nice on Motorola’s part to upgrade the charging system to an equivalent of Xiaomi’s 30W system. Nonetheless, as long as you are willing to wait almost two hours for a full recharge, this will do just fine.
The Motorola One Fusion+ ends up being a well-rounded package for the price it sells. It checks the boxes for powerful chipset, nice and large display, a hefty battery and good cameras. Surely, it looks and feels old but that’s the compromise Motorola chose in order to offer a phone that’s so high on value. On the whole, it ends up being a dependable smartphone that this segment has been lacking for a couple of years.
The biggest question: Is it better than the almighty Poco X2? Let me put it in this way. If you are after a nice user experience, then absolutely. The Motorola One Fusion+ feels almost as good as a Google Pixel device on a daily basis. It has as good cameras as the Poco X2 and a battery life that outdoes the competition. | english |
Nifty50 saw the 19,800 levels, then corrected and now it is below 19,700. Today also it is trying to make that recovery but is it headed?
We have had these issues in pendulum swings which increasingly are getting very difficult to estimate on where we are heading. But if we break the discussion down in two or three segments, it becomes a little more apparent as to why things are so choppy.
First, very clearly the macro situation does not look like it is improving in a hurry. All of us talked about how the bond inclusion will bring in $24 billion in the first year, but if you see the movement of crude from the lows of June, then that itself will take away more than that, so $20 crude movement with a 1.7 billion sort of barrels of annual imports you are going to pay on the balance of payment a very large sum even when you look at in comparison to the JPMorgan flows.
Secondly, the Fed Fund target rate and the repo differential at 100 basis points is really very low. That situation can bring in some additional pressures on forex reserves at the time when it does not look like the situation where the rates, especially in the US, are likely to come down in a hurry. So, we have had a great run since March especially in the small and midcaps but it is time to be a little more watchful and position the portfolios. Everybody is looking for the next round of multibaggers but the time to dial up risk in the portfolio could come later in the year rather than going hunting just right now.
Part of this explains that if you look at the top 10 overweight stocks from the FII portfolio, six are banks. Whenever a globally coordinated interest rate hike happens not only sort of does the valuation of banks increase because they reprise their assets much faster than liabilities, but also capital moves out of the country, it moves out of all risky assets which includes emerging markets which includes India and therefore you have the situation where the value of the underlying asset is rising but the largest shareholder which is the FII is still forced to sell it.
If I can be stock specific, some of your favourites in the portfolio include Satin Creditcare, Archean Chemical and Antony Waste as well. What have been the recent additions in your portfolio, anything that you have picked up in the midcap, smallcap arena?
Not really. As a portfolio, we were 50% smallcap and 10% midcap in March 2023 and if you look at our portfolio in the most recent month, from 60% that exposure has come down to 35%. We intend to bring it down further to 30% as the rally continues. If anything, we are pruning exposure in that space rather than adding more. Life insurance, insurance, banking all make a lot of more sense. Pharmaceuticals will continue to make a lot more sense, but we have not added in the smallcap space.
What are you looking at in terms of pharma if you like it there? Is it more on the midcap side? Also what about IT? Today, a move is coming for some of those midcap IT names as well. Is there anything interesting that you would look at in terms of IT given that we have seen the correction coming in for such a long time there?
Yes, IT is one of those zones which is neither expensive nor cheap but the growth is not really there, So what do you do with a space like this? Within that broader bucket, people are finding niches wherever they can and we do own a few of small/midcap IT names but that is where the entire presence is.
Where a lot of confusion emanates from is the fact that India does not really have tech, we have IT services. Now unlike a Nasdaq Tech, say for example Zoom revenue can increase any given pandemic but that is not really the case with the largecap Indian IT names. But we saw them rally in line with Nasdaq in 2021, the post COVID rally and therefore when you compare on a five-year basis, the valuation looks appealing but if you look at the growth in 2019 which most of these companies were reporting versus the growth what most of them are now guiding, there is a very decisive slowdown.
On the pharma space, we had written an article in April where we highlighted that the US generic space seems like it is bottoming out fairly well. It is a a multi-year, since 2017 a number of factors aligned very well for them and we are trying to see the rate of fall in prices. We are not really seeing the prices rising for a lot of these US generic companies, but the end of a very bad cycle is still reasonably decent news. So, we have some exposure there.
(Subscribe to ETMarkets WhatsApp channel)
Download The Economic Times News App to get Daily Market Updates & Live Business News.
Subscribe to The Economic Times Prime and read the Economic Times ePaper Online.and Sensex Today.
| english |
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include <memory>
#include <ros/ros.h>
#include <std_msgs/String.h>
#include "proto/gnss_status.pb.h"
#include "proto/ins.pb.h"
void ins_status_callback(const apollo::common::gnss_status::InsStatus &ins_status) {
switch (ins_status.type()) {
case apollo::common::gnss_status::InsStatus::GOOD:
fprintf(stdout, "INS status is GOOD.\r\n");
break;
case apollo::common::gnss_status::InsStatus::CONVERGING:
fprintf(stdout, "INS status is CONVERGING.\r\n");
break;
case apollo::common::gnss_status::InsStatus::INVALID:
default:
fprintf(stdout, "INS status is INVALID.\r\n");
break;
}
}
void ins_stat_callback(const ::apollo::drivers::gnss::InsStat &ins_stat) {
std::cout << "INS stat: " << ins_stat.DebugString() << std::endl;
}
void stream_status_callback(const apollo::common::gnss_status::StreamStatus &stream_status) {
switch (stream_status.ins_stream_type()) {
case apollo::common::gnss_status::StreamStatus::CONNECTED:
fprintf(stdout, "INS stream is CONNECTED.\r\n");
break;
case apollo::common::gnss_status::StreamStatus::DISCONNECTED:
fprintf(stdout, "INS stream is DISCONNECTED.\r\n");
break;
}
switch (stream_status.rtk_stream_in_type()) {
case apollo::common::gnss_status::StreamStatus::CONNECTED:
fprintf(stdout, "rtk stream in is CONNECTED.\r\n");
break;
case apollo::common::gnss_status::StreamStatus::DISCONNECTED:
fprintf(stdout, "rtk stream in is DISCONNECTED.\r\n");
break;
}
switch (stream_status.rtk_stream_out_type()) {
case apollo::common::gnss_status::StreamStatus::CONNECTED:
fprintf(stdout, "rtk stream out CONNECTED.\r\n");
break;
case apollo::common::gnss_status::StreamStatus::DISCONNECTED:
fprintf(stdout, "rtk stream out DISCONNECTED.\r\n");
break;
}
}
void gnss_status_callback(const apollo::common::gnss_status::GnssStatus &gnss_status) {
std::cout << "GNSS status: " << gnss_status.DebugString() << std::endl;
}
int main(int argc, char *argv[]) {
ros::init(argc, argv, std::string("gnss_monitor_test"));
ros::NodeHandle nh;
ros::Subscriber ins_status_sub;
ros::Subscriber gnss_status_sub;
ros::Subscriber stream_status_sub;
ros::Subscriber ins_stat_sub;
ins_status_sub = nh.subscribe("/apollo/sensor/gnss/ins_status", 16, ins_status_callback);
gnss_status_sub = nh.subscribe("/apollo/sensor/gnss/gnss_status", 16, gnss_status_callback);
stream_status_sub = nh.subscribe("/apollo/sensor/gnss/stream_status", 16, stream_status_callback);
ins_stat_sub = nh.subscribe("/apollo/sensor/gnss/ins_stat", 16, ins_stat_callback);
ros::spin();
ROS_ERROR("Exit");
return 0;
}
| cpp |
<filename>src/main/resources/static/package-lock.json
{
"name": "static",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"xterm": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/xterm/-/xterm-4.9.0.tgz",
"integrity": "<KEY>
},
"xterm-addon-attach": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/xterm-addon-attach/-/xterm-addon-attach-0.6.0.tgz",
"integrity": "<KEY>
}
}
}
| json |
<filename>discussions/438087.json
[
{
"Id": "1021472",
"ThreadId": "438087",
"Html": "Hello,\r<br />\n<br />\nI'm new to WPF and MVVM.\r<br />\n<br />\nAny idea how to bind a ViewModel property of type FirstFloor.ModernUI.Presentation.LinkCollection with a ModernWindow.MenuLinkGroups.LinkGroup.Links element?\r<br />\n<br />\nI'm tring to accomplish that using Caliburn Micro, or something similar.\r<br />\nWHY: I need to change a source of link in the collection based on a value loaded from the config file.\r<br />\n<br />\n<br />\nThank you in advance for your help<br />\n",
"PostedDate": "2013-03-26T16:34:55.167-07:00",
"UserRole": null,
"MarkedAsAnswerDate": null
},
{
"Id": "1021487",
"ThreadId": "438087",
"Html": "You can define your own LinkGroupCollection property in your ViewModel and bind it to the ModernWindow.MenuLinkGroups property. This way you have complete control over the groups and links in your view model.<br />\n",
"PostedDate": "2013-03-26T17:02:03.3-07:00",
"UserRole": null,
"MarkedAsAnswerDate": null
}
] | json |
<reponame>diegocosta/diegocosta.me
import React from 'react';
import { render } from '@testing-library/react';
import Article from '../Article';
describe('<Article />', () => {
it('should render properly', () => {
const { baseElement, getByTestId, getByText, getAllByTestId } = render(
<Article
title="Awesome Article"
url="/awesome-article"
readingTime={5}
language="en"
date="20/07/2020"
tags={['jest', 'testing-library']}
/>
);
expect(getByText('Awesome Article')).toBeTruthy();
expect(getByText('20/07/2020 · 5 minutes of reading')).toBeTruthy();
expect(getByTestId('article-header-custom-link').href).toBe('http://localhost/awesome-article');
expect(getByTestId('article-header-tags')).toBeTruthy();
expect(getAllByTestId('article-header-tag').length).toEqual(2);
expect(baseElement).toMatchSnapshot();
});
it('should not render the tags', () => {
const { baseElement, queryByTestId, queryAllByTestId, getByText } = render(
<Article title="Awesome Article" url="/awesome-article" readingTime={5} language="pt" date="20/07/2020" />
);
expect(queryByTestId('article-header-tags')).toBeFalsy();
expect(getByText('20/07/2020 · 5 minutos de leitura')).toBeTruthy();
expect(queryAllByTestId('article-header-tag').length).toEqual(0);
expect(baseElement).toMatchSnapshot();
});
it('should not render the link', () => {
const { baseElement, queryByTestId } = render(
<Article title="Awesome Article" readingTime={5} language="en" date="20/07/2020" />
);
expect(queryByTestId('article-header-custom-link')).toBeFalsy();
expect(baseElement).toMatchSnapshot();
});
it('should render properly in Poruguese', () => {
const { baseElement, getByText } = render(
<Article title="Awesome Article" url="/awesome-article" readingTime={5} language="pt" date="20/07/2020" />
);
expect(getByText('20/07/2020 · 5 minutos de leitura')).toBeTruthy();
expect(baseElement).toMatchSnapshot();
});
});
| javascript |
<reponame>Redstoneguy129/Reds-Rubies
package me.redstoneguy129.mod.redsrubies.common.objects.items;
import me.redstoneguy129.mod.redsrubies.common.objects.entities.GuiderPearlEntity;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.block.Blocks;
import net.minecraft.entity.item.EyeOfEnderEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.*;
import net.minecraft.stats.Stats;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
public class GuiderPearl extends EnderEyeItem {
public GuiderPearl() {
super(new Item.Properties().group(ItemGroup.MATERIALS));
}
@Override
public ActionResultType onItemUse(ItemUseContext context) { return ActionResultType.PASS; }
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, PlayerEntity playerIn, Hand handIn) {
ItemStack itemstack = playerIn.getHeldItem(handIn);
playerIn.setActiveHand(handIn);
if (worldIn instanceof ServerWorld) {
BlockPos blockpos = ((ServerWorld)worldIn).getChunkProvider().getChunkGenerator().findNearestStructure(worldIn, "Fortress", new BlockPos(playerIn), 100, false);
if (blockpos != null) {
GuiderPearlEntity guiderPearlEntity = new GuiderPearlEntity(worldIn, playerIn.getPosX(), playerIn.getPosYHeight(0.5D), playerIn.getPosZ());
guiderPearlEntity.func_213863_b(itemstack);
guiderPearlEntity.moveTowards(blockpos);
worldIn.addEntity(guiderPearlEntity);
if (playerIn instanceof ServerPlayerEntity) {
CriteriaTriggers.USED_ENDER_EYE.trigger((ServerPlayerEntity)playerIn, blockpos);
}
worldIn.playSound(null, playerIn.getPosX(), playerIn.getPosY(), playerIn.getPosZ(), SoundEvents.ENTITY_ENDER_EYE_LAUNCH, SoundCategory.NEUTRAL, 0.5F, 0.4F / (random.nextFloat() * 0.4F + 0.8F));
worldIn.playEvent(null, 1003, new BlockPos(playerIn), 0);
if (!playerIn.abilities.isCreativeMode) {
itemstack.shrink(1);
}
playerIn.addStat(Stats.ITEM_USED.get(this));
playerIn.swing(handIn, true);
return ActionResult.resultSuccess(itemstack);
}
}
return ActionResult.resultConsume(itemstack);
}
}
| java |
{
"ver": "01.20.15.00",
"socketUrl": "https://cb4feb04fa32.ngrok.io",
"ngrokUrlUbuntu": "https://cb4feb04fa32.ngrok.io",
"ioServerIpUrl": "http://192.168.4.22:3003/",
"ioServerUrl": "http://localhost:3003/",
"ioServerAzureUrl": "http://soterialct.westus2.cloudapp.azure.com:3000/",
"ngrokUrlLocal": "https://b579976476ed.ngrok.io"
} | json |
[{"namaKab":"GARUT","originalFilename":"1.jpg","namaPartai":"Partai Solidaritas Indonesia","id":276758,"noUrut":1,"nama":"<NAME>\u0027DAN, S.Pd","stringJenisKelamin":"Laki-Laki"},{"namaKab":"GARUT","originalFilename":"2.jpg","namaPartai":"Partai Solidaritas Indonesia","id":274047,"noUrut":2,"nama":"<NAME>","stringJenisKelamin":"Perempuan"},{"namaKab":"GARUT","originalFilename":"3.jpg","namaPartai":"Partai Solidaritas Indonesia","id":270450,"noUrut":3,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"GARUT","originalFilename":"5.jpg","namaPartai":"Partai Solidaritas Indonesia","id":270282,"noUrut":4,"nama":"<NAME>","stringJenisKelamin":"Laki-Laki"},{"namaKab":"GARUT","originalFilename":"7.jpg","namaPartai":"Partai Solidaritas Indonesia","id":274418,"noUrut":5,"nama":"<NAME>","stringJenisKelamin":"Perempuan"},{"namaKab":"GARUT","originalFilename":"6.jpg","namaPartai":"Partai Solidaritas Indonesia","id":271094,"noUrut":6,"nama":"<NAME>, S.Pd","stringJenisKelamin":"Laki-Laki"},{"namaKab":"GARUT","originalFilename":"8.jpg","namaPartai":"Partai Solidaritas Indonesia","id":269853,"noUrut":7,"nama":"SAEPULOH","stringJenisKelamin":"Laki-Laki"},{"namaKab":"GARUT","originalFilename":"9.jpg","namaPartai":"Partai Solidaritas Indonesia","id":271542,"noUrut":8,"nama":"<NAME>","stringJenisKelamin":"Perempuan"}] | json |
<reponame>manulera/YeastDatabase
{"other_ids": [], "mRNA_sequence": [{"index": 0, "type": "five_prime_UTR", "sequence": "GAAATTGTGATTTCTATTTGTAGGAATTTCCGTATAGTTCCTTTTAATTTAGGAACAGTTTTTTGATGATCTGTAGTTAAAAATCCGACGGAACTGCGACTTTGACATACTTTCAATGAATTTGAAAATCAATTTATGGAATTCAAAAGGAACGGTAAGCAAGATAAAAGTCAAAACGTAAAAAGGGGAGAAAGATATAAGCTTTGAATTTCTCTTCACCACTATGTGTATTTAAGAGAAAGTGGACAGGAGTCAATAACTCAACGATAAAACCAACTTAAATTTAATCAAATTCATGTGATGGAAAAAGGCTGATTCATAAAAATGAAATGTTTAGTATAACGAGTCATTAGAAGACAACATAGTTAGATCTTAGCATGGATATTTATATAAGGTAGGAAAGAATCCTTAAGGATAGACAATTTTGTCCTACCACAAACGAACCCACCAAGGATAAACTGAAAATTTAAGACCATAAAAAGTATGCTTTGAAAAATTTCAATAATCATAAAGCAGGAAAGTAAATTTTGCCATGTCATGTACATGAAATTAGGGTTAATAAAGAGATCCTTATCATTCTCTCATTTAAAAGGAAGAAGCCTCTTTAACACTCGTTTTTGTATTGTATTTGCTTCTTCCCATTGACGTTGTCTAGCTCTCGTTGAACTAGACGTGTCACGGTTCAAATGTTGAGCACCTGCGTGCTTTCGCTTAAAGCTTTTACCATCTTCTGTAAGAATCCATCTCTTTTTAGCGCCGGAATGGGTTTTCACTGTTCGAATGGTATCCTTTCTGCCAACCAAGACTGTTGCACGCACAACGCGCTGAAATACCACTAACATCACTCCAAAGGCCCAAAAATCTGAAGCAACAAAATTCTCTCAAGGAGTCAAAACCTATGCTTAAGTTGATCAAGTTCTTAAAAAAAAAACACACTTGATCTCAATGAAAGCGCTGGTAGTGCAATCTTAAGAACCTTTGTTCCA"}, {"index": 1, "type": "CDS", "sequence": "ATGTTAGTGAAACCTATGGCATGTTACTTTGAAATTTGGACGAGAAAAGTAACAACAATAGAGGATTTTTCTTTAGCAATTGCCAACCGTTTTAAACAAATGGGCTCTCATAGTGATTCAGAGGTTGACTGGGATAATGAAG"}, {"index": 2, "type": "intron", "sequence": "GTATGAATAATATGCTTGGCTGTTGTACTGGTCTGAAATCAATGTTTTTTACTTCTGGGGGAATTTGTTGCTTGTTTAGTTAATACTGGAATTCCATGCTATCTTTTTGCGATTATTGCTTGACATGAATGGATATTCATCTCTATCAGTCAATGATGAATGATCCGATTTCCTGGATTGAACATTATTATTCAGGATTTGCTCAATTCCCCTGGGACACGGTTTTCGTTTTTTCTGCTGCTACCCTTTCTTTGAAAGACGATGCATCCCAGCTTTCAAATGGAAACAATAAAGTTAATACTAACTCTTAATAG"}, {"index": 3, "type": "CDS", "sequence": "AGGAAGTTTGGGAGGATGAGGTACATGAATTTTGTTGCTTGTTTTGCGATTCTACCTTTACCTGTTTAAAAGACTTATGGAGTCATTGTAAAGAAG"}, {"index": 4, "type": "intron", "sequence": "GTATGAGTTTTTCTATTTAATTTAAAAATTTTGTATATCTATTAATATTCATACATGGCTAACTTTGGTTCTATTGTAG"}, {"index": 5, "type": "CDS", "sequence": "CACACAACTTTGACTTTTATCAAGTTAAGCAGCAGAATAATTTGGATTTCTATGCTTGCATTAAATTGGTAAATTACATTCGGTCTCAAGTCAAGGAAGGAAAAACACCAGATTTGGACAAACTTTCCGACATTTTACGGTCCGACGAATACATGATTTCTGTACTCCCTGACGACAGTGTACTCTTCTCGCTTGGCGATGAACTCGATTCAGATTTTGAGGACGACAATACTCTCGAAATTGAAGTAGAGAATCCAGCAGATGTTTCTAAAGATGCAGAAATAAAGAAATTAAAGTTACAAAATCAACTTCTTATCTCTCAGCTTGAAGAAATTCGAAAAGATAAAATGAATGAATTGACTAGTCAGACTACAGATCAGCTATCAGTTACCCCAAAGAAAGCAGATAACGATTCTTATTATTTCGAGTCTTACGCTGGAAATGATATTCATTTCCTTATGCTAAACGATTCTGTCCGGACCGAGGGATACCGTGACTTCGTTTATCATAATAAGCATATTTTTGCTGGAAAAACGGTTTTGGATGTAGGATGCGGTACTGGCATTTTATCCATGTTTTGCGCAAAGGCTGGCGCCAAGAAGGTTTATGCTGTGGACAACTCCGATATCATTCAAATGGCTATCTCAAATGCTTTTGAAAATGGTCTTGCTGATCAAATTACTTTTATTCGTGGAAAAATCGAAGATATCAGTTTACCGGTTGGCAAGGTAGATATCATTATTTCGGAATGGATGGGCTATGCTCTAACGTTTGAGAGTATGATTGATTCCGTCCTTGTTGCCAGAGATCGCTTCCTTGCACCTTCTGGAATTATGGCACCGTCCGAGACACGATTGGTACTTACAGCTACCACAAACACTGAATTGTTAGAAGAACCTATTGATTTCTGGAGCGATGTGTATGGTTTCAAAATGAATGGCATGAAGGATGCTTCTTATAAAGGTGTTAGTGTACAAGTCGTTCCTCAAACTTATGTTAACGCCAAGCCTGTTGTTTTTGCAAGGTTTAATATGCATACGTGCAAAGTTCAAGATGTCAGTTTTACTTCCCCCTTCTCTCTAATTATAGACAACGAAGGACCGCTTTGTGCTTTCACTTTATGGTTTGATACGTATTTTACGACTAAGAGAACACAGCCTATTCCAGAAGCTATTGATGAAGCTTGTGGATTTACAACAGGCCCTCAAGGCACTCCTACTCATTGGAAACAATGCGTTTTGTTACTACGTAATCGTCCTTTCCTTCAAAAAGGCACTCGTGTTGAAGGAACTATTTCCTTTTCAAAAAATAAAAAAAACAATCGTGATTTGGACATTTCGGTTCACTGGAATGTAAATGGGAAAGCTGACTCTCAAAGCTACGTGTTGAATTAG"}, {"index": 6, "type": "three_prime_UTR", "sequence": "GATCAAAGTCTTTACTTAAAAATATAGAATTACTGATTAATGTTACTATGCTGTAGGTTTTTGGATTAGGAATCTTGCTGGGGTTTTAAGGCATTTCCTGTAAAATTATTTCCCCAGAGTGGGAATACGGTGGATCGAAAAAATCATCTAGTCTTAAAATATTCTCTATTTTCTATACTACTAAAAAATAACATTTTTTCAATCTTTTAAATATGGAAATTTGAGTACATAAGGATTAAACTATCAACAACTGCACAATGCTTGGGAAAGATTTTTAACGTGAACTATTATTATCGTTGATTTTTTGTTACGATTTGATTATATTTAAGGGATCTCTAAAAATAATTGTGACTTGAATCATAATTCAGATGACTAGCGTTCAATGGTCGTAGAATTGCAAATAAACATATTTCGTTCCGGAAAATTAAATATGGATATTTATAGCCTTAAAA"}], "other_names": [], "id": "SPBC8D2.10c", "name": "rmt3"} | json |
- 4 hrs ago 5 Best Microwave Ovens For Your Kitchen: Deals To Consider As Amazon Sale 2023 Is Nearing!
- Travel Have you been to Vishveshwaraya Falls in Mandya yet? If not, this is the best time!
"My sense of style has changed a bit. It is probably because I feel sexier and more confident in my skin. My relationship has really empowered me and made me more confident in myself and in whatever I want to be and do," says Perry.
Despite of her confidence, Perry is certain that she will make mistakes in fashion wears.
"At the beginning, I was just trying to be cute and playful," she explained.
- astrologyLove Horoscope July 2023: While Gemini Will For Intense Connections, Leo's Heart Will Shine This Month!
GET THE BEST BOLDSKY STORIES! | english |
# Rich Cards Bot Sample
A sample bot to renders several types of cards as attachments.
[![Deploy to Azure][Deploy Button]][Deploy CSharp/RichCards]
[Deploy Button]: https://azuredeploy.net/deploybutton.png
[Deploy CSharp/RichCards]: https://azuredeploy.net
### Prerequisites
The minimum prerequisites to run this sample are:
* The latest update of Visual Studio 2015. You can download the community version [here](http://www.visualstudio.com) for free.
* The Bot Framework Emulator. To install the Bot Framework Emulator, download it from [here](https://emulator.botframework.com/). Please refer to [this documentation article](https://github.com/microsoft/botframework-emulator/wiki/Getting-Started) to know more about the Bot Framework Emulator.
### Code Highlights
Many messaging channels provide the ability to attach richer objects. The Bot Framework has the ability to render rich cards as attachments. There are several types of cards supported: Hero Card, Thumbnail Card, Receipt Card, Sign-In Card, Animation Card, Video Card and Audio Card. Once the desired Card type is selected, it is mapped into an `Attachment` data structure. Check out the key code located in the [CardsDialog](CardsDialog.cs#L46-L51) class where the `message.Attachments` property of the message activity is populated with a card attachment.
````C#
public async Task DisplaySelectedCard(IDialogContext context, IAwaitable<string> result)
{
var selectedCard = await result;
var message = context.MakeMessage();
var attachment = GetSelectedCard(selectedCard);
message.Attachments.Add(attachment);
await context.PostAsync(message);
context.Wait(this.MessageReceivedAsync);
}
````
#### Hero Card
The Hero card is a multipurpose card; it primarily hosts a single large image, a button, and a "tap action", along with text content to display on the card. Check out the `GetHeroCard` method in the [CardsDialog](CardsDialog.cs#L80-L92) class for a Hero Card sample.
````C#
private static Attachment GetHeroCard()
{
var heroCard = new HeroCard
{
Title = "BotFramework Hero Card",
Subtitle = "Your bots — wherever your users are talking",
Text = "Build and connect intelligent bots to interact with your users naturally wherever they are, from text/sms to Skype, Slack, Office 365 mail and other popular services.",
Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Get Started", value: "https://docs.microsoft.com/bot-framework") }
};
return heroCard.ToAttachment();
}
````
#### Thumbnail Card
The Thumbnail card is a multipurpose card; it primarily hosts a single small image, a button, and a "tap action", along with text content to display on the card. Check out the `GetThumbnailCard` method in the [CardsDialog](CardsDialog.cs#L94-L106) class for a Thumbnail Card sample.
````C#
private static Attachment GetThumbnailCard()
{
var heroCard = new ThumbnailCard
{
Title = "BotFramework Thumbnail Card",
Subtitle = "Your bots — wherever your users are talking",
Text = "Build and connect intelligent bots to interact with your users naturally wherever they are, from text/sms to Skype, Slack, Office 365 mail and other popular services.",
Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Get Started", value: "https://docs.microsoft.com/bot-framework") }
};
return heroCard.ToAttachment();
}
````
#### Receipt Card
The receipt card allows the Bot to present a receipt to the user. Check out the `GetReceiptCard` method in the [CardsDialog](CardsDialog.cs#L108-L132) class for a Receipt Card sample.
````C#
private static Attachment GetReceiptCard()
{
var receiptCard = new ReceiptCard
{
Title = "<NAME>",
Facts = new List<Fact> { new Fact("Order Number", "1234"), new Fact("Payment Method", "VISA 5555-****") },
Items = new List<ReceiptItem>
{
new ReceiptItem("Data Transfer", price: "$ 38.45", quantity: "368", image: new CardImage(url: "https://github.com/amido/azure-vector-icons/raw/master/renders/traffic-manager.png")),
new ReceiptItem("App Service", price: "$ 45.00", quantity: "720", image: new CardImage(url: "https://github.com/amido/azure-vector-icons/raw/master/renders/cloud-service.png")),
},
Tax = "$ 7.50",
Total = "$ 90.95",
Buttons = new List<CardAction>
{
new CardAction(
ActionTypes.OpenUrl,
"More information",
"https://account.windowsazure.com/content/6.10.1.38-.8225.160809-1618/aux-pre/images/offer-icon-freetrial.png",
"https://azure.microsoft.com/en-us/pricing/")
}
};
return receiptCard.ToAttachment();
}
````
#### Sign-In Card
The Sign-In card is a card representing a request to sign in the user. Check out the `GetSigninCard` method in the [CardsDialog](CardsDialog.cs#L134-L143) class for a Sign-In Card sample.
> Note: The sign in card can be used to initiate an authentication flow which is beyond this sample. For a complete authentication flow sample take a look at [AuthBot](https://github.com/MicrosoftDX/AuthBot).
````C#
private static Attachment GetSigninCard()
{
var signinCard = new SigninCard
{
Text = "BotFramework Sign-in Card",
Buttons = new List<CardAction> { new CardAction(ActionTypes.Signin, "Sign-in", value: "https://login.microsoftonline.com/") }
};
return signinCard.ToAttachment();
}
````
#### Animation Card
The Animation card is a card that’s capable of playing animated GIFs or short videos. Check out the `GetAnimationCard` method in the [CardsDialog](CardsDialog.cs#L145-L165) class for an Animation Card sample.
````C#
private static Attachment GetAnimationCard()
{
var animationCard = new AnimationCard
{
Title = "Microsoft Bot Framework",
Subtitle = "Animation Card",
Image = new ThumbnailUrl
{
Url = "https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png"
},
Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = "http://i.giphy.com/Ki55RUbOV5njy.gif"
}
}
};
return animationCard.ToAttachment();
}
````
> Note: At the time of writing this sample, Skype requires the Animation card to have a Thumbnail Url.
#### Video Card
The Video card is a card that’s capable of playing videos. Check out the `GetVideoCard` method in the [CardsDialog](CardsDialog.cs#L167-L197) class for a Video Card sample.
````C#
private static Attachment GetVideoCard()
{
var videoCard = new VideoCard
{
Title = "Big Buck Bunny",
Subtitle = "by the Blender Institute",
Text = "Big Buck Bunny (code-named Peach) is a short computer-animated comedy film by the Blender Institute, part of the Blender Foundation. Like the foundation's previous film Elephants Dream, the film was made using Blender, a free software application for animation made by the same foundation. It was released as an open-source film under Creative Commons License Attribution 3.0.",
Image = new ThumbnailUrl
{
Url = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Big_buck_bunny_poster_big.jpg/220px-Big_buck_bunny_poster_big.jpg"
},
Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4"
}
},
Buttons = new List<CardAction>
{
new CardAction()
{
Title = "Learn More",
Type = ActionTypes.OpenUrl,
Value = "https://peach.blender.org/"
}
}
};
return videoCard.ToAttachment();
}
````
> Note: At the time of writing this sample, Skype requires the Video card to have a Thumbnail Url.
#### Audio Card
The Audio card is a card that’s capable of playing an audio file. Check out the `GetAudioCard` method in the [CardsDialog](CardsDialog.cs#L199-L229) class for an Audio Card sample.
````C#
private static Attachment GetAudioCard()
{
var audioCard = new AudioCard
{
Title = "I am your father",
Subtitle = "Star Wars: Episode V - The Empire Strikes Back",
Text = "The Empire Strikes Back (also known as Star Wars: Episode V – The Empire Strikes Back) is a 1980 American epic space opera film directed by <NAME>. <NAME> and <NAME> wrote the screenplay, with George Lucas writing the film's story and serving as executive producer. The second installment in the original Star Wars trilogy, it was produced by <NAME> for Lucasfilm Ltd. and stars <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>.",
Image = new ThumbnailUrl
{
Url = "https://upload.wikimedia.org/wikipedia/en/3/3c/SW_-_Empire_Strikes_Back.jpg"
},
Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = "http://www.wavlist.com/movies/004/father.wav"
}
},
Buttons = new List<CardAction>
{
new CardAction()
{
Title = "Read More",
Type = ActionTypes.OpenUrl,
Value = "https://en.wikipedia.org/wiki/The_Empire_Strikes_Back"
}
}
};
return audioCard.ToAttachment();
}
````
> Note: At the time of writing this sample, Skype requires the Audio card to have a Thumbnail Url.
### Outcome
You will see the following in the Bot Framework Emulator, Facebook Messenger and Skype when opening and running the sample.
#### Hero Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
#### Thumbnail Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
#### Receipt Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
#### Sign-In Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
#### Animation Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
#### Video Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
#### Audio Card
| Emulator | Facebook | Skype |
|----------|-------|----------|
||||
### More Information
To get more information about how to get started in Bot Builder for .NET and Attachments please review the following resources:
* [Bot Builder for .NET](https://docs.microsoft.com/en-us/bot-framework/dotnet/)
* [Message Attachments Property](https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-create-messages#message-attachments)
* [Add media attachments to messages](https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-add-media-attachments)
* [Add rich card attachments to messages](https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-add-media-attachments)
* [Cards and buttons on Microsoft Teams](https://msdn.microsoft.com/en-us/microsoft-teams/bots#cards-and-buttons)
> **Limitations**
> The functionality provided by the Bot Framework Activity can be used across many channels. Moreover, some special channel features can be unleashed using the [ChannelData property](https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-channeldata).
>
> The Bot Framework does its best to support the reuse of your Bot in as many channels as you want. However, due to the very nature of some of these channels, some features are not fully portable.
>
> The Hero card and Thumbnail card used in this sample are fully supported in the following channels:
> - Skype
> - Facebook
> - Telegram
> - DirectLine
> - WebChat
> - Slack
> - Email
> - GroupMe
>
> They are also supported, with some limitations, in the following channel:
> - Kik
>
> On the other hand, they are not supported and the sample won't work as expected in the following channel:
> - SMS
>
> The Receipt card and Sign-in card used in this sample are fully supported in the following channels:
> - Skype
> - Facebook
> - Telegram
> - DirectLine
> - WebChat
> - Slack
> - Email
> - GroupMe
>
> They are also supported, with some limitations, in the following channel:
> - Kik
>
> On the other hand, they are not supported and the sample won't work as expected in the following channel:
> - SMS
> - Microsoft Teams
>
> The Animation card, Video card and Audio card used in this sample are fully supported in the following channels:
> - Skype
> - Facebook
> - WebChat
>
> They are also supported, with some limitations, in the following channel:
> - Slack (Only Animation card is supported)
> - GroupMe
> - Telegram (Only Animation and Audio cards are supported)
> - Email
>
> On the other hand, they are not supported and the sample won't work as expected in the following channel:
> - Microsoft Teams
> - Kik
> - SMS
> | markdown |
<gh_stars>1-10
import * as core from '@actions/core';
import { Utils } from './utils';
async function main() {
try {
core.startGroup('Frogbot');
const eventName : string = Utils.setFrogbotEnv();
await Utils.addToPath();
switch (eventName) {
case "pull_request":
case "pull_request_target":
await Utils.execScanPullRequest();
break;
case "push":
await Utils.execCreateFixPullRequests();
break;
default:
core.setFailed(eventName + " event is not supported by Frogbot");
}
} catch (error) {
core.setFailed((<any>error).message);
} finally {
core.endGroup();
}
}
main();
| typescript |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('cmsplugin_cascade', '0002_auto_20150530_1018'),
]
operations = [
migrations.CreateModel(
name='InlineCascadeElement',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('glossary', jsonfield.fields.JSONField(default={}, blank=True)),
('cascade_element', models.ForeignKey(related_name='inline_elements', to='cmsplugin_cascade.CascadeElement', on_delete=models.CASCADE)),
],
options={
'db_table': 'cmsplugin_cascade_inline',
},
bases=(models.Model,),
),
]
| python |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package sessions provides functions that return AWS sessions to use in the AWS SDK.
package sessions
import (
"context"
"fmt"
"net/http"
"runtime"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/copilot-cli/internal/pkg/version"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
)
// Timeout settings.
const (
maxRetriesOnRecoverableFailures = 8 // Default provided by SDK is 3 which means requests are retried up to only 2 seconds.
credsTimeout = 10 * time.Second
clientTimeout = 30 * time.Second
)
// User-Agent settings.
const (
userAgentProductName = "aws-copilot"
)
// Provider provides methods to create sessions.
// Once a session is created, it's cached locally so that the same session is not re-created.
type Provider struct {
defaultSess *session.Session
// Metadata associated with the provider.
userAgentExtras []string
}
var instance *Provider
var once sync.Once
// ImmutableProvider returns an immutable session Provider with the options applied.
func ImmutableProvider(options ...func(*Provider)) *Provider {
once.Do(func() {
instance = &Provider{}
for _, option := range options {
option(instance)
}
})
return instance
}
// UserAgentExtras augments a session provider with additional User-Agent extras.
func UserAgentExtras(extras ...string) func(*Provider) {
return func(p *Provider) {
p.userAgentExtras = append(p.userAgentExtras, extras...)
}
}
// Default returns a session configured against the "default" AWS profile.
// Default assumes that a region must be present with a session, otherwise it returns an error.
func (p *Provider) Default() (*session.Session, error) {
sess, err := p.defaultSession()
if err != nil {
return nil, err
}
if aws.StringValue(sess.Config.Region) == "" {
return nil, &errMissingRegion{}
}
return sess, nil
}
// DefaultWithRegion returns a session configured against the "default" AWS profile and the input region.
func (p *Provider) DefaultWithRegion(region string) (*session.Session, error) {
sess, err := session.NewSessionWithOptions(session.Options{
Config: *newConfig().WithRegion(region),
SharedConfigState: session.SharedConfigEnable,
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
})
if err != nil {
return nil, err
}
sess.Handlers.Build.PushBackNamed(p.userAgentHandler())
return sess, nil
}
// FromProfile returns a session configured against the input profile name.
func (p *Provider) FromProfile(name string) (*session.Session, error) {
sess, err := session.NewSessionWithOptions(session.Options{
Config: *newConfig(),
SharedConfigState: session.SharedConfigEnable,
Profile: name,
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
})
if err != nil {
return nil, err
}
if aws.StringValue(sess.Config.Region) == "" {
return nil, &errMissingRegion{}
}
sess.Handlers.Build.PushBackNamed(p.userAgentHandler())
return sess, nil
}
// FromRole returns a session configured against the input role and region.
func (p *Provider) FromRole(roleARN string, region string) (*session.Session, error) {
defaultSession, err := p.defaultSession()
if err != nil {
return nil, fmt.Errorf("create default session: %w", err)
}
creds := stscreds.NewCredentials(defaultSession, roleARN)
sess, err := session.NewSession(
newConfig().
WithCredentials(creds).
WithRegion(region),
)
if err != nil {
return nil, err
}
sess.Handlers.Build.PushBackNamed(p.userAgentHandler())
return sess, nil
}
// FromStaticCreds returns a session from static credentials.
func (p *Provider) FromStaticCreds(accessKeyID, secretAccessKey, sessionToken string) (*session.Session, error) {
conf := newConfig()
conf.Credentials = credentials.NewStaticCredentials(accessKeyID, secretAccessKey, sessionToken)
sess, err := session.NewSessionWithOptions(session.Options{
Config: *conf,
})
if err != nil {
return nil, fmt.Errorf("create session from static credentials: %w", err)
}
sess.Handlers.Build.PushBackNamed(p.userAgentHandler())
return sess, nil
}
func (p *Provider) defaultSession() (*session.Session, error) {
if p.defaultSess != nil {
return p.defaultSess, nil
}
sess, err := session.NewSessionWithOptions(session.Options{
Config: *newConfig(),
SharedConfigState: session.SharedConfigEnable,
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
})
if err != nil {
return nil, err
}
sess.Handlers.Build.PushBackNamed(p.userAgentHandler())
p.defaultSess = sess
return sess, nil
}
// AreCredsFromEnvVars returns true if the session's credentials provider is environment variables, false otherwise.
// An error is returned if the credentials are invalid or the request times out.
func AreCredsFromEnvVars(sess *session.Session) (bool, error) {
v, err := Creds(sess)
if err != nil {
return false, err
}
return v.ProviderName == session.EnvProviderName, nil
}
// Creds returns the credential values from a session.
func Creds(sess *session.Session) (credentials.Value, error) {
ctx, cancel := context.WithTimeout(context.Background(), credsTimeout)
defer cancel()
v, err := sess.Config.Credentials.GetWithContext(ctx)
if err != nil {
return credentials.Value{}, fmt.Errorf("get credentials of session: %w", err)
}
return v, nil
}
// newConfig returns a config with an end-to-end request timeout and verbose credentials errors.
func newConfig() *aws.Config {
c := &http.Client{
Timeout: clientTimeout,
}
return aws.NewConfig().
WithHTTPClient(c).
WithCredentialsChainVerboseErrors(true).
WithMaxRetries(maxRetriesOnRecoverableFailures)
}
// userAgentHandler returns a http request handler that sets the AWS Copilot custom user agent to all aws requests.
// The User-Agent is of the format "product/version (extra1; extra2; ...; extraN)".
func (p *Provider) userAgentHandler() request.NamedHandler {
extras := append([]string{runtime.GOOS}, p.userAgentExtras...)
return request.NamedHandler{
Name: "UserAgentHandler",
Fn: request.MakeAddToUserAgentHandler(userAgentProductName, version.Version, extras...),
}
}
| go |
<gh_stars>0
/* Body Changes */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;700&display=swap");
html {
scroll-behavior: smooth;
}
body {
height: 100vh;
margin: 0;
font-family: 'Poppins', arial;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
img {
width: 100%;
}
.navigation-container {
background: #1616ac;
}
.navigation-container
a {
/* sass exclusive feature */
color: white;
}
/* Navigation Header */
header {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
/* This line makes header columns in two lines*/
padding: 2em;
}
header
.logo {
font-weight: bold;
}
header
ul {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
header
ul
a {
display: block;
padding: 0 1em;
}
.social-header,
.hero-design {
display: none;
/* This is off due to mobile view*/
}
/* Hero Design (Landing Page) */
.hero {
background: #2424a0;
color: white;
display: -ms-grid;
display: grid;
text-align: center;
padding: 4em;
}
.meet {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
margin: 0 auto;
width: 200px;
font-weight: bold;
color: #fa824C;
}
span {
margin-top: 1em;
margin-right: .5em;
}
.scroll {
width: 30px;
margin-top: 2em;
}
/* featured section */
section {
padding: 4em 2em;
text-align: center;
}
.featured {
position: relative;
}
.featured::before {
content: '';
position: absolute;
width: 200px;
border-radius: 50%;
background: #8383af;
top: 0;
left: 0;
z-index: -1;
}
.subtitle {
text-transform: uppercase;
font-weight: bold;
letter-spacing: .2em;
color: #1616AC;
font-size: .85em;
}
.featured-title {
color: black;
font-weight: bold;
font-size: 1.3em;
margin-top: -.4em;
display: block;
}
.featured-description {
color: #252525;
margin-top: .3em;
font-size: .9;
line-height: 1.8em;
font-weight: 500;
}
/* Skills Section */
.skills {
background: #3c91e6;
}
.skills-container
ul
li {
background: white;
padding: 2em;
border-radius: 1em;
margin-bottom: 1em;
}
.skills-container
ul
li .icon-container {
height: 100px;
display: -ms-grid;
display: grid;
place-content: center;
margin: 0 auto;
}
.skills-container
ul
li .icon-container.one {
width: 100px;
}
.skills-container
ul
li .icon-container.two {
width: 75px;
}
.skills-container
ul
li .icon-container.three {
width: 80px;
}
.skill-title {
font-weight: bold;
}
.featured-description {
margin-bottom: 2em;
}
/* Portfolio Section */
.portfolio {
background: #ffffff;
}
.portfolio-container
a
img {
border-radius: 1em;
margin-bottom: 2em;
}
/* Media Queries start here */
@media only screen and (min-width: 800px) {
.featured,
.portfolio {
text-align: left;
}
.featured,
.portfolio-container {
display: -ms-grid;
display: grid;
-ms-grid-columns: 40% auto;
grid-template-columns: 40% auto;
}
.left,
.portfolio-left {
display: -ms-grid;
display: grid;
place-content: center;
}
.right {
margin-left: 2em;
margin-top: 1em;
}
.skills {
margin-top: -5em;
margin-bottom: -7em;
padding-top: 7em;
}
.skills-container
ul {
display: -ms-grid;
display: grid;
-ms-grid-columns: (auto)[3];
grid-template-columns: repeat(3, auto);
grid-gap: 1em;
}
.portfolio {
padding-top: 7em;
}
.portfolio-container
img {
margin-left: 2em;
}
}
@media only screen and (min-width: 1050px) {
.hero {
height: 90vh;
}
.navigation-container {
display: -ms-grid;
display: grid;
-ms-grid-columns: 66% auto;
grid-template-columns: 66% auto;
background: unset;
}
.navigation-container header {
background: #1616AC;
}
header {
padding: 2em 2em 2em 4em;
}
.social-header {
padding: 2em 4em 2em 0;
}
section {
padding: 4em;
}
.social-header {
display: block;
}
.social-header ul {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
width: 7em;
float: right;
}
.social-header ul img {
width: 20px;
}
.hero {
display: -ms-grid;
display: grid;
-ms-grid-columns: 66% auto;
grid-template-columns: 66% auto;
background: unset;
padding: 0;
}
.hero .content {
background: #1616ac;
padding: 6em 8em 6em 4em;
text-align: left;
}
.hero .content h1 {
font-size: 3em;
line-height: 1.2em;
}
.meet {
margin: unset;
}
.hero-design {
display: unset;
margin-left: -50%;
margin-top: 15%;
width: 100%;
}
.portfolio
img {
float: right;
max-width: 500px;
}
}
@media only screen and (min-width: 1250px) {
header {
padding: 2em 2em 2em 10em;
}
.social-header {
padding: 2em 10em 2em 0;
}
section {
padding: 10em 10em 4em 10em;
}
.hero
.content {
padding: 6em 8em 6em 10em;
}
}
@media only screen and (min-width: 1550px) {
header {
padding: 2em 2em 2em 20em;
}
.social-header {
padding: 2em 20em 2em 0;
}
section {
padding: 6em 20em 4em 20em;
}
.hero
.content {
padding: 9em 20em 6em 20em;
}
}
/*# sourceMappingURL=main.css.map */ | css |
The agreement was signed on Monday in the presence of Prime Minister Narendra Modi, Home Minister Rajnath Singh and National Security Adviser Ajit Doval by NSCN (IM) leader Thuingaleng Muivah and the government’s interlocutor R N Ravi at the PM’s official residence here.
The signing of the pact marks the culmination of over 80 rounds of negotiations spanning 16 years, with the first breakthrough made in 1997 when a ceasefire agreement was sealed. But the quest for a political settlement to the Naga issue goes back all the way to 1947 when Naga National Council leader A. Z. Phizo declared the independence of the Naga region one day before India itself became independent on August 15 that year.
After several rounds of discussions with Jawaharlal Nehru, India’s first Prime Minister, Phizo took up arms. In the long and bloody civil war which followed, thousands of Naga civilians lost their lives, with the armed forces accused of human rights violations.
Although the ceasefire with the NSCN (IM) – the biggest Naga rebel group – has held firm for 18 years, another NSCN faction led by S. S. Khaplang continues to fight the army and is believed to be behind the deadly attack in Manipur in June that left 18 soldiers dead and 18 injured.
As of Monday night, neither the Government of India nor the NSCN (IM) had made public the text of the agreement signed. While the insurgent group has long conceded its demand for an independent Nagaland, how the new understanding deals with the NSCN (IM)’s long-standing call for integration of all Naga-inhabited areas in the North East across Manipur – including parts of the hill districts of Ukhrul, Senapati, Tamenlong and Chandel – Arunachal Pradesh and Assam, is not yet clear. The NSCN’s demand for what it calls greater ‘Nagalim’ is opposed by these states.
“Details are still being worked out… the framework agreement will be the main principle within which issues will be worked out,” Atem told the Nagaland newspaper from Delhi. He said the agreement would be made public on Tuesday.
The choice of Ravi, a former high official in the Intelligence Bureau, as the government’s interlocutor was not without controversy, given his description of the ceasefire with the NSCN(IM) as “reckless” in an article for The Hindu as recently as January 2014.
Earlier GOI interlocutors have included former governor Swaraj Kaushal, former Union minister Oscar Fernandes, former Union home secretary K Padmanabhaiah, and more recently, R. S. Pandey.
Before Monday’s agreement was signed, Modi spoke to leaders of various parties including Congress President Sonia Gandhi, former Prime Minister Manmohan Singh, Congress’ Mallikarjun Kharge, SP chief Mulayam Singh Yadav, BSP’s Mayawati, NCP supremo Sharad Pawar and CPI(M) general secretary Sitaram Yechury.
He also spoke to West Bengal Chief Minister Mamata Banerjee, her Tamil Nadu counterpart J Jayalalithaa besides the Nagaland Governor Padmanabha Acharya and Chief Minister T R Zeliang. He also called up DMK leader M Karunanidhi and JD(S) leader H D Deve Gowda.
“Today’s agreement is a shining example of what we can achieve when we deal with each other in a spirit of equality and respect, trust and confidence; when we seek to understand concerns and try to address aspirations; when we leave the path of dispute and take the high road of dialogue. It is a lesson and an inspiration in our troubled world,” the Prime Minister said at the signing ceremony.
He said there were not many like Mahatma Gandhi, “who loved the Naga people and sensitive to their sentiments. We have continued to look at each other through the prism of false perceptions and old prejudices. ” .
“The Naga political issue had lingered for six decades, taking a huge toll on generations of our people,” the Prime Minister said in a reference to the violence which has claimed over 3000 lives since Independence.
“Unfortunately, the Naga problem has taken so long to resolve because we did not understand each other… Today, as you begin a new glorious chapter with a sense of pride, self-confidence and self-respect, I join the nation in saluting you and conveying our good wishes to the Naga people,” Modi said.
Muivah appreciated Modi’s “vision” and “wisdom” and said Nagas “can be trustworthy”.
He mentioned that the peace moves were first initiated by the then Prime Minister Narasimha Rao when the outfit gave a commitment about ceasefire. Then the outfit leaders had held talks with Prime Minister Atal Bihari Vajpayee in 2001.
He said they had “propagated terrible myths about Nagas in the rest of the country” and “deliberately suppressed the reality that the Nagas were an extremely evolved society”. The Prime Minister said “negative ideas” were also spread about the rest of India amongst Naga people. “This was part of the well known policy of divide and rule of the colonial rulers,” he said.
He said he had the “deepest admiration for the great Naga people for their extraordinary support to the peace efforts” and complimented the NSCN(IM) for maintaining the ceasefire agreement for nearly two decades, with a sense of honour that defines the great Naga people.
He said he had personally kept in touch with the progress of the negotiations with NSCN(IM).
79-year-old Muivah has been at the forefront of the negotiations with the government.
Despite the government-brokered ceasefire with NSCN(IM) in 1997 and NSCN(K) in 2001, the Naga insurgent groups continued to indulge in inter-factional killings and targeting of security forces outside Nagaland where the ceasefire does not exist.
Rampant corruption, collection of taxes, levies and extortion had added to the woes of the common people in Nagaland and Manipur, official sources said.
19 other top Naga leaders from different groups and civil society organisations were also present at the function to sign the accord.
On its part, the NSCN-IM today said the framework agreement was based on the “unique” history of Nagas and recognised the universal principle that in a democracy sovereignty lies with the people.
Hours after the accord was signed, the Naga rebel group said the attitude of Nagas towards India changed considerably when the BJP government took “realistic” steps in recognising the ‘unique history and situation of the Nagas’ on July 11, 2002 and it demonstrated the desire for a lasting and honourable political solution of the issue.
“Better understanding has been arrived at and a framework agreement has been concluded basing on the unique history and position of the Nagas and recognising the universal principle that in a democracy sovereignty lies with the people,” NSCN-IM general secretary Th Muivah, who signed the pact, said in a statement.
The rebel group, which has been fighting for a sovereign Naga homeland for decades and has finally given up on that, said that after decades of confrontation and untold sufferings, the Nagas responded to have political dialogue with the government of India in view of the acknowledgement that the government will seek a peaceful solution to the Naga issue.
In its statement, the NSCN-IM applauded the leadership of Prime Minister Narendra Modi, who was present when the agreement was signed, saying the pact was concluded due to the “statesmanship and steely resolve” shown by him towards finding a final political solution.
Meanwhile, Nagaland Chief minister T R Zeliang and the lone member of parliament from the state Neiphiu Rio has welcomed the signing of the peace accord between the government of India and NSCN(IM).
Zeliang said in a statement that he was informed by the Prime Minister about the signing of the peace accord with NSCN (IM).
While details of the accord are still awaited, the CM expressed confidence that “both the parties have taken into account the aspirations of the Nagas as expressed by Naga civil societies during their interactions with the interlocutor, R. N. Ravi.
“Our people have been struggling for more than six decades for a settlement to the Naga issue and the signing of the peace accord is a welcome step towards such a settlement,” he said.
The chief minister also said that this positive development will pave the way for a permanent solution acceptable to the Nagas.
Rio said “a historic peace accord was signed between the government of India and NSCN-IM today in New Delhi in the presence of Prime Minister, Narendra Modi”.
Rio said that after the signing of the accord the Prime Minister spoke to him and appealed for cooperation in the peace process. “I assured him of my fullest assistance and cooperation in our common endeavor to achieve permanent peace,” he said.
“It is indeed a landmark occasion for the country, especially the Naga people who have struggled for more than six decades in our search for permanent peace,” he said.
IANS adds: The Naga People’s Movement for Human Rights (NPHMR) chairman N. Krome said, “We were all caught by surprise by the sudden announcement. ” He said they were aware that something was happening “but we did not realise that something like this would happen so soon”.
A top leader of Nagaland’s apex body of tribes on Monday hailed the ‘peace accord’ signed by the Indian government and the NSCN-IM, saying the Nagas were hungry for peace.
But some Nagas wondered why there was so much silence before the accord was signed. Chuba Ozukum, president of Naga Hoho, an apex body, expressed happiness over the accord and hoped it will bring a lasting solution to the Naga problem. “It has been a long-standing desire of the people of Nagaland. However, it is difficult to say much as I am yet to see the contents of the accord,” he said. “The people of the state have been longing for a peace accord for a long time,” he said.
A leader of the Naga Students Federation said on the condition of anonymity: “The announcement came as a shocker. The people of Nagaland have been longing for this. “Now we are waiting eagerly to see the contents,” he added. | english |
Solar flares are scorching and roaring on the sun. Since the enormous sunspot is almost directly toward Earth, there is a great chance that solar flares will impact the planet and trigger a solar storm.
Recent significant blackouts in the USA were caused by an X1-class solar flare outburst on the Sun. The states most affected by Hurricane Ian include Florida, North Carolina, and South Carolina, where rescue efforts and disaster management efforts are under way. The eruption caused GPS and radio transmissions to be obstructed.
According to SpaceWeather.com's experts: "The enormous sunspot AR3112 is about to erupt."Yesterday, according to NOAA forecasters, there was a 65% likelihood of M-flares and a 30% possibility of X-flares.
The Earth may experience brief radio blackouts at the poles if an M-class flare, which is thought to be of medium strength, strikes our planet.
Stronger X-class flares are capable of causing radio blackouts that affect the entire planet. Additionally, they have the capacity to produce powerful solar storms.
While the exact timing of the sunspot explosion cannot be anticipated, it is most likely to occur within the next 48 hours. An X1-class solar flare was produced by the eruption of the previous solar flare, which was caused by a smaller sunspot.
The strongest type of solar flares are classified as X-class. The intensity in the lesson is represented by the number 1. Therefore, an X2-class solar storm will be twice as powerful as an X1 flare. How strong the eruption will be is still unknown.
| english |
# Folder Structure
### Angular 2 Framework
Contains **Angular 2** based components
### React Framework
Contains **React.js** based components
| markdown |
package com.rotanava.boot.system.module.system.controller;
import com.rotanava.boot.system.api.SystemMonitoringService;
import com.rotanava.boot.system.api.module.system.vo.BasicInfoVO;
import com.rotanava.boot.system.api.module.system.vo.PerformanceVO;
import com.rotanava.framework.common.aspect.annotation.AdviceResponseBody;
import com.rotanava.framework.common.aspect.annotation.AutoLog;
import com.rotanava.framework.code.RetData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 系统监控控制器
*
* @author WeiQiangMiao
* @date 2021-03-11
*/
@RestController
@RequestMapping("/v1/systemMonitoring")
public class SystemMonitoringController {
@Autowired
private SystemMonitoringService systemMonitoringService;
@AutoLog("获取系统基本信息")
@AdviceResponseBody
@GetMapping("/getBasicInfo")
public RetData<BasicInfoVO> getBasicInfo() {
return RetData.ok(systemMonitoringService.getBasicInfo());
}
@AutoLog("获取性能")
@AdviceResponseBody
@GetMapping("/getPerformance")
public RetData<PerformanceVO> getPerformance() {
return RetData.ok(systemMonitoringService.getPerformance());
}
}
| java |
The Bombay High Court on July 30 has admitted the discharged application of Sadhvi Pragya Singh and Sameer Kulkarni, two of the accused in the 2008 Malegaon blast case.
“Colonel Purohit’s discharge plea has already been accepted by the Bombay High Court. Today, the plea of Sadhvi Pragya Singh, which was turned down by a trial court, has been admitted by the High Court,” Prashant Maggu,” the lawyer of the accused said.
The move to accept discharge application of two accused comes a week after the court admitted the discharge application of main accused Lieutenant Colonel Prasad Purohit.
The joint hearing in the case is scheduled to be held on August 13.
Six persons were killed and nearly 101 were injured on September 29, 2008, when a bomb strapped to a Hero Hondo motorcycle exploded in Malegaon town of Nashik District near a hotel at Bhikku Chowk.
Sameer Kulkarni, a printing press employee from Bhopal, was arrested soon after the blast and in November 2008, the Anti-Terrorism Squad arrested 11 people. Investigations revealed that Kulkarni is the planner of Malegaon blast.
Earlier, a sessions court in Mumbai granted bail to Kulkarni on a bond of Rs 50,000 on the grounds of parity. | english |
<reponame>nitin42/my-website
import { createP5Sketch } from 'react-generative-tools'
// No of the tiles in the grid
const tileCount = 50
// Random seed value
const actRandomSeed = 0
// Value setting the alpha channel
const alpha = 180
// Store the color value for each shape in our tile
let color
function sketch(p5, props) {
const tiles = tileCount
p5.setup = function() {
p5.createCanvas(props.height, props.width)
p5.noFill()
}
p5.draw = function() {
p5.background(255)
p5.randomSeed(actRandomSeed)
p5.translate(p5.width / tiles / 2, p5.height / tiles / 2)
p5.strokeWeight(p5.random(0.1, 0.25))
for (let gridY = 0; gridY < tiles; gridY++) {
for (let gridX = 0; gridX < tiles; gridX++) {
color = p5.color(gridX, gridY, (gridX * gridY) / 255, alpha)
p5.stroke(color)
// Get the individual tile position
const posX = (p5.width / tiles) * gridX
const posY = (p5.height / tiles) * gridY
// Determine the tile movement
const shiftX =
(p5.width / p5.random(p5.frameCount)) *
p5.random(-p5.mouseX, p5.mouseX)
const shiftY =
(p5.height / p5.random(p5.frameCount)) *
p5.random(-p5.mouseX, p5.mouseX)
// Draw the shape
p5.rect(posX + shiftX, posY + shiftY, p5.mouseY / 15, p5.mouseY / 15)
}
}
}
}
const Squares = createP5Sketch(sketch)
export default Squares
| javascript |
Hadiya’s father Ashokan said he had got permission to visit his daughter whenever he wanted to.
Hadiya will continue to pursue her education as Akhila Ashokan – the name she had before she converted to Islam – the principal of the Sivraj Homoeopathic Medical College in Salem, Tamil Nadu, said on Tuesday, PTI reported.
The Supreme Court had on Monday said that Hadiya, whose conversion from Hinduism to Islam and marriage to a Muslim man has sparked off a controversy, could continue her education at the Salem college and should live in the hostel during the duration of her course.
College principal G Kannan said Hadiya would be treated like any other student. He said no one except Hadiya’s parents will be allowed to meet her.
Deputy Commissioner of Police Subbulakshmi, who met the college administration, told reporters that adequate police protection would be provided to Hadiya who had arrived at the college around 7 pm.
Hadiya’s father Ashokan said that he had received permission to visit his daughter whenever he wanted to. “The court has not given anyone guardianship, including Shafin Jahan, of my child,” PTI quoted him as saying.
| english |
In this Sathiya Sothanai film, Premgi Amaren, Swayam Siddha played the primary leads.
The Sathiya Sothanai was released in theaters on 21 Jul 2023.
Movies like Demonte Colony 2, Vidaamuyarchi, Thangalaan and others in a similar vein had the same genre but quite different stories.
The Sathiya Sothanai had a runtime of 109 minutes.
The soundtracks and background music were composed by Raguraam,Deepan Chakaravarthy for the movie Sathiya Sothanai.
The cinematography for Sathiya Sothanai was shot by Saran RV.
The movie Sathiya Sothanai belonged to the Comedy,Drama, genre.
| english |
Joe Sullivan, the Facebook executive in charge of keeping the social network’s 1.3 billion users safe, is leaving to become Uber's first chief security officer.
The move is a major talent grab by the $40 billion car-hailing-app company, and it comes as cofounder and CEO Travis Kalanick grapples with security concerns escalating so rapidly they threaten to slow Uber’s momentum.
In particular, serious accusations involving its drivers are piling up. District attorneys in both San Francisco and Los Angeles have filed lawsuits against the company, alleging its background checks aren’t adequate. In December, a woman in New Delhi, India accused an Uber driver of raping her, and the woman has since filed a lawsuit.
Meanwhile, similar allegations have cropped up in cities across the United States including Chicago and Boston. In London, a woman alleged an Uber driver sexually harassed her and asked her to perform oral sex. Just two days ago, the Denver Post reported that an UberX driver had been arrested for attempting (unsuccessfully) to break into a passenger’s home after dropping her at the airport.
That’s enough to scare anyone into thinking twice before tapping the Uber icon. And it’s why Kalanick recruited Sullivan, who starts in late April and will report directly to him. Sullivan, 46, will head up Uber’s efforts to keep passengers and drivers safe, and he’ll also oversee global cybersecurity. At Facebook and during an earlier stint at eBay, Sullivan dealt in online security, not physical security. But one often plays into the other, and in addition to his work in Silicon Valley, Sullivan can draw on years of experience as a federal prosecutor.
In a blog post announcing Sullivan’s hire, Kalanick wrote: "We see opportunities ahead not just in technology, through biometrics and driver monitoring, but in the potential for inspiring collaborations with city and state governments around the world." It’s a tall order that will require the company, which has often found itself at odds with city regulators and law enforcement, to work more closely with them.
After more than two decades spent working to combat cybercrime and keep people safe in both the public and private sectors, Sullivan may be uniquely qualified for this challenge. After getting a law degree from the University of Miami, he spent eight years with the United States Department of Justice. As the first federal prosecutor dedicated full-time to fighting high-tech crime, he worked on many high profile internet cases from digital evidence aspects of the 9/11 investigations to economic espionage and child predator cases.
In 2002, he joined eBay where he oversaw security for both the Skype and Paypal units. He grew adept at managing the fine line between complying with authorities, and holding back some information to protect users. During six years at Facebook, he was the guy responsible for weeding out the miscreants from among the social network’s users. He navigated the company’s relationship with law enforcement and investigations, and he managed the teams responsible for information security and product security, among other things.
At Uber, he’ll work closely with Katherine Tassi, who is tasked with safeguarding rider data as the managing counsel of data privacy. Phil Cardenas, the company’s head of global security, will report to him.
Uber has been amping up its safety efforts in recent months. Already, it has a fraud engineering team that reports to CTO Thuan Pham. Cardenas manages compliance and incident response teams as well as a group of people who work with law enforcement.
In a March 25 blog post, Cardenas said Uber will form a safety advisory board of independent experts who will review its practices and advise on future safety features. He also said Uber plans to improve its background checks on drivers, and it has established a new code of conduct.
| english |
## Options
You have ability to customize or disable specific elements of Spacefish. All options must be overridden in your `config.fish`.
Colors for sections can be [basic colors](https://fishshell.com/docs/current/commands.html#set_color) or [color codes](https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg).
**Note:** the symbol `·` in this document represents a regular space character ` `, it is used to clearly indicate when an option default value starts or ends with a space.
### Order
You can specify the order of prompt section using `SPACEFISH_PROMPT_ORDER` option. Use Zsh array syntax to define your own prompt order.
The order also defines which sections that Spacefish loads. If you're struggling with slow prompt, you can just omit the sections that you don't use, and they won't be loaded.
The default order is:
```fish
set SPACEFISH_PROMPT_ORDER user dir git node exec_time line_sep battery char
```
### Prompt
This group of options defines a behavior of prompt and standard parameters for sections displaying.
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_PROMPT_ADD_NEWLINE` | `true` | Adds a newline character before each prompt line |
| `SPACEFISH_PROMPT_SEPARATE_LINE` | `true` | Make the prompt span across two lines |
| `SPACEFISH_PROMPT_FIRST_PREFIX_SHOW` | `false` | Shows a prefix of the first section in prompt |
| `SPACEFISH_PROMPT_PREFIXES_SHOW` | `true` | Show prefixes before prompt sections or not |
| `SPACEFISH_PROMPT_SUFFIXES_SHOW` | `true` | Show suffixes before prompt sections or not |
| `SPACEFISH_PROMPT_DEFAULT_PREFIX` | `via` | Default prefix for prompt sections |
| `SPACEFISH_PROMPT_DEFAULT_SUFFIX` | ` ` | Default suffix for prompt section |
### Char
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_CHAR_PREFIX` | ` ` | Prefix before prompt character |
| `SPACEFISH_CHAR_SUFFIX` | ` ` | Suffix after prompt character |
| `SPACEFISH_CHAR_SYMBOL` | `➜` | Prompt character to be shown before any command |
| `SPACEFISH_CHAR_COLOR_SUCCESS` | `green` | Color of prompt character if last command completes successfully |
| `SPACEFISH_CHAR_COLOR_FAILURE` | `red` | Color of prompt character if last command returns non-zero exit-code |
### Username (`user`)
By default, a username is shown only when it's not the same as `$LOGNAME`, when you're connected via SSH or when you're root. Root user is highlighted in `SPACEFISH_USER_COLOR_ROOT` color (red as default).
| Variable | Default | Meaning |
| :------- | :-----: | ------- |
| `SPACEFISH_USER_SHOW` | `true` | Show user section (`true`, `false`, `always` or `needed`) |
| `SPACEFISH_USER_PREFIX` | `with·` | Prefix before user section |
| `SPACEFISH_USER_SUFFIX` | `$SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after user section |
| `SPACEFISH_USER_COLOR` | `yellow` | Color of user section |
| `SPACEFISH_USER_COLOR_ROOT` | `red` | Color of user section when it's root |
`SPACEFISH_USER_SHOW` defines when to show username section. Here are possible values:
| `SPACEFISH_USER_SHOW` | Show on local | Show on remote |
| :-------------------: | :------------- | :-------------- |
| `false` | Never | Never |
| `always` | Always | Always |
| `true` | If needed | Always |
| `needed` | If needed | If needed |
### Directory \(`dir`\)
Directory is always shown and truncated to the value of `SPACEFISH_DIR_TRUNC`. While you are in repository, it shows only root directory and folders inside it.
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_DIR_SHOW` | `true` | Show directory section |
| `SPACEFISH_DIR_SUFFIX` | `$SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after current directory |
| `SPACEFISH_DIR_TRUNC` | `3` | Number of folders of cwd to show in prompt, 0 to show all |
| `SPACEFISH_DIR_TRUNC_REPO` | `true` | While in `git` repo, show only root directory and folders inside it |
| `SPACEFISH_DIR_COLOR` | `(set_color --bold cyan)` | Color of directory section |
| `SPACEFISH_DIR_PREFIX` | `in·` | Prefix before current directory |
### Git \(`git`\)
Git section is consists with `git_branch` and `git_status` subsections. It is shown only in Git repositories.
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_GIT_SHOW` | `true` | Show Git section |
| `SPACEFISH_GIT_PREFIX` | `on·` | Prefix before Git section |
| `SPACEFISH_GIT_SUFFIX` | `$SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after Git section |
| `SPACEFISH_GIT_SYMBOL` |  | Character to be shown before Git section \(requires [powerline patched font](https://github.com/powerline/fonts) |
#### Git branch \(`git_branch`\)
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_GIT_BRANCH_SHOW` | `true` | Show Git branch subsection |
| `SPACEFISH_GIT_BRANCH_PREFIX` | `$SPACEFISH_GIT_SYMBOL` | Prefix before Git branch subsection |
| `SPACEFISH_GIT_BRANCH_SUFFIX` | ` ` | Suffix after Git branch subsection |
| `SPACEFISH_GIT_BRANCH_COLOR` | `(set_color magenta)` | Color of Git branch subsection |
#### Git status \(`git_status`\)
Git status indicators is shown only when you have dirty repository.
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_GIT_STATUS_SHOW` | `true` | Show Git status subsection |
| `SPACEFISH_GIT_STATUS_PREFIX` | `·[` | Prefix before Git status subsection |
| `SPACEFISH_GIT_STATUS_SUFFIX` | `]` | Suffix after Git status subsection |
| `SPACEFISH_GIT_STATUS_COLOR` | `red` | Color of Git status subsection |
| `SPACEFISH_GIT_STATUS_UNTRACKED` | `?` | Indicator for untracked changes |
| `SPACEFISH_GIT_STATUS_ADDED` | `+` | Indicator for added changes |
| `SPACEFISH_GIT_STATUS_MODIFIED` | `!` | Indicator for unstaged files |
| `SPACEFISH_GIT_STATUS_RENAMED` | `»` | Indicator for renamed files |
| `SPACEFISH_GIT_STATUS_DELETED` | `✘` | Indicator for deleted files |
| `SPACEFISH_GIT_STATUS_STASHED` | `$` | Indicator for stashed changes |
| `SPACEFISH_GIT_STATUS_UNMERGED` | `=` | Indicator for unmerged changes |
| `SPACEFISH_GIT_STATUS_AHEAD` | `⇡` | Indicator for unpushed changes \(ahead of remote branch\) |
| `SPACEFISH_GIT_STATUS_BEHIND` | `⇣` | Indicator for unpulled changes \(behind of remote branch\) |
| `SPACEFISH_GIT_STATUS_DIVERGED` | `⇕` | Indicator for diverged chages \(diverged with remote branch\) |
### Package version (`package`)
> Works only for [npm](https://www.npmjs.com/) at the moment. Please, help [spaceship](https://github.com/denysdovhan/spaceship-prompt) improve this section!
Package version is shown when repository is a package (e.g. contains a `package.json` file). If no version information is found in `package.json`, the `⚠` symbol will be shown.
> **Note:** This is the version of the package you are working on, not the version of package manager itself.
| Variable | Default | Meaning |
| :------- | :-----: | ------- |
| `SPACEFISH_PACKAGE_SHOW` | `true` | Show package version |
| `SPACEFISH_PACKAGE_PREFIX` | `is·` | Prefix before package version section |
| `SPACEFISH_PACKAGE_SUFFIX` | `$SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after package version section |
| `SPACEFISH_PACKAGE_SYMBOL` | `📦·` | Character to be shown before package version |
| `SPACEFISH_PACKAGE_COLOR` | `red` | Color of package version section |
### Node.js (`node`)
Node.js section is shown only in directories that contain `package.json` file, or `node_modules` folder, or any other file with `.js` extension.
If you set `SPACEFISH_NODE_DEFAULT_VERSION` to the default Node.js version and your current version is the same as `SPACEFISH_NODE_DEFAULT_VERSION`, then Node.js section will be hidden.
| Variable | Default | Meaning |
| :------- | :-----: | ------- |
| `SPACEFISH_NODE_SHOW` | `true` | Current Node.js section |
| `SPACEFISH_NODE_PREFIX` | `$SPACEFISH_PROMPT_DEFAULT_PREFIX` | Prefix before Node.js section |
| `SPACEFISH_NODE_SUFFIX` | `$SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after Node.js section |
| `SPACEFISH_NODE_SYMBOL` | `⬢·` | Character to be shown before Node.js version |
| `SPACEFISH_NODE_DEFAULT_VERSION` | ` ` | Node.js version to be treated as default |
| `SPACEFISH_NODE_COLOR` | `green` | Color of Node.js section |
### Battery \(`battery`\)
By default, Battery section is shown only if battery level is below `SPACEFISH_BATTERY_THRESHOLD` \(default: 10%\).
| Variable | Default | Meaning |
| :--- | :---: | --- |
| `SPACEFISH_BATTERY_SHOW` | `true` | Show battery section or not \(`true`, `false`, `always` or `charged`\) |
| `SPACEFISH_BATTERY_PREFIX` | ` ` | Prefix before battery section |
| `SPACEFISH_BATTERY_SUFFIX` | `SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after battery section |
| `SPACEFISH_BATTERY_SYMBOL_CHARGING` | `⇡` | Character to be shown if battery is charging |
| `SPACEFISH_BATTERY_SYMBOL_DISCHARGING` | `⇣` | Character to be shown if battery is discharging |
| `SPACEFISH_BATTERY_SYMBOL_FULL` | `•` | Character to be shown if battery is full |
| `SPACEFISH_BATTERY_THRESHOLD` | 10 | Battery level below which battery section will be shown |
`SPACEFISH_BATTERY_SHOW` defines when to show battery section. Here are possible values:
| `SPACEFISH_BATTERY_SHOW` | Below threshold | Above threshold | Fully charged |
| :---: | :--- | :--- | :--- |
| `false` | Hidden | Hidden | Hidden |
| `always` | Shown | Shown | Shown |
| `true` | Shown | Hidden | Hidden |
| `charged` | Shown | Hidden | Shown |
### Ruby (`ruby`)
Ruby section is shown only in directories that contain `Gemfile`, or `Rakefile`, or any other file with `.rb` extension.
| Variable | Default | Meaning |
| :------- | :-----: | ------- |
| `SPACEFISH_RUBY_SHOW` | `true` | Show Ruby section |
| `SPACEFISH_RUBY_PREFIX` | `$SPACEFISH_PROMPT_DEFAULT_PREFIX` | Prefix before Ruby section |
| `SPACEFISH_RUBY_SUFFIX` | `$SPACEFISH_PROMPT_DEFAULT_SUFFIX` | Suffix after Ruby section |
| `SPACEFISH_RUBY_SYMBOL` | `💎·` | Character to be shown before Ruby version |
| `SPACEFISH_RUBY_COLOR` | `red` | Color of Ruby section |
| markdown |
<reponame>MapTalks/mapresty-client-java
package org.maptalks.javasdk.exceptions;
public class InvalidLayerRTException extends RuntimeException {
public InvalidLayerRTException(final String msg) {
super(msg);
}
}
| java |
import SpotifyWebApi from 'spotify-web-api-node'
import spotifyUri from 'spotify-uri'
import dayjs from 'dayjs'
let spotifyLastRequestedToken = null
const spotifyApi = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET
})
const setup = async () => spotifyApi.clientCredentialsGrant()
.then(data => data?.body?.access_token, console.err)
const setToken = (token) => spotifyApi.setAccessToken(token)
const refreshToken = async () => {
return (spotifyLastRequestedToken === null || dayjs().diff(spotifyLastRequestedToken, 'm') > 58)
? setup().then(setToken)
: Promise.resolve()
}
const isType = (query, type) => {
try {
return spotifyUri.parse(query)?.type === type
} catch (err) {
return false
}
}
export const isTrack = (query) => isType(query, 'track')
export const isPlaylist = (query) => isType(query, 'playlist')
export const getSpotifyId = (query) => spotifyUri.parse(query)?.id
export const getTrack = async (trackId) => {
return refreshToken().then(() => spotifyApi.getTrack(trackId))
}
export const getPlaylist = async (playlistId) => {
return refreshToken().then(() => spotifyApi.getPlaylist(playlistId))
}
export const getPlaylistTracks = async (playlistId) => {
await refreshToken()
const tracks = []
let total = 0
let offset = 0
do {
const playlistTracks = await spotifyApi.getPlaylistTracks(playlistId, { offset })
playlistTracks?.body?.items?.forEach(trackInfo => tracks.push(trackInfo))
total = playlistTracks?.body?.total
offset += playlistTracks?.body?.limit
} while (total > offset)
return tracks
}
export default {
isTrack, isPlaylist, getSpotifyId, getTrack, getPlaylist, getPlaylistTracks
}
| javascript |
package org.broadinstitute.dsm.util;
import org.broadinstitute.dsm.security.RequestHandler;
import org.mockserver.integration.ClientAndServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import java.util.HashMap;
public class GBFMockServerRoute extends RequestHandler {
private static final Logger logger = LoggerFactory.getLogger(GBFMockServerRoute.class);
public static ClientAndServer mockDDP;
private static final String orderNumber = "ORD3343";
HashMap<String, String> pathsAndResponses = new HashMap<>();
@Override
protected Object processRequest(Request request, Response response, String userId) throws Exception {
String message = TestUtil.readFile("gbf/OrderResponse.json");
String confirm = "{\"XML\":\"<ShippingConfirmations><ShippingConfirmation OrderNumber=\\\"" + orderNumber + "\\\" Shipper=\\\"B47456\\\" ShipVia=\\\"FedEx Ground\\\" ShipDate=\\\"2018-06-04\\\" ClientID=\\\"P1\\\">" +
"<Tracking>78124444484</Tracking><Item ItemNumber=\\\"K-DFC-PROMISE\\\" LotNumber=\\\"I4CI8-06/26/2019\\\" SerialNumber=\\\"MB-1236741\\\" ExpireDate=\\\"2019-06-26\\\" ShippedQty=\\\"1\\\">" +
"<SubItem ItemNumber=\\\"S-DFC-PROM-BROAD\\\" LotNumber=\\\"I4CD4-06/29/2019\\\" SerialNumber=\\\"RB-1234513\\\"><ReturnTracking>7958888937</ReturnTracking><Tube Serial=\\\"PS-1234567\\\"/>" +
"<Tube Serial=\\\"PS-1234742\\\"/></SubItem><SubItem ItemNumber=\\\"S-DFC-PROM-MAYO\\\" LotNumber=\\\"I4CE7-06/26/2019\\\" SerialNumber=\\\"GB-1236722\\\">" +
"<ReturnTracking>7959999937</ReturnTracking><Tube Serial=\\\"PR-1234471\\\"/></SubItem></Item></ShippingConfirmation></ShippingConfirmations>\"}";
String status = "{\"success\": true, \"statuses\": [{\"orderNumber\": \"" + orderNumber + "\", \"orderStatus\": \"SHIPPED\"},{\"orderNumber\": \"WRBO64NNRV2C3XVZ1WJJ\", \"orderStatus\": \"SHIPPED\"}," +
"{\"orderNumber\": \"K6289XU7Z69J46FPASZ8\", \"orderStatus\": \"NOT FOUND\"}]}";
return null;
}
public void setResponseForPath(String path, String response){
pathsAndResponses.put(path, response);
}
}
| java |
<filename>src/app/store/preferences/preferences.selectors.ts
import { createSelector } from '@ngrx/store';
import { Column, LinkValue } from '~/models';
import { LabState } from '../';
import { PreferencesState } from './preferences.reducer';
/* Base selector functions */
export const preferencesState = (state: LabState): PreferencesState =>
state.preferencesState;
export const getStates = createSelector(
preferencesState,
(state) => state.states
);
export const getColumns = createSelector(
preferencesState,
(state) => state.columns
);
export const getLinkSize = createSelector(
preferencesState,
(state) => state.linkSize
);
export const getLinkText = createSelector(
preferencesState,
(state) => state.linkText
);
export const getSankeyAlign = createSelector(
preferencesState,
(state) => state.sankeyAlign
);
export const getSimplex = createSelector(
preferencesState,
(state) => state.simplex
);
export const getPowerUnit = createSelector(
preferencesState,
(state) => state.powerUnit
);
export const getLanguage = createSelector(
preferencesState,
(state) => state.language
);
/** Complex selectors */
export const getLinkPrecision = createSelector(
getLinkText,
getColumns,
(linkText, columns) => {
switch (linkText) {
case LinkValue.Items:
return columns[Column.Items].precision;
case LinkValue.Belts:
return columns[Column.Belts].precision;
case LinkValue.Wagons:
return columns[Column.Wagons].precision;
case LinkValue.Factories:
return columns[Column.Factories].precision;
default:
return null;
}
}
);
export const getSavedStates = createSelector(getStates, (states) =>
Object.keys(states).map((i) => ({
id: i,
name: i,
}))
);
export const getColumnsVisible = createSelector(
getColumns,
(columns) => Object.keys(columns).filter((c) => columns[c].show).length
);
| typescript |
<gh_stars>1-10
use actix_web::{test, web, App};
use nodeflux_assignment::routes;
mod all_days {
use super::*;
#[actix_web::test]
async fn returns_200() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::index)),
)
.await;
let req = test::TestRequest::with_uri("/daily").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 200);
}
}
mod all_days_in_year {
use super::*;
#[actix_web::test]
async fn returns_200_given_valid_year() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::specific_year)),
)
.await;
let req = test::TestRequest::with_uri("/daily/2020").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 200);
}
#[actix_web::test]
async fn returns_404_given_invalid_year() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::specific_year)),
)
.await;
let req = test::TestRequest::with_uri("/daily/2018").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 404);
}
}
mod all_days_in_month {
use super::*;
#[actix_web::test]
async fn returns_200_given_valid_month() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::specific_month)),
)
.await;
let req = test::TestRequest::with_uri("/daily/2021/7").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 200);
}
#[actix_web::test]
async fn returns_404_given_invalid_month() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::specific_month)),
)
.await;
let req = test::TestRequest::with_uri("/daily/2021/13").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 404);
}
}
mod specific_date {
use super::*;
#[actix_web::test]
async fn returns_200_given_valid_date() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::specific_date)),
)
.await;
let req = test::TestRequest::with_uri("/daily/2021/7/10").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 200);
}
#[actix_web::test]
async fn returns_404_given_invalid_date() {
let app = test::init_service(
App::new().service(web::scope("/daily").service(routes::daily::specific_month)),
)
.await;
let req = test::TestRequest::with_uri("/daily/2021/2/30").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 404);
}
}
| rust |
<reponame>DelilahEve/ring_of_teleport_fabric-1.17<filename>src/main/java/com/kwpugh/ring_of_teleport/RingOfTeleport.java
package com.kwpugh.ring_of_teleport;
import me.shedaniel.autoconfig.AutoConfig;
import me.shedaniel.autoconfig.serializer.JanksonConfigSerializer;
import me.shedaniel.autoconfig.serializer.PartitioningSerializer;
import net.fabricmc.api.ModInitializer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class RingOfTeleport implements ModInitializer
{
public static final String MOD_ID = "ring_of_teleport";
public Item RING_OF_TELEPORT = new ItemRingTeleport(new Item.Settings().group(ItemGroup.MISC));
public Item RING_OF_TELEPORT2 = new ItemRingTeleport2(new Item.Settings().group(ItemGroup.MISC));
public static final ModConfig CONFIG = AutoConfig.register(ModConfig.class, PartitioningSerializer.wrap(JanksonConfigSerializer::new)).getConfig();
@Override
public void onInitialize()
{
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "ring_of_teleport"), RING_OF_TELEPORT);
Registry.register(Registry.ITEM, new Identifier(MOD_ID, "ring_of_teleport2"), RING_OF_TELEPORT2);
}
} | java |
{
"$schema": "https://raw.githubusercontent.com/Azure/azure-devtestlab/master/schemas/2015-01-01/dtlArtifacts.json",
"title": "Chrome",
"description": "Installs Chrome using the Chocolatey package manager",
"tags": [
"Windows",
"Chrome",
"Google"
],
"iconUri": "https://chocolatey.org/content/packageimages/GoogleChrome.48.0.2564.103.svg",
"targetOsType": "Windows",
"runCommand": {
"commandToExecute": "powershell.exe -executionpolicy bypass -File startChocolatey.ps1 -PackageList googlechrome"
}
} | json |
<reponame>jerrytran-wrk/rn-clean-architecture-template<gh_stars>10-100
import {StoreActionApi} from 'react-sweet-state';
import {StackNavigationProp} from '@react-navigation/stack';
import {RouteProp} from '@react-navigation/native';
import {ParamsType} from '@storyboards';
export type {{$name}}ContainerInitialState = {};
export type {{$name}}StoreState = {};
export type {{$name}}State = {};
export type {{$name}}StoreApi = StoreActionApi<{{$name}}State>;
export type {{$name}}NavigationProps = StackNavigationProp<ParamsType, '{{$name}}'>;
export type {{$name}}RouteProp = RouteProp<ParamsType, '{{$name}}'>;
export type {{$name}}Props = {
navigation: {{$name}}NavigationProps;
route: {{$name}}RouteProp;
};
| typescript |
package io
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
/*
工具包
IO/系统路径相关
*/
//FullPath 获取当前进程路径
func FullPath() string {
file, err := exec.LookPath(os.Args[0])
if err != nil {
log.Panic(err)
}
path, err := filepath.Abs(file)
if err != nil {
log.Panic(err)
}
return path[0:strings.LastIndex(path, string(os.PathSeparator))] + string(os.PathSeparator)
}
//CurrentExecutableName 获取当前进程名称
func CurrentExecutableName() string {
file, err := exec.LookPath(os.Args[0])
if err != nil {
log.Panic(err)
}
return file[strings.LastIndex(file, string(os.PathSeparator))+len(string(os.PathSeparator)):]
}
| go |
The entire Randall Lady Raider bench jumped up and ran to Layla Romero with the speed of the Randall cross country team. They collectively dog piled one another to floor, covered in smiles, sweat and maybe a few tears sprinkled in. Their half of Canyon's gym cheered in jubilation while Canyon's team and section stood in stunned silence.
This was the scene Friday night at Canyon High School following Romero's jumper off a rebound as the clock expired. The basket moved Randall ahead 54-52 with no time remaining, giving Randall a district win over Canyon. A buzzer-beating game-winner is exciting regardless of the context. Within context, though, this was a moment that will go down in CISD history.
The Canyon girls team had not lost a district game since the 2018 season until Friday night. More impressively, Randall (14-5, 5-0) hadn't beaten Canyon in girls basketball since winning the Kids Inc. Tournament in 2007. Romero was born in 2006. All of it made for quite the atmosphere.
"I'm so proud of our girls," Randall head coach Brook Walthal said. "We really prepared well and we knew it was going to be a game like this. It was not a perfect game and you have to give Canyon a lot of credit for what they did at the end there. I'm just really proud of our kiddos."
Romero finished with 11 points including the game-winner.
"(When I got the rebound) I figured there was only like four seconds left so even if I don't get it we go into overtime," she said. "I practice that shot every day in practice so (I took it)."
It was yet another phenomenal night from Amarillo Globe-News Preseason Player of the Year Sadie Sanchez. Sanchez made a ton of highlight worthy plays throughout the evening, ending up with 33 points. Her 3-pointer with 2:35 left in the game gave Randall a five-point edge and she hit a free throw with 24.5 seconds remaining to tie things up.
Perhaps most astonishing of all was Sanchez's nonchalant feeling about beating Canyon for the first time since the year she was born.
"Honestly, I wouldn't say it was that surprising," she said. "I mean, it was a hard game, but we prepared for it the whole season. We knew it was going to be tough but we put ourselves in these situations in practice so we were prepared."
Randall looked like it had the game wrapped up with a 51-46 edge with less than a minute to go. Jaylee Moss hit a 3-pointer with 53 seconds left to pull the Lady Eagles within two and with 24.5 seconds remaining, Addison Cunningham stole an inbound pass, got the ball to a wide-open Moss who hit another 3-pointer to put Canyon up 52-51.
Sanchez's free throw and Romero's putback sealed the deal for Randall in the end, but credit Moss for making a ton of big shots down the stretch. She finished with 27 points on the evening.
Canyon (13-5, 4-1) will visit Pampa on Tuesday while Randall will visit Hereford the same day.
| english |
{
"addons": ["heroku-postgresql:hobby-dev"],
"environments": {
"review": {
"addons": ["heroku-postgresql:hobby-dev"]
}
},
"env": {
"APP_SECRET": {
"description": "Server secret for generating JWT tokens",
"generator": "secret"
}
}
}
| json |
package me.wcc.base.infra.constant;
import java.util.Locale;
/**
* 基础常量
*
* @author <EMAIL> 19-3-10 下午2:29
*/
public class BaseConstants {
public static final Integer FLAG_YES = 1;
public static final Integer FLAG_NO = 0;
/**
* 默认页码
*/
public static final String PAGE = "0";
/**
* 默认页面大小
*/
public static final String SIZE = "10";
/**
* 默认页码字段名
*/
public static final String PAGE_FIELD_NAME = "page";
/**
* 默认页面大小字段名
*/
public static final String SIZE_FIELD_NAME = "size";
/**
* 默认页码
*/
public static final Integer PAGE_NUM = 0;
/**
* 默认页面大小
*/
public static final Integer PAGE_SIZE = 10;
/**
* body
*/
public static final String FIELD_BODY = "body";
/**
* KEY content
*/
public static final String FIELD_CONTENT = "content";
/**
* 默认语言
*/
public static final Locale DEFAULT_LOCALE = Locale.CHINA;
/**
* 默认语言
*/
public static final String DEFAULT_LOCALE_STR = Locale.CHINA.toString();
/**
* KEY message
*/
public static final String FIELD_MSG = "message";
/**
* KEY failed
*/
public static final String FIELD_FAILED = "failed";
/**
* KEY success
*/
public static final String FIELD_SUCCESS = "success";
/**
* KEY errorMsg
*/
public static final String FIELD_ERROR_MSG = "errorMsg";
/**
* 默认编码
*/
public static final String DEFAULT_CHARSET = "UTF-8";
public static final Integer REDIS_DB = 0;
/**
* 基础异常编码
*/
public static final class ErrorCode {
/**
* 数据校验不通过
*/
public static final String DATA_INVALID = "error.data_invalid";
/**
* 资源不存在
*/
public static final String NOT_FOUND = "error.not_found";
/**
* 程序出现错误,请联系管理员
*/
public static final String ERROR = "error.error";
/**
* 网络异常,请稍后重试
*/
public static final String ERROR_NET = "error.network";
/**
* 记录不存在或版本不一致
*/
public static final String OPTIMISTIC_LOCK = "error.optimistic_lock";
/**
* 数据已存在,请不要重复提交
*/
public static final String DATA_EXISTS = "error.data_exists";
/**
* 数据不存在
*/
public static final String DATA_NOT_EXISTS = "error.data_not_exists";
/**
* 资源禁止访问
*/
public static final String FORBIDDEN = "error.forbidden";
/**
* 数据库异常:编码重复
*/
public static final String ERROR_CODE_REPEAT = "error.code_repeat";
/**
* 数据库异常:编号重复
*/
public static final String ERROR_NUMBER_REPEAT = "error.number_repeat";
/**
* SQL执行异常
*/
public static final String ERROR_SQL_EXCEPTION = "error.sql_exception";
/**
* 请登录后再进行操作!
*/
public static final String NOT_LOGIN = "error.not_login";
/**
* 不能为空
*/
public static final String NOT_NULL = "error.not_null";
/**
* 用户名或密码错误
*/
public static final String WRONG_PWD_OR_NAME = "error.auth.wrong_password_or_username";
/**
* 内部错误
*/
public static final String INTERNAL_ERROR = "error.internal_error";
/**
* 不支持的认证错误
*/
public static final String UNKNOWN_AUTH_ERROR = "error.auth.unknown_authentication_error";
public static final String FIELD_NOT_NULL = "error.base.field_not_null";
private ErrorCode() {
}
}
/**
* 日期时间匹配格式
*/
public static final class Pattern {
//
// 常规模式
// ----------------------------------------------------------------------------------------------------
/**
* yyyy-MM-dd
*/
public static final String DATE = "yyyy-MM-dd";
/**
* yyyy-MM-dd HH:mm:ss
*/
public static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy-MM-dd HH:mm
*/
public static final String DATETIME_MM = "yyyy-MM-dd HH:mm";
/**
* yyyy-MM-dd HH:mm:ss.SSS
*/
public static final String DATETIME_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* HH:mm
*/
public static final String TIME = "HH:mm";
/**
* HH:mm:ss
*/
public static final String TIME_SS = "HH:mm:ss";
//
// 系统时间格式
// ----------------------------------------------------------------------------------------------------
/**
* yyyy/MM/dd
*/
public static final String SYS_DATE = "yyyy/MM/dd";
/**
* yyyy/MM/dd HH:mm:ss
*/
public static final String SYS_DATETIME = "yyyy/MM/dd HH:mm:ss";
/**
* yyyy/MM/dd HH:mm
*/
public static final String SYS_DATETIME_MM = "yyyy/MM/dd HH:mm";
/**
* yyyy/MM/dd HH:mm:ss.SSS
*/
public static final String SYS_DATETIME_SSS = "yyyy/MM/dd HH:mm:ss.SSS";
//
// 无连接符模式
// ----------------------------------------------------------------------------------------------------
/**
* yyyyMMdd
*/
public static final String NONE_DATE = "yyyyMMdd";
/**
* yyyyMMddHHmmss
*/
public static final String NONE_DATETIME = "yyyyMMddHHmmss";
/**
* yyyyMMddHHmm
*/
public static final String NONE_DATETIME_MM = "yyyyMMddHHmm";
/**
* yyyyMMddHHmmssSSS
*/
public static final String NONE_DATETIME_SSS = "yyyyMMddHHmmssSSS";
/**
* EEE MMM dd HH:mm:ss 'CST' yyyy
*/
public static final String CST_DATETIME = "EEE MMM dd HH:mm:ss 'CST' yyyy";
//
// 数字格式
// ------------------------------------------------------------------------------
/**
* 无小数位 0
*/
public static final String NONE_DECIMAL = "0";
/**
* 一位小数 0.0
*/
public static final String ONE_DECIMAL = "0.0";
/**
* 两位小数 0.00
*/
public static final String TWO_DECIMAL = "0.00";
/**
* 千分位表示 无小数 #,##0
*/
public static final String TB_NONE_DECIMAL = "#,##0";
/**
* 千分位表示 一位小数 #,##0.0
*/
public static final String TB_ONE_DECIMAL = "#,##0.0";
/**
* 千分位表示 两位小数 #,##0.00
*/
public static final String TB_TWO_DECIMAL = "#,##0.00";
private Pattern() {
}
}
/**
* 符号常量
*/
public static final class Symbol {
/**
* 感叹号:!
*/
public static final String SIGH = "!";
/**
* 符号:@
*/
public static final String AT = "@";
/**
* 井号:#
*/
public static final String WELL = "#";
/**
* 美元符:$
*/
public static final String DOLLAR = "$";
/**
* 人民币符号:¥
*/
public static final String RMB = "¥";
/**
* 空格:
*/
public static final String SPACE = " ";
/**
* 换行符:\r\n
*/
public static final String LB = System.getProperty("line.separator");
/**
* 百分号:%
*/
public static final String PERCENTAGE = "%";
/**
* 符号:&
*/
public static final String AND = "&";
/**
* 星号
*/
public static final String STAR = "*";
/**
* 中横线:-
*/
public static final String MIDDLE_LINE = "-";
/**
* 下划线:_
*/
public static final String LOWER_LINE = "_";
/**
* 等号:=
*/
public static final String EQUAL = "=";
/**
* 加号:+
*/
public static final String PLUS = "+";
/**
* 冒号::
*/
public static final String COLON = ":";
/**
* 分号:;
*/
public static final String SEMICOLON = ";";
/**
* 逗号:,
*/
public static final String COMMA = ",";
/**
* 点号:.
*/
public static final String POINT = ".";
/**
* 斜杠:/
*/
public static final String SLASH = "/";
/**
* 双斜杠://
*/
public static final String DOUBLE_SLASH = "//";
/**
* 反斜杠
*/
public static final String BACKSLASH = "\\";
/**
* 问号:?
*/
public static final String QUESTION = "?";
/**
* 左小括号:(
*/
public static final String LEFT_SMALL_BRACE = "(";
/**
* 右小括号:)
*/
public static final String RIGHT_SMALL_BRACE = ")";
/**
* 左花括号:{
*/
public static final String LEFT_BIG_BRACE = "{";
/**
* 右花括号:}
*/
public static final String RIGHT_BIG_BRACE = "}";
/**
* 左中括号:[
*/
public static final String LEFT_MIDDLE_BRACE = "[";
/**
* 右中括号:[
*/
public static final String RIGHT_MIDDLE_BRACE = "]";
/**
* 反引号:`
*/
public static final String BACKQUOTE = "`";
private Symbol() {
}
}
private BaseConstants() {
}
}
| java |
package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.DataStoreException;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* @author <NAME> (<EMAIL>)
* @since 1.0 (4/9/16)
*/
public class MemoryDataStoreTest {
private MemoryDataStore<String, Person> dataStore;
@BeforeMethod
public void setUp() throws Exception {
dataStore = new MemoryDataStore<>(Person.class);
}
@Test
public void testEntityType() throws Exception {
assertThat(dataStore.getEntityType(), is(equalTo(Person.class)));
}
@Test
public void testSaveAndRetrieve() throws Exception {
assertThat(dataStore.retrieveAll(), is(Matchers.<Person>empty()));
final Person person = new Person();
dataStore.save("key", person);
assertThat(dataStore.retrieveAll(), hasSize(1));
}
@Test
public void testRetrievalByKey() throws Exception {
final Person person = new Person();
final String key = "key";
assertThat(dataStore.retrieve(key), is(nullValue()));
assertThat(dataStore.retrieve(key + "x"), is(nullValue()));
dataStore.save(key, person);
assertThat(dataStore.retrieve(key), is(person));
assertThat(dataStore.retrieve(key + "x"), is(nullValue()));
}
@Test
public void testExistence() throws Exception {
final Person person = new Person();
final String key = "key";
assertThat(dataStore.hasKey(key), is(false));
assertThat(dataStore.hasKey(key + "x"), is(false));
dataStore.save(key, person);
assertThat(dataStore.hasKey(key), is(true));
assertThat(dataStore.hasKey(key + "x"), is(false));
}
@Test
public void testSaveAndDelete() throws Exception {
final Person person1 = new Person();
final Person person2 = new Person();
final String key1 = "key1";
final String key2 = "key2";
assertThat(dataStore.retrieveAll(), is(Matchers.<Person>empty()));
dataStore.save(key1, person1);
assertThat(dataStore.hasKey(key1), is(true));
dataStore.save(key2, person2);
assertThat(dataStore.hasKey(key2), is(true));
assertThat(dataStore.retrieveAll(), hasSize(2));
assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2));
dataStore.delete(key1 + "x");
assertThat(dataStore.hasKey(key2), is(true));
assertThat(dataStore.retrieveAll(), hasSize(2));
assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2));
dataStore.delete(key1);
assertThat(dataStore.hasKey(key1), is(false));
assertThat(dataStore.hasKey(key2), is(true));
assertThat(dataStore.retrieveAll(), hasSize(1));
assertThat(dataStore.retrieveAll(), containsInAnyOrder(person2));
dataStore.delete(key2);
assertThat(dataStore.hasKey(key1), is(false));
assertThat(dataStore.hasKey(key2), is(false));
assertThat(dataStore.retrieveAll(), is(Matchers.<Person>empty()));
}
@Test
public void testKeys() throws Exception {
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
assertThat(dataStore.keys(), containsInAnyOrder("1", "2", "3"));
}
@Test(expectedExceptions = DataStoreException.class)
public void testSavingWithNullKey() throws Exception {
dataStore.save(null, new Person());
}
@Test(expectedExceptions = DataStoreException.class)
public void testSavingWithNullEntity() throws Exception {
dataStore.save("1", null);
}
@Test(expectedExceptions = DataStoreException.class)
public void testDeletingWithNullKey() throws Exception {
dataStore.delete(null);
}
@Test(expectedExceptions = DataStoreException.class)
public void testRetrievingWithNullKey() throws Exception {
dataStore.retrieve(null);
}
@Test
public void testTruncating() throws Exception {
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
assertThat(dataStore.retrieveAll(), hasSize(3));
dataStore.truncate();
assertThat(dataStore.retrieveAll(), is(Matchers.<Person>empty()));
}
} | java |
If the pandemic/lockdown made us socially distant, turned us into deep-throated Amitabh Bachchans waxing eloquent about main aur meri tanhayi (us conversing with our solitude), the force majeure made us yearn more for human/social connections. Pandemic aside, even when we lose/miss an absent loved one, can a stranger fill in that role?
Can they address/absorb our repressed emotions, provide us with closure? Amrita Bagchi’s futuristic Succulent, which picked up the Audience Award for Best First Film at the recently concluded 10th Dharamshala International Film Festival, is our rendezvous with a dystopian reality/future. Set to a balmy background score by Ishaan Divecha (Udta Punjab, Qarib Qarib Single, Paatal Lok), Bagchi’s short film is inconspicuously unsettling.
While Bagchi wrote the film in 2018, before Werner Herzog released his Family Romance, LLC in 2019, both are in the same vein — the former a future possibility in India, the latter a current reality in Japan. Both feature an agency which sends out people for rental family service, to fill in the gaps in people’s lives. Neither Herzog’s Yuichi Ishii, who becomes a fake father/friend, nor Bagchi’s young woman M (Merenla Imsong) have access to, or are allowed, human attachments. Being a rental person, perhaps, helps them, too, to fill the void in their lives (M’s family denies her family time).
M’s company, Complete Companions Inc. , a cubicle (in Ghaziabad), like a defunct spaceship out of a sci-fi movie, throws out shock absorbers into the orbit. For a fee, of course. M is given training material (PDFs, clothes, pen drives) to become a said person she’s to replace: a Kannadiga Brahmin sister, a Jain daughter, a granddaughter. The nameless M plays along, crosses the line (eats chicken pizza in a Jain household), and pushes back. At times, it works like a house on fire; at times, it backfires.
M has for companion green friends, the only life she’s genuinely attached to. Imsong, in real life, has even named her 42 houseplants. M is the succulent who’ll survive in any condition, nurture the soil she grows in, even prick her clients into senses. Like Aditi Iyengar — not accepting the Northeasterner M as her younger sister Smita, as being aware of their Kannadiga Brahmin customs and vocabulary — who projects her repressed anger and bitterness, from Smita’s untimely death by drunk-driving and her inability to protect her, onto M. There’s power dynamics at play, Aditi can humiliate M, she’s paid for her services, but more pointedly, how could the impersonator enjoy while she’s hurting.
Bagchi, 35, a Santiniketan (fine arts) and National Institute of Design, Ahmedabad, graduate (graphics), has designed sets for plays (Motley theatre group, etc), does clowning work for children (Clowns Without Borders), does commissioned writing. She’s dabbled in acting: theatre (Manav Kaul’s Colourblind), films (The Music Teacher, 2019), TV/web shows (Mrinal ki Chitthi in Stories of Rabindranath Tagore; Hasmukh; City of Dreams). She wanted to make a play about loneliness and family rental, a man and a dog — a metaphor that surfaces in the film. The written script, however, was morphed into a multilingual film.
“At that time, my 82-year-old widowed grandmother was staying alone in a small town (Serampore), near Calcutta, very far away from us (in Mumbai). I felt like I wish there was somebody like me with her. So that’s where it came from,” she says. The Kolkata Police and a non-profit has this year started a programme called Pronam, where they, through young volunteers, conduct security audits and needs assessment (medicines, etc) of elderly people/couples living alone.
Bagchi was astounded when Imsong informed her about Japan’s rent-a-family industry, and read about it in The New Yorker. What struck her, however, is that in India, futurism is very different. “There are going to be caste issues, complexion issues, geographical issues. And people will have 20 other problems, because no matter how united we may be, there are many things that have the potential to divide us,” says Bagchi. She lost her mother two months after this, and a couple of days before shooting for Faraz Ali’s debut feature Shoebox, which also screened at the 10th DIFF. Bagchi plays the lead in that film, about a city’s transformation, erosion of the familiar, and a difficult father-daughter relationship. Bagchi designed the Succulent poster and brought on board part of her Shoebox crew, executive producer Shanoo Sheikh, and Ali as the editor, among others. The theme of personal loss, too, connects the two works. Three months later, Bagchi lost her grandmother, as well.
Plants enter the narrative, then. “It is a form of attachment. We ask helpers/neighbours, allow strangers to enter our homes, to water the plants in our absence. My grandmother cared for her tulsi plant, this plant and that plant, all the time. I felt it was a good way to show personal attachment without bringing in more human beings into the picture,” says Bagchi.
Visual representation of futuristic, dystopian things/reality (sci-fi films, for instance) is almost always devoid of any greenery, she says, “I don’t agree that in the future, there’ll be people but no plants. There’ll be one dusty little leaf going somewhere. That’s just life. It was important, for me, to put it in the film,” says the director.
Click for more updates and latest Bollywood news along with Entertainment updates. Also get latest news and top headlines from India and around the world at The Indian Express. | english |
Chiedo tutto il tuo aiuto [ENG/ITA] I'm asking for your help (original son)
How are you? How are you in this crypto world?
How was your day inside those cold block?
Quando blues non c’é quando il blues non c'è.
| english |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.