content
stringlengths 10
4.9M
|
---|
<reponame>marcovit79/vlc_web
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'duration'})
export class DurationPipe implements PipeTransform {
transform(value: number ): string {
let seconds = value % 60;
let minutes = Math.floor( value / 60 ) % 60;
let hours = Math.floor( value / ( 60 * 60) );
let str = ( '0' + minutes).slice( -2) + ":" + ( '0' + seconds).slice( -2);
if ( hours == 0 ) {
str = str + " min";
}
else {
str = hours + ":" + str + " h"
}
return str;
}
} |
<gh_stars>0
/*
Derby - Class org.apache.derby.iapi.store.raw.ContainerKey
Copyright 1998, 2004 The Apache Software Foundation or its licensors, as applicable.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.iapi.store.raw;
import org.apache.derby.iapi.util.Matchable;
import org.apache.derby.iapi.services.io.CompressedNumber;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.services.locks.Lockable;
import org.apache.derby.iapi.services.locks.Latch;
import org.apache.derby.iapi.services.locks.VirtualLockTable;
import java.util.Hashtable;
/**
A key that identifies a Container within the RawStore.
<BR> MT - Immutable
*/
public final class ContainerKey implements Matchable, Lockable
{
private final long segmentId; // segment identifier
private final long containerId; // container identifier
/**
Create a new ContainerKey
*/
public ContainerKey(long segmentId, long containerId) {
this.segmentId = segmentId;
this.containerId = containerId;
}
/**
Return my identifier within the segment
*/
public long getContainerId() {
return containerId;
}
/**
Return my segment identifier
*/
public long getSegmentId() {
return segmentId;
}
/*
** Methods to read and write ContainerKeys.
*/
public void writeExternal(ObjectOutput out) throws IOException
{
CompressedNumber.writeLong(out, segmentId);
CompressedNumber.writeLong(out, containerId);
}
public static ContainerKey read(ObjectInput in) throws IOException
{
long sid = CompressedNumber.readLong(in);
long cid = CompressedNumber.readLong(in);
return new ContainerKey(sid, cid);
}
/*
** Methods of Object
*/
public boolean equals(Object other) {
if (other == this)
return true;
if (other instanceof ContainerKey) {
ContainerKey otherKey = (ContainerKey) other;
return (containerId == otherKey.containerId) &&
(segmentId == otherKey.segmentId);
} else {
return false;
}
}
public int hashCode() {
return (int) (segmentId ^ containerId);
}
public String toString() {
return "Container(" + segmentId + ", " + containerId + ")";
}
/*
** methods of Matchable
*/
public boolean match(Object key) {
// instance of ContainerKey?
if (equals(key))
return true;
if (key instanceof PageKey)
return equals(((PageKey) key).getContainerId());
if (key instanceof RecordHandle) {
return equals(((RecordHandle) key).getContainerId());
}
return false;
}
/*
** Methods of Lockable
*/
public void lockEvent(Latch lockInfo) {
}
public boolean requestCompatible(Object requestedQualifier, Object grantedQualifier) {
if (SanityManager.DEBUG) {
SanityManager.ASSERT(requestedQualifier instanceof ContainerLock);
SanityManager.ASSERT(grantedQualifier instanceof ContainerLock);
}
ContainerLock clRequested = (ContainerLock) requestedQualifier;
ContainerLock clGranted = (ContainerLock) grantedQualifier;
return clRequested.isCompatible(clGranted);
}
/**
This method will only be called if requestCompatible returned false.
This results from two cases, some other compatabilty space has some
lock that would conflict with the request, or this compatability space
has a lock tha
*/
public boolean lockerAlwaysCompatible() {
return true;
}
public void unlockEvent(Latch lockInfo) {
}
/**
This lockable wants to participate in the Virtual Lock table.
*/
public boolean lockAttributes(int flag, Hashtable attributes)
{
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(attributes != null,
"cannot call lockProperties with null attribute list");
}
if ((flag & VirtualLockTable.TABLE_AND_ROWLOCK) == 0)
return false;
attributes.put(VirtualLockTable.CONTAINERID,
new Long(getContainerId()));
attributes.put(VirtualLockTable.LOCKNAME, "Tablelock");
attributes.put(VirtualLockTable.LOCKTYPE, "TABLE");
// attributes.put(VirtualLockTable.SEGMENTID, new Long(identity.getSegmentId()));
return true;
}
}
|
<filename>client/src/components/editor/SmallEditor.test.tsx
import React from "react";
import { fireEvent, render, waitFor } from "@testing-library/react";
import "mutationobserver-shim";
import userEvent from "@testing-library/user-event";
import SmallEditor from "./SmallEditor";
import SourceType from "../../types/source-type";
import ZettelType from "../../types/zettel-type";
import ContentType from "../../types/content-type";
const bookmarkZettle: Zettel = {
id: "80c52c84-95d0-420a-b557-8445d8938481",
number: 201111001,
title: "bookmark title",
content: "bookmark content",
type: ZettelType.BOOKMARK,
tags: ["tag1", "tag2"],
createdAt: new Date("2020-11-11"),
updatedAt: new Date("2020-11-11"),
meta: {
source: {
type: SourceType.URL,
data: "https://www.example.com",
},
renderer: ContentType.MARKDOWN,
},
} as Zettel;
function $(selector: string): any {
return document.querySelector(selector);
}
describe("<SmallEditor />", () => {
it("should set default zettel", () => {
const onSumbit = jest.fn();
const { getByText } = render(
<SmallEditor onSubmit={onSumbit} defaultZettel={bookmarkZettle} />
);
getByText("201111001"); // number
expect($("input[name='title']").value).toBe("bookmark title"); // title
expect($("textarea[name='content']").value).toBe("bookmark content"); // content
// getByText("BOOKMARK") // type
getByText("#tag1"); // tag
expect($("select[name='meta.source.type']").value).toBe(SourceType.URL); // source type
expect($("input[name='meta.source.data']").value).toBe(
"https://www.example.com"
); // link
getByText("수정"); // submit button
});
it("should call onSubmit with correct data when user submit a note", () => {
const onSumbit = jest.fn();
const { getByRole } = render(<SmallEditor onSubmit={onSumbit} />);
userEvent.type($("input[name='title']"), "new title");
fireEvent.change($("textarea[name='content']"), {
target: { value: "content" },
});
userEvent.selectOptions($("select[name='meta.renderer']"), "MARKDOWN");
userEvent.click(getByRole("button"));
return waitFor(
() => {
expect(onSumbit).toBeCalledWith({
title: "new title",
type: "NOTE",
content: "content",
meta: { renderer: "MARKDOWN" },
tags: [],
});
},
{ timeout: 500 }
);
});
it("can add source to note", () => {
const onSumbit = jest.fn();
const { getByLabelText } = render(<SmallEditor onSubmit={onSumbit} />);
expect($("select[name='meta.source.type']")).toBeFalsy(); // source type
userEvent.click(getByLabelText("source"));
expect($("select[name='meta.source.type']")).toBeTruthy(); // source type
});
// it("should render error");
});
|
/**
* <p>Class that stores the attributes of messages as laid out in the
* motd.dat file</p>
*
* @see MOTDService#processFile(boolean) processFile
*/
private class Message
{
/**
* <p>MOTD item id</p>
*/
protected Integer id = null;
/**
* <p>If this MOTD item is active</p>
*/
protected Boolean active = null;
/**
* <p>Item title</p>
*/
protected String title = null;
/**
* <p>Item (HTML) content</p>
*/
protected String content = null;
/**
* <p>User account name</p>
*/
protected String poster_uid = null;
/**
* <p>User account 'real' name</p>
*/
protected String poster_name = null;
/**
* <p>Creates a new message class</p>
*/
private Message()
{
// Nothing to see here. Move along, citizen!
}
/**
* <p>Returns this MOTD message in the form:</p>
* <pre>#666 Benedict Harcourt (bh308@doc): Important Announcement
* DoCitten can now read the Message of the Day data files</pre>
* @return formatted MOTD message
*/
@Override
public String toString()
{
return String.format("#%1$d *%2$s* (%3$s@doc): %4$s\n%5$s",
id, poster_name, poster_uid, title,
content.replaceAll("</?(br|BR)( ?/)?>", " ").replaceAll("</?(p|P) ( ?/)?>", "\n")
);
}
} |
/**
* Generates the certificate required for using SSL.
*/
public class CertificateGeneratorTest {
@Test
public void testGenerateKeyAndTrustStore() throws GeneralSecurityException, IOException, OperatorException {
final File componentsDir = new File("target/test/certificates");
Delete delete = new Delete();
delete.setDir(componentsDir);
delete.execute();
final File testResourcesDir = new File("src/test/resources/certificates/definition-01");
if (!testResourcesDir.exists()) {
throw new IllegalArgumentException("Source directory does not exist.");
}
Copy copy = new Copy();
copy.setProject(getAntProject());
FileSet testSet = new FileSet();
testSet.setDir(testResourcesDir);
testSet.setIncludes("**/*");
copy.add(testSet);
copy.setTodir(componentsDir);
copy.execute();
String[] components = { "ext", "xyz-ca", "xyz-root", "xyz-app", "xyz-idm", "xyz-directory", "xyz-csr" };
for (String componentName : components) {
CertificateManager certificateManager = new CertificateManager(componentsDir, componentName);
certificateManager.createOrComplete();
certificateManager.setAntProject(getAntProject());
}
}
protected Project getAntProject() {
return new LoggingProjectAdapter();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void listSupportedSubjectAttributes() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> clazz = BCStyle.class;
Field field = clazz.getDeclaredField("DefaultSymbols");
field.setAccessible(true);
final Map<?, ?> object = (Map<?, ?>) field.get(null);
final ArrayList arrayList = new ArrayList(object.values());
Collections.sort(arrayList);
System.out.println(arrayList);
}
} |
/**
* Sets the minimum boundary for the generated random float. The minimum is inclusive, i.e. the generated value may
* be greater than or equal to the minimum boundary.
* @param minValue The minimum bound for the generated random value.
* @return A reference to the <code>Randomizer</code> instance so that method calls can be chained.
*/
@Override
public Randomizer<Float> min(Float minValue) {
this.minValue = minValue;
return this;
} |
//Deprecated: Will be removed in a future release and tests in sdlSyncStorageMock_test.go
//should be used instead.
func TestRemoveIfAndPublish(t *testing.T){
var data map[string]interface{}
var channelsAndEvents []string
key := "key"
sdlInstanceMockTest := initSdlInstanceMockTest()
sdlInstanceMockTest.On("RemoveIfAndPublish", channelsAndEvents, key, data).Return(true,nil)
res, err := sdlInstanceMockTest.RemoveIfAndPublish(channelsAndEvents, key, data)
assert.Nil(t, err)
assert.NotNil(t, res)
} |
// DecodeProjectConfig Helper to decode Data field type ProjectConfig
func (e *EventMsg) DecodeProjectConfig() (ProjectConfig, error) {
var err error
p := ProjectConfig{}
switch e.Type {
case EVTProjectAdd, EVTProjectChange, EVTProjectDelete:
d := []byte{}
d, err = json.Marshal(e.Data)
if err == nil {
err = json.Unmarshal(d, &p)
}
default:
err = fmt.Errorf("Invalid type")
}
return p, err
} |
<gh_stars>0
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import {AuthenticationServiceService} from '../../../shared/Services/authentication-service.service';
import {ChangePasswordIn} from '../../../api/models/change-password-in';
import {PasswordValidationService} from '../../../shared/Services/password-validation.service';
import {ProfileService} from '../../../api/services/profile.service';
import {ErrMassageService} from '../../../shared/Services/err-massage.service';
@Component({
selector: 'app-change-password',
templateUrl: './change-password.component.html',
styleUrls: ['./change-password.component.scss']
})
export class ChangePasswordComponent implements OnInit {
changePasswordForm: FormGroup;
sendChangePasData: ChangePasswordData;
changePasswordIn: ChangePasswordIn;
constructor(
private formBuilder: FormBuilder,
private router: Router,
private profileService: ProfileService,
private toastrService: ToastrService,
private messageModal: ErrMassageService,
private authenticationConfig: AuthenticationServiceService
) {
}
ngOnInit() {
this.changePasswordForm = this.formBuilder.group({
oldpass: ['', Validators.required],
newpass: ['', [Validators.required, Validators.minLength(8)]],
newpassconfirm: ['', Validators.required],
},
{
validator: PasswordValidationService.MatchPassword
}
);
}
get oldpass() {
return this.changePasswordForm.get('oldpass');
}
get newpass() {
return this.changePasswordForm.get('newpass');
}
get newpassconfirm() {
return this.changePasswordForm.get('newpassconfirm');
}
changePassword() {
if (this.changePasswordForm.valid) {
this.sendChangePasData = {
changePasswordIn: {
newPassword: this.changePasswordForm.value.newpass,
oldPassword: this.changePasswordForm.value.oldpass
}
};
this.profileService.changePassword(this.sendChangePasData.changePasswordIn).subscribe(
result => {
if (result.status) {
// this.messageModal.openModal('Notice !', result.message);
this.toastrService.success(result.message);
this.router.navigate(['/login']);
localStorage.setItem(this.authenticationConfig.passwordChanged, 'true');
} else {
// this.messageModal.openModal('Warning !', result.message);
this.toastrService.error(result.message);
}
}
);
}
}
cancel() {
this.ngOnInit();
}
}
export interface ChangePasswordData {
changePasswordIn: ChangePasswordIn;
}
|
<filename>src/trace/GLInterceptor/Log.cpp
#include "Log.h"
/* create log file */
#ifdef LOG_MODE_ENABLED
#include "support.h"
#include <sys/timeb.h>
#include <time.h>
using namespace std;
Log* Log::theLog = 0;
Log& Log::log( const char* filename )
{
if ( theLog )
return *theLog;
if ( filename == NULL )
panic("Log", "log()", "Log file name required");
theLog = new Log;
theLog->open(filename);
if ( !theLog->is_open() )
panic("Log", "log()", "Log file cannot be opened");
return *theLog;
}
string Log::time()
{
/* simple time clock */
struct _timeb timebuffer;
char *timeline;
_ftime(&timebuffer);
timeline = ctime(&(timebuffer.time));
char theTime[256];
sprintf(theTime, "%.8s.%hu", &timeline[11], timebuffer.millitm);
return string(theTime);
}
#endif
|
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 10000000
int n, m, i, j, a, b, dist = INF;
int distf(int sx, int sy, int ex, int ey, int dx, int dy) {
if (abs(sx - ex) % dx != 0) return INF;
if (abs(sy - ey) % dy != 0) return INF;
if ((((abs(sx - ex) / dx) ^ (abs(sy - ey) / dy)) & 1) != 0) return INF;
if ((n - 1) < dx && abs(sy - ey) / dy != 0) return INF;
if ((m - 1) < dy && abs(sx - ex) / dx != 0) return INF;
return max(abs(sx - ex) / dx, abs(sy - ey) / dy);
}
int main(int argc, char **argv) {
cin >> n >> m >> i >> j >> a >> b;
dist = min(dist, distf(i, j, 1, m, a, b));
dist = min(dist, distf(i, j, n, 1, a, b));
dist = min(dist, distf(i, j, n, m, a, b));
dist = min(dist, distf(i, j, 1, 1, a, b));
if (dist == INF) cout << "Poor Inna and pony!";
else cout << dist;
return 0;
}
|
Get the biggest daily stories by email Subscribe Thank you for subscribing We have more newsletters Show me See our privacy notice Could not subscribe, try again later Invalid Email
A BIRMINGHAM grime star has been convicted of drugs offences including being concerned in supplying cannabis.
Jermaine Alleyne’s music is regularly played on Radio 1 and he has performed at clubs across the country.
Alleyne, of Frank Fisher Way, West Bromwich, was arrested after police stopped a car in Birmingham in January 2016.
Police have said crack cocaine, heroin and cannabis were discovered during a search of the vehicle which was travelling along Pershore Road at the time.
Appearing at Birmingham Crown Court l ast week, Alleyne pleaded guilty to being concerned in the supply of cannabis and possession of the same drug.
His co-defendant, Omar Brown, 31, of Southfield Road, Edgbaston, pleaded guilty at an earlier hearing to two counts of being concerned in the supply of a Class A drug, two counts of possession of cannabis with intent, and one of possession of cannabis.
Top grime artist Saphan Robinson - who performs as SafOne - had been charged with drugs offences as part of the same case and was cleared of all charges at last week’s hearing.
Alleyne and Brown will be sentenced on January 12 at Birmingham Crown Court.
Alleyne performs under the name Trilla Trilloski and has built up a name for himself in both the grime and bassline scenes and he boasts huge hits on YouTube.
Trilla featured alongside SafOne on ‘She Wants a Man From Brum’, one of the city’s breakout grime hits that landed airplay on BBC Radio 1 and 1 Xtra.
Considered one of the city’s heavyweight MCs, he has been at the forefront of the local scene since 2010 and has spoken out against gang wars based on postcodes.
Trilla’s own track 0121, with references to Broad Street and Handsworth, is one of the other tracks that have helped put the city on the grime map.
Coming from a DJing background, Trilla learnt to play various instruments as a child, becoming an MC at the age of 15 and winning a MC battle competition at school, according to a BBC write-up about him.
During his college years his reputation as a DJ and MC grew and he recorded his first track whilst studying for a Law degree at university. 1Xtra was the first national station to playlist his single Who Are Ya? and tip him for the spotlight in 2011.
Saphan Robinson had posted an Instagram picture of himself alongside his barrister on the steps of Birmingham Crown Court, with the message: “N O T G U I L T Y !!! Promoters/Labels/Real***** and Gyal dat prayed for me HOLLA !!! IM BACK ! Ha ! “
A statement from his lawyer said: “At Birmingham Crown Court on 30th November 2017, Saphan Robinson, a successful Grime star known as SafOne was found not guilty of all charges of being concerned in the supply of drugs. After a three day trial the jury took just 28 minutes to find Mr Robinson not guilty of all charges.
“Mr Robinson was represented by Purcell Parker Solicitors and Barrister, Mr Gurdeep Garcha of Citadel Chambers.
“While waiting for his trial Mr Robinson had to self-fund the release of his albums ‘The Link Up’ and ‘Another One’ as promotions were suspended due to the ongoing case. He was unable to travel abroad for performances and lost a distribution deal but Mr Robinson is now focusing on his future headline tour.
“Mr Robinson would like to thank his many fans for their continued support.”
The Birmingham Mail contacted Mr Robinson and asked if he was upset over his friend Trilla’s convictions. He said: “Well, they haven’t even been sentenced yet so we don’t know what’s going on.” |
This article contains advice from other players, and may be subjective and/or outdated. Read at your own risk and alter to fit your play style as necessary!
Version 0.20: This article may not be up to date for the latest stable release of Crawl.
This walk-through assumes that you have downloaded and installed your first version of Crawl just a few weeks ago, have played a few games, and usually ended up dead after a few levels. Being frustrated and still fascinated by the game, you somehow found this Wiki and are now looking for advice on how to win this game. Let us begin this guide with the bold statement that indeed the game can be won, with the qualifying remark that that does not happen very often, no matter how smart you play. But there are some things that you can learn, and some choices you can make, which will make it much more likely that you take the Orb of Zot into your hands and ascend with it to the surface alive. This walk-through attempts to give you much of the information you need, and it follows one particular strategy which is assumed to be an easy way of winning. “Easy” in the sense that you will have a good chance of surviving many situations which are a lot more difficult to master if you follow a different strategy. “Easy” does not mean that you will not die when following this advice, or that you should feel bad if you loose. A lot in this game just depends on luck, and even a small mistake or a wrong key pressed at the wrong time may get you snuffed. Sometimes the game gives you a bad deal, either by throwing you into a situation from which you cannot escape, or by providing you with suboptimal equipment or stats over a long period of time. When that happens, you will die, and, hopefully, just begin another game.
Another reason to read this walk-through is when so far you have only played melee characters and now for the first time want to see how it is to kill monsters with something else than a physical weapon, playing a caster. This walk-through will not only talk about strategy and tactics, but it will also explain some of the basic game mechanics, particularly those related to casting spells. This makes this page quite wordy, and experienced players won’t need any of this. Beginners, however, will hopefully find much useful information for which they would have to dig deeply into this Wiki for many hours.
Some players object to the idea of a walk-through or character guide, as it sets out with a specific plan, which is somewhat contrary to the philosophy of the game: develop your character as the situation arises and changes. This walk-through, instead, will tell you to be rather inflexible. This is in order to allow you to celebrate your first win as a caster. For a real Crawl experience you should afterwards try to look for different approaches; this will be a while, though. Even if you follow this guide, you should expect to die a few times before being ultimately successful. But once you reach the end of the game, you will have learned so many things about it that the next game will be much easier to you.
Basic Choices
The two first choices of the game determine your strategy, even before you make your first move: You need to pick a species and a background. These two choices together make up your character. In your games so far you will most likely have played some kind of melee-based character, that is, a heavily armored, weapon-swinging brute who slashes/bludgeons its bloody and gory path through all enemies. Well played, such a character can win a game for you, but beginners will have great difficulties keeping a melee-character alive for long. Following this walk-through, you will make different choices: Gargoyle will be your species, and earth elementalist will be your background. This means that instead of using weapons, most of the time you will kill enemies by casting earth-related spells.
The Gargoyle
The gargoyle comes with such a unique list of welcome abilities that it is probably the most survivable species in the whole game. It is therefore well suited for beginners. Among its features are immunity to poison, and resistance to electricity – both frequent causes of untimely death in the early game that you don’t have to worry about much as a gargoyle. Its one level of resistance to negative energy also becomes useful early on, as sources of draining may be encountered already on the first levels. Gargoyles develop permanent flight before it really matters, they don’t breathe and don’t rot, which removes other dangers entirely that kill many characters in the mid-game. Furthermore, a gargoyle is immune to petrification and resistant to torment, which are both very desirable characteristics. And finally, it comes with a huge boost to your armor, which makes it a lot more durable than most other caster characters.
All this comes along with quite impressive aptitudes. A gargoyle is very good at developing defensive skills, which increase its durability. On top of that it does not have difficulties with any weapons or with most kinds of magic. The spellcasting aptitude of -1 does not appear to be that awe-inspiring, but in fact very few species do better in that respect. This comes along with an excellent conjurations and an even better earth Magic aptitude, which is important for the character that we want to develop. On top of that, a gargoyle is reasonably intelligent and can learn to cast even the most difficult spells at a high power.
Crawl gives you nothing for free – if a species has some wonderful traits, it usually pays for this in some handicaps. The gargoyle has some of those, but they are totally out of proportion to its huge advantages. The biggest drawback is probably its low resilience; having 20% less HP means that in theory you die a lot earlier than others. In practice, however, your high armor and your many resistances make it significantly more difficult for your enemies to bite off a big chunk of your HP. This is particularly true in the early and mid-game, where you can shrug off most attacks. But there is absolutely nothing you can do in the late game against the damnation that some enemies hurl against you, and low HP is then a very serious problem. Another handicap is a special vulnerability towards some earth magic spells, which only becomes relevant in the late game. A final species-related drawback is that your stony nature prevents you from using the spell sublimation of blood, which some characters like to cast to restore their mana-pool. You also can't cast Statue Form, but that is because you already are a statue, and enjoy all the benefits of this spell, without doing anything about it, and without the speed penalty.
Earth Elementalist
You begin this game as an Earth elementalist, which is a pure casting background. This means that instead of relying on physical weapons, you will destroy your enemies by the use of powerful spells. This is a very different game-style to what you may have been used to so far; you will have to develop some new habits and have to watch some more stats to be successful. But if you do everything right, this is a very satisfying way of playing Crawl. Earth Magic spells are quite versatile, providing you with powerful offensive options, which throughout the game should give you what you need to survive most situations without breaking a sweat. Earth magic is a big strength of gargoyles, who can achieve high skill levels with very little investment of experience. Finally, the offensive spells of this school are very physical in nature, and cannot be resisted any better than the most powerful physical weapons can. No matter what resistances your opponents bring along (and some late-game bosses are frighteningly resistant to almost anything), none can withstand your destructive power.
Getting Started with Skills and Spells
You find yourself thrown into the same world as usual. All you have is a bread ration, 30 stones, a robe and your starting Book of Geomancy. Note that you have no weapon as of now. The stones are not meant for throwing, but you need them for the only spell you currently know. Before you do anything, however, you need to tweak your skills a little bit, so that you grow the most important of them, while ignoring all the others. To do that, type the m-key, and the skills menu will show up. You may not have looked at this menu before – if you don’t fiddle with this, the game will manage your skills automatically, but not necessarily in a way that is always best for you. Skills are trained whenever you kill an enemy and gain experience. This experience is then invested into your skills according to the settings of your skill screen. So you need to switch over to the manual mode, by hitting the /-key (slash). Your are now in full control of your skills training, and you should deactivate all training for all skills except spellcasting and earth magic, so that both skills receive 50% of all experience. Manual mode means that all selected skills receive the same amount of experience at all times. Highlighted skills receive the double amount (but for now you are not highlighting anything).
This is necessary because your early survival depends on having powerful spells to kill your enemies. What you have right now is just enough to kill one or two goblins, but soon you will encounter monsters that are not impressed by you blowing some grit into their faces. You need to develop some fire-power, and that fast. Right now you only know the Sandblast spell. You can have a look at it by typing z and then *, which opens up the spell menu. You see a (currently very short) list of your available spells. It shows you that Sandblast is assigned to your a-key, that it is a level-1 spell only using the earth school, and that it currently has a failure rate of 6%. All this requires some explanation. Spells in Crawl come in nine different levels. Level 1 is for beginners just as you are right now, and level 9 is the deep end of the pool which you will only get to towards the late game. Those level-9 spells have an obscene damage output, allowing you to kill many monsters with just one cast, and clearing the whole screen with just three or four casts, if things go well. But for now you are stuck with the bread-and-butter of your measly level-1 spell.
Each particular spell is tied to at least one, at most three different spell schools, which means that training the skills of these schools will improve your success rate and your spell power. Your current failure rate of 6% means that in six out of 100 attempts your spell will not work – it is your goal to get this number as low as possible, as a spell miscast not only depletes your mana pool for no return, but also may have dangerous side effects. 6% is not bad for beginners by any means – that you start out so low is the immediate benefit of your gargoyle’s great aptitude with earth magic, which made your earth skill jump right to above 3 to begin with.
You see the spell power when you type the !-key in the spell list view – the list then displays some additional stats about your spells that you did not see before. The spell power for your sandblast shows currently as ##...., with each # showing a step of available spell power, and each dot as a step of spell power so far not available for that spell. For sandblast, the maximal spell power would be ######, which would turn your currently modest source of enemy injuries into a veritable killer for most monsters. You are not there quite yet, but again your ##-power is more than what most characters get for their starting spells, giving you a huge advantage. The most potent spells have a maximal spell power of 10#, which even for very powerful casters is almost impossible to accomplish, and usually only for short time periods. Most likely, the gargoyle will not get that far with its earth spells. The spell power of your spells depends on your skills with the spell-schools involved, on your spellcasting skill, and on your intelligence. The same is true with your success-rate. Your level-1 spells should soon have a failure-rate of 1%, if you train the right skills and invest your stat upgrades into intelligence.
The screen now also shows your hunger-cost for your spell, which currently is #...... – it is possible that a spell causes no hunger whatsoever, when you have a sufficient spellcasting skill and/or sufficient intelligence. All spells of the same level cause the same hunger to you. One # means that for the sandblast you have a very small, even negligible hunger expense. When a spell has a full-blown ####### hunger cost, a successful cast will reduce your satiation status considerably, so that you may find yourself with the need to eat something after casting a spell a few times.
The final spell stat is its range. Your sandblast shows as @-->, which means that you can hit an opponent three tiles away, but not beyond that range. Spells come with very different ranges, and sometimes the range may increase with your spell power. The range of the sandblast spell does not depend on your spell power.
All this being said, it is now clear that your main priority is to train your spell skills, currently earth magic and spellcasting. The higher your skills here, the more powerful, easier to cast and less costly your spells become. All other skills need to wait for now.
A short look at your other stats: Your strength is at 11, your intelligence at 15, and your dexterity at 10. Strength and dexterity are at satisfactory levels for our purposes. Getting more would always be nice, but what you need more than anything else is intelligence, as this has a direct impact on your ability to cast spells with high power and low hunger cost. Every three experience levels you will be asked which stat to increase, and it needs to be intelligence every time. This in itself will get you to 24 INT at experience level 27, plus a few extras, because every fourth level you will get either a STR or INT increase, decided randomly. But really, a high-end caster can only feel comfortable if INT is at least in the low 30s, and a lot of that will have to come from enchanted equipment.
Your AC starts out with 4, which is two more than for most characters, another benefit of being a gargoyle. And it will grow.
Now get going!
Finding Vehumet
Wherever you are in a Crawl game, you always have a few goals to pursue. Your first real quest in the game is to become religious. For the character you want to develop, it is important that you become a worshiper of Vehumet, the god who provides you with tremendous benefits for your intended play style. Worshiping Vehumet means that casting destructive spells becomes a lot easier, which is just what you want. He also increases the range of your spells, and, more importantly, may increase your mana pool when you kill any opponent. His most visible blessing, however, is his gift of spells. Every once in a while he will grant you access to increasingly powerful destructive spells. Many of those won’t fit your skill set, and you will ignore them, but his final gift of three high-end spells is usually (unfortunately not always) geared towards your skills, so that you should have a deadly arsenal by the time Vehumet is done with his gifts. In spite of all these benefits, Vehumet is incredibly easy to please – just kill monsters (you are going to do this anyway), and your piety will go all the way up and stay there. There is no training of invocations with Vehumet, which means that you can invest your experience into more important skills.
So, you’ll want to find an altar of Vehumet as soon as possible, and your task is set. Well, in fact, you also want to find a weapon, any weapon, so you have something to kill an enemy with when your mana runs out, and to conserve stones. This is one of the peculiarities about sandblast: each time you cast it, you use up a stone from your inventory. When you run out of stones, you cannot cast the spell! Crawl will automatically pick up any stone you find and add it to your inventory. This will only change if you tell the software not do that (in the known-items screen, accessed by the \-key).
If you start exploring, you will soon meet your first opponent. Try to get him alone, and make him follow you into explored area. Currently, you will probably not survive more than three pursuing opponents at once. When an opponent is in range, typing z followed by a, your sandblast key, should automatically select him as a target. If there is more than one opponent, the spell will target the nearest opponent, but you can always adjust your targeting. One shot could suffice to kill a goblin, but you may have a miscast, or your shot misses, or is not quite damaging enough. You may need two or three shots, and sometimes even some help of your weapon to do the job; that’s why you try to avoid the attention of too many monsters at once. In the beginning you only have a mana pool of three MP, and each casting reduces that by the number of levels of the spell that you cast. So with three MP you can cast three sandblasts, and then you are left with your weapon, or even your bare fists if you have not found a weapon yet. Over time, your MP will recharge on its own, but this takes a while.
Whenever you cast sandblast, a stone from your inventory gets destroyed. Fortunately, stones are lying around in abundance, but not quite enough to use sandblasts for every action against every monster you meet. A good rule of thumb in the early game is to use sandblast on tough enemies, or for the first shot, until it is badly hurt. Whenever you encounter a weak enemy instead, or when a strong enemy is already close to death, you should try to bring it down with your weapon. But whenever the situation gets out of hand, and things become dangerous for you, you should not be stingy with your stones. Use them up to get you out of a tight spot. Sandblast is currently your strongest weapon!
All this being said, in this very early phase of the game you are most vulnerable. Whenever you have killed an opponent, restore all your HP and MP, and only then continue your exploration. If you get killed, however, it is not as frustrating as getting killed much later in the game. Just start over again, and you should be able to overcome this early-game crisis soon. And gargoyle’s many perks will help you to survive stuff that are killers for anybody else, like these mean adders that poison most budding characters to death. You just give them a mean smile before you smash their heads.
You will pick up potions and scrolls. Don’t try them yet! If you see rings, only try them if you have lots of scrolls, as some jewelery may get you killed if you can’t get it off your fingers. If you have picked up a cursed and badly enchanted weapon, try your scrolls (most numerous scrolls first) until you read a scroll of remove curse, then stop reading. If you don’t have such a scroll, then good luck. Many characters die early because they have bad equipment in their hands or on their fingers, and they don’t have the means to get rid of them. Be wary of shining and glowing items lying around – they can be the very stuff that makes you lose this game!
If you have played a melee character before, you will always have grabbed up the heaviest armor you could find, and even a shield. But leave any body armor where it is, because you can’t wear it as a caster, at least not yet. Body armor will dramatically increase your failure rate, easily up to 100%, and the same for shields. So stick to your robe for now (but have an eye open for enchanted robes, which are very desirable for casters). Gloves, helmets, boots and cloaks, however, do not affect your spellcasting, so you want to grab and wear any you can find. If you see a shield, put it into your inventory, but don’t wear it. Eventually you will want to have a shield, and they are often quite difficult to find.
Right at the beginning you should grab any weapon, as soon as you see one. Even without weapon skills, using a dagger or whip or spear will give you an edge when you have run out of MP. In the long run, you will want to use a weapon of the maces & flails category, so keep your eyes open for a good whip, mace or flail. One-handed weapons will do, but as long as you don’t use a shield, a dire flail is a great find. Enchanted weapons, of course, can be of great benefit, but do not pick up and try out any enchanted dagger or glaive you can find, as there are some dangers involved. A simply enchanted weapon (it is called “glowing” or “runed”, and comes with blue writing) may have the distortion brand, and this early in the game this means you are dead. Enchanted weapons may also be cursed and negatively enchanted, and you don’t want to be stuck for long with one of those. On the other hand, if you see a randart weapon (it comes with white writing, and more elaborate descriptions, such as “heavily runed”, “encrusted” or “steaming”), you should at least collect them and try them when you have enough scrolls of remove curse. They usually don’t have the distortion brand (that would be really bad luck), but they may come with great traits such as resistances or see invisible, which may make your game much easier in some situations. As long as you have not converted to Vehumet, and you have scrolls of remove curse available, you can try out each amulet you find. There are some bad ones out there, but as long as you can remove them, they should not do real harm.
Ok, after exploring some parts of level 1, you will have killed a few enemies, and you’ll have jumped to experience level 2. This will trigger some welcome changes. Your MP is now at 5, giving you two more shots with Sandblast. In the same way your HP counter has increased to 15, making you more resilient. Being on level 2 means that you can now learn a level 2 spell, Passwall. This is an escape spell, allowing you to disappear through a thin rock-wall. Although this spell has its uses, I usually don’t learn it, and I rarely find myself using it if I learn it, except at the very end of the game.
While exploring, you will see sets of down-stairs to the next level of the dungeon. There should be three of them on your level, and you must not go down any of those until you have explored the whole level 1. There are many good reasons for taking the levels one at a time, and for not even peeking down before you are done. But once you are done with level 1, there is nothing else you can do but go down.
Most likely you are still on experience level (XL) 2 before you make it to dungeon level 2, but if you are really lucky, you will have jumped to XL 3. This allows you to learn Stone Arrow. This is a great attack spell with a fixed range of @--->, and a max spell power of ######. Unfortunately you currently only have just one #, because it is a two-school spell, depending on the conjurations skill. But you will start learning this skill now (unfocused), so that you give 33% experience to spellcasting, earth magic and conjurations. Gargoyles have a good aptitude for conjurations, and almost all the attack spells you hope to learn later will make use of conjurations, so this is a very good investment of experience.
Casting Stone Arrow in your next fight is not advisable, though. It takes three MP to cast it, out of the six you currently have, and with a failure rate of 28% it is quite likely that you just waste these three MP. Just wait a little, and Stone Arrow will become your best friend. Right now, Sandblast is more powerful anyway.
Once down on dungeon level 2, you are likely to encounter much more dangerous opponents. The worst possible for you gargoyle is the orc priest, an orc with a green robe. He has a weapon against which you are not prepared, smiting. If you spend more than a few turns in his line of sight (LOS), you will probably die. If you see one, immediately retreat out of sight. If he has spotted you, he will follow you; position yourself so that he is within range of your sandblast when you see him again. If you are already low on HP, retreat to the next upstairs and heal up. You have to be very careful with these guys. Then again, they are not very durable; two good shots, at most three, and they are down, and they give you lots of experience. Unfortunately, they rarely show up alone. They may be supported by regular orcs, or by orc wizards, purple-robed orcs who can confuse you, turn themselves invisible, and hit you from afar with fire. As much as possible, you need to separate these groups and fight them one by one. Upstairs are a good way of doing this. Sometimes you see two or even more orc priests at once. This is very bad news, and you need to act extremely cautious. Don’t take any risks here. Maybe you avoid the area for a short while to return when you are stronger.
Other fearsome enemies showing up much too early are Sigmund, Pikel, Grinder or, if you manage to stumble into his quite recognizable cove, Crazy Yiuf. These are so-called uniques, dangerous enemies that can only show up once per game. If you can, avoid them for now (maybe you are lucky and they don’t wake up when you see them). Give their area a wide berth, and come back for them when you are slightly stronger. When you are at XL 7 or 8, they won’t stand a chance against you (but then there are other uniques waiting for you on deeper levels).
Once you hit XL 4, you will be ready to learn Petrify, but don’t bother. You would not find yourself using this spell very often. Killing an enemy fast always beats incapacitating him for a while. But at this point, a look at your spell list shows that your spells are improving nicely. Sandblast is now at ###, and hunger-free. And with your 9 MP you can now risk to cast Stone Arrow at least once per fight, as it comes with a more manageable failure rate.
From level 2 downwards, you will encounter upstairs to already explored levels. Those which lead to an area on the upper floor that you have not seen yet are marked by a star, so you should check them out, just to make sure that you really have explored that area already. Occasionally the dungeon has disconnected areas, or areas that you can only access from a lower level. Particularly altars or even the entrance to the Temple may be hidden in this way. So, before moving on to the next level, always make sure that you have seen all three upstairs on the current level. If you can only see two on the map, this means that there must be another area of this level that you can only access through an unused downstairs from the previous level. Go back and find these stairs.
Whenever you go down a set of stairs to the next level for a first time, you may be greeted with an announcement for a timed portal, usually to the Sewer or to the Ossuary. These are extra levels on which you may gain more experience and find some treasure. You’ll want to find these portals before they time out, and now would be a good time to start reading your scrolls. One of them may be a scroll of magic mapping, and that would show you exactly where the portal can be found. So, stay on the stairs and start reading. Quite likely one of the scrolls you read will be a scroll of teleportation. If so, then go up the stairs immediately, so that you don’t teleport into an unexplored area. Most other scrolls should be harmless or even beneficial. If you happen to read a scroll of torment (that is about the worst that can happen), just retreat upstairs again to heal up. If you also happen to find the entrance to the Temple this way, first go there to become a follower of Vehumet, and then go to the portal. You’ll want the kills you make there already count towards your piety with Vehumet. If you really read a scroll of magic mapping at the beginning of a level, you will have plenty of time to find a timed portal.
Those early portals (Sewer and Ossuary) are usually no problem, with the single exception of one Ossuary layout where you find yourself immediately surrounded by a large circle of zombies and mummies. If you see that, get out of there at once! There doesn’t seem to be a way to safely beat this level and harvest its treasures.
If reading through the scrolls gets you a scroll of identify, use it on the potions of which you have the biggest stack. If you’re lucky, it will be a potion of heal wounds, which you want to identify as soon as possible.
Blindly quaffing potions is an entirely different matter – it is a lot more risky than reading unidentified scrolls. You may get mutated badly, or receive some pretty bad status changes. In the best case you may waste an awesome potion, such as a potion of haste for nothing, and you won’t find many more of those later on when you need them. Therefore, try not to drink unidentified potions unless in the most dire circumstances. As said above, you’ll want to identify potions of heal wounds soon, so that they can get you out of trouble, and it is perfectly fine to spend a few scrolls of identification on that. If you are lucky, you may witness a monster healing itself by using a potion, which will identify it for you. Once you have identified potions of heal wounds, you don’t need to identify any others for quite some time, so you can just ignore them.
You may find an altar of Vehumet anywhere beginning from dungeon level 2. As soon as you see it, convert to him – there is no reason whatsoever to hold back. Your best chance to find an altar is the Temple, which is always located between dungeons 4-7. But quite often the temple does not contain the altar you are looking for. At the latest, Vehumet’s altar should show up on level 9. In any case, as soon as you can, start worshiping Vehumet.
Clearing the Upper Dungeons
No matter at what point you become a follower of Vehumet, one task assigned to you is to clear the dungeon all the way down to the place where you find the staircase to the Lair of Beasts. This can happen as early as on dungeon level 8, and as late as on dungeon level 11. But while you are looking for it, here is some more advice on things going on during that early phase of the game.
Once you follow Vehumet, you need to change your behavior with amulets. An unidentified specimen could be an amulet of faith, and you don’t want to have those. In theory, they are rather nice, of course, getting you to a high piety quite soon, but the moment you remove them (and you’ll want to soon enough), you lose a good chunk of your piety, and therefore it is just better if you never wear it. Piety with Vehumet rises pretty fast even unaided by said amulet. If he starts his spell gifts while you are not ready for them, this amulet may actually be contra-productive. From now on you need to identify each amulet before you wear it.
Around XL 6 it is about time to learn the two most difficult spells of the starting spell book: The first is Lee's Rapid Deconstruction, in short LRD. As a level-5 spell, this comes quite expensive, as you have only about 16 MP to play with. The failure rate is still high, and the hunger cost almost prohibitive, but over time you are going to love this spell, and use it all the time. It makes you look at your environment with different eyes, always studying the positioning and the material of the dungeon walls. Basically, it allows you to use any dungeon feature or even enemy made of rock, stone, metal, ice, bone or crystal to significantly weaken or even destroy it, and create a blast area around it. With increasing spell power, this spell has an amazing destructive potential, but you need to learn how to apply it for its best benefit. Obviously, it works best if you have a group of enemies inside the blast area of an appropriate dungeon feature. Of course you should not be inside that blast radius yourself. To make things complicated, some materials, like rock walls, have a variable blast area, so you don’t always know for sure what gets hit and what doesn’t. But LRD is your first area of effect spell, capable of hurting or even killing a good number of enemies at the same time, if you use it wisely. Unfortunately, some times you will find yourself in a situation where you cannot apply it at all, and then you need to fall back to your other attack spells. LRD can also be used to punch holes into rock walls (it takes some attempts, usually), and with higher spell power even into stone and metal walls. No need to carry around a wand of digging just for this purpose.
The second spell is Borgnjor's Vile Clutch (BVC), which is a two-school spell, also benefiting from training necromancy. For this reason its success rate will be much lower than LRD, but eventually you will get it down even without training necromancy. It is quite a powerful spell, dealing direct damage to all monsters within a 3x3 grid, while fixing them in place.
While you are on XL 7, you should constantly check your spell list. When Sandblast shows up with a spell power of ####, this is a good time to branch out with your skill training. Up till now, you have only trained three skills: spellcasting, earth magic and conjurations. Now that your spell power for your attack spells has reached decent levels, it is time to do something about your defensive skills, and other critical skills you need. Go to your skills menu (m-key), and select the fighting, maces & flails, armor, dodging and evocations skills. Now all selected skills should get 12% experience. If you have a shield or a buckler in your inventory, you may also decide to start training the shields skill, without actually wearing the shield yet. This would reduce the experience for each skill to 11%. Why these skills?
The fighting skill is a critical skill for you. It increases the damage output of your melee weapon, but since you don’t want to use it a lot, you probably don’t care too much. But higher skills in fighting also increase your hit points, and since you are a rather frail character, this matters a lot to you. As already said, later on in the game you encounter damnation, against which there is absolutely no resistance or protection. Therefore, the higher your HP, the more likely you are to kill the damnation-dealing enemy before he kills you. Consequentially, you will never switch this skill off again, until you finish the game or master the skill at level 27.
Maces & Flails are your weapon of choice. Of course you will kill most of your enemies through magic, but this may not be the best solution at all times, and therefore you still need to become proficient with a real weapon. You have an average aptitude for maces & flails, and there are some very good one-handed weapons of this category, including the eveningstar and the demon whip – both of which are rather difficult to find, so you will mostly work with a flail or a morningstar until you find something better. Training this skill does not increase much the damage output for each hit, but it dramatically increases the frequency of hits you can land in any given time. The eveningstar has a base damage output of 15, and without any skill you can land a hit each 1.5 rounds. Each two points in weapons skill, however, give you a tenth of a round off that delay before the next hit, so that with a skill of two you can hit each 1.4 rounds and so on. With a skill of 16 you have gotten this delay down to 0.7 rounds, and that is as far as it gets for the eveningstar, meaning that in the original 1.5 rounds you can apply more than double damage than without skills training. Maces & Flails has a crosstraining effect with staves, for which you also have an average aptitude; later in the game you may want to decide to make a staff your main weapon. If so, you will already have some significant starting skill from your maces & flails training.
Armor skill you could probably do without, if you are confident that you will always only have a robe as body armor. But since, as a gargoyle, you have this amazing aptitude with the armor skill, it would be a waste not to use it somewhat. Just training this up to 5 or 6 allows you to wear light dragon armor, such as a troll leather armour or the faerie dragon armour, which will give you excellent protection and maybe some welcome resistances. Without armor skill, wearing this kind of armor would make spellcasting significantly more difficult.
The dodging skill, in conjunction with your rather mediocre dexterity, determines how much you can avoid damage by getting out of the way of a blow or of a projectile. As a moving rock, your aptitude for dodging is terrible, unfortunately, but it is still wise to train this skill up as high as possible. It just takes you much longer to reap its benefits.
Many players would dispute the need for training the shields skill, as it is quite costly in experience, and there is value to having two free hands for being able to wield more powerful weapons. But shields have more benefits than just blocking projectiles and hits. Some shields come enchanted with valuable resistances, sometimes giving even stat bonuses, and if you want to wear these as a caster, you need to invest at least enough experience to get you to a shields skill of four (which you will reach very fast). This allows you to cast with a buckler without penalties to your failure rate. For a normal shield you need a skill of 15, and for a large shield it takes 25 to cast penalty-free. Quite a heavy investment, but once you have it, you have an amazing protection against all physical attacks and most projectiles. A shield won’t help you a bit against damnation, though. A normal shield and even a large shield are probably out of reach for you in this 3-rune victory.
The evocations skill is also very important to you. The higher your skill here, the more effective you are using wands and other evocable items. These may give you more ranged options to apply damage when your MP runs out. The evocations skill also helps you when you use a staff of energy when channeling to replenish your MP, and makes the use of a crystal ball of energy much safer. Finally, as already hinted above, you may later decide to use a magical staff as your main weapon. The staff that comes to mind is the staff of earth, which has an obscene damage output dwarfing most other weapons if it is used with high earth and evocations skills. And you will want to wield that staff anyway, as it increases the spell power of your earth spells. So keep training evocations!
Many players object to the skill-training style advocated here, claiming that increasing eight or nine skills simultaneously spreads the experience too thin. But these skills (except maybe for armor and shields) you will need to develop anyway, and over the total course of the game it makes no difference whatsoever whether you train these skills sequentially or simultaneously. Psychologically it feels good to observe a single active skill gaining in large strides, but it comes at the price that your other skills don’t increase at all. The skill strategy proposed here will grow your needed skills slowly but steadily, with the result that you have all you need as the game progresses, without having to fiddle with your skills screen too much.
Other skills are deliberately not on the training list. For you there is no point training any ranged weapons, including throwing. Stealth also is almost pointless for you. The moment you unleash your first LRD on a level, all its inhabitants will have a pretty good idea of where you are, no matter how stealthy you are. Earth magic is mostly noisy and does not go well together with a sneaky approach. Unarmed combat is also something you don’t need to worry about. Of course you could study other spell schools, such as the transmutations school, to unlock the Statue Form spell. But in spite of what was said in the previous paragraph, you want to keep the number of trained skills as low as possible, so that what you train receives as much experience as possible. Once a skill receives less than 10% of the experience, it will grow very slow. Your power and your survival depend on having the right skills trained as high as possible.
Once the failure rate of your Stone Arrow goes below 5%, and your MP pool is above 20, you should make this spell your main attack option. Only when you get low on MP should you resort to Sandblasts, which will then never run out of stones.
A very short time after converting to Vehumet, after killing a bunch of enemies, your new deity will be happy enough with you to shower his blessings on you. You will get a message that Vehumet grants you access to a spell that is not part of any book you have found so far, and a star will show up in your piety counter. At maximum piety you will have six stars, but even this single star begins something that arguably is Vehumet’s greatest gift: MP restoration on killing enemies. Right now it does not look like much, because at low piety it happens only rarely. But when your piety goes up, this god-given ability will overcome the bane of all casters in Crawl: Once you have cast a number of spells, your MP goes to 0, and there may still be some enemies that need killing. Your MP of course regenerates itself over time, but quite often you can’t spare that time. At highest piety Vehumet will grant you some extra MP on killing almost all enemies. By that time you will have spells that can kill many enemies at once (such as LRD which we have already learned), so that it may be a long time before you run out of MP.
Vehumet’s gift of spells is also nothing to sneeze at. But you need to decide carefully whether you really want to learn them or not. You are basically required to decide on a spell strategy early on, and act on that. For this walk-through we assume that you will want to learn attack spells not only from the earth magic school, but also from the fire magic school. So if Vehumet offers you a spell belonging to any of these schools, grab it up. If it is a spell from a different school, ignore it, because you cannot learn an unlimited amount of spells. Your status screen (right-click your mouse on the character) and also the spell memorization menu (M-key) will tell you how many spell levels you have currently left to learn new spells. If you want to learn a level-3 spell, but you have only two levels left, you need to wait until the new levels get unlocked (through increases in XL or the spellcasting skill). Alternatively, you need to forget an already learned spell with a scroll of amnesia. It is therefore a good idea to keep training your spellcasting skill at least until Vehumet has given you his final batch of three spell gifts - that should always give you sufficient spell slots for Vehumet's more interesting gifts.
Of course you may find spells in spell books, not only from Vehumet. Here are a few spells that you should consider learning when you find them:
Conjure Flame – a level 3 fire and conjurations spell which creates a stationary column of fire on a single tile, affectionately called “Gargoyle’s barbecue” by your enemies. Most of them will not walk into it, which makes it a nice way of keeping melee fighters out of their range in a one-tile corridor. Some animals and undead monsters happily walk into the flame to get at you, and you can watch with glee while they get burned to a crisp.
Sticky Flame is a wonderful level 4 fire and conjurations spell that places a very damaging source of fire on an adjacent enemy. This will keep burning for a few rounds, killing the monster over time, while you are running away from it, or apply further damage by different means. If you manage to place this on an invisible enemy, it will make it visible for the time of its effect.
Bolt of Magma – this level 5 fire, earth and conjurations spell shoots a projectile with irresistible force through whole rows of enemies. Line your opponents up in a corridor, and this spell makes short shrift of them. Much more powerful than Stone Arrow. You should be able to cast this very soon.
Iron Shot is a level 6 earth and conjurations spell that works similar to Stone Arrow. It only hits one enemy at a time, but with deadly force. One shot is often enough to kill the worst enemies you encounter at any given time. If you get access to it, learn it at all costs. If you can’t find Magma Bolt or Iron Shot by the time you complete the Lair, it will be very difficult to survive much longer.
Fireball is a level 5 fire and conjurations area-of-effect spell, frying a 3x3 square and all that stands on it. Not helpful against fire resistant monsters, but otherwise very potent.
Bolt of Fire – this level 6 fire and conjurations spell shoots a powerful heat projectile through rows of enemies, with a better range than Magma Bolt, but not useful against fire-resistant monsters.
Ring of Flames is not a weapon as such, but a level 7 fire and charms spell that creates the effect of Conjure flame on all eight tiles around you. Not only that, it greatly increases your resistance to heat and fire, and also boosts the spell power of subsequent fire spells, at the price that it dramatically reduces your resistance to cold effects. But this doesn’t matter that much, as the RoF actually keeps most cold actions away from you.
Ignition is an extremely costly (level 8), but effective upgrade to Fireball, applying its effect on all enemies in sight. When you have the power to cast it, a target-rich environment turns into a furnace, killing anything that is not fire resistant.
Most of Vehumet’s spell gifts are only available to learn until he offers you his next gift. This time window can be rather small. Therefore, if Vehumet offers you other spells than the ones mentioned above, ignore them. They will not add significantly to what you have in this arsenal, and you don’t want to get into the situation that Vehumet offers you Iron Shot, but you don’t have enough spell levels, because you wanted to try what Force Lance or Bolt of Cold do. You want to be ready for the amazing stuff. Generally, ignore all spells dealing with ice, air or poison. Not that they are bad, but they don’t fit your build right now.
Once you have learned a fire-spell, start training fire magic right away. For some of the spells you want to use later you need to have very high levels here, so there is no time to lose.
When you reach XL 10 or 11, LRD has become an affordable spell for you, and you can look for opportunities to use it. It has a much further range than your other earth spells, and it can take care of those orc priests which otherwise snipe at you from positions out of range. Get them!
Vehumet’s second star does not give you any new abilities, but his third star reduces the failure rate of all your destructive spells dramatically. LRD should end up below 5% failure rate now, and you have turned into a killing machine! When Vehumet decides to grant you his fourth star, all your spells have their range increased by one more tile, allowing you to hit approaching enemies a turn earlier.
If you can’t find the Lair before hitting dungeon level 10 or 11, you may encounter a very dangerous enemy, the Unseen horror. If you don’t have a source of see invisible, the first notion you’ll have of this feller is a message that you take damage from something. If you are moving around using your arrow keys, you may not even see this for quite a while until you have already taken significant damage. This enemy is extremely fast and may start and end its turn away from you, while hitting you in between. The unseen horror can whittle you down in a few turns, but you can survive and kill it if you don’t panic. Obviously, if you have a source of see invisible, maybe on an enchanted weapon or a ring, put it on, and the crisis is over. Unseen horrors quickly lose their horror once they are no longer unseen. If you can’t see invisible, move into a corridor, so that you have a better idea from which side your enemy is attacking, and then hit it blindly. LRD is a great tool to hit a larger area where it may be. If you have Sticky Flame, you can try to attach it to the Unseen Horror, and all is well. If possible, have some up-stairs within reach, so that you can heal up in a safe area. If things go badly, teleport away.
Also, before you find the Lair, your inventory may fill up, so that you cannot pick up any new items. If that happens, go to the Temple to drop some items that you won’t need anytime soon, like unidentified potions, or potions of mutation, or wands that you have twice, etc. In the Lair there will be a place where you can establish a secure cache, but maybe you need to do this earlier, and the Temple is always safe.
The Lair
Once you have found the access stairs to the Lair, clear the level around it. You may find the entrance to the Orcish Mines on the same level, or even on an earlier level, but don’t go in there right now – for various reasons it is better to tackle the Lair first. Going down the stairs into the Lair, you will be in an environment that looks significantly different to what you have seen in the dungeon.
Don’t continue exploring the Dungeon before you have tackled the Lair – you’ll need the experience you get here to be strong enough for what faces you further down. Also the Lair provides access to some of the places you need to visit to win this game.
You will also encounter a very different set of monsters. Except for a few uniques (some of them very dangerous), all monsters in the Lair are animals. Most of them are very strong, and they can kill you easily if you don’t handle them well. The following list contains monsters you need to be particularly careful with.
Komodo dragons are solitary animals with a very damaging bite that easily chews through your AC. Finish them off as soon as possible, because you can’t take much of their abuse.
Yaks – these creatures are strong and have a dangerous bite. One on its own is not dangerous, but they come in large packs, and when they manage to surround you, they get your HP down in no time at all. Try to get them into a corridor, or take them upstairs in smaller numbers. High AC helps.
Hydras – even a single hydra may be bad news, when encountered in a bad moment. They are fast and hit with many heads at once. Bladed weapons remove heads, but for each head lost they develop two more. As a caster with earth magic you won’t have that problem. Try to isolate them, and hit them with all you have from as far away as possible. High AC helps. Sandblast at full power is surprisingly strong against hydras.
Blink frogs – they hit much harder than the bullfrogs you have seen earlier, they are more difficult to hit, and they come in large packs. When you see one, make him follow you and retreat. You don’t want to face all of them at once. If you have Sticky Flame, use it, as it kills the hopper even a few turns after it bounced away.
Elephants are like yaks, but even more dangerous, and with more HP. Try to isolate individuals, and never take on the whole pack. Stairs are your friend. Unfortunately, an elephant standing right next to you may trample you, which pushes you off the ground you are standing on, and it will also push you off the stairs you had just decided to use. If you have a wall at your back, this will not happen.
Death yaks – probably the most dangerous animal that you are guaranteed to encounter (in large groups!) somewhere in the Lair, but usually only on the lower levels. They are very hard to kill, and hit extremely hard. Don’t let them surround you, and separate individuals. Even a single death yak is a formidable opponent and should not be taken lightly.
Torpor snails are huge and slow snails, not very difficult to kill. But while you are in LOS, they will slow you down considerably, and that may be very bad news when you are pursued by a pack of death yaks or a hydra. Therefore prioritize torpor snails before killing any other animals. Once the snail is dead, your speed is normal again.
There are lots of other monsters that most players find very dangerous, but for a gargoyle with already well developed AC most of them are rather harmless: basilisks and catoblepas’ can’t petrify you like they do with others, spiny frogs and black mambas can’t poison you, and the electric eel won’t shock you too much. It’s great to be a gargoyle, and the Lair is generally a good place for you.
Fighting all these pests, don’t forget that you have Sandblast, probably at ##### or even ###### power. By now you may also have collected hundreds of stones, and against unarmored enemies, like most of what you find in the Lair, this is a very effective single target spell. Not much later after the Lair, it won’t do you much good any more, so use the spell here a lot. You won’t be able to kill enemies with level 1 spells much longer.
For a long time, Crawl players have used the second level of the Lair as a place to create a cache of items that you don't want to carry around with you all the time. The reasons for this have now disappeared, but tradition might suggest this as a good place to do so anyway. If you choose to do it here, don’t drop all items on the same spot, but lay them out according to category, like all food items in one corner, scrolls in another, etc. Good organization will help you to find stuff when you need it. Drop all but one kind of food in the cache, including all bread and meat rations. Most likely you have a big stack of fruit, and this you should carry around with you, as an emergency snack when you haven’t found a body to butcher in a while. Drop almost all wands here. Just carry with you the strong wands mentioned above. All other wands are either obsolete by now, or even if they still have a potential use, you won’t find yourself using them a lot. Drop all your books here. You’ll come here if you want to learn spells. Drop every scroll of amnesia, scroll of enchant weapon, scroll of enchant armor. Again, you will come here when you want to enchant your equipment. Drop all unknown potions, just carry potions of heal wounds and potions of curing with you. Later on you will identify more potions, and some of them are worth carrying around all the time, but for now they just clutter up your inventory. And you can drop some jewelry and armor and weapons that you think you won’t need in a while. From now on, whenever you are short on inventory slots, come here to lighten your load.
Talking about all your equipment, here are a few tips on what is worth wearing. In terms of amulets, your best find for now would be the amulet of the gourmand, as it allows you to stuff yourself with lots of chunks from defeated enemies, which really helps when you need to cast some expensive spells. Your best ring find would be a ring of see invisible; you don’t need to wear it all the time, but it comes in handy when you are under attack by invisible monsters. You can get the same effect through some head-gear, where it would be more permanent. Otherwise you should look out for (and wear) at least one ring of protection from magic, as your inherent magic protection is very low. The higher your magic protection, the better you can shrug off attempts to confuse or smite you, aside from many other hexes that monsters throw at you. Beyond that, rings of resistance against cold or fire are always good to have around, and they are quickly swapped when your circumstances change. If you happen to find a robe of the Archmagi, stop all training of armor at once. You have then just found the body armor you’ll want to wear for the rest of the game. Not much physical protection, but it boosts the spell-power of your spells considerably, making you much more dangerous early on. When you can kill anything on your first shot, you can afford going easy on your defenses.
In the Lair you may find timed portals to the Volcano, the Ice Cave or the Labyrinth. These places can be quite tricky, and if you don’t have some resistances against cold or fire, you probably should let them pass if you don’t know them very well. But they also come with good loot. You don’t need any resistances for the Labyrinth, and your earth magic should be enough for the opposition in there (usually just a strong minotaur), but you should bring enough food for quite a long time.
Further down the Lair you will find entrances to either the Swamp or the Shoals, then again for either the Snake Pit or the Spider's Nest. You should ignore each of these for now – the opposition in any of them is quite strong. You will come back for these places somewhat later. Near the bottom of the Lair you also find the entrance to the Slime Pits, which is a truly horrible place, best left alone. You won’t need to go there at all for your first victory.
Battling through the Lair, you will gain lots of experience, and before you finish the last, sixth, level of the Lair, you should reach XL 14. This is a milestone level for you gargoyle, as you now have strong enough wings to fly permanently. Start flying with the abilities key (a), and never stop unless you meet one of the following monsters: Gastronok, wind drakes, titans and spriggan air mages have airstrike, a spell which is more damaging to you when you fly. Otherwise flight gives you a huge advantage throughout the game.
While going through the Lair, have a look at your skills constantly. When your armor skill reaches 6, switch it off. You won’t need more, as long as you stick to leather armors or very light dragon armors. And you shouldn’t take anything heavier. If you have found a buckler already and trained the shields skill, switch it off at 4. As much of your experience as possible needs to be invested in your magical skills.
Also have a look at your spells once in a while. Usually, while battling the Lair, you will reach the point where your Sandblast spell power, and even the Stone Arrow spell power show up as ######. This is good news and bad news at the same time. It is good news that now these spells hit your opponents with their full potential, and that makes them quite deadly. Not so good is that there is now nothing you can do to improve these spells, and you will find that it still takes quite a lot of shots to bring down an elephant or a death yak. Not very long after this you will find much more dangerous opponents, and you’ll need something more potent to make them keel over. If you have found Magma Bolt or Iron Shot by now, add them to your inventory. If you have seen a shop with a book containing one of these spells, go and buy this book.
The final level of the Lair is significantly more difficult than the other five levels. It always contains an area with a frightening concentration of high-end monsters, such as death yaks, or dire elephants, particularly robust species of elephants, or dragons, or similarly challenging opponents. If you tread carefully, you should be okay. Again the secret to success is to proceed slowly and to isolate individual opponents.
Subjugating the Orcs
Once you are done in the Lair, proceed to your stash on Lair 2, clean up your inventory and make it to the entrance of the Orcish Mines. You may not have found it yet, which means that you will first have to clear another Dungeon level or two.
If you have never made it to the Mines so far, just like the Lair this place has its own distinctive look, very different from the dungeon. You will see an awful lot of enemies, but most of them die like flies around you. All you need to do is let a horde of orcs come to you, take them upstairs and smash them to pulp with your weapon. No need to waste any MP on these low-level orcs. Orc wizards (purple) are also no problem for you any more, except that they still like to turn invisible. But orc priests (green) continue to demand a lot of respect, and you should hit them as soon as possible. Maybe they stand near rock walls, and then LRD easily takes care of them. Orc warriors are usually well armored, and even more so orc knights. Hit them hard with your best magic, and you’ll be fine.
Up till now you will have marveled about how fast your experience grows in this game. All those Lair-monsters made you jump from one XL to another, so that you probably left the Lair with XL 14 or even 15. Here with the orcs now everything seems to slow down to a crawl. No matter how many monsters you kill, you just don’t seem to make any progress on your experience counter. This tells you that by now you have completely outclassed orcs and play in a different league. But this impression is deceptive, as these two levels contain foes which make dying in the Orcish Mines as easy as anywhere else.
Orc warlord – there should be at least one of these orc bosses in the mines, usually on the second level. They are heavily armored and hit hard. If you still have nothing beyond your Stone Arrow, you will find it very difficult to make him roll over. He also has powerful ranged options.
Orc high priests with their blue robes are found in small numbers on the lower floor, but you may encounter them occasionally upstairs. They are a lot more dangerous than regular priests, particularly because they tend to call demons who can harass you to death. Whenever you see them, they need to be your very first priority. LRD kills them fast, if they position themselves favorably. Killing the orc high priest also makes all of his demons disappear in a puff of smoke.
Orc sorcerers can ruin your day as any orc high priest can. They also call demons, and they may resurrect all those slain enemies around you, so that you have to fight them again. On top of that, they may send bolts of fire or draining your way, and both may hurt you a lot. Killing the sorcerer will not make his undead minions disappear, so be prepared for a prolonged fight afterwards.
Various elfs. The entrance to the Elven Halls is found on Orc 2, and in case you’d miss it, the game places some inhabitants around this entrance. Some of them may be quite dangerous casters. Elfs are usually easy to kill, but if they get their chance, they can damage you badly.
Sonja is a unique which poisons and incapacitates non-poison-resistant players with a blowgun. No problem for you, but once she gets close, she may hit you with a dagger of distortion. Don’t let that happen, as it may get you thrown into the Abyss, and you are not ready for this.
Ogre mages also have the ability to banish you into the Abyss, so here is another monster that you need to prioritize. They should not show up on level 1.
Saint Roka is very bad news if you encounter him already now. Best to turn around and go fight in some other places for a long time. Most likely you are not quite ready yet to kill him, and if you won’t kill him, he will kill you. Don’t even try to fight him if you don’t have at least Iron Shot at your disposal, and at least 30 MP, hopefully more. Saint Roka comes along with a large band of minor, but still rather strong, orcs. There is no hope to defeat the boss as long as all those are still hopping around. If you are lucky, you can isolate them from Roka one by one, so that in the end you only have to face him alone. No need to expect Roka before level 2.
The first level of the mines usually consist of two or three disconnected areas; the other areas you can only reach by first going to the lower level, or by some foolhardy teleporting. If you have plenty of wands of digging, you can also shoot wastefully in all directions and see if it does not open a way to another unexplored area. This becomes a lot less wasteful by reading a scroll of magic mapping, but this is wasteful in itself. When you enter the lower level, move very carefully, exploring in circles around the upstairs. Don’t use other up-stairs before you are sure that the area you leave behind downstairs is clear; it does not do to escape a fight on level 1 to find yourself surrounded by some bullies of the level-2 crowd of the mines.
Just like in the Lair, you may have announcements about the presence of a Volcano or Ice Cave when entering a new area here. Find it and clear it – by now you should be ready. Otherwise, there might also be a timed entrance to the Bailey, a level with lots of armed monsters, usually goblins, kobolds, orcs or gnolls. Most of them you can defeat easily, but there will always be some high-end bosses to kill, so you might find yourself forced to retreat from the area before you have reaped the loot. This loot can be quite desirable, such as a potion of experience, which is about the best shake you can quaff in this game.
Except for what your slain enemies let fall to the floor in their death rattle, there is absolutely no loot to be found in the Mines. The appeal of this place lies in the abundance of gold lying around everywhere. If you have not squandered away a good part of it already in some shop, by the end of fighting in the Mines you should have at least 2000 gold pieces, if not more. And then you’ll have four guaranteed shops on level 2 where you can spend it all, and quite often more shops on the other level. But you should also have a look at what your enemies leave behind for you. Enchanted robes or leather armors, and maybe a well-enchanted morningstar can definitely improve your equipment.
The shops on level 2 are well defended, though. Quite often all four shops are found in a vault area. High concentrations of the strongest enemies you can find in the Mines make it necessary to advance slowly, and to always retreat when you have attracted the attention of more than two or three enemies. Always know where the next stairs are, and make sure that you know what to expect up those stairs.
Once you have conquered level 2, have your eyes open for a bookshop. If you are lucky, you can buy a Book of Annihilations here, which would give you access to two of the three spells you want to learn later on: Lehudib's Crystal Spear and Fire Storm. The third spell, Shatter, can be found in the Book of Earth and the Book of the Tempests. Don’t buy any of these books yet, when you see them, as you won’t be ready for these spells for quite a while. Hopefully Vehumet will grant you what you need anyway, or you may find these books lying around somewhere. But it is always good to know that you can buy the spell you need, if it eludes you otherwise.
If you find a potions shop, go in there and see what potions they sell that you don’t know. Particularly bad potions, like a potion of degeneration, will be on offer for very little money – a good way of identifying these without wasting a scroll of identification.
First Visit to the Elven Halls
As already mentioned, the entrance to the Elven Halls is conveniently located on level 2 of the Mines. It is recommended that you visit this place somewhat later, but if you feel brave and still have a few inventory slots free, you might pop in for a visit right away. If you don't have three stars of magic resistance, it is indeed better to wait a bit longer to come here. In fact, you don't have to come here at all to win the game. The Elven Halls are a lot more challenging than the Orcish Mines, and for now you will only visit the first two of the three levels. Here there is lots of loot to be found, hopefully some books, or good jewelry. But you need to fight for almost every step of the way. Do it slowly and systematically, so that you always have a clear path to the way out of here.
Elves come in lots of varieties. Almost all use some kind of spell, at least to boost themselves. Some are very proficient with a bow, others are melee fighters, but quite a few are pure casters (blue-grey robes). And a few bosses already start slinging damnation at you (red or blue robes). Kill them quickly! That is the good news about all these elves: They can’t take a lot, and since most of the layout here consists of narrow corridors and small rooms, LRD will take care of most situations for you. Killing an elf gives considerable experience, and also Vehumet restores a lot of MP for killing them.
There is a reason not to enter the Elven Halls right after clearing the Mines: Occasionally you’ll find a timed portal in the Halls, which goes down to a Wizard Laboratory. These are very challenging places, where you may find very exciting treasures after surviving insane dangers. Generally, you have a significantly better chance making it through them if you take them on with much more experience under your belt. For this walk-through, since your main goal is to win your first game, let’s assume that you are not going to try the lab, if you find it. You may have a peek, but don’t stroll too far away from the exit – or you may find your way out blocked.
Another feature that is always a part of the second level of the Halls is the Hall of Blades. You know that you are near when you see sealed doors defended by self-propelled weapons. By all means, clear the rest of the level first. Even then, only walk in if you have a better spell than your Stone Arrow, such as Magma Bolt or Iron Shot. If you do, however, you are better prepared than most, because these floating weapons are resistant against most elemental damage. Still, you need to be very careful. All these weapons are somehow branded, they are extremely fast, hard to hit, and tend to surround you. An executioner's axe of flaming will chop you to smoking pieces if you don’t kill it first. Some of the weapons may also drain all your skills out of you. On top of that, there are countless elves running around in that place, adding to the weapons’ damage. Again your tactics is to go in until you see an enemy, and then lure him back towards safer places to finish him off. The rewards of this place are the weapons you defeat – they are all yours to grab, and that may be a nice place to find an eveningstar, probably the best weapon you can find in this game for your build.
Other things to look out for in the Elven Halls are bucklers. You should find at least a few, and hopefully a nicely enchanted specimen among them.
Some of the elves have the ability to banish you into the Abyss. Of course, this could happen sooner to you, but going through the Halls, there is quite some likelihood that you involuntarily find yourself in that dreadful place. The later this happens, the better your chances to come out alive. For an early-game character the Abyss usually means that the game is over, if you don’t happen to be thrown right next to a very rare exit. But by now you should be strong enough to survive for quite a while, maybe even long enough to fight your way to an exit. For this it is important not to panic. The Abyss consists of five levels, each level increasingly more horrible than the previous. So you’ll want to stay on the lowest level. If you kill enough monsters, an exit will eventually spawn. Sometimes you may need to heal up in an unseen corner, and that is okay. Most monsters will see you, and that means that you will have to fight them. LRD may be your best bet, but it has the bad side effect of attracting more monsters. Soon you will find yourself hopelessly surrounded and low on health, so it is time to teleport away. This takes longer than elsewhere in the game, so plan for that delay. Hopefully you have lots of potions of heal wounds. A potion of ambrosia would be a boon, but you are not likely to have one yet. These things can keep you alive long enough until you find an exit. If you see one, go there without delay, no matter what treasures are around you – the Abyss may teleport you away without warning. Once you have made it out, kill the monster that banished you. For a while you are immune against banishing; that should be long enough to eliminate that danger. BTW, there is a rune to be found in the Abyss, from level 3 on downwards, but right now you would not survive looking for it, and by no means you need to have it to win this game. For the rest of this walk-through we will pretend that the Abyss just does not exist. That’s better.
For now ignore level 3 of the Elven Halls. You’ll come back later for that.
The Side-Branches of the Lair
Having cleared the Lair, the Orcs and most of the Elves, you will not proceed any further down the dungeon for now, but return to the Lair. Clean up your inventory at your stash in level 2, and then proceed to one of the side-branches. You will have found an entry to either the Swamp or the Shoals, and another entry to either the Spider's Nest or the Snake Pit. This gives two side branches for you to explore (plus the Slime Pits, but you will leave those alone for the purposes of your first victory). Each of these side branches consists of four levels. On the lowest level you will find a Rune of Zot, which you need to obtain to win this game. But for now you will only clear out the first three levels of each branch. The fourth level is somewhat more difficult, and you will want to come back for it slightly more experienced.
For a Gargoyle, none of these branches is particularly challenging, as you are both immune to poison, and you can fly. But if you need to tackle the Spiders in your game, you should delay that if you have not found a source of see invisible yet. In the end you’ll have to go there anyway, but it will be rather problematic.
While clearing out these branches, Vehumet will soon give you his final gift – three high-end spells, two of which are probably level-9 spells. As mentioned earlier, you really hope for Lehudib's Crystal Spear (LCS), for Shatter and for Fire Storm. If Vehumet gives you access to all three of those, that would be awesome. In theory, this final gift should be influenced by your skills, but there is no guarantee that you’ll end up with more than one of these spells.
Currently you won’t be able to learn any of these three spells. You’ll need really high skills in earth, fire and conjurations (depending on the spell), plus some spellcasting, and you don’t have those yet. But that does not matter – Vehumet will keep these spells available as long as you worship him, so there is no rush. For Firestorm or Shatter your skills need to be in the range of 18 before you can cast them confidently, and also you need much more intelligence than you currently have. LCS is somewhat easier to cast, but it is still out of reach for you for quite some time.
Anyway, since these are Vehumet's final gifts, you can ease up on your training of the spellcasting skill a bit, to use your experience for the other skills. Train spellcasting whenever you run out of spell slots from now on, or if you are not happy with your MP pool.
Here are some details about each side branch:
Swamp
In the Swamp you’ll find yourself in some kind of mangrove area with few dry spots, lots of shallow water and some deep water. All this does not bother you, as you fly permanently. The most dangerous enemies here are hydras, which you already know from the Lair, and Swamp dragons, except that these are not really dangerous to you, as you are immune to their poison. But giant leeches, alligators and swamp worms bite hard, and bog bodies hit you from far with bolts of cold. Insubstantial wisps are hard to hit and tend to surround you. You may also get surrounded by slime creatures, but that would be a good thing to happen – because if they don’t surround you, they would combine into large or even titanic slime creatures, whose incredible whack would bring you to your knees in two or three turns. When you are pursued by a titanic slime creature, run away until you are surrounded by open ground or water. When the slime arrives, it will split and surround you, and they are a lot less dangerous that way, with the AC you have acquired by now. The biggest danger comes from various uniques which like to roam the Swamp, such as Saint Roka with his cool gang, Urug, Donald or Jorgrun, who all need to be killed as fast as possible, if you don’t even wisely avoid them for some more time.
Shoals
The Shoals have even more water than the Swamp, and the change of the tides shows the same spot sometimes as shallow water and sometimes as dry ground. Again, with your permanent flight you couldn’t care less. There are many dangerous enemies in the Shoals, though. All kind of merfolk hurl projectiles against you, so it may be a good idea to wear an item with the Repel Missiles brand, which might add some protection for you. Snapping turtles, and their big brothers, the alligator snapping turtles, have a dangerous bite, even from two tiles distance. Manticores shoot barbs which reduce your health until you find the peace and quiet to remove them from your flesh. Kraken are out in the open water, and their many tentacles hit you senseless. Fortunately they react well to Magma Bolt or Bolt of Fire – any tentacle segment you hurt, hurts the whole Kraken, and a few shots should send it to the bottom of the ocean. If you meet a wind drake, remember to immediatly switch off your permanent flight, as its Airstrike will hurt you a lot more if you're in the air. Polyphemus and Kirke are both frequently found in the Shoals, and both come supported: Polyphemus by death yaks and a catoblepas, Kirke by a herd of hogs which should turn into friendly humans once you kill her, or into tasty snacks if you kill them before. Trouble is, Kirke may easily turn you into a hog and then into a snack yourself. Magic resistance is one of your growth areas, and gargoyles are usually easy prey for Kirke’s transmutations. Then again, it has a somewhat entertaining effect when you find yourself to be the first flying pig ever.
Snake Pit
The Snake Pit is a usually dry and very orderly place full of snakes of all kind, nagas, salamanders, and anacondas. Anacondas and nagas will start to constrict you when you are in melee range, but your good AC gives you a lot more time to deal with it than other casters. The most dangerous regular enemies are naga warriors (blue) and nagarajas (red), who have lots of HP and are often well armored. Nagas are normally slow, but the guys can hasten themselves and still catch you. Salamanders use ranged weapons very competently, and again Repel Missiles would be a good thing to have. Mana vipers are not dangerous as such, but they come to melee range fast with a bite that reduces your MP, so you need to prioritize them. Aizul is a unique frequently found in the Pit, and he may put you to sleep for a while. Because he is so boring. A remnant dwarf found down here is Jorgrun. He casts LRD and Shatter himself, and you are highly vulnerable to both. Kill him quick – don’t give him the few turns he needs to smash you. Azrael is a fiery efreet swinging a sword of flaming, and he comes supported by fire elementals and a pack of hell hounds. Obviously, you will want some resistance to fire when you meet this group. A wand of iceblast is about the most efficient thing you can find to take care of this situation.
Spider's Nest
The Spider's Nest is also mostly dry, but a lot more chaotic in layout than the Snake Pit. Most of your enemies here are all kinds of arachnoids, which means that they are very poisonous. Although you are immune against venom, their bite still hurts badly, and some of them are very fast, surrounding you quickly. Demonic crawlers are not spiders, but very tough and very resistant creepers that would scare you to death if you did not have your powerful earth magic to subdue them. Orb spiders lob very damaging orbs of destruction at you, and a few of those may kill you. Emperor scorpions are a lot more hardy and destructive than their small cousins you squished earlier in the game. It takes a lot of MP to bring one down. Probably the most dangerous inhabitant of the Nest is the ghost moth. If you are lucky, you won’t see it until level 4, which you will visit later. But in fact, not seeing it has nothing to do with luck, as it is permanently invisible. The moment it sees you (it really needs to see you, so if you are invisible, it helps) it starts reducing your MP in huge chunks, leaving you without mana in at most three turns. It can also reduce some of your other stats, so you really want to kill these moths as soon as possible. Asterion has been seen in the Nest, and, even more dangerously, Mara. This unique splits itself into up to four apparitions, only one of which being real enough to be killed. It will also create a double of yourself, very really killing you. For now you are probably not in a shape to defeat Mara. Come back with Shatter, and that will be the swift end of him.
Liberating the Dungeon
So, now you have explored three levels of each of the side branches. Return to your stash and drop what you don’t need next. This is also a good opportunity to re-evaluate your situation. You should now have enough scrolls of identification to reveal all your potions. If you feel daring, you could experiment a bit with a potion of mutation – if you are lucky, you might get two really good mutations at the price of a bad mutation that does not bother you too much. But even so-called good mutations can ruin your day. A pair of horns won’t do you much good, but prevents you from wearing a helmet. Probably it is best, though, to leave these potions alone and keep them for emergencies, when you need to get rid of some really nasty malmutations, such as permanent reductions to your HP, MP, or spell power.
Reading through all your unknown scrolls you will hopefully also discover a scroll of acquirement. This is one of the biggest sources of joy and frustration in the game. If you are lucky, it may give you genuinely awesome stuff – just what you need. Sometimes, however, it gives you incredible junk. If you have identified the scroll already, you should collect all subsequent finds for about this time in the game. Now you know what spells Vehumet has given you, and you know the books you have found. Are you still lacking one or two of the big spells? Well, read the scroll for a book, and hopefully it will supply you with the missing Book of Earth or Book of Annihilations. If you already have all the books you need, use it for jewelry, armor or weapons. No need to ask for money or food in this game. Well, it might also give you a good staff, to enhance your spellcasting.
By now you should be in your late teens regarding your XL, and your INT without any boosters should be in the low twenties. Looking at your skills, you have made significant progress, and you may appear well-rounded except that you are still miles away from casting these high-level spells that Vehumet and hopefully some books have put into your reach. You need to address this problem now. For a while all your skills training needs to focus on your spells. Only train earth magic, fire magic and conjurations, plus, if it is much lower than these skills, some spellcasting. The only non-magic skill you train should be fighting. You can also leave fighting out for a while, if you promise yourself to not take too many risks when going into fights. This should give you 25 or 33% experience for each skill. This measure will help you to get closer to the high-level spells, about which you still need to learn a few things:
Lehudib's Crystal Spear is the most powerful single target spell in the game. Level 8 and two spell schools (earth and conjurations) make it quite difficult to learn, but once you can cast it confidently, you need to fear nothing and no-one in this game. It is a bit low in range, but Vehumet is committed to help you with that. If you know Iron Shot, it may be possible to do without LCS, but the extra power this gives you may be the edge you need in some tough fights.
Shatter is a level-9 spell of just the earth school (conjurations don’t help you here), with a devastating effect on almost anything in line of sight. It seems to create the effect of a brutal earthquake, and dungeon features also get badly affected by this. The only drawback is that it does not affect flying monsters very well, and of those you encounter a lot the deeper you get.
Fire Storm is seen by many as the crown of conjurations in the game. It is a level-9 spell, and because it needs both fire and conjurations, it is somewhat harder to learn than Shatter. When you cast it, you can select any tile in LOS, and around it you create a killing field three or four tiles in radius, on which anything is fried to a crisp – even highly fire-resistant monsters can’t escape that effect fully. Because this killing field may well extend beyond your line of sight, even monsters you have never seen get roasted that way.
You’ll want those spells, and getting them online is now your most pressing need. To get there, our secondary goal at present is to clear out the Dungeon down to its lowest level 15. Most likely you won’t have to do more than four or five levels for that. You are now a lot more powerful than at the time that you first entered the Lair, and initially you will find very few worthy opponents. But on the last two or three levels of the Dungeon things will begin to become tougher again. Ugly things and very ugly things are very dangerous opponents, as they swarm you in big numbers. Find a corridor to grind them down. All kinds of giants show up now, and their damage output is fearsome. And you will have to fight your first tengus, who are both good at spells and melee fighting.
Two notable dungeon features you will encounter on your way down. On level 13 or down from there you will find the entrance to the Vaults, a place you will visit very soon. It is guarded by some monsters you’ll have to fight there, so have a good look, and be careful around them. And finally, on level 15, there is the entrance to the Depths, also well guarded. You may admire the entrance structure, but don’t go in there yet!
Your First Two Runes
Now that you have completed the dungeon, every next step is somewhat risky. The Depths are a brutal place, and you have a much better chance in there if you try it with a lot more experience. The Vaults are also rough, but not quite as badly as the Depths, so this should be your next quest. Trouble is, you don’t get in there without at least one Rune of Zot under your belt, and right now you don’t have one. But at the bottom of each of the two side branches of the Lair you can find a rune, and it is now time to grab them. We have delayed going into these two places, because they are considerably harder than the rest of these branches, but now there is nothing else you can do to delay it. Off you go! When you enter the final level, this is a good time to read a scroll of magic mapping, of which you should have enough by now. This reveals where you’ll find the final rune vault, and therefore the stiffest resistance.
Swamp 4
This level looks very much like the rest of the Swamp, except for the rune vault, which is usually an enclosure surrounded by stone walls, with only one entrance. Don’t approach this entrance before you have cleared the whole level outside the enclosure. Once you have attracted the attention of some enemies within, you will have to fight off an onslaught of countless hydras, spiny frogs, alligators and swamp dragons. It will be necessary to retreat at least a couple of times and then come back. Having a stone structure to play with at least should give you a few good opportunities for casting LRD on the bad guys. The layout inside the vault can vary – sometimes you may even find some stretches of lava in there which is great for keeping hydras at bay. You can fly, they don’t. The rune is just lying around somewhere. Pick it up and feel its power! But you may have to fight the terrible Lernaean hydra first, which, having 27 heads, you shouldn’t let come within melee range. Shoot it from far with your most powerful shots.
Shoals 4
This is a bit different than the other branch ends. It does not come with one big vault, but at least five or six smaller vaults. All of them contain an assortment of dangerous enemies and some treasure. One of them also has the rune. Outside the vaults you will almost certainly get attacked by Ilsiuw and her gang of aquatic ruffians. She is extremely dangerous, and you need to use alternating sets of stairs to separate her from her support team, killing the minions off one by one on level 3. Only when they are gone (and they are dangerous enough), you can start taking shots at the boss. Be fast! Once Ilsiuw is down, you may encounter the odd kraken, but for the most part, the level and the rune are yours.
Snake Pit 4
The map will reveal a somewhat differently shaped area which clearly sticks out from the rest of the level. But careful here – some stairs to level 4 may take you right into the vault area. If so, go back up quickly and take a different set of stairs. Stay away from the vault until you have seen and cleared everything else. Once done with that, get a set of stairs behind you and then slowly approach the vault area. There are dozens of nagas and salamanders in there, and you need to avoid facing all of them at once. Lure them away from their friends and finish them off where they die as lone and unsung heroes. All this takes a while, but slowly you should conquer the vault, always taking four steps forward and three steps back. Some vaults feature a large lake of lava, which should give you an advantage, as nothing flies down here. The rune lies around somewhere in the back area of the vault.
Spider's Nest 4
Here again the map will identify a differently shaped area, often circular or elliptical, as the rune vault, and again it is important to clear everything around it first. Inside the vault you will find many spiders, demonic crawlers, emperor scorpions, and, worst of all, ghost moths. If you don’t see invisible, those moths may be a good reason to delay clearing this level for some more time, as you will be almost helpless against them. You already have a rune from Swamp or Shoals, and that is all you need for now to enter the Vaults branch. But if you see invisible, do it now. Whenever a ghost moth shows up, forget everything else and hit it as hard as you can. LRD should work fine, as there should be plenty of walls here. If your MP does get drained, escape up the next stairs to recharge, and try again. Inside the vault you may find the rune in a somewhat hidden corner, plus some potions of ambrosia, some weird stuff which restores your MP and HP really quickly, but at the price of you being confused. That sounds pretty bad, but you may still consider carrying it with you always. In case you are thrown into the Abyss, this stuff may come in handy.
The Vaults
Now that you are done with everything you can find in the Lair (at least for the purposes of this game), and the Dungeon cleared all the way down, you have reached another milestone. You have finished what is called the mid-game, which has become manifest in the fact that you are now carrying two runes of Zot. Your character is pretty well developed by now, so that you can attack the late game branches. Unfortunately, if you look at your late-game spells, they are most likely still very difficult to cast. Don’t even consider casting Shatter or Fire Storm when the failure rate is still above 30%. If it is below 30%, but above 15%, you can consider casting it if no-one is around, just to see how it looks. The trouble with these high-end spells is that they have some terrible miscast effects. Most likely you get damaged in some pretty bad way, but in any case you will collect contamination. The contamination of one miscast is usually not dangerous, but if you have two miscasts in a row, level-9 spells will quickly give you yellow contamination, which means that you are about to catch a very bad malmutation, if you don’t have something to prevent it. If you have it with you, a potion of cancellation will reduce your contamination to harmless levels.
If you have learned a high-end spell, and find yourself in a situation where it would be really good to use it, you can reduce your failure rate in the following ways:
A ring of wizardry or the staff of wizardry will significantly reduce your failure rate, possibly to a point where you feel more confident. Unfortunately, these devices don’t stack well, so there is not much point to have two rings, or a staff and a ring.
Drinking a potion of brilliance will increase your INT a lot, and that has a very beneficial effect on spell success. It also increases the spell power.
A ring of intelligence, depending on its enchantment value, will also increase your success rate. Some enchanted armor may also give you extra intelligence, particularly some head gear.
Check if you are wearing heavy armor or a shield without the necessary skills to compensate for spell penalties. Taking off the shield and replacing the armor with something lighter might reduce the failure rate.
Therefore, if your failure rate for a spell is somewhere around 50%, drinking a potion of brilliance and using an item with the wizardry effect will usually get your failure rate far enough down that you can cast that spell at least once or twice before you have to stop because of your contamination.
Your next stop is the entrance to the Vaults. Going down there will show you how one of your runes is put to good use. You’ll find yourself once more in a very different environment. Everything here is very angular, with lots of closed rooms, corridors, mazes and plenty of open space. It may be a bit difficult to find your way in here, as the connections from one part of a level to the other are not always very obvious. No worries, you will find all places by just looking around.
This looking around, however, is made quite dangerous by the monsters you encounter here. Sometimes it is just another band of harmless orcs or ogres (still watch out for these ogre mages, who have not lost any zeal for banishing you to the Abyss). But many of your new opponents are humans with some terrible abilities. Vault guards are just heavily armored grunts, and you can deal with them easily by now. But be careful when you see a vault warden, who may block all doors and staircases in LOS, thereby blocking your escape to safer areas or levels. The probably most dangerous inhabitant is the vault sentinel, easily recognizable by his blue armor. When he sees you, he may attach a mark to you, which means that you will find yourself surrounded by almost every monster on that level, which may easily include a couple of wardens blocking your escape. When that happens, teleport away as soon as possible, and pray that you find an upstairs anywhere nearby. Or this may be the great opportunity for a potion of brilliance and your first attempt at Shatter.
You will also meet more giants, particularly frost giants and fire giants. Try to have some resistance against their element when you approach them. The good old trusty yak now gets upgraded to a yaktaur, a warrior who excels with a crossbow, and never comes alone. Try not to take on a whole pack of them in the open. Lure them around corners and see what LRD can do to unarmored enemies! The Vaults may also be the place where you find your first deep troll earth mages, which hit you hard with LRD and Shatter. Kill them quickly, before they get you. Fire crabs hurl something like a Fire Storm at you, hurting you badly if you have no resistance.
Whenever you enter a new level of the Vaults, you may get an announcement for a timed bazaar. These are safe areas where you can shop in a number of different outlets, and usually find stuff you really want to have, if you have the money. If you don’t have much money, then don’t bother, because racing to the bazaar in a hurry can easily get you killed in the Vaults. But if you have some coin, then read a scroll of magic mapping and see if you can’t make it to the place, possibly by using a different set of stairs. Again, being able to shop somewhere is not worth getting killed for, so be cautious, and take a rest after a fight, even if the entrance to the bazaar is just round the next corner. If you find yourself surrounded in sight of the entrance, use a scroll of blinking – no monsters will follow you inside, and you will come out rested.
Even without finding a bazaar, you should find plenty of good loot in the Vaults. You may have to return to your stash on Lair 2 a couple of times to clear your inventory. The Vaults are also a place where you may find a Wizard Laboratory. If you find one now, you may courageously have a look. You should be powerful enough to survive by now, but be prepared to die anyway – Wizard Labs are full of surprises, and few of them are good for you.
The first two levels of the Vaults are made up of stone walls. The next two levels often have metal or crystal walls, which is just fine with you, as they give you the best material for LRD. On level 2 or 3 you will find the entrance to the Crypt, usually guarded by some undead monsters. You will visit this place later, but for now you just leave it alone. Level 5 is very different, and you must not go down there for now, for whatever reason – not even to take a peek!
The Depths
If you’d thought that the Vaults were bad, now brace yourself for the real thing: your next destination will be the Depths. At first glance they don’t look much different to the dungeon, and for the most part, you won’t find many new monsters down here. But the onslaught you have to face is truly brutal. Every step you move forward you have to fight wave after wave of the toughest opponents you have met so far. The noteworthy new monsters down here are the gold dragon, which has various breath attacks and a very tough skin, the iron dragon, which seems to be almost indestructible, and the tentacled monstrosity, which approaches you swiftly to constrict you. Your earth magic should have little difficulty in bringing these buddies down, but you almost always have to face quite a lot of them! Particularly unpleasant are caustic shrikes, which are fast and very hard to hit. They hurt you with acid while surrounding you, and because many of your earth-shots miss them, you may find yourself out of MP with still a lot of them to fight. In terms of uniques, pay particular attention to Sojobo, who looks like a cute little tengu, but he is merciless with his conjurations, and he comes with a strong gang of dedicated supporters. The same is true for the Enchantress, a very powerful spriggan boss. Once you have killed her, check her armor – the faerie dragon armour is potentially one of the best body armors you can wear as a caster, depending on its rather random enchantment. An armor skill of five or six should be enough to wear it without bad effect on your spellcasting.
The good news about all this stiff opposition is that there is so much experience to be found down here that by the end of the five levels you will have Shatter at a reasonable success rate, and maybe even Fire Storm. Always have an eye on your spell stats and decide when it is a good time for a first blast.
If you have acquired at least two levels of resistance against fire, it may be a good idea to look for all scrolls of immolation that you have ignored so far in the dungeon. For a fire-resistant character they are a very useful weapon in a target-rich environment. They enchant all enemies in LOS so that they explode on being killed, leaving some columns of flame behind for a few turns on all nine squares around them.
From all being said so far, it becomes clear that you need to approach the Depths with extreme caution. Quite often the access stairs are all in the same location, which means that the road to safety may become very long. Don’t use auto-explore, but explore in circles around the stairs, so that you always h |
def _sign(self, args):
elements = [self.shared_secret]
for key in sorted(args.keys()):
elements.append(key)
elements.append(args[key].encode('utf-8'))
return md5(''.join(elements)).hexdigest() |
/*
* Used for directly placing blocks (ie saplings) and items (ie sugarcane). Pass in source ID to constructor,
* so one instance per source ID.
*/
public class PlantableStandard implements IFactoryPlantable
{
private int sourceId;
private int plantedBlockId;
public PlantableStandard(int sourceId, int plantedBlockId)
{
if(plantedBlockId >= Block.blocksList.length)
{
throw new IllegalArgumentException("Passed an Item ID to FactoryPlantableStandard's planted block argument");
}
this.sourceId = sourceId;
this.plantedBlockId = plantedBlockId;
}
@Override
public boolean canBePlantedHere(World world, int x, int y, int z, ItemStack stack)
{
int blockId = world.getBlockId(x, y, z);
return Block.blocksList[plantedBlockId].canPlaceBlockAt(world, x, y, z) &&
(Block.blocksList[blockId] == null || Block.blocksList[blockId].isAirBlock(world, x, y, z));
}
@Override
public void prePlant(World world, int x, int y, int z, ItemStack stack)
{
return;
}
@Override
public void postPlant(World world, int x, int y, int z)
{
return;
}
@Override
public int getPlantedBlockId(World world, int x, int y, int z, ItemStack stack)
{
if(stack.itemID != sourceId)
{
return -1;
}
return plantedBlockId;
}
@Override
public int getPlantedBlockMetadata(World world, int x, int y, int z, ItemStack stack)
{
return stack.getItemDamage();
}
@Override
public int getSourceId()
{
return sourceId;
}
} |
package app
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/chrisolsen/aetemplate/core"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
"google.golang.org/appengine/memcache"
)
const (
tokensTable = "tokens"
)
// Errors
var (
errMissingAuthToken = errors.New("Auth token does not exist")
errMissingAuthHeader = errors.New("No authorization header supplied")
errMultipleAuthTokens = errors.New("Duplicate auth token exist")
)
// Token keys
const (
newTokenHeader string = "new-auth-token"
newTokenExpiryHeader string = "new-auth-token-expiry"
)
// TokenDetails is the data type that is stored in memcache using the token as a key.
type tokenDetails struct {
Expiry time.Time
AccountKey string
Token string
}
func (t *tokenDetails) isExpired() bool {
return t.Expiry.Before(time.Now())
}
func (t *tokenDetails) willExpireIn(duration time.Duration) bool {
future := time.Now().Add(duration)
return t.Expiry.Before(future)
}
// AuthMiddleware .
type AuthMiddleware struct{}
// FormAuth .
func (a *AuthMiddleware) FormAuth(c context.Context, w http.ResponseWriter, r *http.Request) context.Context {
var err error
var cookieName = "app-cookie"
c, cancel := context.WithCancel(c)
returnURL := fmt.Sprintf("/signin?returnUrl=%s", r.RequestURI)
cookie, err := r.Cookie(cookieName)
if err != nil {
http.Redirect(w, r, returnURL, http.StatusTemporaryRedirect)
cancel()
return c
}
tokenDetails, err := a.getTokenDetails(c, cookie.Value)
if err != nil {
http.Redirect(w, r, returnURL, http.StatusTemporaryRedirect)
cancel()
return c
}
// if token has expired return 401
if tokenDetails.isExpired() {
http.Redirect(w, r, returnURL, http.StatusTemporaryRedirect)
cancel()
return c
}
accountKey, err := datastore.DecodeKey(tokenDetails.AccountKey)
if err != nil {
http.Redirect(w, r, returnURL, http.StatusTemporaryRedirect)
cancel()
return c
}
// if the token's expiry less than a week away, get new token
if tokenDetails.willExpireIn(time.Hour * 24 * 7) {
newToken, err := a.getNewToken(c, accountKey)
if err != nil {
http.Redirect(w, r, returnURL, http.StatusTemporaryRedirect)
cancel()
return c
}
// send back the new token values
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Expires: time.Now().Add(time.Hour * 24 * 14), // 2 weeks from now
HttpOnly: true,
Secure: !appengine.IsDevAppServer(),
Value: newToken.Value(),
})
}
// add accountKey to context
c = session.SetAccountKey(c, accountKey)
return c
}
// APIAuth .
func (a *AuthMiddleware) APIAuth(c context.Context, w http.ResponseWriter, r *http.Request) context.Context {
// let option requests through
if r.Method == http.MethodOptions {
return c
}
var err error
c, cancel := context.WithCancel(c)
authHeader := r.Header.Get("Authorization")
if len(authHeader) <= len("token=") {
log.Errorf(c, "missing token header: %v", err)
w.WriteHeader(http.StatusUnauthorized)
cancel()
return c
}
// prevent token caching with blank string value
rawToken := authHeader[len("token="):]
if len(rawToken) == 0 {
log.Errorf(c, "missing token value: %v", err)
w.WriteHeader(http.StatusUnauthorized)
cancel()
return c
}
tokenDetails, err := a.getTokenDetails(c, rawToken)
if err != nil {
log.Errorf(c, "failed to get token details: %v", err)
w.WriteHeader(http.StatusUnauthorized)
cancel()
return c
}
// if token has expired return 401
if tokenDetails.isExpired() {
log.Errorf(c, "expired Token")
w.WriteHeader(http.StatusUnauthorized)
cancel()
return c
}
accountKey, err := datastore.DecodeKey(tokenDetails.AccountKey)
if err != nil {
log.Errorf(c, "failed to decode account key: %v", err)
w.WriteHeader(http.StatusUnauthorized)
cancel()
return c
}
// if the token's expiry less than a week away, get new token
if tokenDetails.willExpireIn(time.Hour * 24 * 7) {
newToken, err := a.getNewToken(c, accountKey)
if err != nil {
log.Errorf(c, "failed to create new token: %v", err)
w.WriteHeader(http.StatusUnauthorized)
cancel()
return c
}
// send back the new token values
w.Header().Add(newTokenHeader, newToken.Value())
w.Header().Add(newTokenExpiryHeader, newToken.Expiry.Format(time.RFC3339))
}
// add accountKey to context
c = session.SetAccountKey(c, accountKey)
return c
}
// Gets the token for the rawToken value
func (a *AuthMiddleware) getTokenDetails(c context.Context, rawToken string) (*tokenDetails, error) {
var err error
tokenDetails, err := a.getCacheToken(c, rawToken)
if err != nil && err != memcache.ErrCacheMiss {
return nil, err
}
if err == memcache.ErrCacheMiss {
tokenKey, err := datastore.DecodeKey(rawToken)
if err != nil {
return nil, fmt.Errorf("decoding token key: %v", err)
}
var token core.Token
err = TokenStore.Get(c, tokenKey, &token)
if err != nil {
if err == datastore.ErrNoSuchEntity {
return nil, errMissingAuthToken
}
return nil, err
}
// add the token to memcache
tokenDetails, err = a.setCacheToken(c, token.Key.Parent(), &token)
if err != nil {
return nil, err
}
}
return tokenDetails, nil
}
// getCacheToken attemps to fetch the token details for the raw token string passed in
func (a *AuthMiddleware) getCacheToken(c context.Context, rawToken string) (*tokenDetails, error) {
var tokenDetails tokenDetails
_, err := memcache.JSON.Get(c, rawToken, &tokenDetails)
return &tokenDetails, err
}
// setCacheToken memcaches the passed in raw token value
func (a *AuthMiddleware) setCacheToken(c context.Context, accountKey *datastore.Key, token *core.Token) (*tokenDetails, error) {
tokenDetails := tokenDetails{
AccountKey: accountKey.Encode(),
Expiry: token.Expiry,
Token: token.Value(),
}
// save to memcache
err := memcache.JSON.Set(c, &memcache.Item{
Key: token.Value(),
Object: tokenDetails,
Expiration: -1 * time.Since(token.Expiry),
})
if err != nil {
return nil, err
}
return &tokenDetails, nil
}
// Creates a new token and links it to the account for the old token
func (a *AuthMiddleware) getNewToken(c context.Context, accountKey *datastore.Key) (*core.Token, error) {
if accountKey == nil {
return nil, errors.New("account key is required to create a token")
}
return TokenStore.Create(c, accountKey)
}
|
/**
* Terminate a partial aggregation and return the state. If the state is a
* primitive, just return primitive Java classes like Integer or String.
*/
public UDAFTopNState terminatePartial() {
if (state.queue.size() > 0) {
return state;
} else {
return null;
}
} |
<gh_stars>0
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package common
import "fmt"
// MT is a PRNG implementing the Mersenne Twister algorithm.
// See https://en.wikipedia.org/wiki/Mersenne_Twister for details and pseudocode.
type MT struct {
mt []uint64
index int
lmask uint64
umask uint64
params *MTParams
}
func newMT(params *MTParams, seed uint64) *MT {
var lm uint64 = (1 << params.R) - 1
m := &MT{
mt: make([]uint64, params.N),
index: params.N,
lmask: lm,
umask: ^lm & params.WMask,
params: params,
}
m.mt[0] = seed
for i := 1; i < params.N; i++ {
m.mt[i] = params.WMask & (params.F*(m.mt[i-1]^(m.mt[i-1]>>(params.W-2))) + uint64(i))
}
return m
}
// Params returns a copy of the constant parameters used by the algorithm.
func (m *MT) Params() MTParams {
return *m.params
}
// SetState replaces m's internal state with st.
// m's index is also reset to 0.
func (m *MT) SetState(st []uint64) {
if len(st) != m.params.N {
panic(fmt.Sprintf("state has size %v; need %v", len(st), m.params.N))
}
copy(m.mt, st)
m.index = 0
}
// Extract returns the next number.
func (m *MT) Extract() uint64 {
if m.index >= m.params.N {
m.twist()
}
y := m.mt[m.index]
y ^= (y >> m.params.U) & m.params.D
y ^= (y << m.params.S) & m.params.B
y ^= (y << m.params.T) & m.params.C
y ^= (y >> m.params.L)
m.index++
return y & m.params.WMask
}
func (m *MT) twist() {
for i := 0; i < m.params.N; i++ {
x := (m.mt[i] & m.umask) + (m.mt[(i+1)%m.params.N] & m.lmask)
xa := x >> 1
if x%2 != 0 { // lowest bit of x is 1
xa ^= m.params.A
}
m.mt[i] = m.mt[(i+m.params.M)%m.params.N] ^ xa
}
m.index = 0
}
// NewMT19937 returns a new MT using the Mersenne prime 2^19937−1.
func NewMT19937(seed uint64) *MT {
return newMT(&mt19937Params, seed)
}
// Parameter values are listed at https://en.wikipedia.org/wiki/Mersenne_Twister.
type MTParams struct {
W int // word size (in number of bits)
N int // degree of recurrence
M int // middle word, an offset used in the recurrence relation defining the series x, 1 ≤ m < n
A uint64 // coefficients of the rational normal form twist matrix
B, C uint64 // TGFSR(R) tempering bitmasks
D uint64 // additional Mersenne Twister tempering bitmask
R int // separation point of one word, or the number of bits of the lower bitmask, 0 ≤ r ≤ w - 1
S, T int // TGFSR(R) tempering bit shifts
U, L int // additional Mersenne Twister tempering bit shifts
F uint64 // "another parameter to the generator, though not part of the algorithm proper"
WMask uint64 // mask for bottom w bits
}
var mt19937Params = MTParams{
W: 32,
N: 624,
M: 397,
A: 0x9908B0DF,
B: 0x9D2C5680,
C: 0xEFC60000,
D: 0xFFFFFFFF,
R: 31,
S: 7,
T: 15,
U: 11,
L: 18,
F: 1812433253,
WMask: (1 << 32) - 1,
}
|
//
// LXProgressView.h
// MierMilitaryNews
//
// Created by 李响 on 15/9/11.
// Copyright (c) 2015年 miercn. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, LXProgressIndicatorStyle) {
LXProgressIndicatorStyleNormal = 0,
LXProgressIndicatorStyleLarge = 1,
};
@interface LXProgressView : UIView
@property (assign, nonatomic) LXProgressIndicatorStyle progressIndicatorStyle;
@property (strong, nonatomic) UIColor *strokeColor;
- (instancetype)initWithProgressIndicatorStyle:(LXProgressIndicatorStyle)style;
- (void)startProgressAnimating;
- (void)stopProgressAnimating;
@end
|
/**
* Created by jiankuan on 1/27/15.
*/
public class BinaryTreeLevelOrderOutput {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
int i = 0;
while (true) {
ArrayList<Integer> level = new ArrayList<>();
if (doLevelOrder(root, 0, i, level)) {
res.add(level);
} else {
break;
}
i++;
}
return res;
}
private boolean doLevelOrder(TreeNode root, int curHeight, int targetHeight, List<Integer> level) {
if (root == null) {
return false;
}
if (curHeight == targetHeight) {
level.add(root.val);
return true;
}
if (curHeight > targetHeight) {
return false;
}
boolean leftEnd = doLevelOrder(root.left, curHeight + 1, targetHeight, level);
boolean rightEnd = doLevelOrder(root.right, curHeight + 1, targetHeight, level);
return leftEnd || rightEnd;
}
public static void main(String[] args) {
TreeNode root = new BinaryTreeCodec().fromBSTString("3,9,20,#,#,15,7");
ArrayList<ArrayList<Integer>> res = new BinaryTreeLevelOrderOutput().levelOrder(root);
for (ArrayList<Integer> list: res) {
System.out.println(list);
}
}
} |
-- Test instances for tuples up to 15
-- For Read, Show, Eq, Ord, Bounded
module Main where
data T = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O
deriving( Eq, Ord, Show, Read, Bounded )
t15 = (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O)
t14 = (A,B,C,D,E,F,G,H,I,J,K,L,M,N)
t13 = (A,B,C,D,E,F,G,H,I,J,K,L,M)
t12 = (A,B,C,D,E,F,G,H,I,J,K,L)
t11 = (A,B,C,D,E,F,G,H,I,J,K)
t10 = (A,B,C,D,E,F,G,H,I,J)
t9 = (A,B,C,D,E,F,G,H,I)
t8 = (A,B,C,D,E,F,G,H)
t7 = (A,B,C,D,E,F,G)
t6 = (A,B,C,D,E,F)
t5 = (A,B,C,D,E)
t4 = (A,B,C,D)
t3 = (A,B,C)
t2 = (A,B)
t0 = ()
big = (t0,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15)
main = do print big
print (read (show big) `asTypeOf` big)
print (big == big)
print (big < big)
print (big > big)
print (minBound `asTypeOf` big)
print (maxBound `asTypeOf` big) |
I didn’t grow up in the sticks, but I wasn’t an urban kid, either. I guess edge of the sticks might be an appropriate descriptor for my neighbourhood: the outside rings of cheap housing on the borders of a bedroom community which was itself on the outside of a mid-sized Cascadian burg. No sidewalks defined our roads, only aged grey asphalt crumbling at the edges into tarry pebbles, scrub pine needles and the discarded rusty skin of arbutus trees. There was a field bordering a line of warehouses near the railroad tracks on the walk to my grade school: older kids would harvest mushrooms in the fall there, and in the summer you could find hobo campsites. Black rings of sodden ash and garbage, the smell of piss steaming off the grass in the morning and discarded porno mags peeking out from under logs.
Above my school, the Sooke Hills bunched up to the north and west. There was a giant cannibal woodpecker that lived up there, in a gully near a clearing where we’d take our air rifles for target practice. Don’t ask why we called it a cannibal woodpecker; it only ate humans, that we knew of. Legends. A high school girl had died up there, in the gully. Overdose on something, on whatever the scary drug of the moment was. Beyond that gully was a make-out spot and smoke pit, and beyond that a rock outcropping where a slow Jehovah’s Witness kid I knew had caused another kid’s Ouija board to levitate and disintegrate itself in mid-air: a dead-easy thing to do, apparently. Just ask the device the true name of God, natch.
And a little farther on was the lake where the Tree lived. It wasn’t even really a lake, more a dirty pond, but it was narrow and boomerang-shaped, you couldn’t see the opposite end of it, so maybe it felt like a lake. Anyway. The Tree was this mostly-dead yellow cedar, fire-blasted and grey but still managing to green up a little each year, though its core had all rotted away into aromatic mulch. The only fish you could catch in the lake were these anaemic sunfish that seemed to especially go for the thick grey wormy pupae-type things that you could only find in that mulch, in that Tree. And the dare we’d always throw at each other, when fishing wasn’t the reason for being there, when new kids needed initiation, or a spot of cruelty was more entertaining than woodsy adventure, was always “go stand inside the Tree”.
Standing inside the Tree was not pleasant. There was something old about it, older than the Tree itself, the wood and skin of it. Something sick and bad. I don’t recall anyone lasting more than three, maybe five minutes in the Tree. Kids, eh? Who knows why they do anything? But that’s what we did. Whatever it was we knew about the Tree, it was unspoken and it was true on a gut level. Instinctual.
I t hought about the Tree while reading The Children of Old Leech, the new Laird Barron tribute anthology from Word Horde. I thought about the Tree a lot. This book really took me back there.
I haven’t read all of Barron’s collected work, but I’ve read enough to dig him, to get where he’s been and where he was at while writing; enough to maybe make a stab at where he’s going, and I’m pleased to report that the authors collected in The Children of Old Leech get him, too, and have riffed on Barron’s grim, muscular worldview with humour, insight, and a great heaving pile of unhealthy shavings from that Tree, or trees like it. This is an anthology to make you squirm, to gasp at the shock of sudden revelation, to think about man’s place in the cosmos (it’s low, so low), and do all this while treating your fiction-appreciation glands to a good massage. It gets right in there, too, and roots around like a sumbitch. Great holes are dug where Earth’s pores ought to suffice, to casually paraphrase old H P. A few highlights, then, since to break down every tale and my reasons for liking them would drag a little…
The Harrow by Gemma Files is the first shot out of the box, and it’s a doozy: poignant and sorrowful before descending to a very dark place, to black spaces in the earth and in the brain. The method of that descent? Oh, just a little bit of auto-surgery the ancients liked to practice. Yeah, trepanning. Goddamn if this isn’t a fascinating subject, with loads of medical, psychological, and spiritual import, and Files uses it to dig deep and deliver some true horror. Loved it. First story, and I was already loving the book.
A little later on came the epistolary Good Lord, Show Me the Way by the always-wry Molly Tanzer. There’s a thing with Barron’s treatment of bad things in the woods and in the holes, and that’s the kind of oblique way he comes at them: a glancing reference here, a bald but vague statement there. Desperate people attempting to get a bead on the unthinkable and unspeakable, only to see their shots ricochet off in useless, misleading directions. The bad thing is always there, in the center, getting worse and worse, defining its boundaries by what-it-is-not, and that suggestion is what makes Barron’s beasties (both real and metaphorical) terrifying. Tanzer here embodies this aspect of Barron’s fiction through a dry e-mail exchange between the professors, adjuncts, and thesis defenders surrounding a talented student who chooses to investigate and write her paper on a little known forest community, a cult, living in the woods near to where she grew up. Tanzer doesn’t show us what happens to the student, but then, she doesn’t have to: the glib, ivory-towered rhetoric and glazed snappiness of her superiors after the reality of her disappearance sinks in (or doesn’t) is terror enough. Masterful.
T. E. Grau’s Love Songs from the Hydrogen Jukebox telegraphs its punches a bit: before you’re a third of the way in, you can see what’s coming, but the trip there is pure amphetamine-fueled beatnik joy. This isn’t the only story in TCoOL to feature a boundary-busting orgy of weirdness (Michael Griffin’s Firedancing does that better, and weirder) but the energy Grau expends getting his proto-Cassady guru and his nebbish-y protégé out of San Francisco and up to the fateful world-ending party in the mountains, and the crunchy imagery he deploys once they’re there with the Truth and the Horrors, is great stuff. A good ride leading into the book’s very satisfying center.
The Old Pageant is another dark little gem in the crown of Richard Gavin. Barron’s crones and powerful, interesting women with connections are a staple of his world, and here Gavin taps into that deep old double-X chromosomal knowledge for another of his trademarked deft characterizations. Read any story by Gavin, and you will feel for his characters, mourn their losses, their catastrophic decisions in the face of the ineffable and deadly. The Old Pageant is no exception, and though it shares the pages with stories just as chilling or more so, the chill at the end of this one is especially unsettling. There’s trees in this one. There’s trees in most every tale here, but Gavin’s grove is creepy plus.
Paul Tremblay’s Notes for “A Barn in the Wild” is a stand-out for a lot of excellent reasons. I’m a sucker for diarist-as-narrator formats (because it can be flubbed so badly, when it goes well it goes really well), and following Tremblay’s narrator as he tracks down a McCandless-style free-spirit who goes missing in Labrador with the aid of a “Black Guide” (a travelogue listing bizarre and powerful places off the beaten path) is an exercise in literary puzzlin’ I loved. Only knowing what you’re being told, but knowing there’s more, much more? Goddamn delicious. Barn in the Wild feels like the first time you saw The Blair Witch Project, in every way that was good, before its sublime effect was watered-down by a decade-and-change of imitators. (An aside regarding the production of TCoOL: I pre-ordered the book early on, and I’m getting the diary, a Blue Notebook, with the entire text of the story, footnotes and scribbles in the margins and everything, written in Tremblay’s own hand, as a special add-on. How’s that for premium? Bam. I’m learning that with Lockhart’s Word Horde, it’s the little things.)
The Last Crossroads on a Calendar of Yesterdays was the only selection that I just couldn’t get into, but this is my own fault; I’ve been told repeatedly that Joe Pulver is “jazz” and is therefore an acquired taste. I’ve yet to acquire it, I guess. There’s a pack of bohunk neo-Nazis in this, and some kind of golem cobbled together out of blood and the text and paper of another Black Guide, but beyond that I couldn’t pull much from this. It’s atmospheric, for sure, and bops along with a sketchy energy I can appreciate, but I could have used some additional straight-up narrative.
John Langan’s Ymir, however, is a wonderful tribute to and continuation of Barron’s Hallucigenia, following Marissa, a private military contractor suffering from PTSD, who’s hired to guard the body of a classic Barron bad-man-with-money-and-time. This fellow is tracking down the vanished (transformed? transubstantiated? in any case, fucked) Wallace Smith and his wife Helen, not so much out of duty or concern, as for the hints regarding the monstrous geniuses of the Choate clan connected with the case. Their sleuthing takes them north, to the Arctic Circle, and a throbbing sore in the skin of our reality buried at the bottom of a mine. When Barron strikes his cryptogenetics chord, prepare to be disturbed, to feel body-horror deeply: his is the long view, a sere chuckling appraisal of our place in the red-fanged grind of Time. Langan here gets that view, and the ending (is there ever a true ending for a Barron protagonist? no) is perfect.
Of A Thousand Cuts is a killer transhumanist gladiatorial gore-fest from Cody Goodfellow. Honestly, I’ve never read anything like this. It was a revelation. Goodfellow gets down into the meat and viscera of what it means to be human, reshapes what he finds there, augments the weak parts with fierce bionics, overclocks the feed into the strong parts, laces the spastic fibres with nano-wires running molten streams of pure love and despair and consuming hate, and when that surgery is through, he sluices what’s left of the human soul through a dark-side-Zen psychical re-programming algorithm. At the other end of this completely transcendent mind-job is a shining, multi-faceted product, an exquisite artefact of a story that you actually hesitate to return and read again, it’s so goddamn sharp. But it’s the hesitation of a moment only. Want to learn how to kill with a poem? Right here, folks.
So, those are my top picks in The Children of Old Leech, but really, there’s not a dud in the bunch here. Each is a class in storytelling, every one is entertaining, and every other one is thought provoking. Lockhart and Steele have a winner on their hands, I think; this is one I’ll keep coming back to, much as I do with Laird’s work. Reading TCoOL was like standing in that Tree beside that lake in the hills, up to my ankles in smoky rot and grey grubs, unable to move, while the sun dipped down to dusk. Recommended.
Edited by Ross E. Lockhart and Justin Steele
* * * * *
Scott R Jones is the author of the short story collections Soft from All the Blood and The Ecdysiasts, as well as the non-fiction When the Stars Are Right: Towards An Authentic R’lyehian Spirituality. His poetry and prose have appeared in Innsmouth Magazine, Cthulhu Haiku II, Broken City Mag, and upcoming in Andromeda Spaceways Inflight Magazine. |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package driver;
import java.io.*;
import java.util.Arrays;
/**
*
* @author Admin
*/
public class Test{
public question[] q;
public Test(question[] Question){
q=Question;
}
public String toString(){
String r="";
for(int i=0; i<q.length;i++){
r+=i+1+")"+q[i].Print();
}
return r;
}
// would be used to print the test's answer key
//String[] answer=new String[q.length];
public String toAnswerString() {
String r="";
for(int i=0; i<q.length;i++){
r+=i+1+"."+q[i].Answer()+"\r\n";
}
return r;
}
public int getTotalPoints() {
int sum=0;
for(int i=0;i<q.length;i++){
sum+=q[i].Point();
}
return sum;
}
}
|
def list_artifacts(self):
response = request('get',
f'{self.base_path}/{self.id}/list-artifacts/')
return response['files'] |
Turkey has decided to downgrade its diplomatic ties with Israel to the lowest possible level, Turkish Foreign Minister Ahmet Davutoglu said on Friday, following Israel's continued refusal to apologize for a 2010 raid on a Gaza-bound aid flotilla.
The findings of a UN probe into Israel's deadly raid on a 2010 flotilla to Gaza known as the Palmer Commission Report, which were leaked to The New York Times Thursday, have further raised tensions between Israel and Turkey, and senior Foreign Ministry officials warned that Turkey could respond to the report's publication by expelling the Israeli ambassador and scaling back diplomatic relations.
Turkish FM Ahmet Davutoğlu, Turkish PM Recep Tayyip Erdogan, and PM Benjamin Netanyahu Avi Ohayun - GPO / Reuters
Speaking to reporters on Friday, Davutoglu announced the downscale of diplomatic relations with Jerusalem, saying the move was a direct response to Israel's refusal to apologize for the deaths of nine Turkish nationals in the May 2010 raid.
The implications of the downgrade are that the level of diplomatic representation in both countries will be scaled back from ambassador to first secretary. This means Israel's ambassador to Turkey, Gabby Levy, and his deputy, Ella Afek, will be expelled.
A statement by the Turkish Foreign Ministry, published minutes following Davutoglu's press conference, indicated that Turkish and Israeli diplomats due to leave their respective posts as a result of the downgrade will do so by September 7.
Take part in the debate over the downgrading of diplomatic relations between Israel and Turkey on the Haaretz.com page on Facebook
"Israel squandered all of the opportunities to end the crisis, and now it must pay for it," Davutoglu said, adding that Turkey's official position was that Israel's blockade on the Gaza Strip was illegal, despite the fact that the UN report supported its legality.
Keep updated: Sign up to our newsletter Email * Please enter a valid email address Sign up Please wait… Thank you for signing up. We've got more newsletters we think you'll find interesting. Click here Oops. Something went wrong. Please try again later. Try again Thank you, The email address you have provided is already registered. Close
Hinting at the possible consequences of Turkey's disagreement with the UN's interpretation of Israel's blockade, the Turkish FM said that Ankara would "do whatever it takes to implement its interpretation of the significance of international waters in the Mediterranean."
"We cannot accept the blockade on Gaza. We cannot say that the blockade aligns with international law," he said, adding that the stance taken by the Palmer Commission Report was the author's "personal opinion, one which does not correspond with Turkey's position."
Additionally, Davutoglu announced the cancellation of all defense contracts between Israel and Turkey, adding that Ankara would both initiaite legal action against the Gaza blockade in international courts, as well as aid families of those killed in the Gaza flotilla raid in seeking litigation against Israel.
Warning of the possible consequences of Israel's refusal to apologize for the flotilla raid, Davutoglu said on Thursday that Friday's official release of the Palmer Report constituted Israel's last chance to apologize for its raid on the Turkish-sponsored flotilla and warned of consequences, including sanctions, should Israel continue to refuse to apologize.
Unless there is an Israeli apology, "we will put Plan B into play," Davutoglu said. He said Turkey intended to impose sanctions, "which both Israel and other international parties are aware of."
Referring to Israel's request for another delay in the report's publication, he said that Ankara "cannot accept another six-month extension."
Senior Israeli officials said Thursday that Israel would not apologize for the raid and that Prime Minister Benjamin Netanyahu had reiterated this to the U.S. administration in the past few days.
Turkey is also planning a diplomatic and legal campaign against Israel in the United Nations, and will help the families of those killed and injured in the raid to file lawsuits against Israel in courts worldwide.
In addition, Ankara is threatening to halt trade between Turkey and Israel, which totals billions of dollars. |
The premium was meant to account partly for taxes that customers may have paid, said Ashlee Yingling, a McDonald’s spokeswoman.
“We are making sure our customers are fairly compensated for the recall experience,” she said in an e-mail message. While 12 million of the Shrek glasses were intended for distribution in the United States, about 7.5 million were sold to consumers, the company said last week.
McDonald’s announced the recall after the Consumer Product Safety Commission said that tests on the glasses showed that low levels of cadmium, a heavy metal identified as a carcinogen, could come off on the hands of a person holding the glasses. The commission said, however, that the glasses were not considered toxic and that the risk to children was low.
Photo
The level of cadmium in the glasses, according to the commission, was much lower than the level of the metal found in some children’s jewelry that prompted three recalls earlier this year, including the recall of 55,000 necklaces sold at Wal-Mart.
In the case of the jewelry, officials worried that children could suck on pieces or swallow them and that high levels of cadmium could be absorbed into their bodies.
The federal government has set a limit for the amount of cadmium that can be used in toys. The safety commission is working to set acceptable levels for other products.
Newsletter Sign Up Continue reading the main story Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. You must select a newsletter to subscribe to. Sign Up You will receive emails containing news content , updates and promotions from The New York Times. You may opt-out at any time. You agree to receive occasional updates and special offers for The New York Times's products and services. Thank you for subscribing. An error has occurred. Please try again later. View all New York Times newsletters.
Long-term exposure to cadmium has been associated with a variety of health problems, including kidney and bone ailments.
While the recalled jewelry was made in China, the recalled glassware was manufactured in the United States, by Arc International. Walt Riker, a McDonald’s spokesman, said last week that the company did not know where the paint used on the glasses came from, but he said that it did not come from China.
Advertisement Continue reading the main story
Cadmium is used in some paints to make bright colors, but industry representatives said that it was unusual for paints containing cadmium to be used in consumer products like glassware.
“To me the whole thing about the McDonald’s glasses is very much a mystery, and why they would be putting cadmium pigments in there,” said Hugh Morrow, a consultant for the International Cadmium Association and a former president of the trade group in North America. “Our position is that cadmium pigments should not be painted on consumer glasses.”
Meanwhile, McDonald’s announced on Tuesday that sales at stores in the United States that were open at least 13 months rose 3.4 percent in May, compared with those in the month a year earlier.
The company said that the sales increase was due in part to the popularity of Shrek-themed promotions for its Chicken McNuggets and Happy Meals. The statement on the monthly results did not mention whether the glassware promotion, which began on May 21, had also lifted sales. |
<reponame>smarterclayton/cluster-kube-controller-manager-operator<gh_stars>0
package operator
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"time"
"github.com/ghodss/yaml"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/diff"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/flowcontrol"
"k8s.io/client-go/util/workqueue"
operatorconfigclientv1alpha1 "github.com/openshift/cluster-kube-controller-manager-operator/pkg/generated/clientset/versioned/typed/kubecontrollermanager/v1alpha1"
operatorconfiginformerv1alpha1 "github.com/openshift/cluster-kube-controller-manager-operator/pkg/generated/informers/externalversions/kubecontrollermanager/v1alpha1"
)
type observeConfigFunc func(kubernetes.Interface, *rest.Config, map[string]interface{}) (map[string]interface{}, error)
type ConfigObserver struct {
operatorConfigClient operatorconfigclientv1alpha1.KubecontrollermanagerV1alpha1Interface
kubeClient kubernetes.Interface
clientConfig *rest.Config
// queue only ever has one item, but it has nice error handling backoff/retry semantics
queue workqueue.RateLimitingInterface
rateLimiter flowcontrol.RateLimiter
observers []observeConfigFunc
}
func NewConfigObserver(
operatorConfigInformer operatorconfiginformerv1alpha1.KubeControllerManagerOperatorConfigInformer,
kubeInformersForOpenShiftKubeControllerManagerNamespace informers.SharedInformerFactory,
kubeInformersForKubeSystemNamespace informers.SharedInformerFactory,
operatorConfigClient operatorconfigclientv1alpha1.KubecontrollermanagerV1alpha1Interface,
kubeClient kubernetes.Interface,
clientConfig *rest.Config,
) *ConfigObserver {
c := &ConfigObserver{
operatorConfigClient: operatorConfigClient,
kubeClient: kubeClient,
clientConfig: clientConfig,
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "ConfigObserver"),
rateLimiter: flowcontrol.NewTokenBucketRateLimiter(0.05 /*3 per minute*/, 4),
observers: []observeConfigFunc{
observeClusterConfig,
},
}
operatorConfigInformer.Informer().AddEventHandler(c.eventHandler())
kubeInformersForOpenShiftKubeControllerManagerNamespace.Core().V1().ConfigMaps().Informer().AddEventHandler(c.eventHandler())
kubeInformersForKubeSystemNamespace.Core().V1().ConfigMaps().Informer().AddEventHandler(c.eventHandler())
return c
}
// sync reacts to a change in controller manager images.
func (c ConfigObserver) sync() error {
var err error
observedConfig := map[string]interface{}{}
for _, observer := range c.observers {
observedConfig, err = observer(c.kubeClient, c.clientConfig, observedConfig)
if err != nil {
return err
}
}
operatorConfig, err := c.operatorConfigClient.KubeControllerManagerOperatorConfigs().Get("instance", metav1.GetOptions{})
if err != nil {
return err
}
// don't worry about errors
currentConfig := map[string]interface{}{}
json.NewDecoder(bytes.NewBuffer(operatorConfig.Spec.ObservedConfig.Raw)).Decode(¤tConfig)
if reflect.DeepEqual(currentConfig, observedConfig) {
return nil
}
glog.Infof("writing updated observedConfig: %v", diff.ObjectDiff(operatorConfig.Spec.ObservedConfig.Object, observedConfig))
operatorConfig.Spec.ObservedConfig = runtime.RawExtension{Object: &unstructured.Unstructured{Object: observedConfig}}
if _, err := c.operatorConfigClient.KubeControllerManagerOperatorConfigs().Update(operatorConfig); err != nil {
return err
}
return nil
}
// observeClusterConfig observes cloud provider configuration from
// cluster-config-v1 in order to configure kube-controller-manager's cloud
// provider.
func observeClusterConfig(kubeClient kubernetes.Interface, clientConfig *rest.Config, observedConfig map[string]interface{}) (map[string]interface{}, error) {
clusterConfig, err := kubeClient.CoreV1().ConfigMaps("kube-system").Get("cluster-config-v1", metav1.GetOptions{})
if errors.IsNotFound(err) {
glog.Warningf("cluster-config-v1 not found in the kube-system namespace")
return observedConfig, nil
}
if err != nil {
return observedConfig, err
}
installConfigYaml, ok := clusterConfig.Data["install-config"]
if !ok {
return observedConfig, nil
}
installConfig := map[string]interface{}{}
err = yaml.Unmarshal([]byte(installConfigYaml), &installConfig)
if err != nil {
glog.Warningf("Unable to parse install-config: %s", err)
return observedConfig, nil
}
// extract needed values
// data:
// install-config:
// platform:
// aws: {}
platform, ok := installConfig["platform"].(map[string]interface{})
if !ok {
glog.Warningf("Unable to parse install-config: %s", err)
return observedConfig, nil
}
cloudProvider := ""
switch {
case platform["aws"] != nil:
cloudProvider = "aws"
default:
glog.Warningf("No recognized cloud provider found in install-config/platform")
return observedConfig, nil
}
// set observed values
// extendedArguments:
// cloud-provider:
// - "name"
unstructured.SetNestedStringSlice(observedConfig, []string{cloudProvider},
"extendedArguments", "cloud-provider")
return observedConfig, nil
}
func (c *ConfigObserver) Run(workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
glog.Infof("Starting ConfigObserver")
defer glog.Infof("Shutting down ConfigObserver")
// doesn't matter what workers say, only start one.
go wait.Until(c.runWorker, time.Second, stopCh)
<-stopCh
}
func (c *ConfigObserver) runWorker() {
for c.processNextWorkItem() {
}
}
func (c *ConfigObserver) processNextWorkItem() bool {
dsKey, quit := c.queue.Get()
if quit {
return false
}
defer c.queue.Done(dsKey)
// before we call sync, we want to wait for token. We do this to avoid hot looping.
c.rateLimiter.Accept()
err := c.sync()
if err == nil {
c.queue.Forget(dsKey)
return true
}
utilruntime.HandleError(fmt.Errorf("%v failed with : %v", dsKey, err))
c.queue.AddRateLimited(dsKey)
return true
}
// eventHandler queues the operator to check spec and status
func (c *ConfigObserver) eventHandler() cache.ResourceEventHandler {
return cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { c.queue.Add(workQueueKey) },
UpdateFunc: func(old, new interface{}) { c.queue.Add(workQueueKey) },
DeleteFunc: func(obj interface{}) { c.queue.Add(workQueueKey) },
}
}
|
// Check that wildcards are not supported by default
@Test(expected = InternalServerErrorException.class)
public void testSearchUserWildcard() throws Exception {
WebClient wc = WebClient.create("http://localhost:" + PORT);
wc.path("users/search/name==a*").get(User.class);
} |
Here’s a hint: it involved carbon freezing.
As we all know, Rogue One: A Star Wars Story went through innumerable iterations; some of them you saw in trailers and on the big screen, others never made it that far. Recently, Rogue One’s first writer Gary Whitta revealed an alternate, happier ending where Jyn and Cassian survived. However, that wasn’t the only alternative ending according to the creator of Rogue One’s story, John Knoll.
Advertisement
John Knoll is the Chief Creative Officer and Senior Visual Effects Supervisor for Industrial Light & Magic, the visual effects house that works on Star Wars as well as dozens of other films. He was also the person who originally came up with and pitched the idea of making a movie about stealing the Death Star plans. Before any writers were hired, he came up with several different versions of the story.
We were at ILM to talk to Knoll about the upcoming Rogue One home release, but when we asked him about the “happy ending” revealed earlier this week, he gladly told us about a few other possible endings that were considered for the film. These two started the same way, but then broke off into two different paths.
1) Fleeing to Coruscant
Jyn and Cassian lead a team that steals the Death Star plans, and escape Scarif on a Rebel ship. In hot pursuit is Darth Vader, whose ship keeps attacking them even after multiple jumps to lightspeed. Soon, they’ve taken so much damage, they realize they aren’t going to make it.
Advertisement
“And the last jump they do, they try to get lost in the traffic that’s around Coruscant,” Knoll said. “It’s a giant cloud of ships. Ten-thousand ships coming and going and they’re trying to get lost in that traffic but they don’t make it. There’s still an hour’s flight away from Coruscant and their ship gets damaged.”
Jyn and Cassian realize if they don’t get the plans off the ship, the whole mission has failed. “So they discover that Leia’s ship has just taken off from Coruscant and is on its way to its diplomatic mission to Alderaan,” Knoll said. “They know that she’s secretly working for the Rebellion and they risk blowing her cover by transmitting the plans to her ship with the hope that this transmission won’t be detected but Vader’s ship.”
Obviously, it is detected, but Jyn and Cassian realize that whether Vader catches Leia’s ship or not, they will inevitably be tortured for information by the Empire and could reveal the Rebellion’s secrets, potentially leading to its destruction. So the two Rebels decide to blow up their ship with them on it.
Advertisement
That’s one ending Knoll considered. The second idea is largely the same ending but has another layer to it and a twist at the end. And here’s where things get crazy.
2) The Double Agent
Then I had a version of it where the Cassian character, originally, was a double agent. He was a spy planted by the Empire into the Rebellion. And over the course of the mission he becomes aware that the Death Star actually is a real thing and it’s not just propaganda. The Empire really built it, intends to use it and its only purpose is a genocide weapon. He realizes a lot of what he’s been told is a lie and that he’s been on the wrong side. So he switches sides to the Rebellion and he realizes he can let everyone live. They’ve got a carbon freeze bomb on the ship and the idea is that he forces everyone into the airlock. “I’m going to set this off and you’re all going to survive.” He sort of times it with one of the hits from Vader’s ship so he blows up the ship and sets off this carbon freeze bomb and everyone is frozen. Then on Vader’s ship they detect no life signs and they think everyone’s dead. And they’re like, “Where’s that ship the plans were transmitted too?” and they go. So I was going to leave our heroes out of the picture. It’s why they don’t show up in Empire or Jedi — they’re stuck in [carbon freeze].
Advertisement
It’s an awesome, if kind of absurd idea. But it also is the type of ending that would have hypothetically worked in canon and allowed Jyn to appear in later works. (If you’re wondering about the other heroes in the film, like Chirrut and Baze, they hadn’t even been conceived at this point.) Even so, it would have been a bit of a cheat and thankfully, as development went along everyone agreed that just killing everyone was a more heroic, fitting, and simpler piece of storytelling.
And yet, I hope someone brings the Carbon Freeze bomb back at some point. It’s far too awesome an idea not to use.
Rogue One hits digital download on March 24 and DVD/Blu-ray April 4. We’ll have more soon. |
Oct. 1, 2012: In space, they say, no one can hear you scream.
Nobody ever said anything about singing, though. A NASA spacecraft has just beamed back a beautiful song sung by our own planet.
"It's called chorus," explains Craig Kletzing of the University of Iowa. "This is one of the clearest examples we've ever heard." [Play the audio]
A new ScienceCast video explores the eerie-sounding radio emissions that come from our own planet. Play it
Chorus is an electromagnetic phenomenon caused by plasma waves in Earth's radiation belts. For years, ham radio operators on Earth have been listening to them from afar. Now, NASA's twin Radiation Belt Storm Probes are traveling through the region of space where chorus actually comes from--and the recordings are out of this world.
"This is what the radiation belts would sound like to a human being if we had radio antennas for ears," says Kletzing, whose team at the University of Iowa built the “EMFISIS” (Electric and Magnetic Field Instrument Suite and Integrated Science) receiver used to pick up the signals.
He's careful to point out that these are not acoustic waves of the kind that travel through the air of our planet. Chorus is made of radio waves that oscillate at acoustic frequencies, between 0 and 10 kHz. The magnetic search coil antennas of the Radiation Belt Storm Probes are designed to detect these kinds of waves.
"Chorus emissions are front and center for the Storm Probe mission," says Kletzing. "They are thought to be one of the most important waves for energizing the electrons that make up the outer radiation belt."
In particular, chorus might be responsible for so-called "killer electrons," high-energy particles that can endanger both satellites and astronauts. Many electrons in the radiation belts are harmless, with too little energy to do damage to human or electronic systems. But, sometimes, these electrons can catch a chorus wave, like a surfer riding a wave on Earth, and gain enough energy to become dangerous—or so researchers think.
The Radiation Belt Storm Probes are on a two-year mission to explore the Van Allen Belts. [ more
The Radiation Belt Storm Probes are on a mission to find out for sure.
“The production of killer electrons is a matter of much debate, and chorus waves are only one possibility,” notes the Storm Probes’ mission scientist Dave Sibeck.
Launched in August 2012, the two probes are orbiting inside the radiation belts, sampling electromagnetic fields, counting the number of energetic particles, and listening to plasma waves of many frequencies.
“We hope to gather enough data to solve the mystery once and for all,” says Sibeck.
At the moment, the spacecraft are still undergoing their 60-day checkout phase before the main mission begins. So far, things are checking out very well.
“One of things we noticed right away is how clear the chorus sounds in the recording,” notes Kletzing. That's because our data is sampled at 16 bits, the same as a CD, which has not been done before in the radiation belts. This makes the data very high quality and shows that our instrument is very, very healthy.”
Eventually, Kletzing hopes to release unprecedented stereo recordings of Earth’s chorus.
“We have two spacecraft with two receivers,” he says, “so a stereo recording is possible.”
Such a recording would not only sound wonderful, but also have real scientific value. “One of the things we don't know is how broad the region is over which chorus occurs. The widely-separated ‘stereo capability’ of the Storm Probes will give us the ability to figure this out,” he explains.
With a two-year mission planned for the Storm Probes, the chorus is just getting started.
Author: Dr. Tony Phillips | Production editor: Dr. Tony Phillips | Credit: Science@NASA |
def save(self, filename="", path=MODEL_SAVE_PATH):
if filename == "":
filename = f"{self.name}"
create_folders(path)
with open(f'{path}/{filename}.pickle', 'wb') as f:
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) |
Text IQ chief executive Apoorv Agarwal says his software's job is to spot a needle in a haystack – but a costly one. Make a mistake in discovery during litigation, and a company can face sanctions of tens or hundreds of millions of dollars, he says. "It's a high-stakes needle."
Like other startups, Text IQ's raised funding to solve that problem. Unlike others, Text IQ is profitable. And for its first outside funding, it's taking only about $3 million from top investor Floodgate and a group of veteran legal counsels in a seed round its founders say could be the only money it ever needs.
The tech industry’s interest in legal discovery isn’t new. A quick web search will yield a host of “eDiscovery” options that promise to speed up and cheapen the process, in which a company pays a gaggle of attorneys to look through documents to flag what's privileged or irrelevant. Text IQ says it's different as the only one to really do so through AI.
“There are a lot of companies and a lot of hype around AI,” Agarwal says. “We are trying to attack this problem from a different perspective."
In a super-hot market for AI that's leading some to quip that academics can now raise funding on just a concept, Text IQ started making money instead. The startup is profitable, with January revenue of 10x its burn rate, says cofounder Omar Haroun, and sales expected to be in the millions for the quarter. Customers saved $3 million in legal expenses so far this year, the company says—not including the much higher costs of bad outcomes averted by its use.
The heads-down moneymaking impressed self-described “jaded" investor Mike Maples, a perennial Midas Lister whose firm Floodgate led the seed investment in Text IQ. “Everyone talks about how they will be tomorrow’s unicorn before they’ve done anything,” Maples says. “These guys had real customers. I liked that they solved the problem without throwing money at it.”
Text IQ took funding at all to gain access to Floodgate's partners and get legal experts skin in the game, its founders say. That includes Dan Cooperman, the former counsel of Apple and Oracle, as well as Randy Milch, former counsel at Verizon.
The origins of Text IQ come out of academia, inspired by PhD research that Agarwal conducted at Columbia University that could scan a 19th century British novel and map out the characters’ relationships. Agarwal's research had been funded by the National Science Foundation and DARPA, the startup investment wing of the Department of Defense. He and Haroun then built the beginnings of their business from some cash from friends and family.
While many eDiscovery services flag messages that come from law firms or include sensitive keywords, Tex tIQ deduces links between parties that aren’t spelled out in the text. That could be 10 medical documents that when combined allow a reader to reasonably infer the identity of the individual involved, says Agarwal, or spotting attorney-client privilege just from the tone a lawyer typically uses.
Testing Text IQ’s claims is simple: clients simply conduct a bake-off, running the software on a series of documents already used by their existing service for a discovery process. When Twitter tried the product, Text IQ caught all the documents its outside reviewer did, but also more privileged documents that would’ve slipped through, says Wendy Riggs, senior manager of eDiscovery and litigation operations at Twitter. “The results were great.”
Text IQ has won every bake-off its conducted so far and already works anonymously with some of the biggest companies in the country, says Haroun, its COO, with contracts running into the hundreds of thousands and millions of dollars.
One difficulty facing Text IQ now: how to add new services without moving too fast and tripping up. Customers like Twitter and investors get excited envisioning how to use Text IQ for more functions than just discovery. At Twitter, for example, Riggs would like Text IQ to work with all the legal team’s document workflow, not just checking for privilege. Floodgate partner Arjun Chopra, who led the investment for the firm, agrees that’s a major opportunity, but says he’s cautioning the startup not to rush. “Part of the challenge they are facing is there is need across the board,” says Chopra. Move too fast, and Text IQ could become players in a few use cases and masters of none.
With more than 70% of its team PhD or masters degree holders in computer science, Haroun says over-selling isn’t wired into Text IQ’s DNA. “A big part of this is, from a technology standpoint, with less than 20 people you can accomplish what companies with 2,000 people do.” |
Halogen Nuclear Quadrupole Coupling Constants in Non-axially symmetric Molecules; Ab initio Calculations, which Include Correlation, Compared with Experiment
Abstract Ab initio determination of the electric field gradient (EFG) tensors at halogen and other centres ena-bled determination of the nuclear quadrupole coupling constants (NQCC) for a diverse set of C2v , C3v and other symmetry molecules of general formula MH2X2 and MHX3 , where the halogen atoms (X) are Cl, Br and I, and the heavy central atoms (M) are C and Si. The study presents results at a standardised level of calculation, triple-zeta in the valence space plus polarisation functions (TZVP) for the equilib-rium geometry stage; all-electron MP2 correlation is included in all these studies. For the bromo and iodo compounds, especially the latter, it is essential to allow core polarisation, by decontraction of the p,d-functions. This is conveniently done by initial optimization of the structure with a partly contract-ed basis, followed by reestablishment of the equilibrium structure with the decontracted basis. The NQCCs, derived from the EFGs, using the 'best' values for the atomic quadruple moments Cl, Br and I, lead to good agreement with the inertial axis (IA) data obtained from microwave spectroscopy. When the data from the present study is plotted against the values derived from the IA data, obtained by whatever approximations chosen by the MW authors, we obtain a linear regression for the data (85 points) with the slope 1.0365 and intercept -0.1737, with standard errors of 0.0042 and 0.2042, respectively; these are statistically identical results irrespective of whether the data is restricted to IA or EFG principal axis (PA) data. Since as in the C3v MH3X compounds studied previously, a close correlation of the microwave spectral data with the calculations was observed using the 'best' current values for Qz , there seems no need to postulate that the values of QBr for both 79Br and 81Br are seriously in error. A scaling downwards of Qz by about 5% for Br and I increases the agreement with experiment, but the contributions of relativistic effects are unknown, and could lead to further reassessment. Of the two common assumptions used in MW spectroscopy, to convert from IA to EFG-PA data, either (a) cylindrical symmetry of the NQCC along the bond direction, or (b) coincidence of the tensor principal element with the bond axis, the latter is found to be a much more realistic approximation. |
// workspaceExists checks if workspace exists in Kong.
func workspaceExists(config utils.KongClientConfig) (bool, error) {
workspace := config.Workspace
if workspace == "" {
return true, nil
}
if config.SkipWorkspaceCrud {
return true, nil
}
config.Workspace = ""
rootClient, err := utils.GetKongClient(config)
if err != nil {
return false, err
}
_, err = rootClient.Workspaces.Get(nil, &workspace)
if err != nil {
if kong.IsNotFoundErr(err) {
return false, nil
}
return false, errors.Wrap(err, "error when getting workspace")
}
return true, nil
} |
/**
* Class ReducedCostMatrix
* <p>
* Inherited from GraphMatrix
* </p>
* Created by rayandrew on 3/30/2017.
*/
public class ReducedCostMatrix extends GraphMatrix {
private int[] cost;
private int[][] reduced;
/**
* ReduceCostMatrix constructor.
* @param file file external
* @throws FileNotFoundException if file not found
*/
public ReducedCostMatrix(File file) throws FileNotFoundException {
super(file);
//nameOfGraph = "ReducedCostMatrix";
cost = new int[row]; // max allocation for spanning the graph
reduced = new int[row][col];
visited = new boolean[row];
visited[0] = true;
pathOf = new int[row + 1];
pathOf[neffOfPath] = 0;
pathOf[row] = 0;
neffOfPath++;
for (int idx = 0; idx < row; idx++) {
System.arraycopy(weightMatrix[idx], 0, reduced[idx], 0, col);
}
cost[0] = Utility.rowReduction(reduced) + Utility.colReduction(reduced);
}
private int[][] reducingMatrix(int fromLoc, int toLoc) {
int[][] matrixTemporary = new int[row][col];
for (int idx = 0; idx < row; idx++) {
System.arraycopy(reduced[idx], 0, matrixTemporary[idx], 0, col);
}
for (int idx = 0; idx < matrixTemporary.length; idx++) {
matrixTemporary[fromLoc][idx] = 99999;
}
for (int idx = 0; idx < matrixTemporary.length; idx++) {
matrixTemporary[idx][toLoc] = 99999;
}
matrixTemporary[toLoc][fromLoc] = 99999;
return matrixTemporary;
}
private int calculateBound(int fromLoc, int toLoc) {
int[][] matrixTemporary = reducingMatrix(fromLoc, toLoc);
return (
Utility.rowReduction(matrixTemporary)
+ Utility.colReduction(matrixTemporary)
+ cost[fromLoc]
+ reduced[fromLoc][toLoc]);
}
private boolean checkVisited() {
boolean check = true;
for (int idx = 0; idx < row; idx++) {
check = check && visited[idx];
}
return check;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append(row);
str.append(" X ");
str.append(col);
str.append("\n");
for (int idx = 0; idx < row; idx++) {
for (int jdx = 0; jdx < col; jdx++) {
str.append(reduced[idx][jdx]);
str.append(" ");
}
str.append("\n");
}
return str.toString();
}
@Override
public void run() {
for (int jdx = 1; jdx < col; jdx++) {
System.out.println("Calculate Bound from " + 0 + " to " + jdx);
cost[jdx] = calculateBound(0, jdx);
System.out.println("Cost = " + cost[jdx]);
}
int minimum = Utility.minOfArr(cost, 1, col - 1);
System.out.println("Minimum = " + minimum);
finalCost = cost[minimum];
pathOf[neffOfPath] = minimum;
reduced = reducingMatrix(0, minimum);
visited[minimum] = true;
neffOfPath++;
int minimumAfter;
while (!checkVisited() && neffOfPath < row) {
for (int idx = 1; idx < row; idx++) {
if (!visited[idx]) {
//System.out.println("Calculate Bound from " + minimum + " to " + idx);
cost[idx] = calculateBound(minimum, idx);
//System.out.println("Cost = " + cost[idx]);
nodeGenerated++;
}
}
minimumAfter = Utility.minOfArr(cost, 1, col - 1, minimum);
System.out.println("MinimumAfter = " + minimumAfter);
finalCost = cost[minimumAfter];
pathOf[neffOfPath] = minimumAfter;
reduced = reducingMatrix(minimum, minimumAfter);
visited[minimumAfter] = true;
minimum = minimumAfter;
for (int idx = 0; idx < row; idx++) {
if (visited[idx] && idx != minimumAfter) {
cost[idx] = 99999;
}
}
neffOfPath++;
}
bestPath();
}
} |
def create(cls, obj):
existing_owner = cls.get_owner(obj)
if not existing_owner:
try:
return cls.objects.create(owner=obj)
except IntegrityError:
return None
return existing_owner |
package rider
import (
"compress/gzip"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"sync"
)
const (
BestCompression = gzip.BestCompression
BestSpeed = gzip.BestSpeed
DefaultCompression = gzip.DefaultCompression
NoCompression = gzip.NoCompression
)
type gzipWriter struct {
http.ResponseWriter
writer *gzip.Writer
}
func Gzip(level int) HandlerFunc {
var gzPool sync.Pool
gzPool.New = func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
}
return func(c Context) {
if !shouldCompress(c.Request().request) {
c.Next()
return
}
res := c.Response()
originW := res.writer
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(res.writer)
c.SetHeader(HeaderContentEncoding, "gzip")
c.AddHeader(HeaderVary, HeaderAcceptEncoding)
gw := &gzipWriter{}
gw.ResponseWriter = res.writer
gw.writer = gz
res.writer = gw
defer func() {
if res.Size == 0 {
//当发生panic的时候会走到这一步;将response的writer恢复为原来的writer,因为gzip的writer无法正确处理错误
if res.Header().Get(HeaderContentEncoding) == "gzip" {
res.Header().Del(HeaderContentEncoding)
}
res.writer = originW
}
gz.Close()
}()
c.Next()
}
}
func (g *gzipWriter) WriteString(s string) (int, error) {
return g.writer.Write([]byte(s))
}
func (g *gzipWriter) WriteHeader(code int) {
if code == http.StatusNoContent {
g.Header().Del(HeaderContentEncoding)
g.Header().Del(HeaderContentLength)
}
g.ResponseWriter.WriteHeader(code)
}
func (g *gzipWriter) Write(data []byte) (int, error) {
return g.writer.Write(data)
}
func shouldCompress(req *http.Request) bool {
if !strings.Contains(req.Header.Get(HeaderAcceptEncoding), "gzip") {
return false
}
extension := filepath.Ext(req.URL.Path)
if len(extension) < 4 { // fast path
return true
}
switch extension {
case ".png", ".gif", ".jpeg", ".jpg":
return false
default:
return true
}
}
/*
func (g *gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
rw := &bufio.ReadWriter{}
writer := bufio.NewWriter(g)
rw.Writer = writer
n, _ := net.Dial("tcp", "mv.51mzzk.com:5000")
return n, rw, nil
}
*/
//在客户端关闭连接但还未发送响应体时,关闭连接
func (g *gzipWriter) CloseNotify() <-chan bool {
/*notify := r.writer.(http.CloseNotifier).CloseNotify()
go func() {
<-notify
r.server.logger.WARNING("HTTP connection just closed.")
}()*/
return g.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
|
Wit.ai, the Y Combinator startup, that has been working on an open and extensible natural language platform all the while helping developers to build applications and devices that turns speech into actionable data, announced earlier this week, its acquisition by Facebook.
“It is an incredible acceleration in the execution of our vision. Facebook has the resources and talent to help us take the next step. Facebook’s mission is to connect everyone and build amazing experiences for the over 1.3 billion people on the platform – technology that understands natural language is a big part of that, and we think we can help,” said a blog post making the announcement.
Wit.ai’s expertise could bolster Facebook’s strategy towards voice control development tools alongside its Parse development platform all the while assisting “with voice-to-text input for Messenger”, and helping “improve Facebook’s understanding of the semantic meaning of voice, and create a Facebook app you can navigate through speech,” points out TechCrunch.
Founded 18 months ago, Wit.ai already has more than 6000 developers on its team who have built hundreds of apps and devices. It is also reported that the platform will remain open and free for everyone.
Read more here.
Follow @DataconomyMedia
(Image credit: wit.ai) |
import 'remirror/styles/all.css';
import { htmlToProsemirrorNode } from 'remirror';
import { TextHighlightExtension } from 'remirror/extensions';
import { ProsemirrorDevTools } from '@remirror/dev';
import { Remirror, ThemeProvider, useCommands, useRemirror } from '@remirror/react';
export default { title: 'Extensions / TextHighlight' };
const extensions = () => [new TextHighlightExtension()];
const HighlightButtons = () => {
const commands = useCommands();
return (
<>
<button onClick={() => commands.setTextHighlight('red')}>Highlight red</button>
<button onClick={() => commands.setTextHighlight('green')}>Highlight green</button>
<button onClick={() => commands.removeTextHighlight()}>Remove</button>
</>
);
};
export const Basic = (): JSX.Element => {
const { manager, state, onChange } = useRemirror({
extensions: extensions,
content: `<p>Some text</p>`,
stringHandler: htmlToProsemirrorNode,
});
return (
<ThemeProvider>
<Remirror
manager={manager}
autoFocus
onChange={onChange}
initialContent={state}
autoRender='end'
>
<HighlightButtons />
<ProsemirrorDevTools />
</Remirror>
</ThemeProvider>
);
};
|
def _run_step(self, commands_0, commands_1):
if commands_1:
commands_team_1 = commands_1
else:
commands_team_1 = Aibehaviour.next_command(self.buster_team1, self.ghosts)
commands_team_0 = commands_0
for i in range(self.buster_number):
buster_team0 = self.buster_team0[i]
buster_team1 = self.buster_team1[i]
command_0 = commands_team_0[i]
command_1 = commands_team_1[i]
self.score_team0 += buster_team0.buster_command(command_0)
self.score_team1 += buster_team1.buster_command(command_1)
for ghost in self.ghosts:
if ghost.value != Constants.VALUE_GHOST_BASIC and ghost.alive:
buster_team_0_busting_this_ghost = []
buster_team_1_busting_this_ghost = []
for buster in self.buster_team0:
if buster.value == ghost.id:
buster_team_0_busting_this_ghost.append(buster)
for buster in self.buster_team1:
if buster.value == ghost.id:
buster_team_1_busting_this_ghost.append(buster)
if len(buster_team_0_busting_this_ghost) == len(buster_team_1_busting_this_ghost) and len(
buster_team_1_busting_this_ghost) > 0:
ghost.busting_cancelled()
for buster in buster_team_0_busting_this_ghost + buster_team_1_busting_this_ghost:
buster.cancelling_bust()
elif len(buster_team_0_busting_this_ghost) != len(buster_team_1_busting_this_ghost):
if len(buster_team_0_busting_this_ghost) > len(buster_team_1_busting_this_ghost):
closest = buster_team_0_busting_this_ghost[0]
winner_busters = buster_team_0_busting_this_ghost
else:
closest = buster_team_1_busting_this_ghost[0]
winner_busters = buster_team_1_busting_this_ghost
dist = MathUtility.distance(ghost.x, ghost.y, closest.x, closest.y)
for buster in winner_busters:
new_dist = MathUtility.distance(ghost.x, ghost.y, buster.x, buster.y)
if new_dist < dist:
dist = new_dist
closest = buster
if closest and len(buster_team_0_busting_this_ghost) + len(buster_team_1_busting_this_ghost) >= 1:
if closest.action == Constants.ACTION_BUSTING:
ghost.being_captured(closest)
closest.capturing_ghost()
if closest.type == Constants.TYPE_BUSTER_TEAM_0:
self.score_team0 += 1
elif closest.type == Constants.TYPE_BUSTER_TEAM_1:
self.score_team1 += 1
else:
ghost.updating_position(closest)
for buster in buster_team_0_busting_this_ghost + buster_team_1_busting_this_ghost:
if buster != closest:
buster.cancelling_bust()
for ghost in self.ghosts:
if not ghost.captured and ghost.alive:
ghost.run_away(self.buster_team0 + self.buster_team1)
for ghost in self.ghosts:
if ghost.is_in_team_0_base and not ghost.captured and ghost.alive:
self.score_team0 += 1
ghost.kill()
elif ghost.is_in_team_1_base and not ghost.captured and ghost.alive:
self.score_team1 += 1
ghost.kill() |
#include <bits/stdc++.h>
using namespace std;
char maze[110][110];
int n, k;
inline int get(int a, int b){
return max(0, k - (k-1-min(k-1, a)) - (k-1-min(k-1, b)));
}
int main(){
//freopen("in.txt", "r", stdin);
ios::sync_with_stdio(0); cin.tie(0);
int x,y;
while(cin >> n >> k){
for(int i = 0; i < n; ++i) cin >> maze[i];
int x = 1, y = 1, ansx = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
if(maze[i][j] == '.'){
int a = 0, b = 0, c = 0, d = 0;
for(int k = j-1; k >= 0; --k) {
if(maze[i][k] == '.') ++a;
else break;
}
for(int k = j+1; k < n; ++k) {
if(maze[i][k] == '.') ++b;
else break;
}
for(int k = i-1; k >= 0; --k) {
if(maze[k][j] == '.') ++c;
else break;
}
for(int k = i+1; k < n; ++k) {
if(maze[k][j] == '.') ++d;
else break;
}
int tmp = get(a, b) + get(c, d);
//cout << (i+1) << " " << (j+1) << " " << tmp << endl;
//cout << a << " " << b << " " << c << " " << d << endl;
//cout << "------------------------" << endl;
if(tmp > ansx) {
x = i+1; y = j+1;
ansx = tmp;
}
}
}
}
cout << x << " " << y << endl;
}
return 0;
}
|
/**
* Invokes a method declared in a target object.
* @param target to call the method.
* @param methodName the method name.
* @param argTypes array of types for the method argument.
* @param args actual arguments.
* @return a value returned from the method.
* @see Class#getDeclaredMethod(String, Class[])
* @see Method#invoke(Object, Object...)
*/
public static <T> T invoke(Object target, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> clazz = target.getClass();
Method method = clazz.getDeclaredMethod(methodName, argTypes);
method.setAccessible(true);
return (T) method.invoke(target, args);
} |
Design and development of a sensor for the direct and continuous measurement of inhaled nitric oxide: factors affecting sensitivity
Nitric oxide (NO), in concentrations between 0 and 20 ppm, is currently being used as an inhaled agent to treat patients with post surgical complications and respiratory disorders. Because excessive levels of NO can be detrimental to the patient, NO must be monitored accurately and continuously. Currently available instruments have problems that limit their usefulness for this application. This paper discusses the development of an inexpensive, direct and continuous sensor for the measurement of inhaled nitric oxide. The sensor incorporates a 0.05 inch, gas permeable, flow-through liquid cell into a probe, which can be incorporated into a ventilator circuit. Sensor operation is based on the complexation reaction of NO with cytochrome-c, a biologically derived heme. The complex is monitored spectrophotometrically by measuring the absorbance in the visible region of the spectrum at 563 nm. The sensor is specific to NO in the presence of oxygen. This paper will address experiments to optimize sensitivity of the sensor. Increasing the flow rate and pressure of NO into the sensing chamber increased the optical absorbance at a high concentration of NO. Increasing the concentration of cytochrome-c increased the sensitivity of the sensor. The sensor is currently sensitive to a minimum concentration of 5 ppm and linear in the range of 5 to 175 ppm. |
class Meta:
model = Article
"""
List all of the fields that could possibly be included in a request
or response, this includes fields specified explicitly above.
"""
fields = ['id', 'title', 'body', 'description', 'tagList',
'author', 'slug', 'published', 'created_at', 'updated_at', ] |
def inject(self, field, expr, offset=0):
variables = list(retrieve_function_carriers(expr)) + [field]
idx_subs, eqns = self._interpolation_indices(variables, offset)
eqns.extend([Inc(field.subs(vsub), expr.subs(vsub) * b)
for b, vsub in zip(self._coefficients, idx_subs)])
return eqns |
<reponame>cstom4994/SourceEngineRebuild
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "BaseVSShader.h"
#include "commandbuilder.h"
#include "vr_distort_texture_ps20.inc"
#include "vr_distort_texture_ps20b.inc"
#include "vr_distort_texture_vs20.inc"
#include "vr_distort_texture_ps30.inc"
#include "vr_distort_texture_vs30.inc"
#include "../materialsystem_global.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class CVRDistortTexture_DX9_Context : public CBasePerMaterialContextData
{
public:
uint8 *m_pStaticCmds;
CCommandBufferBuilder< CFixedCommandStorageBuffer< 1000 > > m_SemiStaticCmdsOut;
void ResetStaticCmds( void )
{
if ( m_pStaticCmds )
{
delete[] m_pStaticCmds;
m_pStaticCmds = NULL;
}
}
CVRDistortTexture_DX9_Context( void )
{
m_pStaticCmds = NULL;
}
~CVRDistortTexture_DX9_Context( void )
{
ResetStaticCmds();
}
};
static const float kAllZeros[ 4 ] = { 0.0f, 0.0f, 0.0f, 0.0f };
BEGIN_VS_SHADER( vr_distort_texture, "Help for warp" )
BEGIN_SHADER_PARAMS
SHADER_PARAM( BASETEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "" )
SHADER_PARAM( DISTORTMAP, SHADER_PARAM_TYPE_TEXTURE, "vr_distort_map", "" )
SHADER_PARAM( USERENDERTARGET, SHADER_PARAM_TYPE_INTEGER, "0", "" )
END_SHADER_PARAMS
SHADER_INIT_PARAMS()
{
}
SHADER_FALLBACK
{
return 0;
}
SHADER_INIT
{
LoadTexture( BASETEXTURE, TEXTUREFLAGS_SRGB );
LoadTexture( DISTORTMAP, TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_NOLOD | TEXTUREFLAGS_NODEBUGOVERRIDE |
TEXTUREFLAGS_SINGLECOPY | TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT );
}
SHADER_DRAW
{
CVRDistortTexture_DX9_Context *pContextData = reinterpret_cast< CVRDistortTexture_DX9_Context *> ( *pContextDataPtr );
bool bNeedRegenStaticCmds = ( !pContextData ) || pShaderShadow;
if ( !pContextData ) // make sure allocated
{
pContextData = new CVRDistortTexture_DX9_Context;
*pContextDataPtr = pContextData;
}
if ( pShaderShadow || bNeedRegenStaticCmds )
{
pContextData->ResetStaticCmds();
CCommandBufferBuilder< CFixedCommandStorageBuffer< 5000 > > staticCmdsBuf;
staticCmdsBuf.BindTexture( this, SHADER_SAMPLER0, BASETEXTURE, -1 );
staticCmdsBuf.BindTexture( this, SHADER_SAMPLER1, DISTORTMAP, -1 );
staticCmdsBuf.End();
// now, copy buf
pContextData->m_pStaticCmds = new uint8[ staticCmdsBuf.Size() ];
memcpy( pContextData->m_pStaticCmds, staticCmdsBuf.Base(), staticCmdsBuf.Size() );
}
if ( pShaderAPI && pContextData->m_bMaterialVarsChanged )
{
// need to regenerate the semistatic cmds
pContextData->m_SemiStaticCmdsOut.Reset();
pContextData->m_bMaterialVarsChanged = false;
pContextData->m_SemiStaticCmdsOut.SetAmbientCubeDynamicStateVertexShader();
pContextData->m_SemiStaticCmdsOut.End();
}
SHADOW_STATE
{
SetInitialShadowState( );
pShaderShadow->EnableDepthWrites( false );
pShaderShadow->EnableDepthTest( false );
pShaderShadow->EnableBlending( false );
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, true );
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true );
pShaderShadow->EnableSRGBWrite( true );
pShaderShadow->EnableAlphaWrites( false );
pShaderShadow->EnableAlphaTest( false );
DefaultFog();
int nFormat = 0;
nFormat |= VERTEX_POSITION;
pShaderShadow->VertexShaderVertexFormat( nFormat, 2, 0, 0 );
if ( !g_pHardwareConfig->SupportsShaderModel_3_0() )
{
DECLARE_STATIC_VERTEX_SHADER( vr_distort_texture_vs20 );
SET_STATIC_VERTEX_SHADER( vr_distort_texture_vs20 );
if ( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_STATIC_PIXEL_SHADER( vr_distort_texture_ps20b );
SET_STATIC_PIXEL_SHADER( vr_distort_texture_ps20b );
}
else
{
DECLARE_STATIC_PIXEL_SHADER( vr_distort_texture_ps20 );
SET_STATIC_PIXEL_SHADER( vr_distort_texture_ps20 );
}
}
else
{
DECLARE_STATIC_VERTEX_SHADER( vr_distort_texture_vs30 );
SET_STATIC_VERTEX_SHADER( vr_distort_texture_vs30 );
DECLARE_STATIC_PIXEL_SHADER( vr_distort_texture_ps30 );
SET_STATIC_PIXEL_SHADER( vr_distort_texture_ps30 );
}
}
DYNAMIC_STATE
{
CCommandBufferBuilder< CFixedCommandStorageBuffer< 1000 > > DynamicCmdsOut;
DynamicCmdsOut.Call( pContextData->m_pStaticCmds );
DynamicCmdsOut.Call( pContextData->m_SemiStaticCmdsOut.Base() );
pShaderAPI->SetDefaultState();
int useRenderTarget = ( params[ USERENDERTARGET ]->GetIntValue() == 0 ) ? 0 : 1;
if ( !g_pHardwareConfig->SupportsShaderModel_3_0() )
{
DECLARE_DYNAMIC_VERTEX_SHADER( vr_distort_texture_vs20 );
SET_DYNAMIC_VERTEX_SHADER( vr_distort_texture_vs20 );
if ( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_DYNAMIC_PIXEL_SHADER( vr_distort_texture_ps20b );
SET_DYNAMIC_PIXEL_SHADER_COMBO( CMBO_USERENDERTARGET, useRenderTarget );
SET_DYNAMIC_PIXEL_SHADER( vr_distort_texture_ps20b );
}
else
{
DECLARE_DYNAMIC_PIXEL_SHADER( vr_distort_texture_ps20 );
SET_DYNAMIC_PIXEL_SHADER_COMBO( CMBO_USERENDERTARGET, useRenderTarget );
SET_DYNAMIC_PIXEL_SHADER( vr_distort_texture_ps20 );
}
}
else
{
DECLARE_DYNAMIC_VERTEX_SHADER( vr_distort_texture_vs30 );
SET_DYNAMIC_VERTEX_SHADER( vr_distort_texture_vs30 );
DECLARE_DYNAMIC_PIXEL_SHADER( vr_distort_texture_ps30 );
SET_DYNAMIC_PIXEL_SHADER_COMBO( CMBO_USERENDERTARGET, useRenderTarget );
SET_DYNAMIC_PIXEL_SHADER( vr_distort_texture_ps30 );
}
DynamicCmdsOut.End();
pShaderAPI->ExecuteCommandBuffer( DynamicCmdsOut.Base() );
}
Draw();
}
END_SHADER
|
/**
* Block until the job finishes executing
*
* @return final job status
* @throws JobManagerException if there is an error while waiting for the job to finish
*/
public StatusOutputType waitForCompletion()
throws JobManagerException {
logger.info("called");
super.waitForCompletion();
try {
GlobusURL baseURL = new GlobusURL(gridFTPBase);
GridFTPClient client = new GridFTPClient(baseURL.getHost(),
baseURL.getPort());
client.authenticate(gssCred);
client.setPassive();
client.setLocalActive();
File wd = new File(workingDir);
String remoteDir = baseURL.getPath() +
File.separator +
wd.getName();
client.changeDir(remoteDir);
Object[] remoteFiles = client.list().toArray();
for (int i = 0; i < remoteFiles.length; i++) {
FileInfo fileInfo = (FileInfo) remoteFiles[i];
if (fileInfo.isFile()) {
String fileName = fileInfo.getName();
logger.info("Staging output file: " + fileName);
UrlCopy uc = new UrlCopy();
uc.setSourceUrl(new GlobusURL(gridFTPBase + "/" +
wd.getName() + "/" +
fileName));
uc.setDestinationUrl(new GlobusURL("file:///" + workingDir + "/" +
fileName));
uc.setCredentials(gssCred);
uc.copy();
}
}
} catch (Exception e) {
String msg = "Exception while staging output files";
logger.error(msg, e);
throw new JobManagerException(msg + " - " + e.getMessage());
}
return status;
} |
package suggest
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/antonjah/leif/internal/pkg/constants"
"github.com/sirupsen/logrus"
)
func GetSuggestion(logger *logrus.Logger) string {
var words []string
resp, err := http.Get(constants.RandomWordApiURL)
if err != nil {
logger.Error(err)
return "Failed to get random word, please check my logs"
}
page, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Error(err)
return "Failed to get random word, please check my logs"
}
err = json.Unmarshal([]byte(page), &words)
if err != nil {
logger.Error(err)
return "Failed to get random word, please check my logs"
}
result := fmt.Sprintf("How about you use '%s'?", strings.Title(words[0])+strings.Title(words[1]))
return result
}
|
package com.dumblthon.messenger.auth.security;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
@Configuration
public class JwtConfiguration {
@Value("${key.store.file}")
private String keyStoreFile;
@Value("${key.store.pass}")
private String keyStorePass;
@Value("${key.alias}")
private String keyAlias;
@Value("${key.pass}")
private String keyPass;
@Value("${key.id}")
private String kid;
@Bean
public RSAKey rsaKey() throws IOException, NoSuchAlgorithmException, KeyStoreException,
CertificateException, UnrecoverableKeyException, JOSEException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
Path path = Paths.get("src/main/resources", keyStoreFile);
FileInputStream pkcs = new FileInputStream(path.toFile());
keyStore.load(pkcs, keyStorePass.toCharArray());
// Given final block not properly padded. Such issues can arise if a bad key is used during decryption
RSAPrivateKey privateKey = (RSAPrivateKey) keyStore.getKey(keyAlias, keyPass.toCharArray());
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyAlias);
RSAKey publicKey = RSAKey.parse(certificate);
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyUse(KeyUse.SIGNATURE)
.algorithm(JWSAlgorithm.RS256)
.keyID(kid)
.build();
}
}
|
/*******************************************************************************
*
* Function avdt_msg_bld_reconfig_cmd
*
* Description This message building function builds a reconfiguration
* command message.
*
*
* Returns void.
*
******************************************************************************/
static void avdt_msg_bld_reconfig_cmd(uint8_t** p, tAVDT_MSG* p_msg) {
AVDT_MSG_BLD_SEID(*p, p_msg->reconfig_cmd.hdr.seid);
p_msg->reconfig_cmd.p_cfg->psc_mask = 0;
avdt_msg_bld_cfg(p, p_msg->reconfig_cmd.p_cfg);
} |
// Copyright (c) 2019 Uber Technologies, 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.
package async
import (
"context"
"sync"
log "github.com/sirupsen/logrus"
)
// Daemon represents a function that we want to start and run continuously until stopped.
type Daemon interface {
// Start starts the daemon. The daemon is running when the underlying
// runnable is started. Start blocks until the runnable is in the running
// state. Otherwise it returns and does not block.
Start()
// Stop stops the daemon. The daemon is running until the underlying
// runnable returns. Stop blocks until the runnable is in state stopped.
// Otherwise it returns and does not block.
Stop()
}
// Runnable represents a runnable function that can return an error.
type Runnable interface {
// Run will run the runnable with a context and return any errors that
// might occur.
Run(ctx context.Context) (err error)
}
type runnable struct {
runFunc func(context.Context) error
}
func (r *runnable) Run(ctx context.Context) (err error) {
return r.runFunc(ctx)
}
// NewRunnable creates a new runnable from a function type.
func NewRunnable(runFunc func(context.Context) error) Runnable {
return &runnable{
runFunc: runFunc,
}
}
// NewDaemon will create a new daemon.
func NewDaemon(name string, runnable Runnable) Daemon {
return &daemon{
condition: sync.NewCond(&sync.Mutex{}),
name: name,
runnable: runnable,
}
}
type status uint
func (s status) String() string {
switch s {
case running:
return "running"
case cancelled:
return "cancelled"
case stopped:
return "stopped"
default:
return "unknown"
}
}
const (
stopped status = iota
running
cancelled
)
type daemon struct {
cancelFunc context.CancelFunc
condition *sync.Cond
status status
name string
runnable Runnable
}
// notifyOfStop will notify the daemon that the runnable stopped running and update the running flag.
func (d *daemon) notifyOfStop() {
d.condition.L.Lock()
defer d.condition.L.Unlock()
d.status = stopped
d.condition.Broadcast()
}
func (d *daemon) Start() {
d.condition.L.Lock()
defer d.condition.L.Unlock()
loop := true
for loop {
switch d.status {
case running:
return
case cancelled:
d.condition.Wait()
case stopped:
loop = false
continue
}
}
// Status is stopped => launch the runnable
ctx, cancelFunc := context.WithCancel(context.Background())
d.cancelFunc = cancelFunc
// Start the runnable
go func() {
defer d.notifyOfStop()
d.runnable.Run(ctx)
}()
d.status = running
d.condition.Broadcast()
log.WithField("name", d.name).
WithField("status", d.status).
Info("Daemon started")
}
func (d *daemon) Stop() {
d.condition.L.Lock()
defer d.condition.L.Unlock()
for {
switch d.status {
case running:
d.status = cancelled
if d.cancelFunc != nil {
d.cancelFunc()
d.cancelFunc = nil
}
d.condition.Wait()
case cancelled:
d.condition.Wait()
case stopped:
log.WithField("name", d.name).
WithField("status", d.status).
Info("Daemon stopped")
return
}
}
}
|
/**this class creates the central panel in which the game is played.
*
*
*/
class guiPanel extends JPanel implements Runnable{
Main_Deck md;
player_deck pl1,pl2;
compPlay cp;
cardArraylist cal;
Image img;
ImageIcon iic;
Thread t;
boolean gameOn=true,playerturn=true;
guiClass gc;
String result,addres="Images/";
int startX=100,startY=600,width,height,mouseX,mouseY,points1,points2,sweep1=0,sweep2=0;
ArrayList<playing_card> mouse,eaten;
guiPanel(guiClass gc){
super();
cp=new compPlay();
mouse=new ArrayList<>();
eaten=new ArrayList<>();
this.gc=gc;
pl1=gc.pl1;
pl2=gc.pl2;
cal=gc.cal;
img=gc.img;
width=img.getWidth(this);
height=img.getHeight(this);
addMouseListener(new MouseActions());
addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseMoved(MouseEvent me){ //displays picked cards
mouseX=me.getX();
mouseY=me.getY();
if(!mouse.isEmpty()){
//System.out.println("inside mousemoved");
repaint();
}
}
});
//setBackground( Color.green );
//setForeground( Color.green );
}
int createdialog(Object[] options){
return JOptionPane.showOptionDialog(this, null, null, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,null,options,options[0]);
}
@Override
public void addNotify(){
super.addNotify();
t=new Thread(this);
t.start();
}
@Override
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true) {
if(pl1.size()==0&&pl2.size()==0){
if(gc.md.size()==0) {
cleanup();
gameOn=false;
}
else gc.redistribute();
}
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = 50 - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
@Override
public void paint(Graphics g){
super.paint(g);
if(gameOn){
setBackground( new Color(0,120,0) );
//test(g);
drawCompcards(g); //displays computer cards
drawArena(g); //displays arena cards
drawplcards(g); //displays player cards
mouseDraw(g); //displays cards picked by mouse
}
else{
draweaten(g); //displays eaten cards
gameOver(); //calculates points
g.drawString(result+" Your points = "+points1+" Computer points = "+points2, 500, 500 );
}
// Toolkit.getDefaultToolkit().sync();
// if(mouse.size()!=0) mouseDraw(g);
}
/*void test(Graphics g){
g.drawImage(img,50,50,this);
}*/
void drawCompcards(Graphics g){
short x=100,y=100;
for(int b=0;b<pl2.size();b++){
if(pl2.visibility(b)){//System.out.println(b);
String name="back.png";
iic=new ImageIcon(addres+name);
img=iic.getImage();
g.drawImage(img,x,y,this);
}
x+=img.getWidth(this)+10;
}
g.setColor(Color.yellow);
g.drawString("Points="+points2, x, y);
}
void mouseDraw(Graphics g){
int x=(mouseX+15),y=mouseY;
for(byte b=0;b<mouse.size();b++){
playing_card pc=mouse.get(b);
String name=(pc.getColor())+"_"+(pc.getNum())+".png";
iic=new ImageIcon(addres+name);
img=iic.getImage();
g.drawImage(img,x,y,this);
y+=18;
}
}
void drawplcards(Graphics g){
int x=startX,y=startY;
for(int b=0;b<pl1.size();b++){
if(pl1.visibility(b)){//System.out.println(b);
String name=(pl1.seeCard(b).getColor())+"_"+(pl1.seeCard(b).getNum())+".png";
iic=new ImageIcon(addres+name);
img=iic.getImage();
g.drawImage(img,x,y,this);
}
x+=img.getWidth(this)+10;
}
g.setColor(Color.yellow);
g.drawString("Points="+points1, x, y);
}
void drawArena(Graphics g){
short x=400,y=300;
for(byte b=0;b<cal.size();b++){
for(byte c=0;c<cal.sizeOfGrp(b);c++){
String name=(cal.getCard(b,c).getColor())+"_"+(cal.getCard(b,c).getNum())+".png";
iic=new ImageIcon(addres+name);
img=iic.getImage();
g.drawImage(img,x,y,this);
y+=18;
}
x+=img.getWidth(this)+10;
y=300;
}
}
void draweaten(Graphics g){
int x=100,y=100;
g.setColor(Color.yellow);
for(byte b=0;b<cp.eaten.size();b++){
String name=(cp.eaten.get(b).getColor())+"_"+(cp.eaten.get(b).getNum())+".png";
iic=new ImageIcon(addres+name);
img=iic.getImage();
g.drawImage(img, x, y, this);
x+=width+10;
if(x+width>this.getWidth()){
x=100;
y+=height+10;
}
}
x=100; y=510;
for(byte b=0;b<eaten.size();b++){
String name=(eaten.get(b).getColor())+"_"+(eaten.get(b).getNum())+".png";
iic=new ImageIcon(addres+name);
img=iic.getImage();
g.drawImage(img, x, y, this);
x+=width+10;
if(x+width>this.getWidth()){
x=100;
y+=height+10;
}
}
}
void cleanup(){
while(cal.size()!=0){
cp.eaten.addAll(cal.removeGrp(0));
}
}
void repair(){
for(byte b=0;b<cal.size();b++){
if(cal.sizeOfGrp(b)>1){
int sum=0;
for(byte c=0;c<cal.sizeOfGrp(b);c++){
sum+=cal.getCard(b, c).getNum();
}
if(sum<=13) {//System.out.println("nascent for "+b);
cal.setType(b, cardArrayBox.nascent);
}
else{//System.out.println("stack for "+b);
cal.setType(b, cardArrayBox.stack);
}
for(byte c=13;c>8;c--){
if(sum==36||sum==60){
break;
}
if(sum%c==0){
cal.setID(b, c);//System.out.println("StackID of "+b+"="+c);
}
}
}
}
}
void changeTurn(){ //enables change of turn
// System.out.println("inside chengeturn");
playerturn=false;
repair();
if(cal.size()==0){
sweep2++;
}
cp.play(pl2, cal);
repair();
if(cal.size()==0){
sweep1++;
}
playerturn=true;
gameOver();
}
void gameOver(){
int sum1=0,sum2=0;
for(byte b=0;b<eaten.size();b++){
if(eaten.get(b).getColor()==4) sum1+=eaten.get(b).getNum();
else{
if(eaten.get(b).getNum()==1) sum1+=eaten.get(b).getNum();
if(eaten.get(b).getNum()==10&&eaten.get(b).getColor()==3)sum1+=eaten.get(b).getNum();
}
}
int s1=sweep1;
while(s1!=0){
sum1-=50;
s1--;
}
for(byte b=0;b<cp.eaten.size();b++){
if(cp.eaten.get(b).getColor()==4) sum2+=cp.eaten.get(b).getNum();
else{
if(cp.eaten.get(b).getNum()==1) sum1+=cp.eaten.get(b).getNum();
if(cp.eaten.get(b).getNum()==10&&cp.eaten.get(b).getColor()==3)sum1+=cp.eaten.get(b).getNum();
}
}
int s2=sweep2;
while(s2!=0){
sum2-=50;
s2--;
}
points1=sum1;
points2=sum2;
if(sum1>sum2)result="You Win";
else result="You Lose";
}
class MouseActions extends MouseAdapter{
@Override
public void mouseClicked(MouseEvent me){
if (playerturn) {
int mx = me.getX();
int my = me.getY();
if(cal.size()==0){
if (my > startY && my < (startY + height) && mx > startX) {
byte b;
for (b = 1; b <= 12; b++) {
if (mx < (startX + (width * b)) + (10 * (b - 1))) {
// System.out.println(pl1.size()+" "+b);
cal.add(pl1.removeCard(b - 1));
// pl1.setVisibilityFalse(b-1);
break;
}
}changeTurn();
}
}else{
if (mouse.isEmpty()) {
if (my > startY && my < (startY + height) && mx > startX) {
byte b;
for (b = 1; b <= 12; b++) {
if (mx < (startX + (width * b)) + (10 * (b - 1))) {
// System.out.println(pl1.size()+" "+b);
mouse.add(pl1.removeCard(b - 1));
// pl1.setVisibilityFalse(b-1);
break;
}
}
}
}
else {
if (mouse.size()==1) {
if (my > startY && my < (startY + height) && mx > startX) {
for (byte b = 1; b <= 12; b++) {
if (mx < (startX + (width * b)) + (10 * (b - 1))) {
// System.out.println(pl1.size()+" "+b);
mouse.add(pl1.removeCard(b - 1));
pl1.addCard(mouse.remove(0), b - 1);
// pl1.setVisibilityFalse(b-1);
break;
}
}
}
}
if (my > 300 && my < (300 + height) && mx > 400) {
for (byte b = 1; b <= cal.size(); b++) {
//System.out.println("mx=" + mx);
if (mx < (400 + (width * b) + 10 * (b - 1))) {
//System.out.println("here");
if (mouse.size()==1) {
Object[] options = {"Eat", "Pick", "make stack", "throw"};
doCard(createdialog(options), b);
break;
} else {
Object[] options = {"Eat", "Pick", "make stack"};
doCard(createdialog(options), b);
break;
}
}
}
}
}
}
}
}
void doCard(int num,int b){
if(num==0){
if(mouse.size()==1){
if(cal.getID(b-1)==mouse.get(0).getNum()){
eaten.addAll(cal.removeGrp(b-1));
eaten.add(mouse.remove(0));
}
else if(cal.getCard(b-1).getNum()==mouse.get(0).getNum()){
eaten.add(cal.removeCard(b-1));
eaten.add(mouse.remove(0));
}
else {num=3;
JOptionPane.showMessageDialog(null, "Illegal Action");
}
}
else{
if (cal.sizeOfGrp(b-1)==1) {
int sum = cal.getCard(b - 1).getNum();
for (byte c = 1; c < mouse.size(); c++) {
sum += mouse.get(c).getNum();
}
//System.out.println("sum=" + sum);
if (sum % mouse.get(0).getNum() == 0) {
eaten.add(cal.removeCard(b - 1));
eaten.addAll(mouse);
mouse.removeAll(mouse);
} else {num=3;
JOptionPane.showMessageDialog(null, "Illegal Action");
}
}
else {
if(cal.getType(b-1)!=cardArrayBox.single){
int sum=cal.getID(b-1);
for(byte c=1;c<mouse.size();c++){
sum+=mouse.get(c).getNum();
}
if(sum%mouse.get(0).getNum()==0){
eaten.addAll(cal.removeGrp(b-1));
eaten.addAll(mouse);
mouse.removeAll(mouse);
}
else {num=3;
JOptionPane.showMessageDialog(null, "Illegal Action");
}
}
else {num=3;
JOptionPane.showMessageDialog(null, "Illegal Action");
}
}
}
}
if(num==1){
mouse.addAll(cal.removeGrp(b-1));
}
if(num==2){
if(cal.sizeOfGrp(b-1)==1){
int sum=cal.getCard(b-1).getNum();
for(byte c=0;c<mouse.size();c++){
sum+=mouse.get(c).getNum();
}
boolean check=false;
for(byte d=9;d<=13;d++){
if(sum==36||sum==60)break;
if(sum%d==0){
for(byte e=0;e<pl1.size();e++){
if(d==pl1.seeCard(e).getNum()) {check=true;
while(!mouse.isEmpty()){
cal.add(mouse.remove(0),b-1);
}
cal.setID(b-1,d);
if(sum==d) cal.setType(b-1,cardArrayBox.nascent);
else cal.setType(b-1,cardArrayBox.stack);
}
}
if(!check) {num=3; check=true;
JOptionPane.showMessageDialog(null, "Illegal Action\nYou do not have "+d+" with you");
}
}
}if(!check) {num=3;
JOptionPane.showMessageDialog(null, "Illegal Stack");
} //System.out.println("StackID="+cal.getID(b-1));
}
else{
if(mouse.size()==1){//System.out.println("mouse="+mouse.get(0).getNum()+" "+cal.getID(b-1));
boolean check=false;
if(mouse.get(0).getNum()==cal.getID(b-1)){
for(byte c=0;c<pl1.size();c++){
if(pl1.seeCard(c).getNum()==cal.getID(b-1)) {check=true;
cal.add(mouse.remove(0),b-1);
break;
}
}if(!check) {num=3;
JOptionPane.showMessageDialog(null, "Illegal Move");
}
}
else if(cal.getType(b-1)==cardArrayBox.nascent){
for(byte c=0;c<pl1.size();c++){
if(pl1.seeCard(c).getNum()==(cal.getID(b-1)+mouse.get(0).getNum())) {check=true;
cal.setID(b-1, (cal.getID(b-1)+mouse.get(0).getNum()));
cal.add(mouse.remove(0),b-1);
break;
}
}if(!check) {num=4;
JOptionPane.showMessageDialog(null, "Illegal Move");
}
}
else {num=3;
JOptionPane.showMessageDialog(null, "Illegal Action");
}
}
else {
int sum = 0;
for (byte c = 0; c < mouse.size(); c++) {
sum += mouse.get(c).getNum();
}
if (sum % cal.getID(b - 1) == 0) {
while (!mouse.isEmpty()) {
cal.add(mouse.remove(0), b - 1);
}
} else {num=3;
JOptionPane.showMessageDialog(null, "Illegal Move");
}
}
}
}
if(num==3){
for(byte c=0;c<mouse.size();c++){
cal.add(mouse.remove(0));
}
}if(num!=1)
changeTurn();
}
}
} |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.favicon;
import android.graphics.Bitmap;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.content_public.browser.WebContents;
/**
* This is a helper class to use favicon_service.cc's functionality.
*
* You can request a favicon image by web page URL. Note that an instance of
* this class should be created & used & destroyed (by destroy()) in the same
* thread due to the C++ base::CancelableTaskTracker class
* requirement.
*/
public class FaviconHelper {
private long mNativeFaviconHelper;
/**
* Callback interface for getting the result from getLocalFaviconImageForURL method.
*/
public interface FaviconImageCallback {
/**
* This method will be called when the result favicon is ready.
* @param image Favicon image.
* @param iconUrl Favicon image's icon url.
*/
@CalledByNative("FaviconImageCallback")
public void onFaviconAvailable(Bitmap image, String iconUrl);
}
/**
* Callback interface for the result of the ensureIconIsAvailable method.
*/
public interface IconAvailabilityCallback {
/**
* This method will be called when the availability of the icon has been checked.
* @param newlyAvailable true if the icon was downloaded and is now available, false if the
* favicon was already there or the download failed.
*/
@CalledByNative("IconAvailabilityCallback")
public void onIconAvailabilityChecked(boolean newlyAvailable);
}
/**
* Allocate and initialize the C++ side of this class.
*/
public FaviconHelper() {
mNativeFaviconHelper = nativeInit();
}
/**
* Clean up the C++ side of this class. After the call, this class instance shouldn't be used.
*/
public void destroy() {
assert mNativeFaviconHelper != 0;
nativeDestroy(mNativeFaviconHelper);
mNativeFaviconHelper = 0;
}
/**
* Get Favicon bitmap for the requested arguments. Retrieves favicons only for pages the user
* has visited on the current device.
* @param profile Profile used for the FaviconService construction.
* @param pageUrl The target Page URL to get the favicon.
* @param desiredSizeInPixel The size of the favicon in pixel we want to get.
* @param faviconImageCallback A method to be called back when the result is available. Note
* that this callback is not called if this method returns false.
* @return True if GetLocalFaviconImageForURL is successfully called.
*/
public boolean getLocalFaviconImageForURL(
Profile profile, String pageUrl, int desiredSizeInPixel,
FaviconImageCallback faviconImageCallback) {
assert mNativeFaviconHelper != 0;
return nativeGetLocalFaviconImageForURL(mNativeFaviconHelper, profile, pageUrl,
desiredSizeInPixel, faviconImageCallback);
}
/**
* Get 16x16 Favicon bitmap for the requested arguments. Only retrives favicons in synced
* session storage. (e.g. favicons synced from other devices).
* TODO(apiccion): provide a way to obtain higher resolution favicons.
* @param profile Profile used for the FaviconService construction.
* @param pageUrl The target Page URL to get the favicon.
* @return 16x16 favicon Bitmap corresponding to the pageUrl.
*/
public Bitmap getSyncedFaviconImageForURL(Profile profile, String pageUrl) {
assert mNativeFaviconHelper != 0;
return nativeGetSyncedFaviconImageForURL(mNativeFaviconHelper, profile, pageUrl);
}
// TODO(jkrcal): Remove these two methods when FaviconHelper is not used any more by
// org.chromium.chrome.browser.suggestions.ImageFetcher. https://crbug.com/751628
/**
* Tries to make sure that the specified icon is available in the cache of the provided profile.
* The icon will we cached as an on-demand favicon.
* @param profile Profile used for the FaviconService construction.
* @param webContents The object used to download the icon.
* @param pageUrl The target Page URL to get the favicon for.
* @param iconUrl The URL of the icon to retrieve.
* @param isLargeIcon Specifies whether the type is kTouchIcon (true) or kFavicon (false).
* @param callback Called when completed (download not needed, finished or failed).
*/
public void ensureIconIsAvailable(Profile profile, WebContents webContents, String pageUrl,
String iconUrl, boolean isLargeIcon, IconAvailabilityCallback callback) {
nativeEnsureIconIsAvailable(mNativeFaviconHelper, profile, webContents, pageUrl, iconUrl,
isLargeIcon, callback);
}
/**
* Mark that the specified on-demand favicon was requested now. This postpones the automatic
* eviction of the favicon from the database.
* @param profile Profile used for the FaviconService construction.
* @param iconUrl The URL of the icon to touch.
*/
public void touchOnDemandFavicon(Profile profile, String iconUrl) {
nativeTouchOnDemandFavicon(mNativeFaviconHelper, profile, iconUrl);
}
private static native long nativeInit();
private static native void nativeDestroy(long nativeFaviconHelper);
private static native boolean nativeGetLocalFaviconImageForURL(long nativeFaviconHelper,
Profile profile, String pageUrl, int desiredSizeInDip,
FaviconImageCallback faviconImageCallback);
private static native Bitmap nativeGetSyncedFaviconImageForURL(long nativeFaviconHelper,
Profile profile, String pageUrl);
private static native void nativeEnsureIconIsAvailable(long nativeFaviconHelper,
Profile profile, WebContents webContents, String pageUrl, String iconUrl,
boolean isLargeIcon, IconAvailabilityCallback callback);
private static native void nativeTouchOnDemandFavicon(
long nativeFaviconHelper, Profile profile, String iconUrl);
}
|
package org.fisco.bcos.channel.client;
import static org.fisco.bcos.web3j.abi.Utils.typeMap;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Semaphore;
import org.fisco.bcos.web3j.abi.FunctionReturnDecoder;
import org.fisco.bcos.web3j.abi.TypeReference;
import org.fisco.bcos.web3j.abi.Utils;
import org.fisco.bcos.web3j.abi.datatypes.Bool;
import org.fisco.bcos.web3j.abi.datatypes.DynamicArray;
import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes;
import org.fisco.bcos.web3j.abi.datatypes.StaticArray;
import org.fisco.bcos.web3j.abi.datatypes.Type;
import org.fisco.bcos.web3j.abi.datatypes.Utf8String;
import org.fisco.bcos.web3j.abi.datatypes.generated.Int16;
import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
import org.fisco.bcos.web3j.abi.datatypes.generated.StaticArray2;
import org.fisco.bcos.web3j.abi.datatypes.generated.Uint16;
import org.fisco.bcos.web3j.crypto.Credentials;
import org.fisco.bcos.web3j.crypto.ECKeyPair;
import org.fisco.bcos.web3j.crypto.gm.GenCredential;
import org.fisco.bcos.web3j.protocol.Web3j;
import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService;
import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CallContractTest {
static Logger logger = LoggerFactory.getLogger(CallContractTest.class);
public static Web3j web3j;
public static ECKeyPair keyPair;
public static Credentials credentials;
public static BigInteger gasPrice = new BigInteger("3000000000");
public static BigInteger gasLimit = new BigInteger("3000000000");
public static void main(String[] args) throws Exception {
try {
// init the Service
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Service service = context.getBean(Service.class);
service.setGroupId(Integer.parseInt(args[0]));
service.run(); // run the daemon service
// init the client keys
credentials = GenCredential.create();
logger.info("-----> start test in CallContractTest!");
ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setTimeout(10 * 1000);
channelEthereumService.setChannelService(service);
web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
if (args.length == 2) {
String address = args[1];
CallContract callContract = new CallContract(credentials, web3j);
System.out.println(
"************************ Test call & sendTrandation ************************");
testSyncCallContract(callContract, address);
testAsyncCallContract(callContract, address);
System.out.println("************************ Test decode ************************");
testDecode(callContract, address);
System.out.println("Test CallContract successfully.");
} else {
System.out.println("Please input group id and contract address.");
}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
System.exit(1);
}
System.exit(0);
}
private static void testSyncCallContract(CallContract callContract, String address) {
CallResult contractResult;
contractResult =
callContract.call(
address,
"getStringOld",
new Utf8String("hello world"),
new Int256(10086),
new Bool(true));
List<TypeReference<?>> referencesList =
Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {});
List<Type> returnList1 =
FunctionReturnDecoder.decode(
contractResult.getOutput(), Utils.convert(referencesList));
System.out.println("call getStringOld: " + (String) returnList1.get(0).getValue());
TransactionReceipt receipt;
receipt =
callContract.sendTransaction(
gasPrice,
gasLimit,
address,
"setAndget",
new Utf8String("hello world"),
new Int256(10086));
referencesList =
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>() {}, new TypeReference<Int256>() {});
List<Type> returnList2 =
FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
System.out.println(
"call setAndget: "
+ (String) returnList2.get(0).getValue()
+ ", "
+ (BigInteger) returnList2.get(1).getValue());
receipt =
callContract.sendTransaction(
address, "setAndget", new Utf8String("hello world"), new Int256(10086));
referencesList =
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>() {}, new TypeReference<Int256>() {});
List<Type> returnList3 =
FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
System.out.println(
"default call setAndget: "
+ (String) returnList3.get(0).getValue()
+ ", "
+ (BigInteger) returnList3.get(1).getValue());
contractResult =
callContract.call(
address,
"getArray",
new StaticArray2(
typeMap(
Arrays.asList(
BigInteger.valueOf(-1), BigInteger.valueOf(2)),
Int16.class)),
new DynamicArray(
typeMap(
Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2)),
Uint16.class)));
List<Type> returnList4 =
callContract.decode(
contractResult.getOutput(),
new TypeReference<StaticArray2<Int16>>() {},
new TypeReference<DynamicArray<Int16>>() {});
System.out.println(
"call getArray: "
+ callContract.convertList((List<Type>) returnList4.get(0).getValue())
+ ", "
+ callContract.convertList((List<Type>) returnList4.get(1).getValue()));
List<List<BigInteger>> dyadicArray = new ArrayList<List<BigInteger>>();
dyadicArray.add(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(2)));
dyadicArray.add(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(992)));
byte[] bytes = new byte[] {'a', 'b'};
contractResult =
callContract.call(
address,
"newTest",
new StaticArray2(typeMap(dyadicArray, StaticArray2.class, Int256.class)),
new DynamicBytes(bytes));
List<Type> returnList5 =
callContract.decode(
contractResult.getOutput(),
new TypeReference<StaticArray2<StaticArray2<Int256>>>() {},
new TypeReference<DynamicBytes>() {});
System.out.println(
"call newTest: "
+ callContract.convertListList(
(List<StaticArray<Int256>>) returnList5.get(0).getValue())
+ ", "
+ new String((byte[]) returnList5.get(1).getValue())
+ ", "
+ dyadicArray);
}
static class TransactionCallback extends TransactionSucCallback {
TransactionCallback() {
try {
semaphore.acquire(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void onResponse(TransactionReceipt receipt) {
this.receipt = receipt;
semaphore.release();
}
public TransactionReceipt receipt;
public Semaphore semaphore = new Semaphore(1, true);
};
private static void testAsyncCallContract(CallContract callContract, String address) {
TransactionCallback callback = new TransactionCallback();
TransactionReceipt receipt;
callContract.asyncSendTransaction(
callback,
gasPrice,
gasLimit,
address,
"setAndget",
new Utf8String("hello world"),
new Int256(10086));
try {
callback.semaphore.acquire(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println(e.getLocalizedMessage());
}
receipt = callback.receipt;
List<TypeReference<?>> referencesList =
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>() {}, new TypeReference<Int256>() {});
List<Type> returnList1 =
FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
System.out.println(
"async call setAndget: "
+ (String) returnList1.get(0).getValue()
+ ", "
+ (BigInteger) returnList1.get(1).getValue());
callContract.asyncSendTransaction(
callback, address, "setAndget", new Utf8String("hello world"), new Int256(10086));
try {
callback.semaphore.acquire(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println(e.getLocalizedMessage());
}
receipt = callback.receipt;
referencesList =
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>() {}, new TypeReference<Int256>() {});
List<Type> returnList2 =
FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
System.out.println(
"default async call setAndget: "
+ (String) returnList2.get(0).getValue()
+ ", "
+ (BigInteger) returnList2.get(1).getValue());
}
private static void testDecode(CallContract callContract, String address) throws Exception {
CallResult contractResult;
contractResult = callContract.call(address, "getInt", new Int256(10086));
System.out.println("Decode Int: " + callContract.decode(contractResult.getOutput(), "Int"));
contractResult = callContract.call(address, "getString", new Utf8String("hello world"));
System.out.println(
"Decode String: " + callContract.decode(contractResult.getOutput(), "String"));
contractResult =
callContract.call(
address,
"getIntArray",
new DynamicArray(
typeMap(
Arrays.asList(
BigInteger.valueOf(110), BigInteger.valueOf(120)),
Int256.class)));
System.out.println(
"Decode IntArray: " + callContract.decode(contractResult.getOutput(), "IntArray"));
contractResult =
callContract.call(
address,
"getStringArray",
new DynamicArray(typeMap(Arrays.asList("hehe", "xixi"), Utf8String.class)));
System.out.println(
"Decode StringArray: "
+ callContract.decode(contractResult.getOutput(), "StringArray"));
contractResult =
callContract.call(
address,
"getAll",
new Int256(10086),
new DynamicArray(
typeMap(
Arrays.asList(
BigInteger.valueOf(110), BigInteger.valueOf(120)),
Int256.class)),
new Utf8String("hello world"),
new DynamicArray(typeMap(Arrays.asList("hehe", "xixi"), Utf8String.class)));
System.out.println(
"Decode All: "
+ callContract.decode(
contractResult.getOutput(), "Int,IntArray,String,StringArray"));
}
}
|
def create_complex_formation(self, verbose=True):
formation_id = "formation_" + self.id
if formation_id in self._model.reactions:
raise ValueError("reaction %s already in model" % formation_id)
formation = ComplexFormation(formation_id)
formation.complex_data_id = self.id
formation._complex_id = self.complex_id
self._model.add_reaction(formation)
formation.update(verbose=verbose) |
Proposal for a smart city index for municipalities in Argentina
The development of smart cities has yielded into a desirable objective among many cities around the world. International indexes of smart cities focus on large urban cities without interest on intermediate cities of developing countries. This paper pretends to fill this gap by proposing a smart city index for the capital cities in Argentina, together with Buenos Aires City and Bahia Blanca. The index is compound of four dimensions: Environment, Governance, Society and ICT, and Mobility and Transport which are based on a set of indicators. Data emerges from official websites and national statistics. In the case of Bahia Blanca, a wider smart city index with subjective indicators from an online survey is built. Alternative versions of the index, weighted (according to the vision of citizens, enterprises and politicians) and non-weighted are provided. Results show that the cities of Bahia Blanca, Ciudad Autonoma de Buenos Aires and Cordoba are the third smartest cities in Argentina. |
<filename>TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/Power_Blue_Pos1_Storage.java
package org.firstinspires.ftc.teamcode.autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.GlobalTelemetry;
import org.firstinspires.ftc.teamcode.odometry.MovementManager;
import org.firstinspires.ftc.teamcode.submodules.RobotHardware;
@Disabled
@Autonomous(name="Power%Blue%Pos1%Storage%Duck:no", group="Blue")
public class Power_Blue_Pos1_Storage extends LinearOpMode {
GlobalTelemetry gt = new GlobalTelemetry(telemetry);
RobotHardware robot = new RobotHardware(gt);
MovementManager move = new MovementManager(robot, gt);
@Override
public void runOpMode() throws InterruptedException {
robot.init(hardwareMap);
telemetry.addData("/> STATUS:", "INIT COMPLETE");
waitForStart();
move.fieldDrive(1, 1, move.powerToAngle(0, 1), 0.3);
sleep(2500);
robot.chassis.stop();
while (opModeIsActive() && getRuntime() < 10){
move.fieldDrive(0,0,move.powerToAngle(0,1), 0.25);
}
robot.chassis.stop();
robot.sound.playAutoComplete();
}
} |
use std::{
io::{self, Read},
net::SocketAddr,
};
pub use hazel::*;
pub use netobjects::*;
pub use objects::*;
pub use packets::*;
use crate::reader::{Deserialize, PacketRead, PacketReader};
mod hazel;
mod netobjects;
mod objects;
mod packets;
impl Deserialize for SocketAddr {
fn deserialize<T: PacketRead + Read>(r: &mut PacketReader<T>) -> io::Result<Self> {
Ok(SocketAddr::from((
[r.read_u8()?, r.read_u8()?, r.read_u8()?, r.read_u8()?],
r.read_u16()?,
)))
}
}
|
def _rsync(self, sources, dest, key, port=22, login=None):
def generateUniq(name):
import time
epoch = int(time.time())
return "%s__%s" % (epoch, name)
sourcelist = list()
if dest.find(":") != -1:
dest = dest if dest.endswith("/") else dest + "/"
sourcelist = [source.rstrip("/") for source in sources if j.do.isDir(source)]
else:
if j.do.isDir(dest):
dest = dest if dest.endswith("/") else dest + "/"
sourcelist = [source.rstrip("/") for source in sources if source.find(":") != -1]
source = ' '.join(sourcelist)
keyloc = "/tmp/%s" % generateUniq('key')
j.system.fs.writeFile(keyloc, key)
j.system.fs.chmod(keyloc, 0o600)
login = login or 'root'
ssh = "-e 'ssh -o StrictHostKeyChecking=no -i %s -p %s -l %s'" % (
keyloc, port, login)
destPath = dest
if dest.find(":") != -1:
destPath = dest.split(':')[1]
verbose = "-q"
if j.application.debug:
print("copy from\n%s\nto\n %s" % (source, dest))
verbose = "-v"
cmd = "rsync -a -u --exclude \"*.pyc\" --rsync-path=\"mkdir -p %s && rsync\" %s %s %s %s" % (
destPath, verbose, ssh, source, dest)
if j.application.debug:
print cmd
j.do.execute(cmd)
j.system.fs.remove(keyloc) |
/**
* Created by Administrator on 2014/10/13.
*/
public class VideoMainActivity extends BaseFragmentActivity {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private TabPagerAdapter adapter;
public List<Fragment> fragments = new ArrayList<Fragment>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_activity_main);
fragments.add(new VideoLocalFragment());
fragments.add(new VideoOnlineFragment());
tabs = (PagerSlidingTabStrip) findViewById(R.id.video_pager_tabs);
pager = (ViewPager) findViewById(R.id.video_pager);
pager.setOffscreenPageLimit(2);
adapter = new TabPagerAdapter(getSupportFragmentManager(), pager, fragments);
pager.setAdapter(adapter);
tabs.setViewPager(pager);
tabs.setTabsStyle(getResources().getDisplayMetrics());
UIHelp.setHeaderMenuView(this, "视频播放");
}
public class TabPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {
private List<Fragment> fragments; // 每个Fragment对应一个Page
private FragmentManager fragmentManager;
private ViewPager viewPager; // viewPager对象
private int currentPageIndex = 0; // 当前page索引(切换之前)
private OnExtraPageChangeListener onExtraPageChangeListener; // ViewPager切换页面时的额外功能添加接口
public TabPagerAdapter(FragmentManager fragmentManager, ViewPager viewPager, List<Fragment> fragments) {
this.fragments = fragments;
this.fragmentManager = fragmentManager;
this.viewPager = viewPager;
this.viewPager.setAdapter(this);
this.viewPager.setOnPageChangeListener(this);
}
private final String[] TITLES = {"本地视频", "网络视频"};
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(fragments.get(position).getView()); // 移出viewpager两边之外的page布局
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = fragments.get(position);
if (!fragment.isAdded()) { // 如果fragment还没有added
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(fragment, "tab_" + position);
ft.commit();
/**
* 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
* 会在进程的主线程中,用异步的方式来执行。
* 如果想要立即执行这个等待中的操作,就要调用这个方法(只能在主线程中调用)。
* 要注意的是,所有的回调和相关的行为都会在这个调用中被执行完成,因此要仔细确认这个方法的调用位置。
*/
fragmentManager.executePendingTransactions();
}
if (fragment.getView().getParent() == null) {
container.addView(fragment.getView()); // 为viewpager增加布局
}
return fragment.getView();
}
/**
* 当前page索引(切换之前)
*
* @return
*/
public int getCurrentPageIndex() {
return currentPageIndex;
}
public OnExtraPageChangeListener getOnExtraPageChangeListener() {
return onExtraPageChangeListener;
}
/**
* 设置页面切换额外功能监听器
*
* @param onExtraPageChangeListener
*/
public void setOnExtraPageChangeListener(OnExtraPageChangeListener onExtraPageChangeListener) {
this.onExtraPageChangeListener = onExtraPageChangeListener;
}
@Override
public void onPageScrolled(int i, float v, int i2) {
if (null != onExtraPageChangeListener) { // 如果设置了额外功能接口
onExtraPageChangeListener.onExtraPageScrolled(i, v, i2);
}
}
@Override
public void onPageSelected(int i) {
fragments.get(currentPageIndex).onPause(); // 调用切换前Fargment的onPause()
if (fragments.get(i).isAdded()) {
fragments.get(i).onResume(); // 调用切换后Fargment的onResume()
}
currentPageIndex = i;
if (null != onExtraPageChangeListener) { // 如果设置了额外功能接口
onExtraPageChangeListener.onExtraPageSelected(i);
}
}
@Override
public void onPageScrollStateChanged(int i) {
if (null != onExtraPageChangeListener) { // 如果设置了额外功能接口
onExtraPageChangeListener.onExtraPageScrollStateChanged(i);
}
}
}
/**
* page切换额外功能接口
*/
public class OnExtraPageChangeListener {
public void onExtraPageScrolled(int i, float v, int i2) {
}
public void onExtraPageSelected(int i) {
}
public void onExtraPageScrollStateChanged(int i) {
}
}
} |
class Receptacle:
'''
A class that stores various ingredients
'''
def __init__(self, name):
self.name = name
self.ingredients = []
def add(self, ingredient):
self.ingredients.append(ingredient)
recipe_maker.add_ingredient(self, ingredient)
def remove_ingredients(self, to_ignore=[]):
names = [ing.name for ing in self.ingredients if ing.name not in to_ignore]
self.ingredients.clear()
return Ingredient('/'.join(names), 1, 'Mixture') |
/*
ardubson.h - Library for the BSON (Binary-JSON) format.
Created by <NAME> (argandas), April 6, 2016.
Released into the public domain.
*/
#include "ardubson.h"
// Constructor /////////////////////////////////////////////////////////////////
BSONObject::BSONObject(char *data)
{
uint32_t size = 0;
memcpy((void *)&size, (void *)data, sizeof(uint32_t));
if ((size > 0) && (size <= BSON_BUFF_SIZE))
{
memcpy((void *)&_objData[0], (void *)data, size);
}
else
{
// Error
// Serial.println("Invalid size");
}
}
// Public Methods //////////////////////////////////////////////////////////////
char *BSONObject::rawData(void)
{
return (char *)&_objData;
}
int32_t BSONObject::len(void)
{
int32_t size = 0;
memcpy((void *)&size, (void *)&_objData[0], sizeof(int32_t));
return size;
}
BSONElement BSONObject::getField(const char *fieldName)
{
char *e_data = NULL;
int e_len = 0;
BSONElement be;
getFieldIndex(fieldName, &e_data, &e_len);
if ((NULL != e_data) && (0 < e_len))
{
return be.Fill(e_data, e_len);
}
else
{
#if 0
Serial.println("key not found!");
Serial.print("e_data = ");
Serial.println((int)e_data);
Serial.print("e_len = ");
Serial.println(e_len);
#endif
return BSONElement(); //Empty result
}
}
void BSONObject::getFieldIndex(const char *fieldName, char **dest, int *size)
{
char *e_data = NULL;
int e_len = 0;
bool key_found = false;
/*
Serial.print("fieldName = ");
Serial.println(fieldName);
*/
// Skip document size field
int32_t off = sizeof(uint32_t);
while ((off + 1) < len())
{
if ((uint32_t)BSON_EOO == _objData[off])
{
break;
}
else
{
// Get next element data type
signed char type = _objData[off];
e_data = &_objData[off];
off++;
e_len = 1;
/*
Serial.print("type = ");
Serial.println(type);
*/
// Check data type range
if ((type > (signed char)BSON_MINKEY) && (type < (signed char)BSON_MAXKEY))
{
// Get element key
char *key = (char *)&_objData[off];
/*
Serial.print("key = ");
Serial.println(key);
*/
off += strlen(key) + 1;
e_len += strlen(key) + 1;
if (type == (char)BSON_TYPE_STRING)
{
// Get field value length
uint32_t string_size = 0;
memcpy((void *)&string_size, (void *)&_objData[off], sizeof(uint32_t));
// Increment field size length
off += sizeof(uint32_t);
e_len += sizeof(uint32_t);
// Increment field value length
off += string_size;
e_len += string_size;
}
else if (type == (char)BSON_TYPE_INT32)
{
// Get value
//int32_t val = *(int32_t *) &_objData[off];
off += sizeof(int32_t);
e_len += sizeof(int32_t);
}
else if (type == (char)BSON_TYPE_INT64)
{
// Get value
//int64_t val = *(int64_t *) &_objData[off];
off += sizeof(int64_t);
e_len += sizeof(int64_t);
}
else if (type == (char)BSON_TYPE_BOOLEAN)
{
// Get value
//char val = *(char *) &_objData[off];
off += sizeof(char);
e_len += sizeof(char);
}
else if (type == (char)BSON_TYPE_NUMBER)
{
// Get value
//float val = doublePacked2Float((byte *) &_objData[off], LSBFIRST);
off += 8;
e_len += 8;
}
if (0 == strcmp(fieldName, key))
{
key_found = true;
break;
}
}
else
{
// Ignore incoming data
break;
}
}
}
if (key_found)
{
*dest = e_data;
*size = e_len;
}
else
{
// Serial.println("key not found");
*dest = NULL;
*size = 0;
}
}
bool BSONObject::updateField(const char *key, int16_t value)
{
return updateField(key, (int32_t)value);
}
bool BSONObject::updateField(const char *key, int32_t value)
{
char *e_data = NULL;
int e_len = 0;
bool result = false;
getFieldIndex(key, &e_data, &e_len);
if ((NULL != e_data) && (0 < e_len))
{
char type = *e_data++;
if (BSON_TYPE_INT32 == type)
{
// Get element key
char *key = e_data;
void *val = (void *)key + strlen(key) + 1;
if (NULL != memcpy(val, (void *)&value, sizeof(int32_t)))
{
result = true;
}
}
#if 0
else
{
Serial.println("type mismatch!");
Serial.print("type = ");
Serial.println(type);
}
}
else
{
Serial.println("key not found!");
Serial.print("e_data = ");
Serial.println((int)e_data);
Serial.print("e_len = ");
Serial.println(e_len);
#endif
}
return result;
}
bool BSONObject::updateField(const char *key, int64_t value)
{
// #helpwanted
(void)key;
(void)value;
return false;
}
bool BSONObject::appendJSON(const char *data)
{
int len = strlen((char *)&_jsonStr);
if (data != NULL)
{
if ((len + strlen(data)) < JSON_MAX_SIZE)
{
strcat((char *)&_jsonStr, data);
}
}
return true;
}
char *BSONObject::jsonString(int decimal_places)
{
/* Clear buffer */
memset(_jsonStr, 0x00, JSON_MAX_SIZE);
appendJSON("{\r\n ");
char *data = (char *)&_objData;
bool first = true;
uint32_t len = *(uint32_t *)data;
data += sizeof(uint32_t);
while ((uint32_t)(data - (char *)&_objData) < len)
{
// Get next element data type
signed char type = *data;
data += sizeof(char);
//Serial.print("type = ");
//Serial.println(type);
// Check data type range
if ((type > (signed char)BSON_MINKEY) && (type < (signed char)BSON_MAXKEY))
{
// Add trailing comma
if (!first)
{
appendJSON(",\r\n ");
}
// Get element key
char *key = data;
data += strlen(key) + 1;
//Serial.print("key = ");
//Serial.println(key);
appendJSON("\"");
appendJSON(key);
appendJSON("\":");
// Switch according to data type
switch (type)
{
case BSON_TYPE_STRING:
{
// Get string size
uint32_t string_size = 0;
memcpy((void *)&string_size, (void *)data, sizeof(uint32_t));
data += sizeof(uint32_t);
appendJSON("\"");
appendJSON(data);
appendJSON("\"");
data += string_size;
break;
}
case BSON_TYPE_INT32:
{
int32_t val = 0;
memcpy((void *)&val, (void *)data, sizeof(int32_t));
data += sizeof(int32_t);
char buff[8];
itoa(val, buff, 10);
appendJSON(buff);
break;
}
case BSON_TYPE_INT64:
{
int64_t val = *(int64_t *)data;
data += sizeof(int64_t);
/* TODO: Fix int64 data type being truncated to int by using itoa() */
char buff[8];
itoa(val, buff, 10);
appendJSON(buff);
break;
}
case BSON_TYPE_NUMBER:
{
float val = doublePacked2Float((byte *)data, LSBFIRST);
data += 8;
appendJSON(String(val, decimal_places).c_str());
break;
}
case BSON_TYPE_BOOLEAN:
{
char val = *(char *)data;
data += sizeof(char);
if (val == 0x1)
{
appendJSON("true");
}
else
{
appendJSON("false");
}
break;
}
default:
appendJSON("NaN");
}
// EOO
if (BSON_EOO == *data)
break;
}
else
{
// Invalid type
appendJSON("NaT");
break;
}
// At least one element has been added
first = false;
}
appendJSON("\r\n}");
return (char *)&_jsonStr;
}
|
Astronomical events are always one of the most fascinating events for everyone. This time a rare lunar eclipse is going to occur on night of 27 September 2015. You must be thinking that lunar eclipse happens many times a year than what is so special about this one. This lunar eclipse is coinciding with one more astronomical event related to moon that is called Supermoon.
The Supermoon is that full moon when the moon is at the closest distance from the Earth called the perigee. The usual distance of moon from the Earth is averagely 384, 399 km but during Supermoon it comes as close as 356, 400 km from Earth. This moon is also called blood moon or Harvest moon in the northern hemisphere. Harvest moon is the full moon falling closest to the autumn equinox. In Southern hemisphere this is first full moon of spring.
Supermoon appears 14 % larger and 33 % brighter than the normal full moon. The Supermoon with lunar eclipse is rare event which happened last time in 1982 and next time will happen in 2033.
During the lunar eclipse, the Earth comes in between the moon and sun in straight line and shadow of Earth fall on moon. The brightness of moon disappears but it does not become completely dark. The light around the Earth through the atmosphere falls on moon and a faint coppery red moon can be seen. The blue color of sunlight gets scattered by the atmosphere of Earth but the red component survives and reaches the surface of moon and thus moon appears coppery red. The exact redness depends on the particles present in the atmosphere of Earth during the lunar eclipse. Sometimes, for example during the volcanic eruption the particles in the atmosphere increases which give rise to deep red color moon.
The lunar eclipse have three stages penumbral eclipse, umbral (partial) eclipse and total eclipse. During penumbral the brightness of moon decrease so slightly that it usually remains unidentified by normal people. During partial eclipse, the moon getting covered by the shadow of Earth. In total eclipse, the moon is completely covered in the shadow of Earth.
In US, Canada, and Central and South America, the eclipse will start on the evening of September 27, 2015. In Europe, South/East Asia, Africa, and the Arctic and in the Pacific, Atlantic and Indian oceans, the eclipse will occur after midnight on September 28, 2015.
The exact timing of lunar eclipse are different for various locations can be looked from the references. The moon eclipse can easily be observed with naked eyes as it is not harmful in any sense. For better view, you can switch off light or go to a place far from lights. Usually lunar eclipse occur after the midnight but this time it is occurring in the evening after sunset for many location which makes observation more comfortable.
I hope you will enjoy, the beautiful view of lunar eclipse. If you want to know more about astronomy please subscribe us for email notification. You may also follow us on facebook, Google Plus or Twitter.
References :
http://earthsky.org/?p=51212
http://www.timeanddate.com/eclipse/lunar/2015-september-28
Save |
def dcount(n):
cnt=0;
while n>0:
n=int(n/10)
cnt+=1
return cnt
w,m,k=raw_input().split()
w=int(w)
m=int(m)
k=int(k)
d=dcount(m)
ten=1
for i in range(d):
ten*=10
cnt=0
while w>(ten-m)*d*k:
cnt+=ten-m
w-=(ten-m)*d*k
d+=1
m=ten
ten*=10
cnt+=w/(d*k)
print cnt |
Predictions for reverberating spectral line from a newly formed black hole accretion disk: case of tidal disruption flares
Tidal Disruption Events (TDEs) can be perfect probes of dormant SMBHs in normal galaxies. During the rising phase, the accretion luminosity can increase by orders of magnitude in several weeks and the emergent ionizing radiation illuminates the fresh accretion flow. In this paper, we simulated the evolution of the expected spectral line profile of iron due to such a flare by using a ray-tracing code with effects of general relativity (GR) taken into account. We found that the time-dependent profile changes significantly with black hole spin, inclination angle with respect to the black-hole equatorial plane, and the expansion velocity of the ionization front. At low values of spin, a"loop"feature appears in the line profile vs. time plot when the inclination is no less than $30^\circ$ and the expansion velocity $v_{\rm exp}$ is no less than half speed of light, due to a shadow in the emission of the truncated disk. In the light curve two peaks occur depending on the inclination angle. At large $v_{\rm exp}$, a shallow"nose"feature may develop ahead of the loop, its duration depends on the expansion velocity and the inclination angle. We explore the entire interval of black hole spin parameter ranging from extreme prograde to extreme retrograde rotation, $-1<a<1$. In the prograde case, a low-energy tail appears to be more pronounced in the evolving centroid energy of the line. Our results demonstrate the importance to search for X-ray spectral lines in the early phase of TDE flares in order to constrain black hole mass and spin, as well as properties of the innermost accretion flow.
INTRODUCTION
X-ray spectroscopy reveals that atoms and ions of iron can produce a strong Fe K spectral line, which is thought to be shaped by relativistic effects as it emerges from the inner regions of an accretion disk. Hard X-ray photons from a hot black hole corona can irradiate the accretion flow. Emission from an irradiated flow then contains the reflection component (see Fabian & Ross 2010, and further references cited therein for a review). The emerging signal includes both the continuum flux and spectral lines, namely, the prominent fluorescent emission. The latter is produced by de-excitation of an atom with a vacancy in the K-shell being filled by an outer electron. The yield of the fluorescent line scales as Z 4 (quartic power of the atomic number), hence the iron fluorescent line is particularly strong. About 80% of the Fe K line photons come directly from the Fe atoms/ions without experiencing scattering.
X-ray spectra have been successfully used to study black holes that are surrounded by an accretion disk. Starving black holes are more difficult to explore. Also when the surrounding material is inactive (e.g. a nonaccreting clumpy torus) then the electromagnetic signatures cannot be employed to reveal the black hole. In such circumstances the immediate vicinity of the black hole horizon can be probed when a star passes too close to the black hole, so that it becomes destroyed in a Tidal Disruption Event (TDE; see Komossa & Greiner 1999;Gezari et al. 2009;Kocsis & Loeb 2014;Komossa 2015, and further references cited therein). The resulting transient accretion is delayed and it occurs much later after the moment of disruption of the star, as the debris material proceeds to the black hole on the viscous time-scale. Eventually, the gas approaches the innermost stable circular orbit and at this stage the enhanced accretion gives us an opportunity to examine the black hole by lighting up its environment and producing distinct spectral signatures.
While predictions for optical spectra have been discussed in more detail (Strubbe & Quataert 2009Komossa 2012), X-rays reach closer to the black hole and relativistically skewed spectral line can strongly constrain the parameters, thus enabling us to explore effects of strong gravity (Chen & Bogdanović 2015).
As the relativistic line is produced near the horizon, the line energy will be influenced by the gravitational redshift and the Doppler effect (Fabian et al. 1989;Laor 1991). Hence, the observed spectral profile will be different from the rest-frame shape of the spectral feature, in particular, the line centroid energy will be shifted (the change towards higher or lower energy is possible depending on parameters; Karas 2006). As a result, the reflected spectra are distorted and the observed iron Kα line profile becomes broad and skewed. Assuming that the flow extends down to the innermost stable circular orbit (ISCO; Bardeen et al. 1972), the emerging spectrum can be used to infer the spin of the central compact object. This has been done for both Galactic black hole X-ray binaries (XRBs; e.g., Miller et al. 2013) and supermassive black holes (SMBHs) in Active Galactic Nuclei (AGNs; e.g., Risaliti et al. 2013). Besides that, the iron line profile can help us probe the geometry of the hard X-ray emitter (Fabian et al. 2002).
The emergent spectral line depends on the ionization state of the gaseous material. As first recognized by , in the case of X-ray irradiation the strength of the resulting line emission is suppressed due to Auger destruction when the ionization parameter ξ (defined as ξ ≡ L/nr 2 , where L is the hard X-ray luminosity, n is the electron number density of the irradiated disk, and r is the radius) is in the range of 100-500. Then the equivalent width of the line increases for ξ 500 due to the presence of Fe XXIV and Fe XXV (the emission lines of iron are dominated by contributions from these two species). At very high ionization state (ξ 5000), the emission line would be suppressed again since a large fraction of the iron atoms are fully ionized (Matt et al. 1993(Matt et al. , 1996Karas et al. 2000).
A detailed shape of the observed (relativistically skewed) line can in principle be used to constrain parameters of the accreting system, in particular, the black hole spin. However, Reynolds & Begelman (1997) showed that there is a degeneracy in determining the spin by time-averaged X-ray spectra. Dovčiak et al. (2004b) demonstrated that the interplay between radius of the inner edge (offset from ISCO) and spin can be disentangled, but only with spectra of very high quality.
On the other hand, in a time-resolved process, the variability of the central hard X-ray sources would "echo" on the irradiated accretion flow. Reynolds et al. (1999) and studied the resulting reverberation features of black hole spin, given the geometry of the X-ray emitting source, and they simulated the resulting response to a δ function flare in AGN. Recently, the promising reverberation technique has become debated in the context of time lags emerging in the new X-ray data (Zoghbi et al. 2010(Zoghbi et al. , 2013. For AGN, the lamp-post model of the irradiated inner accretion disk has been adapted as a suitable working hypothesis (Matt et al. 1991;Martocchia et al. 2000;Miniutti & Fabian 2004). In this scenario the accretion disk is illuminated by a primary source which is located above the disk plane. The frequently-used assumption places the primary source on the common axis of the rotating black hole and the equatorial accretion disk. The source of primary photons represents a corona or a base of the jet. Following an onset of the illumination, the primary photons travel along null geodesics until some of them hit the surface of the accretion disk, where they are reprocessed and the emerging signal (including the reflection spectral line photons) then proceeds toward a distant observer. In such a geometrical set-up, the illuminating light front can effectively move at a superluminal speed across the disk surface. On the other hand, formation of the irradiation source in the lamp-post model could be enhanced by relic inactive (collision-less) plasma structures persisting as remnants of previous accretion episodes (Cremaschini et al. 2013;Cremaschini & Stuchlík 2014;Kovář et al. 2014), including the potential disruption of asteroids and small bodies by the supermassive black holes (Kostić et al. 2009(Kostić et al. , 2012Zubovas et al. 2012).
In the present paper, we investigate a possibility of ionizing the freshly accreted material of debris flow, formed from a disrupted or partially damaged star as well as pre-existent gas near SMBH. This material is activated by X-ray illumination that would be produced near the black hole from a hot corona or a hot inner accretion flow as the accretion rate grows above the Eddington limit.
An expanding ionization region develops and proceeds through the accretion flow. This is thought to be triggered by a TDE in a normal galaxy center, where the induced variation of the spectrum can be revealed more easily than in a typical AGN (the latter would be intrinsically highly variable). In consequence of the changing ionization the spectral line becomes modulated in strength and energy via increasing ionization. Indeed, it occurs that the medium near the central black hole is often in the form of a highly inhomogeneous and clumpy cloudlets which stay undetected unless illuminated by an external source. The actual flare is expected to occur somewhat delayed with respect to the pericenter passage of the affected star, as the illuminating corona builds gradually during the (super)-Eddington phase of fast accretion following the moment of TDE.
A non-negligible radial infall velocity of the accreted material is likely. The ionization front therefore moves radially outward at v = v exp (r) not exceeding the speed of light. We set v exp ≃ const as one of the free model parameters that could be constrained by the observed spectra. The scenario of ionization wave being induced by TDE and launched from the inner disk provides an alternative scheme with a small number of free parameters and somewhat different properties with respect to changing spectral properties of the evolving line.
TDEs near SMBHs
Tidal disruption events (TDEs) can be used to probe the cosmological SMBHs in the centers of inactive galaxies. A TDE occurs if the stellar orbit falls within radius r = R p such that the ratio between stellar surface gravity and tidal acceleration at pericenter, where R p , R ⋆ , M ⋆ and M • are the pericenter radius, stellar radius, stellar mass and the central SMBH mass, respectively (Luminet & Marck 1985;Rees 1988;Evans & Kochanek 1989;Phinney 1989). The exact value of η for the disruption to happen depends on the internal structure, compressibility and rotation of the star (Eggleton 1983). Simulations confirm that, after the disruption, nearly half of the stellar debris should remain on the bound orbit and they would be eventually accreted by the SMBH. Based on the viscous mechanism, the mass fall-back rate is estimated to bė which can significantly exceed the Eddington accretion rate for a period of weeks to years (Strubbe & Quataert 2009. The mass of the SMBHs associated with TDEs is peaked at ∼ 10 6.5 solar mases (Stone & Metzger 2014). The presence of a stellar ring or a secondary intermediate-mass black hole near a SMBH can enhance the TDE rate by increasing the eccentricity fluctuations of stellar trajectories (Vokrouhlický & Karas 1998;Karas &Šubr 2012;Karas et al. 2014;Li et al. 2015).
In the X-ray and Optical/UV bands, ∼ 20 candidate TDEs have been reported (Renzini et al. 1995;Bade et al. 1996;Komossa & Greiner 1999;Greiner et al. 2000;Donley et al. 2002;Gezari et al. 2006Gezari et al. , 2008Gezari et al. , 2009Gezari et al. , 2012Maksym et al. 2010). These events are characterized by thermal emission with temperature of ∼ 10 4 -10 5 K, and the peak bolometric luminosity of about 10 43 -10 45 erg s −1 . For the events with good coverage during the decay, the luminosity decline was consistent with a power-law delay with index of −5/3. Compared with quiescent supermassive black holes (SMBHs), such as Sgr A* in our Galaxy radiating at the level of 10 35 erg s −1 , the luminosity can increase significantly, by several (even up to ten) orders of magnitude during TDE outbursts.
In 2011, two putative TDEs were detected: Swift J1644+57 (e.g., Burrows et al. 2011;Levan et al. 2011;Zauderer et al. 2011) and Swift J2058.4+0516 (e.g., Cenko et al. 2012). Their X-ray spectra showed a powerlaw shape, and the peak luminosity of ∼ 10 48 erg s −1 far exceeded the Eddington limit of a SMBH of a presumed reasonable mass. They also exhibited radio emission with isotropic luminosity of ∼ 10 42 erg s −1 . These are believed to be due to a relativistic jet viewed at a very small angle. The amplitude was very large in these two cases. For Swift J1644+57 the ROSAT 3σ upper limit was 2.4 × 10 −13 erg s −1 cm −2 , and the peak flux during the outburst was ∼ 5.0 × 10 −9 erg s −1 cm −2 (Burrows et al. 2011), showing an amplitude of more then four orders of magnitude. For Swift J2058.4+0516, the ROSAT upper limit was ∼ 10 −13 erg s −1 cm −2 while the peak flux during outburst was ∼ 10 −10 erg s −1 cm −2 , showing fluctuations with amplitude of three orders of magnitude.
TDEs can be revealed with a better chance in sources where the central supermassive black hole is not fed by vigorous accretion (Saxton & Komossa 2012). In this context, AGN have been an unfavored type of objects to reveal tidal disruptions because accretion is an inherently variable process which can hide signatures of TDEs. The X-ray light curve of a typical AGN varies on multiple time-scales, and so a sporadic flare by a TDE can hardly be discovered in the background of stochastic fluctuations due to the intrinsic properties of the accretion flow. Relatively quiet low-luminosity nuclei appear to be more suitable for this task.
Follow-up optical spectroscopy observations can give additional information on characteristics to TDE host galaxies (e.g., Komossa et al. 2004;Clausen et al. 2012;Wang et al. 2012). Here we propose that the evolving X-ray spectral line profile expected in the very early phase of TDE accretion flares can provide a unique probe of the SMBHs in an otherwise inactive galaxy. Well after the tidal disruption happens, an accretion disk forms from the circularized flow of debris. The subsequent evolution is crucial for understanding the light curves in TDE events (Shen & Matzner 2014).
The accretion of the debris material starts from low accretion rates and it continues all the way to super-Eddington rates during the rising phase of TDEs. In the early rising phase, the accretion process is expected to proceed in the regimes of radiatively inefficient/hot accretion. The resulting signal mimics the one seen in many AGN where the lamp-post model has been applied to model the irradiation of the disk. A newly formed accretion disk will become ionized when the source reaches and exceeds the Eddington luminosity. Figure 1. A schematic representation of a "partially ionized accretion flow", where an ionisation wave front is launched from around the inner edge and proceeds outwards. The stellar disruption causes enhanced accretion onto SMBH which can reach and exceed the super-Eddington rate. At time t after the onset of TDE flare, the ionised region expands to radius r ≃ vexp t. The inner disk is fully ionized and no iron line emission can emerge; only the outer part can produce the line emission. The fully ionized inner disk and partially ionized outer ring are plotted in dark and light gray colors, respectively.
The idea of this investigation is based on the fact that an instantaneous illumination and the resulting release of radiation energy by the event occurring near the center (at the tidal radius R p of the supermassive black hole) shall induce an ionizing front that propagates outwards and changes the ionization state of the accretion disk. Consequently, it also influences the spectral line emissivity in a very specific manner. The proposed approach offers an interesting opportunity, nevertheless, it is a challenge because the iron line flux is probably weak in TDEs, even in underluminous nuclei with a low accretion rate and no prior accretion disk.
We constructed a simplified scheme to simulate the response of the fluorescent iron line to the central TDE flare, where the rising edge of the TDE flare can be the perfect illuminating signal for reverberation mapping purposes. The advantage of our description is the parameterization of the model by only a small number of free parameters. The main purpose of this work is to identify characteristic patterns in the line emission, not only limited to iron lines, that may be used to probe SMBH mass and spin via general relativistic effects in TDEs. These are thought to be rare events by their nature, however, the main advantage is that they can be used to explore SMBH in otherwise non-active galaxies and therefore these systems have a potential advantage of being more clean than AGN. On the other hand, different but related aspects of complex iron-line diagnostics have been discussed in the context of binary black-hole mergers (e.g., McKernan et al. 2013).
Signatures of Expanding Ionization Front
In the following we denote the gravitational constant G, the mass of the supermassive black hole M , and the speed of light c (units of radius, time and velocity are GM/c 2 , GM/c 3 and c, respectively).
Because in the rising phase of TDE accretion flares the continuum flux can vary in a large range, we adopt a correspondingly wide range of ionization into consideration Goosmann et al. 2006). For a 10 6 M ⊙ SMBH, the peak mass fall-back rate can reach ∼ 1.5 M ⊙ yr −1 (Evans & Kochanek 1989), corresponding to the luminosity of 8.5 × 10 45 erg s −1 with the radiation efficiency of 0.1.
For a particular ring centered at radius r in the equatorial plane, the ionization parameter at time t is ξ(t) = L(t − δt)/(nr 2 ), where L(t ′ ) denotes the luminosity of the irradiating emission at time t ′ . The fluorescent emission of the ring is expected to vary corresponding to the change of the central engine, but with a delay δt which accounts for the photon traveling from the center to the ring. The reverberating fluorescent emission emerges at t = t 0 + δt where t 0 is the time of the outburst onset, and it disappears after t 1 when ξ(t 1 ) = L(t 1 − δt)/(nr 2 ) ∼ 5000. Looking at the entire disk, during the outburst rise, the iron line emission is localized to a ring composed of partially ionized medium. Outside the ring the photons have not arrived yet; inside the ring the accretion flow is fully ionized. This partially ionized region expands with time ( Figure 1 illustrates this scheme).
The expansion velocity v exp of the "partially ionized ring" depends on the height h of the illuminating source: v exp = 1 + h 2 /r 2 . If the source lies near the equatorial plane, v exp is close to speed of light (for an illuminating source above the equatorial plane, the expansion would appear even superluminal). The infall velocity cannot be neglected at high accretion rates when v exp would be equal 1 − v r , and hence less than unity.
Assumptions and the Model Set-Up
In the local frame the line-emitting region is confined in a ring area of the disk. In the simulation we simplified the region to be a ring of narrow width (about unity in terms of gravitational radii), and the irradiating source flux evolves as a step-function profile. In this scenario the width of the ionization ring relies on the shape of the rising edge. Then we computed the emerging time-resolved iron line profiles, as observed by a distant observer.
For simplicity we assumed a rotating planar disk representing a geometrically-thin Keplerian accretion disk formed from the TDE debris material, extending down to ISCO when we see the X-ray emission associated with the TDE. The outer boundary of the disk in our code was set to be 1000, which is large enough to investigate the current reverberation problem for our purposes. The radial power-law emissivity index was set to 3 (the Newtonian value at large radii; Vaughan et al. 2004). We assumed the iron line emission to be locally isotropic. Detailed analysis of the angular distribution of the line emission (Svoboda et al. 2009;Garcia et al. 2014) showed that it is likely to exhibit a weakly limb-brightening dependence, with maximum ratio of only ∼2 compared to an isotropic assumption. This is less extreme then I ∝ ln(1 + 1/µ), which is another commonly assumed law for the angular dependence of an X-ray illuminated slab (Haardt 1993). Hence, our assumption of isotropic emission would not change the result very much. We assumed the line to be intrinsically narrow and its profile to be a δ-function in energy centered at 6.4 keV, i.e., the laboratory energy of Fe I Kα. The results for spectral lines at different energies can be inferred from our simulation.
With all the assumptions above, the local emissivity is This is obviously a rather simplistic parameterisation of a much more complicated situation, nonetheless, we find it useful for the sake of demonstrating the role of GR effects in the context of wave perturbation that is launched from the inner rim of the disk and then starts travelling outwards.
3.2. Ray tracing of the emission from an expanding ionization region near a black hole The basic properties of black hole X-ray spectra from the innermost regions of an accretion disc are well-known (Fabian et al. 2000;Reynolds & Nowak 2003). Gravitational effects act on the spectral features from black-hole accretion disks and coronae by smearing their spectral features and moving them across energy bins. In this way gravity exerts the influence on the ultimate form of the observed spectrum (Cunningham & Bardeen 1973;Cunningham 1975;Karas 2006). The reprocessed radiation reaches the observer from different regions of the system. Furthermore, as strong-gravity plays a crucial role, photons emitted at the same moment may even follow multiple separate paths, joining each other at the observer at different moments. Individual rays experience diverse time lags for purely geometrical reasons, for relativistic time-dilation, and by repressing within the medium.
To simulate the evolution of the observed spectral line, we have employed the general-relativistic ray-tracing method (KYcode; Dovčiak et al. 2004aDovčiak et al. , 2004b. This code uses pre-calculated information about the form of light rays (i.e., the geometrical shape and the timing relations along null geodesics, which describe the photon propagation in the approximation of geometrical optics). A fine grid is used with multiple scales that allow us to reproduce the effects of varying energy shifts, gravitational lensing near caustics, frame-dragging near the ergosphere, and time delays in the gravitational field of a rotating (Kerr) black hole (dimensionless spin parameter −1 ≤ a ≤ 1).
First, the source of the emerging signal is represented by an expanding ionization wave launched in the equato- Figure 2. Contour lines of redshift factor g(r, φ) ≡ E obs /E loc in the equatorial plane of a rotating black hole for several values of its spin (rows) and of observer's inclination (columns). In this plot the black hole rotates in both clockwise (a > 0) and counter-clockwise (a < 0) sense, as indicated (a = 0 is the static case with zero angular momentum). The radiating atoms follow Keplerian circular motion around the black hole, while a distant observer has the line-of-sight directed downward. In each panel the black circle in the middle indicates the location of ISCO. The value of g is color coded, as indicated by the color bar to the right of the figure. rial plane, as introduced in the previous section and further detailed below in Sec. 4. The resulting spectra and the corresponding light curves are produced in the form predicted for a distant observer, i.e., as they are expected to be recorded at the detector plane (defined by the viewangle inclination with respect to the black hole rotation axis) at radial infinity. The code uses the relevant functions stored in FITS files, so that the subsequent computations of the spectral changes are performed in very efficient manner. This allows us to reconstruct the impact of energy shifts (both the Doppler red/blue shifts due to positive/negative component of motion along the line of sight, as well as the overall gravitational red shift near the horizon), light focusing, and the photon travel time from the point of emission towards an observer far from the source.
We have set-up a grid of the interpolation mesh with respect to relevant variables: black-hole spin, the inclination angle, and the expansion velocity of the front. For the spin we select exemplary values of a = −0.998, −0.5, 0, 0.25, 0.5, 0.75, and 0.998. Both prograde (co-rotating, a > 0) and retrograde (counter-rotating, a < 0) cases are investigated in this work. This covers the entire range of spin values that allow for the black hole horizon, while assuming that the inner rim is linked with the ISCO radius (the latter recedes in the retrograde case, and so the relativistic effects become less important). 1 For the inclination angle we adopt the grid 1 In principle, the values of |a| > 1 should not be excluded from values in the range from i = 0 (corresponding to the rotation axis) up to i = 85 • (almost edge-on view), with the resolution of 5 • . For the expansion velocity, we set the reference value at v exp = 1 (corresponding to the case of an illuminating source lying in the disk plane and the ionization taking effect immediately), and we show v exp = 0.5 and 0.75. These allow us to take the effects of accreted debris radial inflow into account. For reference and comparison we also calculated the case of v exp = 1.2 and 2.0 which can represent the superluminal expansion for an illuminating source located above the disc plane, such as the case of lamp-post scenario in Kerr metric (Martocchia et al. 2000).
Let us note that the constant value of the expansion velocity v exp = const is introduced to illustrate the expected dependencies and it serves as a simplified parameterisation. In a realistic description the ionisation front will proceed in the interaction with the inflowing material, which exhibits a radially dependent infall velocity. Also, the relativistic effects will modify the simplistic scheme. Nevertheless, even the lamp-post scenario finds its phenomenological substantiation as it can mimic the role of the inner accretion disk self-irradiation, where the light-bending causes an additional energy input impinging onto the disk surface predominantly over the location on the disk axis at distance of roughly the light circle the analysis a priori, however, we do not consider this possibility because then a naked singularity develops and this would bring us beyond the standard scenario of black-hole accretion (work in progress). (3GM/c 2 for a = 0). For this reason we think it is useful to explore the entire range of v exp from small values to greater than unity.
RESULTS
We show how the different values of black hole spin, inclination angle and expansion velocity affect the evolution of the relativistic spectral line emission as predicted in this model.
To better understand where the features in the timeresolved line profile originate, we first illustrate the distribution of redshift and time delays for photons emitted in the equatorial disk in Kerr space-time for different values of black-hole spin a and observer's inclination angle i. These functions then determine the time-dependent profiles of the iron line. Figure 2 shows the distribution of the redshift on the equatorial disk plane, for different values of a and i. The redshift g(r, φ) = E obs /E loc is affected by both gravitational field of the central black hole and also the Keplerian circular motion of the disk. The redshift function reaches minimum in the innermost region of the accretion flow, which is closest to the black hole (see the bottom panels of Fig. 2, where a = 0.998 and the ISCO lies on r = 1.23). The redshift factor can be as small as ∼ 0.2 in the inner region around ISCO. Photons emitted from this area contribute to the extended red wing of the broad iron line in X-ray spectra of AGNs and galactic XRBs. The Doppler effect is more profound for large inclination angle edge-on systems, as the component of the velocity along the line-of-sight increases with the inclination. Fig. 3 shows the effect of purely geometrical (general relativistic) relative time delay of photons arriving from the equatorial plane. In the case of prograde rapidly rotating black hole (a = 0.998, the bottom panels), the spectral-line photons experience large time-delays in the inner disk. For the high inclination systems (i = 85 • ; right panels), the photons from behind the black hole are delayed when they pass the black hole. In the extreme case of both large inclination and rapidly rotating black hole (the right-bottom panel), the frame-dragging effect is also seen.
In Figures 4-6 we show the time-resolved line profile, both for Schwarzschild (a = 0) and extreme Kerr black holes (a = 0.998, −0.998). We set zero time as mean time, defined by t 0 = t f (t)dt/ f (t) dt where f (t) denotes the photon counts recorded at the detector plane. 2 The corresponding lightcurves are shown in figure 7, where Schwarzschild and Kerr cases are plotted in dash-dotted and solid lines, respectively. Let us note that here we show the (computed) light curves of the background-subtracted model; hence, the plot exhibits the expected variation of that part of the observed signal restricted to the energy of the iron line emission.
To characterize the changing profile we employ the line centroid energy, where E is the photon energy, and f (E) is the photon number density flux in the line, both of which are measured with respect to the observer's frame. While the details of the evolving spectrum are telling about GR effects from the theoretical point of view, the centroid energy provides a robust characteristic that can be compared with observation. For the Schwarzschild black hole case at i = 5 • (i.e. viewed almost along the symmetry axis), the iron line has a narrow profile at any time and the line energy increases with time asymptotically towards the rest-frame value. As the inclination angle increases from 5 • to 85 • (close to an edge-on view), the observed line profile at any time becomes broadened due to an increasing velocity component of the disk material along the line of sight.
Once v exp ≥ 0.5 and i ≥ 30 • , a loop is seen in the line profile vs. time plot (see Figs. 4-6). The time span of the loop increases with the inclination angle. At v exp 1.0, two peaks can be seen in the line lightcurve, as shown in Fig. 7, and the first and the second peaks correspond to the left and the right edges of the loop, respectively.
We computed the time span of the two peaks and we found that their time difference stays roughly constant with varying expansion velocity. For example, when i = 60 • , the time separation is 13.8, 13.6, 13.4 for v exp = 1.0, 1.2 and 2.0, respectively. On the other hand, the time separation and intensity ratio of the two peaks depend on the inclination. The mean time separation (v exp = 1.0, 1.2 and 2.0) is 7.1, 13.6 and 17.3 for i = 30 • , 60 • , and 85 • . The intensity ratio of the first to the second peak decreases with the inclination angle in most cases. During the first peak, a dip occurs in the centroid-energy evolution, and between the two peaks the centroid energy exhibits a bump (see Figure 8).
The time delay between the central TDE X-ray irradiating flare and the induced iron line is denoted as ∆t and contributed by two factors: the first one is the expansion time, t exp ≃ r/v exp , and the second one is the travel time needed from the disk to the observer, t delay (Fig. 3). At large radius where the spacetime is flat to a good precision, t delay ≃ −r sin φ + const, where φ is the azimuthal angle on the disk plane. As v exp is of the order of unity, the two are comparable, and ∆t is dominated by the longer one. Hence in the case of v exp ≥ 1, ∆t is dominated by t delay .
At large inclination angles, the photons originating from the disk in front of the black hole reach the observer first, then come those photons from the disk near ISCO, and the last are those photons from the disk behind the black hole. The loop feature in the line profile vs. time plot is seen due to the existence of a hole (due to our assumption that the disk would be truncated inside the ISCO). The left edge of the loop corresponds to the innermost isochronous disk plane unaffected by ISCO in front of the black hole, and the right edge of the loop corresponds to the innermost isochronous plane unaffected by ISCO behind the black hole. Roughly, the time span of the loop equals to l ∼ 2r ISCO sin i (where r ISCO is the radius of the ISCO), which is consistent with the time separation between the two observed line intensity peaks in the light curve.
The relative intensity of the second peak is enhanced for large inclination angles as it is formed mainly by the photons emerging from the disk behind the black hole (that get more focused at high inclinations). In the case of low expansion velocity, ∆t is dominated by t exp , and the observed image of the emission region expands outwards from the ISCO. In the cases of high expansion velocity combined with high inclination angle, there are "noses" occurring ahead of the loop. In these cases, the observed image of the emission region first expands outside the ISCO and only later on reaches the region below the ISCO. This expansion creates the nose that is followed by the loop and two intensity peaks are visible in the light curve at the time when the image reaches and subsequently leaves the ISCO.
The duration of the nose increases with inclination angle, and with the expansion velocity as well. The noses are contributed by photons emerging from the disk in front of the black hole. Higher inclination and larger expansion velocity cause that the first image of the emission region comes from further away from the centre which prolongs the nose in time-energy graphs. The centroid energy of the noses is close to the rest frame energy of 6.4 keV (this is also reflected in Figs. 4-6).
Comparing with the Schwarzschild case, in extreme Kerr black hole cases, the line energy can extend to both lower and higher energies, due to stronger gravitational Figure 6. As in the previous figure, but for a counter-rotating black hole (spin a = −0.998). Unlike the previous figure, retrograde rotation means that the accreted material has its angular momentum opposite to the black hole. This leads to receding ISCO radius, and therefore decreasing the span of energy that the event covers in the plot above in comparison with the case of prograde rotation. and Doppler energy shifts as the inner edge shrinks with increasing spin. The loop feature is no longer seen, while the nose stays unaffected.
At v exp 0.5 speed of light, a low-energy tail appears in the profile (see Fig. 5). A similar signature has been noticed for Kerr black holes . As the inner edge is very close to the black hole, the photons from this region of the disk suffer from large time delays (see bottom panels of Fig. 3) and strong gravitational redshift (see bottom panels of Fig. 2), and for this region ∆t is dominated by t delay at v exp ≥ 0.5. These two contributing effects produce the delayed low-energy tail. As a result, the two intensity peaks do not develop in the light curve, while a dip remains to be seen in the centroid energy evolution.
DISCUSSION AND CONCLUSIONS
We simulated the time-resolved iron-line profiles from TDE flares, as they are expected to be seen in a distant observer's frame. Because the maximum mass fall-back rate can be supper-Eddington in TDEs, a large range of luminosity is expected in these events. Hence, the energetic photons from the central region can bring the accretion flow to high ionization state. The rising edge of TDE flares can produce and modulate the fluorescent iron line. The line emission would disappear in the accretion flow where the disk material is highly ionized (in terms of ξ 5000).
We explored a simple parameterization according to which the velocity of a moving ionization front v exp defines a different kind of variable compared to the more standard height h of the lamp-post scenario. Other parameters of the model are the black hole spin a (Kerr metric is assumed) and the line-of-sight view angle i of the system. Motivation of the model set-up arises in the context of spectral-line reverberation mapping of the spectral line from the debris disk illuminated after a tidal-disruption event. We suggest that this scheme can be useful to study the properties of tentative TDEs, where the emerging spectral line is modified by an outward propagating circle which grows and changes the line emissivity. The accretion process is expected to be highly non-stationary in such a situation.
We conclude that notable signatures can be expected: (i)-For i 30 • , v exp 1, and small or negative (retrograde) spin, a loop feature appears in iron line profile Figure 7. The observed count rates in the fluorescent iron line (as computed by our ray-tracing method, background subtracted), for different inclination angles i and expansion velocity vexp, as indicated at each corresponding row and column, respectively. The dash-dotted, solid, and dotted lines correspond to the extreme retrograde Kerr (a = −0.998), non-rotating Schwarzschild (a = 0), and extreme prograde Kerr (a = 0.998) black holes, respectively. Each lightcurve is normalized by its maximum value.
vs. time plot and it manifests itself in the line flux showing two peaks in the corresponding light curve. The time separation and intensity ratio of the two peaks mainly depend on the inclination angle. For large values of positive (prograde) spin parameter, the radiation emitted close above the horizon destroys the loop (see also the point (iii) below).
(ii)-For large expansion velocities of the ionization circle and large inclination angles, a nose appears ahead of the loop in the iron line profile vs. time plot. The duration of the nose is determined by both the expansion velocity and the inclination angle.
(iii)-For v exp 0.5 and a → 1 (extreme prograde rotation), a more prominent low-energy tail is seen. Occurrence of this feature can serve as a probe of the fastrotating Kerr black hole. On the other hand, in the nonrotating and retrograde cases the low-energy tail is suppressed and it happens earlier in time.
Let us note that the retrograde sense of rotation is often dismissed in accretion disk modelling and spectra fitting because it appears to be less likely compared to the prograde case. It can be argued that the long-term evolution the accretion flow tends to align the angular momentum vector of the flow with that of the black hole. However, the situation with TDEs is quite different (Sochora et al. 2011). An infalling star approaches the central SMBH from the surrounding nuclear star-cluster, which can be considered as spherical and isotropic in zero approximation, and so counter-rotating motion is equally possible as co-rotating with the black hole. Furthermore, counter-rotating stellar rings and disks have been reported in some galaxies, so we included this possibility in our considerations.
Once a TDE-induced relativistic line is detected and its parameters reliably determined in the future, these signatures in time-resolved signal can be used to constrain the black hole spin, inclination, and the expansion velocity of the ionization front.
We would like to thank the anonymous referee for useful comments. This work was supported in part by the National Natural Science Foundation of China under grant No. 11073043, 11333005, and 11350110498, by Strategic Priority Research Programme "The Emergence of Cosmological Structures" under grant No. XDB09000000, and the XTP project No. XDA04060604, by the Shanghai Astronomical Observatory Key Project, and by the Chinese Academy of Sciences Fellowship for Young International Scientists Grant. VK thanks to Czech Science Foundation -Deutsche Forschungsgemeinschaft project (GAČR 13-00070J) and the scientific exchange programme MŠMT-Kontakt (LH14049), titled "Spectral and Timing Properties of Cosmic Black Holes". MD acknowledges continued support from EU 7th Framework Programme No. 312789 "StrongGravity". |
/**************************************************************************/
/**
* Free a vNIC Use.
*
* Free off the ::MEASUREMENT_VNIC_USE supplied. Will free all the contained
* allocated memory.
*
* @note It does not free the vNIC Use itself, since that may be part of a
* larger structure.
*****************************************************************************/
void evel_free_measurement_vnic_use(MEASUREMENT_VNIC_USE * const vnic_use)
{
EVEL_ENTER();
assert(vnic_use != NULL);
assert(vnic_use->vnic_id != NULL);
free(vnic_use->vnic_id);
vnic_use->vnic_id = NULL;
EVEL_EXIT();
} |
def logp(value, mu):
lam = at.inv(mu)
return bound(
at.log(lam) - lam * value,
value >= 0,
lam > 0,
) |
/**
* @func Initialize the RFID subsystem
*
* @todo Move this routine into new nfc.c/h module and get rid of extra layers
*/
void initRFID(void) {
#ifdef _15693_1of256
initialize_1outof256();
initialize_15693_protocol();
initialize_hdr();
#else
initialize_14443_B_protocol();
initialize_nfc_wisp_protocol();
initialize_bpsk();
#endif
} |
/*
Attempt1: Lintcode 83% correct, but Does not work for : [9876141516171818818181890001988181700198181778786761256512651653145345143, 55]
my output: 1111111134143
expect: 1111111345143
Not sure where went wrong.
Thoughts:
This seems to be: Pick (N - k) digits and make a smallest number, without changing the order of digits.
Create an array with length == (N - k): digits
Starting from i = 0, digits[0] = A.charAt[0] - '0'
if A[i] < digits[i] , replace digits[i] with A[i]
Note: here loop through (N - k) and see if the A[i] can be put anywhere
Note: handle prefix '0' in string
*/
public class Solution {
public static String DeleteDigits(String A, int k) {
if (A == null || A.length() == 0 || k < 0) {
return A;
}
int n = A.length() - k;
//System.out.println(A.length() + " " + n);
int[] digits = new int[n];
for (int j = 0; j < n; j++) {
digits[j] = -1;
}
int[] backup = Arrays.copyOf(digits, digits.length);
for (int i = 0; i < A.length(); i++) {
int digit = (int)(A.charAt(i) - '0');
for (int j = 0; j < n; j++) {
if ((digit < digits[j] || digits[j] < 0) && (A.length() - i) >= (n - j)) {
//System.out.println(j + " " + digit + " | " + (A.length() - i) + " " + (n - j));
if (j == 0) {
digits = Arrays.copyOf(backup, backup.length);
}
digits[j] = digit;
break;
}
}
}
//System.out.println(Arrays.toString(digits));
String rst = "";
for (int j = 0; j < n; j++) {
if (rst.length() == 0 && digits[j] == 0) {
continue;
} else {
rst += digits[j];
}
}
return rst;
}
} |
<filename>towerapi/towerapi.go
package towerapi
import (
"net/http"
"os"
"github.com/mpeter/go-towerapi/towerapi/authtoken"
"github.com/mpeter/go-towerapi/towerapi/credentials"
"github.com/mpeter/go-towerapi/towerapi/errors"
"github.com/mpeter/go-towerapi/towerapi/groups"
"github.com/mpeter/go-towerapi/towerapi/hosts"
"github.com/mpeter/go-towerapi/towerapi/inventories"
"github.com/mpeter/go-towerapi/towerapi/job_templates"
"github.com/mpeter/go-towerapi/towerapi/organizations"
"github.com/mpeter/go-towerapi/towerapi/projects"
"github.com/mpeter/sling"
)
const (
libraryVersion = "0.1.0"
userAgent = "go-towerapi/" + libraryVersion
mediaType = "application/json"
defaultEndpoint = "http://localhost/api/v1/"
defaultUsername = "admin"
defaultPassword = "<PASSWORD>"
)
// Client manages communication with Ansible Tower V1 API.
type Client struct {
// HTTP client used to communicate with the Ansible Tower API.
sling *sling.Sling
// AuthToken obtained from calling Ansible Tower API /authtoken/ endpoint
Token *authtoken.AuthToken
// User agent for client
UserAgent string
// Services used for communicating with the API
AuthToken *authtoken.Service
Credentials *credentials.Service
Groups *groups.Service
Hosts *hosts.Service
Inventories *inventories.Service
JobTemplates *job_templates.Service
Organizations *organizations.Service
Projects *projects.Service
//ActivityStream *ActivityStreamService
//AdHocCommands *AdHocCommandsService
//Config *ConfigService
//Dashboard *DashboardService
//InventoryScripts *InventoryScriptsService
//InventorySources *InventorySourcesService
//JobEvents *JobEventsService
//Jobs *JobsService
//Labels *LabelsService
//Me *MeService
//NotificationTemplates *NotificationTemplatesService
//Notifications *NotificationsService
//Ping *PingService
//Projects *ProjectsService
//Roles *RolesService
//Schedules *SchedulesService
//SystemJobTemplates *SystemJobTemplatesService
//SystemJobs *SystemJobsService
//Teams *TeamsService
//UnifiedJobTemplates *UnifiedJobTemplatesService
//UnifiedJobs *UnifiedJobsService
//Users *UsersService
}
type Config struct {
Endpoint string
Username string
Password string
AuthToken *authtoken.AuthToken
HttpClient *http.Client
}
func DefaultConfig() *Config {
config := &Config{
Endpoint: "http://127.0.0.1/api/v1/",
Username: "admin",
Password: "",
AuthToken: nil,
HttpClient: http.DefaultClient,
}
if e := os.Getenv("TOWER_ENDOINT"); e != "" {
config.Endpoint = e
}
if u := os.Getenv("TOWER_USERNAME"); u != "" {
config.Username = u
}
if p := os.Getenv("TOWER_PASSWORD"); p != "" {
config.Password = p
}
return config
}
func (c *Config) LoadAndValidate() error {
base := sling.New().Client(c.HttpClient).Base(c.Endpoint)
body := &authtoken.CreateRequest{
Username: c.Username,
Password: c.Password,
}
token := new(authtoken.AuthToken)
apierr := new(errors.APIError)
_, err := base.Post("authtoken/").BodyJSON(body).Receive(token, apierr)
if error := errors.BuildError(err, apierr); error != nil {
return error
}
c.AuthToken = token
return nil
}
func NewClient(c *Config) (*Client, error) {
if c.HttpClient == nil {
c.HttpClient = http.DefaultClient
}
base := sling.New().Client(c.HttpClient).Base(c.Endpoint)
base.Set("Authorization", "Token "+c.AuthToken.Token)
return &Client{
sling: base,
AuthToken: authtoken.NewService(base.New()),
Credentials: credentials.NewService(base.New()),
Groups: groups.NewService(base.New()),
Hosts: hosts.NewService(base.New()),
Inventories: inventories.NewService(base.New()),
JobTemplates: job_templates.NewService(base.New()),
Organizations: organizations.NewService(base.New()),
Projects: projects.NewService(base.New()),
//ActivityStream: NewActivityStreamService(base),
//AdHocCommands: NewAdHocCommandsService(base),
//Config: NewConfigService(base),
//Dashboard: NewDashboardService(base),
//InventoryScripts: NewInventoryScriptsService(base),
//InventorySources: NewInventorySourcesService(base),
//JobEvents: NewJobEventsService(base),
//Jobs: NewJobsService(base),
//Labels: NewLabelsService(base),
//Me: NewMeService(base),
//NotificationTemplates: NewNotificationTemplatesService(base),
//Notifications: NewNotificationsService(base),
//Ping: NewPingService(base),
//Roles: NewRolesService(base),
//Schedules: NewSchedulesService(base),
//SystemJobTemplates: NewSystemJobTemplatesService(base),
//SystemJobs: NewSystemJobsService(base),
//Teams: NewTeamsService(base),
//UnifiedJobTemplates: NewUnifiedJobTemplatesService(base),
//UnifiedJobs: NewUnifiedJobsService(base),
//Users: NewUsersService(base),
}, nil
}
|
Fourth Industrial Revolution in Japan: Technology to Address Social Challenges
In Japan, the challenges posed by its low birthrate and aging population expanded rapidly with the collapse of the bubble economy in the early 1990s, and in March 2011, energy and environmental problems such as power supply shortages and nuclear radiation issues occurred in the wake of the Great East Japan Earthquake and Fukushima nuclear accident. Also, with the beginning of the coronavirus pandemic in January 2020, digital transformation has emerged as a social challenge. In particular, Japan's aging population combined with a decrease in the working age population, has caused the government to face fiscal crisis due to the burden of social insurance, and a sense of crisis of labor shortage in the medical, manufacturing and logistics sectors. This is also leading to a sense of crisis at local governments as well, seen with the collapse of the medical service supply system under “Tokyo centralization,” the rapid increase of the vulnerable in transportation due to the super-aging of rural areas, and the risk of extinction of local communities. The analysis on the healthcare and medical care sectors was conducted in chapter 2, and the manufacturing, mobility, and logistics sectors in Chapter 3, and the local revitalization in Chapter 4 respectively. And chapter 5 of conclusion remarks presents policy implications for the Korean government. |
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "obs-precomp.h" // Precompiled headers
#include <mrpt/obs/gnss_messages.h> // Must include all message classes so we can implemente the class factory here
#include <mrpt/utils/CMemoryStream.h>
#include <map>
using namespace std;
using namespace mrpt::obs::gnss;
#define LIST_ALL_MSGS \
/* ====== NMEA ====== */ \
DOFOR(NMEA_GGA) \
DOFOR(NMEA_RMC) \
DOFOR(NMEA_ZDA) \
DOFOR(NMEA_VTG) \
DOFOR(NMEA_GLL) \
/* ====== TopCon mmGPS ====== */ \
DOFOR(TOPCON_PZS) \
DOFOR(TOPCON_SATS) \
/* ====== Novatel OEM6 ====== */ \
DOFOR(NV_OEM6_GENERIC_FRAME) \
DOFOR(NV_OEM6_BESTPOS) \
/* ====== Novatel SPAN+OEM6 ====== */ \
DOFOR(NV_OEM6_GENERIC_SHORT_FRAME) \
DOFOR(NV_OEM6_INSPVAS) \
DOFOR(NV_OEM6_RANGECMP) \
DOFOR(NV_OEM6_RXSTATUS) \
DOFOR(NV_OEM6_RAWEPHEM) \
DOFOR(NV_OEM6_VERSION) \
DOFOR(NV_OEM6_RAWIMUS) \
DOFOR(NV_OEM6_MARKPOS) \
DOFOR(NV_OEM6_MARKTIME) \
DOFOR(NV_OEM6_MARK2TIME) \
DOFOR(NV_OEM6_IONUTC)
// Class factory:
gnss_message* gnss_message::Factory(const gnss_message_type_t msg_id)
{
#define DOFOR(_MSG_ID) \
case _MSG_ID: \
return new Message_##_MSG_ID();
switch (msg_id)
{
LIST_ALL_MSGS
default:
return nullptr;
};
#undef DOFOR
}
bool gnss_message::FactoryKnowsMsgType(const gnss_message_type_t msg_id)
{
#define DOFOR(_MSG_ID) \
case _MSG_ID: \
return true;
switch (msg_id)
{
LIST_ALL_MSGS
default:
return false;
};
#undef DOFOR
}
const std::string& gnss_message::getMessageTypeAsString() const
{
static bool first_call = true;
static std::map<gnss_message_type_t, std::string> gnss_type2str;
if (first_call)
{
first_call = false;
#define DOFOR(_MSG_ID) gnss_type2str[_MSG_ID] = #_MSG_ID;
LIST_ALL_MSGS
#undef DOFOR
}
return gnss_type2str[this->message_type];
}
// Save to binary stream. Launches an exception upon error
void gnss_message::writeToStream(mrpt::utils::CStream& out) const
{
const int32_t msg_id = message_type;
out << msg_id;
this->internal_writeToStream(out);
}
// Load from binary stream. Launches an exception upon error
void gnss_message::readFromStream(mrpt::utils::CStream& in)
{
int32_t msg_id;
in >> msg_id;
ASSERT_EQUAL_((int32_t)msg_id, this->message_type);
this->internal_readFromStream(in);
}
// Load from binary stream and creates object detecting its type (class
// factory). Launches an exception upon error
gnss_message* gnss_message::readAndBuildFromStream(mrpt::utils::CStream& in)
{
int32_t msg_id;
in >> msg_id;
gnss_message* msg =
gnss_message::Factory(static_cast<gnss_message_type_t>(msg_id));
if (!msg)
THROW_EXCEPTION_FMT(
"Error deserializing gnss_message: unknown message type '%i'",
static_cast<int>(msg_id));
msg->internal_readFromStream(in);
return msg;
}
// Ctor (default: nullptr pointer)
gnss_message_ptr::gnss_message_ptr() : ptr(nullptr) {}
// Ctor:Makes a copy of the pointee
gnss_message_ptr::gnss_message_ptr(const gnss_message_ptr& o)
{
if (!o.ptr)
{
ptr = nullptr;
}
else
{
mrpt::utils::CMemoryStream buf;
o->writeToStream(buf);
buf.Seek(0);
ptr = gnss_message::readAndBuildFromStream(buf);
}
}
/** Assigns a pointer */
gnss_message_ptr::gnss_message_ptr(const gnss_message* p)
: ptr(const_cast<gnss_message*>(p))
{
}
void gnss_message_ptr::set(gnss_message* p)
{
if (ptr)
{
delete ptr;
ptr = nullptr;
}
ptr = p;
}
// Makes a copy of the pointee
gnss_message_ptr& gnss_message_ptr::operator=(const gnss_message_ptr& o)
{
mrpt::utils::CMemoryStream buf;
o->writeToStream(buf);
buf.Seek(0);
ptr = gnss_message::readAndBuildFromStream(buf);
return *this;
}
gnss_message_ptr::~gnss_message_ptr()
{
if (ptr)
{
delete ptr;
ptr = nullptr;
}
}
// ---------------------------------------
UTC_time::UTC_time() : hour(0), minute(0), sec(0) {}
void UTC_time::writeToStream(mrpt::utils::CStream& out) const
{
out << hour << minute << sec;
}
void UTC_time::readFromStream(mrpt::utils::CStream& in)
{
in >> hour >> minute >> sec;
}
// Build an MRPT timestamp with the hour/minute/sec of this structure and the
// date from the given timestamp.
mrpt::system::TTimeStamp UTC_time::getAsTimestamp(
const mrpt::system::TTimeStamp& date) const
{
using namespace mrpt::system;
TTimeParts parts;
timestampToParts(date, parts, false /* UTC, not local */);
parts.hour = this->hour;
parts.minute = this->minute;
parts.second = this->sec;
return buildTimestampFromParts(parts);
}
|
import _ from 'lodash';
import { getPerfCase } from '../cases';
import { createDIV, getSeq, removeDIV, mock } from '../../helper';
import { ChartType, PerfData, PerfDatum, Data, ChangeOption, DataAttributeType } from '../../types';
import { CHART_TYPES } from '../../common/const';
/**
* 运行一个单测
* @param engine 渲染引擎
* @param type 性能测试 case
* @param length 数据条数
*/
async function runPerfCase(engine: string, type: ChartType, length: number, mockData: Data): Promise<PerfDatum> {
const perfCase = getPerfCase(engine, type);
// 创建容器
const div = createDIV(document.getElementById('modalBody'));
// 执行
const time = await perfCase(div, mockData.slice(0, length)); // TODO 优化一下 slice,具备有一定的随机性
removeDIV(div);
return {
engine,
length,
time,
type,
};
}
/**
* 运行显示进度
* @param engine 渲染引擎
* @param type 性能测试 case
* @param length 数据条数
* @param amount 总条数
* @param count 数据条数
*/
function changeBreadCrumb({ engine, type, length, amount, count, total }: ChangeOption) {
// 图表文本
const chartType = _.find(CHART_TYPES, ({ value }) => _.isEqual(value, type))?.label;
// 文本显示
_.set(
document.getElementsByClassName('accounted'),
'[0].innerHTML',
`render <b>${chartType}</b> on <b>${engine}</b>, ${length} / ${total} `
);
const percent = `${_.round((count / amount) * 100, 2)}%`;
// 完成度显示
_.set(document.getElementsByClassName('progress'), '[0].innerHTML', `Finished: ${percent}`);
// 进度条样式
_.set(document.getElementsByClassName('progressBackground'), '[0].style.width', percent);
}
/**
* 具体的执行
* @param engines
* @param types
*/
export async function run(engines: string[], types: ChartType[], dataAttribute: DataAttributeType): Promise<PerfData> {
const r: PerfData = {};
const seq = getSeq(..._.map(dataAttribute, (item) => item.num));
// 最大的
const mockData = mock(seq[seq.length - 1]);
const total = mockData.length;
const amount = seq.length * engines.length * types.length; // 总条数
let count = 0; // 记录当前条数
for (const engine of engines) {
for (const type of types) {
for (const length of seq) {
const perfDatum = await runPerfCase(engine, type, length, _.shuffle(mockData));
count++;
changeBreadCrumb({ engine, type, length, amount, count, total });
if (!r[type]) {
r[type] = [];
}
r[type].push(perfDatum);
}
}
}
return r;
}
|
/**
* Created by nelson on 28/07/15.
*/
public class SortIgnoreCase implements Comparator<String> {
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
} |
Update: URL Fixer was acquired and is now hosted at http://urlfixer.org/
Earlier this year, I added a feature to URL Fixer (a browser add-on that fixes errors in URLs that you type in the address bar) that collects anonymous usage stats from users who opt in in order to help improve the ways that URL Fixer corrects typos; the collected data includes domains that are typed in the URL bar as well as the locale (language/country) of the user who typed them.
I now have six months of data, and I’ve run some statistical analysis on it in order to share some interesting stats with you. (If I were more creative, I would make an infographic out of this information.) Note that this data does not include bookmarked links or links that users click on in websites. It is strictly domains that have been typed directly into the address bar.
Care to guess the most commonly typed domain? That’s right: facebook.com. It was typed almost three times as often as the second most popular domain, google.com.
The top 10 domains account for 20% of all typed domains. facebook.com 9% twitter.com 1.1% amazon.com 0.5% google.com 3.3% mail.google.com 0.6% reddit.com 0.5% youtube.com 3.3% yahoo.com 0.6% gmail.com 1.1% hotmail.com 0.6%
The most popular TLD for typed domains is .com, followed by .org, .net, and .de. .com 63% .org 4% .net 4% .de 4% .ru 2% .hu 1% .fr 1% .co.uk 1% .br 1%
The top 17 TLD typos are all variations of .com. In order of frequency, they are .com\, .ocm, .con, .cmo, .copm, .xom, “.com,”, .vom, .comn, .com’, “.co,”, .comj, .coim, .cpm, .colm, .conm, and .coom.
The website that appears to benefit the most from users mistyping a legitimate URL is faceboook.com (count the o’s). It’s a scammy website set up to make you think that you have been chosen as a “Facebook Winner.” However, it is only typed once for every 7,930 times that someone correctly types facebook.com. (googe.com and goole.com are runners-up in this category, albeit with much less scammy sites in place than faceboook.com.)
49.5% of domains are typed with a leading “www.”.
The most popular non-.com/.net/.org domains: google.de, vkontakte.ru (a Russian social network), and google.fr.
The only locales where neither Google nor Facebook control the most popular domain are ru-RU (Russia – vkontakte.ru), fi-FI (Finland – aapeli.com, a gaming website), ko-KR (Korea – fomos.kr, an e-sports website), and zh-CN (China – baidu.com).
How does domain length correlate with typing frequency? (Facebook is to thank for the spike at 12 characters.)
How about alphabetical order? Has the old trick of choosing a site name early in the alphabet in order to show up above the fold on DMOZ had any lasting effect? Facebook and Google certainly make their letters stand out, but there doesn’t appear to be a correlation between the first letter of the domain and its popularity.
None of the domains with more than a 0.0005% share are unregistered, indicating that this kind of usage data would not be very useful to a scammer or phisher looking for new domain names. |
/**
*
* @author Tomas Zezula
*/
final class ModuleFileManager implements JavaFileManager {
private static final Logger LOG = Logger.getLogger(ModuleFileManager.class.getName());
private final CachingArchiveProvider cap;
private final ClassPath modulePath;
private final Function<URL,Collection<? extends URL>> peers;
private final Source sourceLevel;
private final boolean cacheFile;
private final Location forLocation;
private Set<ModuleLocation> moduleLocations;
public ModuleFileManager(
@NonNull final CachingArchiveProvider cap,
@NonNull final ClassPath modulePath,
@NonNull final Function<URL,Collection<? extends URL>> peers,
@NullAllowed final Source sourceLevel,
@NonNull final Location forLocation,
final boolean cacheFile) {
assert cap != null;
assert modulePath != null;
assert peers != null;
assert forLocation != null;
this.cap = cap;
this.modulePath = modulePath;
this.peers = peers;
this.sourceLevel = sourceLevel;
this.forLocation = forLocation;
this.cacheFile = cacheFile;
}
// FileManager implementation ----------------------------------------------
@Override
public Iterable<JavaFileObject> list(
@NonNull final Location l,
@NonNull final String packageName,
@NonNull final Set<JavaFileObject.Kind> kinds,
final boolean recursive ) {
final ModuleLocation ml = ModuleLocation.cast(l);
final String folderName = FileObjects.convertPackage2Folder(packageName);
try {
final List<Iterable<JavaFileObject>> res = new ArrayList<>();
List<? extends String> prefixes = null;
final boolean supportsMultiRelease = sourceLevel != null && sourceLevel.compareTo(SourceLevelUtils.JDK1_9) >= 0;
for (URL root : ml.getModuleRoots()) {
final Archive archive = cap.getArchive(root, cacheFile);
if (archive != null) {
final Iterable<JavaFileObject> entries;
// multi-release code here duplicated in CachingFileManager
// fixes should be ported across, or ideally this logic abstracted
if (supportsMultiRelease && archive.isMultiRelease()) {
if (prefixes == null) {
prefixes = multiReleaseRelocations();
}
final java.util.Map<String,JavaFileObject> fqn2f = new HashMap<>();
final Set<String> seenPackages = new HashSet<>();
for (String prefix : prefixes) {
Iterable<JavaFileObject> fos = archive.getFiles(
join(prefix, folderName),
null,
kinds,
null,
recursive);
for (JavaFileObject fo : fos) {
final boolean base = prefix.isEmpty();
if (!base) {
fo = new MultiReleaseJarFileObject((InferableJavaFileObject)fo, prefix); //Always inferable in this branch
}
final String fqn = inferBinaryName(l, fo);
final String pkg = FileObjects.getPackageAndName(fqn)[0];
final String name = pkg + "/" + FileObjects.getName(fo, false);
if (base) {
seenPackages.add(pkg);
fqn2f.put(name, fo);
} else if (seenPackages.contains(pkg)) {
fqn2f.put(name, fo);
}
}
}
entries = fqn2f.values();
} else {
entries = archive.getFiles(folderName, null, kinds, null, recursive);
}
res.add(entries);
if (LOG.isLoggable(Level.FINEST)) {
logListedFiles(l,packageName, kinds, entries);
}
} else if (LOG.isLoggable(Level.FINEST)) {
LOG.log(
Level.FINEST,
"No archive for: {0}", //NOI18N
ml.getModuleRoots());
}
}
return Iterators.chained(res);
} catch (final IOException e) {
Exceptions.printStackTrace(e);
}
return Collections.emptySet();
}
@Override
public FileObject getFileForInput(
@NonNull final Location l,
@NonNull final String pkgName,
@NonNull final String relativeName ) {
return findFile(ModuleLocation.cast(l), pkgName, relativeName);
}
@Override
public JavaFileObject getJavaFileForInput (
@NonNull final Location l,
@NonNull final String className,
@NonNull final JavaFileObject.Kind kind) {
final ModuleLocation ml = ModuleLocation.cast(l);
final String[] namePair = FileObjects.getParentRelativePathAndName(className);
final boolean supportsMultiRelease = sourceLevel != null && sourceLevel.compareTo(SourceLevelUtils.JDK1_9) >= 0;
List<? extends String> reloc = null;
for (URL root : ml.getModuleRoots()) {
try {
final Archive archive = cap.getArchive (root, cacheFile);
if (archive != null) {
final List<? extends String> prefixes;
if (supportsMultiRelease && archive.isMultiRelease()) {
if (reloc == null) {
reloc = multiReleaseRelocations();
}
prefixes = reloc;
} else {
prefixes = Collections.singletonList(""); //NOI18N
}
for (int i = prefixes.size() - 1; i >=0; i--) {
final String prefix = prefixes.get(i);
Iterable<JavaFileObject> files = archive.getFiles(
join(prefix,namePair[0]),
null,
null,
null,
false);
for (JavaFileObject e : files) {
final String ename = e.getName();
if (namePair[1].equals(FileObjects.stripExtension(ename)) &&
kind == FileObjects.getKind(FileObjects.getExtension(ename))) {
return prefix.isEmpty() ?
e :
new MultiReleaseJarFileObject((InferableJavaFileObject)e, prefix); //Always inferable
}
}
}
}
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
return null;
}
@Override
public FileObject getFileForOutput(
@NonNull final Location l,
@NonNull final String pkgName,
@NonNull final String relativeName,
@NullAllowed final FileObject sibling ) throws IOException {
throw new UnsupportedOperationException("Output is unsupported."); //NOI18N
}
@Override
public JavaFileObject getJavaFileForOutput( Location l, String className, JavaFileObject.Kind kind, FileObject sibling )
throws IOException, UnsupportedOperationException, IllegalArgumentException {
throw new UnsupportedOperationException ("Output is unsupported.");
}
@Override
public void flush() throws IOException {
}
@Override
public void close() throws IOException {
}
@Override
public int isSupportedOption(String string) {
return -1;
}
@Override
public boolean handleOption (final String head, final Iterator<String> tail) {
return false;
}
@Override
public boolean hasLocation(Location location) {
return true;
}
@Override
public ClassLoader getClassLoader (final Location l) {
return null;
}
@Override
public String inferBinaryName (Location l, JavaFileObject javaFileObject) {
if (javaFileObject instanceof InferableJavaFileObject) {
return ((InferableJavaFileObject)javaFileObject).inferBinaryName();
}
return null;
}
@Override
public boolean isSameFile(FileObject a, FileObject b) {
return a instanceof FileObjects.FileBase
&& b instanceof FileObjects.FileBase
&& ((FileObjects.FileBase)a).getFile().equals(((FileObjects.FileBase)b).getFile());
}
@Override
@NonNull
public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
return moduleLocations(location).stream()
.map((ml) -> Collections.<Location>singleton(ml))
.collect(Collectors.toList());
}
@Override
@NullUnknown
public String inferModuleName(@NonNull final Location location) throws IOException {
final ModuleLocation ml = ModuleLocation.cast(location);
return ml.getModuleName();
}
@Override
@CheckForNull
public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
//todo: Only for Source Module Path & Output Path
return null;
}
@Override
@CheckForNull
public Location getLocationForModule(Location location, String moduleName) throws IOException {
return moduleLocations(location).stream()
.filter((ml) -> moduleName != null && moduleName.equals(ml.getModuleName()))
.findFirst()
.orElse(null);
}
private Set<ModuleLocation> moduleLocations(final Location baseLocation) {
if (!forLocation.equals(baseLocation)) {
throw new IllegalStateException(String.format(
"Locations computed for: %s, but queried for: %s", //NOI18N
forLocation,
baseLocation));
}
if (moduleLocations == null) {
final Set<ModuleLocation> moduleRoots = new HashSet<>();
final Set<URL> seen = new HashSet<>();
for (ClassPath.Entry e : modulePath.entries()) {
final URL root = e.getURL();
if (!seen.contains(root)) {
final String moduleName = SourceUtils.getModuleName(root);
if (moduleName != null) {
Collection<? extends URL> p = peers.apply(root);
moduleRoots.add(ModuleLocation.create(baseLocation, p, moduleName));
seen.addAll(p);
}
}
}
moduleLocations = moduleRoots;
}
return moduleLocations;
}
private JavaFileObject findFile(
@NonNull final ModuleLocation ml,
@NonNull final String pkgName,
@NonNull final String relativeName) {
assert ml != null;
assert pkgName != null;
assert relativeName != null;
final String resourceName = FileObjects.resolveRelativePath(pkgName,relativeName);
final boolean supportsMultiRelease = sourceLevel != null && sourceLevel.compareTo(SourceLevelUtils.JDK1_9) >= 0;
List<? extends String> reloc = null;
for (URL root : ml.getModuleRoots()) {
try {
final Archive archive = cap.getArchive (root, cacheFile);
if (archive != null) {
final List<? extends String> prefixes;
if (supportsMultiRelease && archive.isMultiRelease()) {
if (reloc == null) {
reloc = multiReleaseRelocations();
}
prefixes = reloc;
} else {
prefixes = Collections.singletonList(""); //NOI18N
}
for (int i = prefixes.size() - 1; i >= 0; i--) {
final String prefix = prefixes.get(i);
final JavaFileObject file = archive.getFile(join(prefix, resourceName));
if (file != null) {
return prefix.isEmpty() ?
file :
new MultiReleaseJarFileObject((InferableJavaFileObject)file, prefix); //Always inferable
}
}
}
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
return null;
}
private static void logListedFiles(
@NonNull final Location l,
@NonNull final String packageName,
@NullAllowed final Set<? extends JavaFileObject.Kind> kinds,
@NonNull final Iterable<? extends JavaFileObject> entries) {
final StringBuilder urls = new StringBuilder ();
for (JavaFileObject jfo : entries) {
urls.append(jfo.toUri().toString());
urls.append(", "); //NOI18N
}
LOG.log(
Level.FINEST,
"Filesfor {0} package: {1} type: {2} files: [{3}]", //NOI18N
new Object[] {
l,
packageName,
kinds,
urls
});
}
@NonNull
private List<? extends String> multiReleaseRelocations() {
final List<String> prefixes = new ArrayList<>();
prefixes.add(""); //NOI18N
final Source[] sources = Source.values();
for (int i=0; i< sources.length; i++) {
if (sources[i].compareTo(SourceLevelUtils.JDK1_9) >=0 && sources[i].compareTo(sourceLevel) <=0) {
prefixes.add(String.format(
"META-INF/versions/%s", //NOI18N
normalizeSourceLevel(sources[i].name)));
}
}
return prefixes;
}
@NonNull
private static String normalizeSourceLevel(@NonNull final String sl) {
final int index = sl.indexOf('.'); //NOI18N
return index < 0 ?
sl :
sl.substring(index+1);
}
@NonNull
private static String join(
@NonNull final String prefix,
@NonNull final String path) {
return prefix.isEmpty() ?
path:
path.isEmpty() ?
prefix :
prefix + FileObjects.NBFS_SEPARATOR_CHAR + path;
}
} |
export const mapHTML = (name, co2, meat, electro): string =>
`<div class="map-hoverinfo hoverinfo">
<strong class="map-name mb-1 d-block"> ${name} </strong>
<div class="d-flex flex-between">
<div>
<div class="map-co2 bold"> CO2 Emmision: </div>
<div class="bold"> CO2-Fleischkonsum: </div>
<div class="map-electro bold"> Stromverbrauch: </div>
</div>
<div>
<div> ${co2} MT </div>
<div> ${meat} MT</div>
<div> ${electro} gCO2eq/kWh </div>
</div>
</div>
</div>`; |
def _retrieve_singular(method: Callable, *args, **kwargs):
kwargs['limit'] = kwargs.get('limit', 2)
results = method(*args, **kwargs)
criteria = '\nargs: {}\nkwargs: {}'.format(args, kwargs)
if len(results) == 0:
raise NotFoundError("No {} fit criteria:{}".format(method.__name__, criteria))
if len(results) != 1:
raise MultipleFoundError("Multiple {} fit criteria:{}".format(method.__name__, criteria))
return results[0] |
“Slow” marine animals show their secret life under high magnification. Corals and sponges build coral reefs and play crucial roles in the biosphere, yet we know almost nothing about their daily lives. These animals are actually very mobile creatures, however their motion is only detectable at different time scales compared to ours and requires time lapses to be seen.
Make sure you watch it on a large screen! You won’t be able to appreciate this clip or see individual cells moving in a sponge on a smartphone. This clip is displayed in Full HD, yet the source footage (or the whole clip), is available in UltraHD 4k resolution for media productions.
Visit my website to see more work: www.microworldsphotography.com
Learn more about what you see in this video: http://notes-from-dreamworlds.blogspot.com.au/2014/03/slow-life.html
The answer to a common question: yes, colors are “real” and not exaggerated by digital enhancement. I have only applied basic white balance correction. When photographers use white light on corals, they simply miss the vast majority of colors. Read more about fluorescence and why these corals are natural: http://notes-from-dreamworlds.blogspot.com.au/2013/06/fluorescent-colors-of-reef-coral.html
The duration of sequences varied from 20 minutes to 6+ hours.
=== Technical details ===
To make this little clip I took 150000 shots. Why so many? Because macro photography involves shallow depth of field. To extend it, I used focus stacking. Each frame of the video is actually a stack that consists of 3-12 shots where in-focus areas are merged. Just the intro and last scene are regular real-time footage. One frame required about 10 minutes of processing time (raw conversion + stacking). Unfortunately, the success rate was very low due to copious technical challenges and I spent almost 9 long months just to learn how to make these kinds of videos and understand how to work with these delicate creatures.
I am glad that I abandoned the idea of making this clip in 3D (with two cameras) – very few people have 3D screens and it doubles processing time.
Gear:
– Cameras: Canon 7D (died at the beginning of the project as I had overused it in my research), Canon 5d Mkiii (90% of footage is done with it)
– Lenses: Canon MP-E 65 mm lens, and a custom photomacrography rig (custom lenses are better for this type of task)
– Lights: adjustable custom-spectrum lamps (3 different models) – they were needed to recreate natural underwater illumination.
– several motorized stages, including StackShot for focus stacking. StackShot, is sadly not 100% reliable at all and kept destroying my footage.
– multiple computers to process thousands of 22+ Mpx raw images and perform focus stacking (an old laptop died on that mission after 3 weeks of continuous processing).
Edited in Sony Vegas, Adobe Photoshop CS6, Zerene Stacker, and Helicon Focus.
Music: Atmostra III by Cedric Baravaglio, Jonathan Ochmann and Zdravko Djordjevic.
=== Sharing/Use ===
Inquiries/licensing/press: find my contact details here: http://www.microworldsphotography.com/About
Please do not share this clip to promote or endorse marine aquarium industry. I simply want people to admire life, but not to be told to buy stuff, especially poses captive animals
More about using my videos:
http://www.microworldsphotography.com/Image-Use/Video-Use-and-Licensing
(consideration to buy a print from my website or to use the tip jar below the video is always welcome, but this option is better: https://secure.marineconservation.org.au/donate.php?campid=701900000006kqX) |
/**
* Print the usage for a given command.
*
* @param command a command
*/
private void printUsage(String command)
throws RecognitionException, TokenStreamException {
client.printUsage(command);
skip();
} |
<reponame>iron-tech-space/react-tech-design
export default FormTable;
declare const FormTable: React.ForwardRefExoticComponent<React.RefAttributes<any>>;
import React from "react";
|
package dao
import (
"encoding/json"
"github.com/pourer/pikamgr/utils/log"
)
func jsonEncode(flag string, v interface{}) []byte {
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
log.Panicln("encode to json failed. flag:", flag, "err:", err)
}
return data
}
func jsonDecode(flag string, v interface{}, data []byte) error {
if err := json.Unmarshal(data, v); err != nil {
log.Errorln("decode from json failed. flag:", flag, "err:", err)
return err
}
return nil
}
|
use std::collections::BTreeMap as Map;
use std::env;
use structopt::StructOpt;
use tagsearch::{
filter::Filter,
utility::{get_files, get_tags_for_file},
};
mod budgetitem;
use budgetitem::BudgetItem;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, StructOpt)]
#[structopt(name = "budget", about = "summarise individual budget files")]
struct Opt {
/// Show only entries matching tags
tags: Vec<String>,
/// Show archive
#[structopt(short, long)]
archive: bool,
/// Show files matching each tags
#[structopt(short, long)]
verbose: bool,
/// Show summary of all tags related to filtered files
#[structopt(long)]
all: bool,
}
fn main() -> Result<()> {
let opts = Opt::from_args();
let finance_dir = match env::var("FINANCES") {
Ok(f) => f,
Err(_) => {
return Err("Must provide directories, or set FINANCES env var".into());
}
};
let mut tags = opts.tags.iter().map(|x| x.as_str()).collect::<Vec<&str>>();
if !opts.archive {
tags.push("!archive");
}
let filter = Filter::new(&tags, false);
let mut tag_map: Map<String, Vec<BudgetItem>> = Map::new();
let mut matching_files = Vec::new();
for file in get_files(Some(finance_dir))? {
let b = BudgetItem::new(file.clone())?;
if filter.matches(&b.tags) {
for tag in &b.tags {
(*tag_map.entry(tag.to_string()).or_insert(Vec::new())).push(b.clone());
}
matching_files.push(b);
}
}
let tagmap_related_keywords: Vec<String> = tag_map
.keys()
.filter(|keyword| !tags.contains(&keyword.as_str()))
.map(|x| x.to_owned())
.collect();
let total_for_matching: f64 = matching_files.iter().map(|x| x.cost).sum();
if opts.tags.is_empty() {
println!("Total: {:.2}", total_for_matching);
} else {
println!(
"Total for `{}`: {:.2}",
opts.tags.join("+"),
total_for_matching
);
}
if !opts.all {
if opts.verbose {
for item in matching_files {
println!("\t{}", item);
}
println!();
}
println!("Related: {}", tagmap_related_keywords.join(" "));
} else {
println!("\nBreakdown for matching tags");
for (key, budgetitems) in tag_map {
let total: f64 = budgetitems.iter().map(|x| x.cost).sum();
println!("{} - {:.2}", key, total);
if opts.verbose {
for item in budgetitems {
println!("\t{}", item);
}
}
}
}
Ok(())
}
|
Indonesia returned to Mozambique after a lengthy absence and came away with a long list of items to pursue in an effort to reinvigorate a sluggish bilateral partnership across various sectors.
Foreign Minister Retno LP Marsudi ended her first tour of the African continent this year by flying into the Mozambique capital of Maputo on Tuesday, local time, for business match-making and bilateral talks with some of the country’s high-ranking officials. The meetings focused mostly on strengthening trade and investment with one of Indonesia’s biggest partners in Africa.
“Economic cooperation between Indonesia and Mozambique isn’t indicative of the potential that both countries possess,” she said after talks with Mozambique Prime Minister Carlos Agostinho do Rosário and Minister of Foreign Affairs and Cooperation Oldemiro JM Baloi.
During meetings with both the prime minister and the foreign minister, Retno offered a concrete list of economic priorities that both countries should focus on moving forward.
Retno asked Mozambique to provide wider market access to Indonesian investors who are keen to explore projects in the country.
After a 13-year absence, Retno visited the country with an entourage of business players from the private and public sectors, including representatives from the Indonesian Chamber of Commerce and Industry (Kadin), the Indonesia Eximbank and shipbuilder PT PAL.
She hoped that the presence of Eximbank and Kadin would help provide concrete solutions to one of the biggest stumbling blocks in Indonesian-African trade relations: trade cooperation financing.
Indonesian investors include energy players from diversified conglomerates Besmindo Group and Bakrie Group, as well as state-owned train manufacturer PT Industri Kereta Api (Inka), which recently exported its first shipment of passenger trains to Bangladesh. Inka is eyeing Mozambique as its next target, said Daniel Tumpal Simandjuntak, the ministry’s director for African affairs.
During a separate business forum event in Maputo, Retno underlined the importance for both Indonesian and Mozambican businesses to take advantage of all available opportunities in order to revitalize weakening trade and investment ties.
Two-way trade between the countries reached almost US$34 million between January and October last year, continuing a downward trend from $119.46 million in 2015, according to data from the Trade Ministry.
Retno also met with Mozambique President Filipe Jacinto Nyusi to officially invite him to participate in the upcoming Indian Ocean Rim Association (IORA) Leaders’ Summit in Jakarta next month. |
def autostart_pools(cls):
cls.pool_lock.acquire()
try:
for inst in XendAPIStore.get_all(cls.getClass()):
if inst.is_managed() and inst.auto_power_on and \
inst.query_pool_id() == None:
inst.activate()
finally:
cls.pool_lock.release() |
<filename>third_party/virtualbox/src/VBox/Main/src-client/win/precomp_vcc.h
/* $Id: precomp_vcc.h $ */
/** @file
* VirtualBox COM - Visual C++ precompiled header for VBoxC.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <iprt/cdefs.h>
#include <iprt/win/winsock2.h>
#include <iprt/win/windows.h>
#include <VBox/cdefs.h>
#include <iprt/types.h>
#include <iprt/cpp/list.h>
#include <iprt/cpp/meta.h>
#include <iprt/cpp/ministring.h>
#include <VBox/com/microatl.h>
#include <VBox/com/com.h>
#include <VBox/com/array.h>
#include <VBox/com/Guid.h>
#include <VBox/com/string.h>
#include "VBox/com/VirtualBox.h"
#if defined(Log) || defined(LogIsEnabled)
# error "Log() from iprt/log.h cannot be defined in the precompiled header!"
#endif
|
import Data.Maybe
import Control.Monad
import qualified Data.ByteString.Char8 as C
readInt' = fst.fromJust.C.readInt
readLnInt = map readInt'.C.words<$>C.getLine
readCsInt n = concat<$>replicateM n readLnInt
main = do
[n] <- readLnInt
s <- getLine
putStr $ solve n s
solve n s
| (length s) <= n = s
| otherwise = (take n s) ++ "..."
|
package main
import (
"net/http"
"github.com/go-chi/chi"
"github.com/pieterclaerhout/go-log/versioninfo"
"github.com/pieterclaerhout/go-webserver/v2/binder"
"github.com/pieterclaerhout/go-webserver/v2/respond"
"github.com/pkg/errors"
)
// SampleApp defines a sample web application
type SampleApp struct {
}
// Name returns the name of this app
func (a *SampleApp) Name() string {
return "sample"
}
// Register registers the routes for this app
func (a *SampleApp) Register(r *chi.Mux) {
r.Get("/json", a.handleJSON())
r.Get("/html", a.handleHTML())
r.Get("/text", a.handleText())
r.Get("/auto", a.handleAuto())
r.Get("/parse", a.handleParse())
r.Post("/parse", a.handleParse())
r.Get("/error", a.handleError())
r.Get("/panic", a.handlePanic())
r.NotFound(a.handleNotFound())
r.MethodNotAllowed(a.handleMethodNotAllowed())
}
func (a *SampleApp) handleJSON() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
a.sampleResponse().ToJSON(w)
}
}
func (a *SampleApp) handleHTML() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
a.sampleResponse().ToHTML(w)
}
}
func (a *SampleApp) handleText() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
a.sampleResponse().ToText(w)
}
}
func (a *SampleApp) handleAuto() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
a.sampleResponse().Write(w, r)
}
}
func (a *SampleApp) handleError() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
respond.Error(errors.New("an error")).ToJSON(w)
}
}
func (a *SampleApp) handlePanic() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
panic(errors.New("an error"))
}
}
func (a *SampleApp) handleParse() http.HandlerFunc {
type request struct {
Value string `json:"value" form:"value"`
}
return func(w http.ResponseWriter, r *http.Request) {
req := &request{}
if err := binder.Bind(r, &req); err != nil {
respond.Error(err).Write(w, r)
return
}
respond.OK(req).ToJSON(w)
}
}
func (a *SampleApp) handleNotFound() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
respond.NotFound("nothing here").Write(w, r)
}
}
func (a *SampleApp) handleMethodNotAllowed() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
respond.MethodNotAllowed(r.Method+" is not supported").Write(w, r)
}
}
func (a *SampleApp) sampleResponse() *respond.Response {
type response struct {
Name string `json:"name"`
Description string `json:"description"`
Copyright string `json:"copyright"`
Version string `json:"version"`
Revision string `json:"revision"`
Branch string `json:"branch"`
}
return respond.OK(
response{
Name: versioninfo.ProjectName,
Description: versioninfo.ProjectDescription,
Copyright: versioninfo.ProjectCopyright,
Version: versioninfo.Version,
Revision: versioninfo.Revision,
Branch: versioninfo.Branch,
},
)
}
|
<filename>authentication/urls.py<gh_stars>0
from django.urls import path
from .views import CustomObtainTokenPairAPIView, CustomTokenRefreshAPIView
urlpatterns = [
path("", CustomObtainTokenPairAPIView.as_view(), name="token_create"),
path("refresh/", CustomTokenRefreshAPIView.as_view(), name="token_refresh")
]
|
/**
* Append lines to FTP.
* @param ftp FTP client
* @param lines Lines to append
* @throws IOException If some I/O problem inside
*/
@RetryOnFailure(verbose = false)
private void append(final FTPClient ftp, final Iterable<String> lines)
throws IOException {
final String name = FilenameUtils.getBaseName(this.file);
if (!ftp.appendFile(name, this.toStream(lines))) {
throw new IOException(
String.format(
"failed to append to %s at %s because of '%s'",
this.file, this.batch,
ftp.getReplyString().trim()
)
);
}
Logger.debug(
this,
"#append(..): appended some lines to '%s' in %s",
this.file, this.batch
);
} |
def open(self):
if self._shell_channel is None:
self._debug('connecting to {}'.format(self))
transport = self.ssh_client.get_transport()
if transport is None:
self.ssh_client.connect(self.host, username=self.username, password=self.password)
transport = self.ssh_client.get_transport()
action = "established"
else:
action = "reusing"
transport_info = ['local version = {}'.format(transport.local_version),
'remote version = {}'.format(transport.remote_version),
'using socket = {}'.format(transport.sock)]
self._debug(' {} ssh transport to {}:{} |{}\n {}'.format(action, self.host, self.port, transport,
"\n ".join(transport_info)))
self._shell_channel = self.ssh_client.invoke_shell()
self._remember_channel_of_transport(self._shell_channel)
self._debug(' established shell ssh to {}:{} [channel {}] |{}'.format(self.host, self.port,
self._shell_channel.get_id(),
self._shell_channel))
self._info('connection {} is open'.format(self))
return contextlib.closing(self) |
<filename>scripts/migration/migrate_confirmed_user_emails.py
"""Ensure that confirmed users' usernames are included in their emails field.
"""
import logging
import sys
from modularodm import Q
from website import models
from website.app import init_app
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
def main():
# Set up storage backends
init_app(routes=False)
dry_run = 'dry' in sys.argv
count = 0
if not dry_run:
scripts_utils.add_file_logger(logger, __file__)
logger.info("Finding users with username not in confirmed emails")
for user in get_users_with_username_not_in_emails():
user.emails.append(user.username)
logger.info(repr(user))
if not dry_run:
user.save()
count += 1
logger.info('Migrated {} users'.format(count))
def get_users_with_username_not_in_emails():
return (
user for user in
models.User.find(Q('date_confirmed', 'ne', None))
if user.is_active and
user.username.lower() not in [email.lower() for email in user.emails] and
user.username is not None
)
if __name__ == '__main__':
main()
|
/**
* Adds one or more style names to the suggestion. Multiple styles can be
* specified as a space-separated list of style names. The style name will
* be rendered as a HTML class name, which can be used in a CSS definition.
*
* @param styleName The new style to be added to the suggestion.
*/
public void addStyleName(String styleName) {
if (styleName == null || styleName.isEmpty()) {
return;
}
if (styleName.contains(" ")) {
StringTokenizer tokenizer = new StringTokenizer(styleName, " ");
while (tokenizer.hasMoreTokens()) {
addStyleName(tokenizer.nextToken());
}
return;
}
if (styleNames == null) {
styleNames = new ArrayList<>();
}
styleNames.add(styleName);
} |
// SendDataByDeviceID sends data to specific device id
func (s *Server) SendDataByDeviceID(deviceID string, data []byte) error {
for k := range s.connections {
if s.connections[k].DeviceID == deviceID {
return s.connections[k].Send(data)
}
}
return errors.New(fmt.Sprint("no connection with deviceID ", deviceID))
} |
RF Electromagnetic Field Treatment of Tetragonal Kesterite CZTSSe Light Absorbers
In this work, we propose a method to improve electro-optical and structural parameters of light-absorbing kesterite materials. It relies on the application of weak power hydrogen plasma discharges using electromagnetic field of radio frequency range, which improves homogeneity of the samples. The method allows to reduce strain of light absorbers and is suitable for designing solar cells based on multilayered thin film structures. Structural characteristics of tetragonal kesterite Cu2ZnSn(S, Se)4 structures and their optical properties were studied by Raman, infrared, and reflectance spectroscopies. They revealed a reduction of the sample reflectivity after RF treatment and a modification of the energy band structure.
Background
The problem of energy generation and accumulation becomes increasingly important both due to depletion of conventional sources of energy and increase of economical demands. This pushes forward the limits of alternative energy sources technology and, particularly, the technology of light-harvesting devices. Ranging from common Si-based solar cells (SCs) to highly efficient although expensive III-V semiconductor-based SCs (single or multi-junction ) and cheap but less efficient organic photovoltaic devices, the SC technologies remain in active search for optimal materials. At present, thin film SCs (TFSCs) based on kesterite structure Cu 2 ZnSn(S, Se) 4 (CZTSSe) are being developed rapidly . CZTSSe-based SCs have a number of advantages in contrast to other TFSCs (e.g., CuInGaSe 2based TFSC) being cost-efficient with respect to source components and non-toxic during the synthesis. The improved properties of Cu 2 ZnSnS 4 (CZTS) include a direct band gap (about 1.5 eV) and a high absorption coefficient (above 10 4 cm −1 in the visible spectral range), making it well suitable for photovoltaic applications . Currently, the record efficiency of a prototype CZTSSe SC is 12.6% . In order to increase the efficiency, several problems should be resolved. First, it is the non-stoichiometric composition of CZTSSe and the concentration of intrinsic defects. The second problem is a material degradation due to the coexistence of different crystallographic phases. Finally, it is the possible presence of the impurities of secondary binary and ternary compounds which are formed during the synthesis. Different phases present in material are hardly distinguishable mainly due to the imperfection of traditional methods of investigation . These problems occur due to the small difference in cross-sections between the Cu and Zn in the X-ray scattering and similar diffraction patterns for kesterite, stannite, and their disordered phases. Therefore, it is difficult to determine the crystalline structure and the degree of structural disorder using X-ray diffraction (XRD) setup. Such information may be obtained by neutron diffraction or synchrotron X-ray diffraction investigations . As was demonstrated in Ref. , the power of beam using in XRD method cannot be fully exploited for the identification of secondary phases of ternary compounds in complex systems like CZTS. The same problem appears while distinguishing the structures of similar modifications with the same ternary or quaternary composition, e.g., kesterite and its "defect" modification or stannite. The intensity of the XRD reflex corresponds to the volume of a phase. Therefore, it is often impossible to distinguish tiny and typical broadening due to small size of the inclusion of the secondary phase peak when it is situated in the vicinity of the main peak of the principal phase. For this reason, researchers working in the field are looking for alternative but accessible methods for the identification and detection of the secondary phase. One of such promising methods is Raman spectroscopy. Application of such methods can simplify the postprocessing methods for structural homogeneity improvement of CZTSSe materials. Moreover, analysis of structural properties represents an important technological task and is highly demanded for various photovoltaic applications. In Ref. , the high efficiency of SC was reached with record efficiency of 12.6% for CZTSSe. There, CZTSSe films were grown from the Sn and Cu chalcogenides dissolved in hydrazine solution as well as from the ZnS and ZnSe particles dispersed in the solution. Hydrazine was utilized to the growth process only, and post-growth treatment is performed by annealing in N 2 and air, which allows dissolving certain precursors easily. However, it is highly toxic, and its explosive properties limit the potential usage. In this work, we propose a hydrazine-free method as a post-growth treatment for the improvement of the structural properties of light absorbers in the bulk and multilayered configurations. It is based on the application of hydrogen weak power plasma discharges using an electromagnetic field of radio frequency region.
Methods
First, the method of radio frequency (RF) treatment was applied for silicon-based SCs in typical configuration. The area of diffusion field Si-SC was 2 cm 2 , and the layered structure consisted of (i) Al front grid, (ii) 50 nm thick antireflection Si 3 N 4 layer, (iii) 30 nm thick charged dielectric SiO 2 layer, (iv) inducted n ++ layer, (v) diffusion n + layer, (vi) quasi-neutral base area or p-Si, (vii) diffusion isotype junction or p + layer, and (viii) backside Al metallization. For measurements, the miniature SCs were collected in 10 groups. They were divided into three subgroups for future use as a reference, indoor and outdoor masks. During processing, samples were masked to avoid etching of the surface anti-reflection coatings. An inert gas was used as a mediator for RF beam. The SC samples were treated by 13.56 MHz RF beam. The initial sample (i.e., not subjected to the treatment) served as a reference. Variable parameters were the exposure time and the power of RF beam. The ranges of exposure time and beam power were 1-15 min and 0.19-2.25 W/cm 2 , respectively. The area of holder of RF reactor was 132 cm 2 . The hydrogen pressure in the chamber was fixed to 0.2 Torr. During depositions, the value of the voltage on the substrate was fixed (1900 V). Depositions were carried out at room temperature of holder. N 2 -based plasma treatment for pre-cleaning of the surfaces was performed using PlasmaEtch PE-50 XL (4.5′′ W × 6′′D + 2.5′′ Clearance) with power of generator 150 W at 50 KHz.
Dark and illuminated (AM1.5) IU characteristics were measured using Kelvin probe with Keithley 2410h and LabTraser NI software assistance. To calculate the parameters of Si-SCs, we used the double-diode model following Ref. .
Next, RF treatment with optimal regimes was used in the processing of light-absorbing materials. RF-stimulated H + plasma discharge with the source power of 0.8 W/cm 2 was applied during 15 min. Sample surface was masked by Si wafer during the treatment. For our aims, we utilized three kinds of bulk CZTSSe with tetragonal structure. First, specimen type was obtained by the deposition of ZnS, CuS, and SnS binary compounds by flash evaporation on glass substrates with pre-deposited molybdenum as a bottom layer with subsequent annealing of the structure (see Ref. ). Samples of second type were grown by Bridgman method (vertical aligned zone) from respective source elements. In the next step, grown crystals were sputtered onto the glass substrates with and without molybdenum bottom layer by magnetron sputtering at different substrate temperatures and by electron beam evaporation (for SC manufacturing). The transmission/ (n-R specular reflection) within the IR range was measured by FTIR spectrometer Infralum FT-801 in the 500-5000 cm −1 (0.06-0.5 eV) range: Specord-210 (A setup was configured as an attenuated total reflectance (ATR)), Shimadzu UV-3600 (B s and B d setups were configured as a specular/diffuse reflectance with integrating sphere of 100 mm), PerkinElmer Lambda-950 (C setup was configured as a diffuse reflectance with integrating sphere of 150 mm), UV-VIS-NIR Varian Cary 5000 (D setup was configured as a normal incidence beam for specular reflectance). A, B s , B d , C, and D configurations were used for UV, VIS, and NIR ranges, respectively. Absorption spectra were determined from the reflection spectra using dispersion integrals similar to well known method described in Refs. . To investigate the structural properties of the CZTSSe, μ-Raman spectroscopy (T64000 Horiba Jobin Yvon) was performed in backscattering configuration. For excitation of Raman spectra, the radiation of Ar + laser with a wavelength of 514.5 nm was used. The power of laser irradiation was chosen sufficiently small (the power flux of the beam was 0.1 mW/μm 2 ) to avoid change of the film structure during measurements. Raman spectra were recorded at room temperature, and the registration time was less than 1 min. Different parts of the sample were tested by several measurements for reproducibility and uniformity estimation. A ×50 objective of Olympus microscope was applied to focus onto the surface with diameter of spot less than 1 μm. Raman spectra were collected in different areas of each sample for accuracy, as non-uniform spots on the surface were visible under the light microscope. Collected results were averaged, and the nature of segregated crystalline phases was established.
Results and Discussion
As a proof of a principle, we start to study the influence of RF for SCs treatment. The collected results are presented in Fig. 1.
Efficiency (η, %) and fill factor (FF) of Si-SCs were 11.692 and 0.746 (curve 1), respectively, and were improved after the treatments: 95 W = 12.337/0.775 (curve 2); 225 W = 12.291/0.783 (curve 3); 300 W = 11.458/0.752 (curve 4). Slopes of the curves 2 and 3 slightly differ from that corresponding to the initial sample (curve 1). We suppose this to be a result of degradation of Schottky contacts due to the heating occurring under RF. As can be seen from Fig. 1, the values of U oc decreased but the values of I sc increased. This can possibly happen due to the passivation of dangling bonds by highly reactive H atoms. Application of high-power RF treatment resulted in cracking of striped metallic contacts and destruction of p-n junction. This was observed in optical microscope, explaining the behaviour of curve 4 and its significant change. Thus, we assume that the proposed method can be applied for the modification of η and FF, but it should be optimized for TFSC improvement.
For sample characterization, we proceeded with the measurements of the reflectivity spectra. Generally, the absorption coefficient can be easily extracted from the measurements of transmission. However, there are difficulties in both accurate measurement of thickness and reflectivity losses in case of multilayered configuration of absorber, or if its appropriate thickness is less than 1 μm. For these reasons, it is highly desirable to make the second and independent method for measurement of absorption coefficient from measurements of reflectivity. Absorption coefficient is related to extinction coefficient by simple relation: is the extinction coefficient, ω is the angular frequency, λ is the wavelength, c is the speed of light, and ℏ is the reduced Planck's constant, respectively. The complex reflection amplitude can be written using Fresnel equations, and in the case of normal incidence reads where n 0 is the refraction index of media for an incident beam (n 0 ≥ 1), and material refraction is characterized by the complex refractive index n = n 1 + ik. While r is a complex reflectivity and is not measured itself, it can be easily decomposed as any complex number using Euler's formula: where R is the ratio of the intensities of reflected and incident light beams that can be measured directly, θ is the phase of reflected light, A and B are the real and imaginary components of complex reflectivity, and n 1 and k are the refraction and extinction indices of absorber, respectively. Eq. (1) can be rewritten by direct decomposition into real and imaginary parts as If we know R and θ are transformed by the algorithm used in Refs. , the solution of the system of Eq.
(2) gives where auxiliary coefficients are In the region where the oscillator strengths for the optical transitions are mostly exhausted the dielectric function can be represented by the classical Drude formula : where σ(ω) is the complex optical conductivity (lowercase indices r and im denote real and imaginary part, respectively), ω p is the plasma frequency of the valence electrons, m* is the free electron mass, N v is the effective density of the valence electrons, τ is the average collision time, and ε 0 is the vacuum permittivity, respectively. All these parameters should be attributed to the value of plasma frequency using the sum rule: Transformed optical spectra of R(E) initial /R(E) RF of CZTSSe corresponding to different technological conditions are shown in Fig. 2a. Analysis showed that the reflection of structures after RF treatment decreased in the frequency range of 1.2 to 3 eV in the case of multilayered structure (curves 2 and 3) and in the range of 2.4 to 3.3 eV (curve 1) for bulk structures. The mismatch of the improvement ranges occurs due to post-processed free sample for bulk (curve 1) and the presence of Schottky contacts or hetero-junctions for layered sample (curves 2 and 3). It shall be noted that transformation of spectra following the procedure of Ref. would not be correct without correction terms depending on the measurement configuration of beams. In the case of A setup, ATR setup changes of the period of complex phase angle influences on the determination of the complex refractive index and should be corrected. Using non-ATR technique, the actual phase shift θ act can be obtained similar to the procedure described in Ref. . In our experiments, the best prediction of refractive index was realized to D setup, slightly worse to B s setup, and difficult to A setup. This depends on the transitions during multi-reflections from mirrors. It was found to be impossible doing adequate estimation of phase angle in C setup due to the diffuse integrating sphere. Thus, we conclude that the determination of absorption coefficient as well as pseudo-optical functions from the reflectivity measurements is correct for the measurement of normal incidence single-beam absolute specular reflection. Otherwise, all results must be attributed to the parameters obtained by direct method (e.g., Brewster angle-based technique).
The next stage of experiments included transmission and reflection measurements of the films on the glass with lateral dimensions larger than typical aperture of the beams of double-beam spectrophotometers. For this aim, the bulk CZTS was evaporated by electron beam and then additionally treated by RF plasma. The step for exposition was 1 min. Respective reflectance and transmittance (insert) spectra are illustrated in Fig. 2b, in accordance with exposure ratio. The maximal effect has been revealed for the sample exposure time of 3 min (curve 3).
After that, the corresponding absorption coefficients and ratios between the initial optical conductivities were calculated by Eqs. (3) and (6) using the result obtained by the most effective method. They are illustrated in Fig. 2c and in the inset in this figure, respectively.
A least-squares estimation of nonlinear parameters can be done by minimizing procedure using the following relations: Here, the first relation is known as Beer's law in the case of multi-reflections in parallel plate and the second one is the square of the absolute value of complex reflectivity.
As can be seen from Fig. 2c, the light-absorbing properties of CZTS increased after RF treatment mainly within the band gap. The value of optical conductivity can be evaluated using the assumption in the Drude model of conductivity as well as the plasma frequency parameter corresponding to the treatments. In the case of RF treatment, its value is 2.294 eV which is slightly higher than that for initial case (2.278 eV). Based on these results, we assume that RF treatment improves the absorption. But the presence of Cu-rich and other metal-enriched components results in poor electronic properties, and treatment condition should be optimized by additional cleaning.
To estimate the role of plasma components during the treatment, FTIR technique was applied. Absorption spectra are presented in Fig. 3. Absorption bands for bulk CZTS 4 with and without RF treatment ranged from 500 to 4000 cm −1 (wave numbers). These bands include C-N (1250 cm −1 , 1600 cm −1 ); sp 2 hybridized bonds (1490-1650 cm −1 ) of C-C, C=C stretching bands; stretching band of CH n at 2870 and 3100 cm −1 , corresponding to sp n hybridized bonds; CO 2 (2350 cm −1 ); and 2700 and 3600 cm −1 attributed to water and organic components . As we can see, RF treatment resulted in the reduction of absorption in the whole spectral range. In the case of absorption by sp 2 hybridized bonds for C-C and C=C units at 1500-1650 cm −1 , the explanation is well known. Normally, graphite-like phases being exposed to H + plasma are removed from the structures . The decrease of intensity for absorption band related to symmetric oscillations of CH 3 bond (at 2872 cm −1 ), CH, and CH 2 (2900-2926 cm −1 ) can be explained by the reduction of hydrogen concentration in the film. Thus, H + ions remove the components of impurities due to its high mobility even if the sample is masked without accumulation of sp n hybridized compositions.
The Raman spectra of the bulk CZTS were deconvoluted on Lorentzian components and are presented in Fig. 4. The two dominant peaks at 286 and 335 cm −1 and the bands at 251, 305, 343, and 356 cm −1 were attributed to A, E, and B symmetry modes, respectively. Their positions were similar to those in the experimental results described in Refs. , and their symmetry assignment was consistent with theoretical calculations reported in Refs. . Fitting the Raman spectrum by a set of components, we can assume that a weaker component around 329 cm −1 is observed at the lowfrequency side for the most intense band (335 cm −1 ). This Raman band can be assigned to the disordering of Zn and Cu atoms in CZTS lattice as was discussed in Ref. . This disordering is often caused by so-called anti-site defects such as Zn atoms replacing Cu (Cu Zn ) and vice versa (Zn Cu ). The influence of phase on the change of Raman spectra for kesterite is discussed in Fig. 2 Optical spectra of CZTSSe before and after RF treatments. a 1 Ratio of reflectances for bulk CZTS processed from metallic precursors (A setup); 2 ratio of reflectances for glass/Mo/Cu/CZTSe (A setup); 3 reflectance of bulk CZTS processed from sulfide precursors (B d setup). b Reflectance and transmittance (insert) of CZTS with respect to plasma exposure (C setup) with the steps of 1, 3, and 7. c Spectra of absorbance of CZTS thin films with (black) and without (red) RF treatment during 3 min (C setup). Insert: optical conductivity spectra of the same films Ref. . The disordering degree for kesterite structure can be estimated using intensity ratio I 329 /I 335 of the peaks at 329 and 335 cm −1 . In our case, this ratio was 0.11 and is comparable to the values obtained for thin films described in . It should be noted that the Raman spectra changes for light and dark areas are negligibly small that correlates with Ref. .
Raman spectra of CZTS and Cu 2 ZnSnSe 4 (CZTSe) samples after RF treatments are shown in Fig. 5a, b respectively. They are marked blue and red corresponding to initial and RF treated samples, respectively. As can be seen from Fig. 5a (red line), the position of the band at 286 cm −1 is shifted to the high-frequency region by 2 cm −1 , and its half-width is decreased by almost two times (22 cm −1 ), .
. resulting in the increase of intensity of the band. In Ref. , Suragg et al. suggested a hypothesis that the I 286 /I 305 ratio may be used for the determination of the ordering of compound. Uniform compound is characterized by the higher ratio value and vice versa. Applying this assumption, the intensity of the band increase of ratio I 288 /I 305 and its correlation with our results (the decrease of the ratio I 331 /I 337 ) was established. Both values indicate the structure ordering of the compound. As can be seen, the most intense band at 335 cm −1 for A symmetry shifts by 2 cm −1 after the treatment, but its half-width remains equal to 10 cm −1 corresponding to that of untreated sample. We assume that all improvements appeared due to the ordering of kesterite crystal lattice. The disordered kesterite has a structure like the stannite and manifests in the spectrum as a band at 331 cm −1 . Our assumption is based on the decrease of the ratio I 331 /I 337 equal to 0.06 . In the inset in Fig. 5a, we demonstrate three curves and show that the RF-inducted changes are stable in time anyways within 1-month period as indicated by the stability of the main band positions. At the same time, the band at 370 cm −1 is corresponding to CZTS and being visible after the treatment disappeared during this period. The increase of the band intensity at 370 cm −1 with respect to that of the initial samples was associated with the RF treatment, since after 1-month storage in air the band intensity has decreased. Similar treatment was provided to CZTSe processed in multilayered configuration, and its deconvoluted spectra are shown in Fig. 5b. The spectrum is characterized by the presence of two main peaks at 193 and 176 cm −1 identified as the main resonances in CZTSe as well as weaker CZTSe specific peaks located at 223 and 245 cm −1 . The frequency band of 223 cm −1 corresponds to the oscillation of E symmetry kesterite-like structure of CZTSe, a band with a frequency of 245 cm −1 that corresponds to B symmetry of kesterite-like structure . Unlike CZTSSe, there are no distinct spectral features that can be associated with technological conditions. Secondary phase positions mainly for ZnSe and Cu 2 SnSe 3 differ from those discussed in Ref. , in our case without any significant second phases. The electron beam evaporation of bulk samples in this case was performed on a substrate under the heating up to 190°C without additional annealing to reach stoichiometry. The conditions depended on the use of organic substrate during subsequent processing. Nevertheless, RF treatment also resulted in the positive effect for the spectrum of CZTSe whose main band was shifted by 2 cm −1 from 191 cm −1 (blue curve) to 193 cm −1 (red curve). This gives reasons to assume that influence of the treatment has a similar effect for both materials and is associated with the partial reduction of structural defects.
Conclusions
In this work, we applied hydrogen-based weak power plasma discharges using radio frequency (13.56 MHz) electromagnetic field treatment for the improvement of the optical properties of bulk and thin film kesterite samples. The structural characteristics and optical properties were studied by Raman, FTIR, and normal incidence reflection spectroscopy. It was shown that the position of main kesterite band (286 and 335 cm −1 for CZTS) shifted to the high-frequency region by 2 cm −1 and its full-width at half maximum decreased by almost two times (for the 286 cm −1 mode). This results in the increase of the band intensity. Similar shift by 2 cm −1 with respect to the main band of A symmetry appeared in the Raman scattering of CZTSe thin films. The analysis showed that the improvements resulted from the ordering of the crystal lattice and were stable during 1-month period. FTIR spectroscopy showed that sample treatments removed carbon-based impurities and inhibited accumulation of sp n . . Fig. 5 Raman spectra of bulk samples before (blue curves) and after (red curves) RF treatment for materials. a CZTS (inset shows the spectra before, straight after, and 1 month after RF treatment). b CZTSe film deposited onto Cu/Mo coated glass (inset shows the deconvolution by Lorentzian fits) hybridized compositions. Reflection spectra were transformed into absorption spectra using the dispersion integrals in the visible spectral range. This allowed estimating pseudo-optical function, Drude conductivity, and carrier mobility change, as well as concentration before and after plasma treatments. Therefore, plasma treatment resulted in not only surface cleaning from organic inclusions but also relieved internal stress. Such processing can be performed inside vacuum chambers during the post-processing stage. We conclude therefore that proposed hydrazine-free method of treatment can be applied for the creation of light absorbers with reduced strain and is suitable for the production of thin film multilayered solar cell. |
import math
from typing import Dict, List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import options, utils
from fairseq.modules import (
# MultiheadAttention,
LayerNorm
)
from torch import Tensor
from .multihead_attention import MultiheadAttention
DEFAULT_MAX_SOURCE_POSITIONS = 512
DEFAULT_MAX_TARGET_POSITIONS = 512
class EncoderLayer(nn.Module):
"""Encoder layer block.
In the original paper each operation (multi-head attention or FFN) is
postprocessed with: `dropout -> add residual -> layernorm`. In the
tensor2tensor code they suggest that learning is more robust when
preprocessing each layer with layernorm and postprocessing with:
`dropout -> add residual`. We default to the approach in the paper, but the
tensor2tensor approach can be enabled by setting
*args.encoder_normalize_before* to ``True``.
Args:
args (argparse.Namespace): parsed command-line arguments
"""
def __init__(self, args):
super().__init__()
self.embed_dim = args.encoder_embed_dim
self.dropout = args.dropout
self.activation_fn = utils.get_activation_fn(
activation=getattr(args, "activation_fn", "relu")
)
self.activation_dropout = getattr(args, "activation_dropout", 0)
if self.activation_dropout == 0:
# for backwards compatibility with models that use args.relu_dropout
self.activation_dropout = getattr(args, "relu_dropout", 0)
self.self_attn = MultiheadAttention(
self.embed_dim,
args.encoder_attention_heads,
dropout=args.attention_dropout,
self_attention=True,
apply_chunk_mask=args.apply_chunk_mask
)
self.self_attn_layer_norm = LayerNorm(self.embed_dim)
self.normalize_before = args.encoder_normalize_before
self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim)
self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim)
self.final_layer_norm = LayerNorm(self.embed_dim)
def upgrade_state_dict_named(self, state_dict, name):
"""
Rename layer norm states from `...layer_norms.0.weight` to
`...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
`...final_layer_norm.weight`
"""
layer_norm_map = {"0": "self_attn_layer_norm", "1": "final_layer_norm"}
for old, new in layer_norm_map.items():
for m in ("weight", "bias"):
k = "{}.layer_norms.{}.{}".format(name, old, m)
if k in state_dict:
state_dict["{}.{}.{}".format(name, new, m)] = state_dict[k]
del state_dict[k]
def forward(self, x, encoder_padding_mask, attn_mask: Optional[Tensor] = None,
chunk_mask: Optional[Tensor] = None):
"""
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
attn_mask (ByteTensor): binary tensor of shape (T_tgt, T_src), where
T_tgt is the length of query, while T_src is the length of key,
though here both query and key is x here,
attn_mask[t_tgt, t_src] = 1 means when calculating embedding
for t_tgt, t_src is excluded (or masked out), =0 means it is
included in attention
Returns:
encoded output of shape `(seq_len, batch, embed_dim)`
"""
residual = x
if self.normalize_before:
x = self.self_attn_layer_norm(x)
if attn_mask is not None:
attn_mask = attn_mask.masked_fill(attn_mask.to(torch.bool), -1e8)
# anything in original attn_mask = 1, becomes -1e8
# anything in original attn_mask = 0, becomes 0
# Note that we cannot use -inf here, because at some edge cases,
# the attention weight (before softmax) for some padded element in query
# will become -inf, which results in NaN in model parameters
# TODO: to formally solve this problem, we need to change fairseq's
# MultiheadAttention. We will do this later on.
x, _ = self.self_attn(
query=x, key=x, value=x, key_padding_mask=encoder_padding_mask, chunk_mask=chunk_mask
)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
if not self.normalize_before:
x = self.self_attn_layer_norm(x)
residual = x
if self.normalize_before:
x = self.final_layer_norm(x)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=float(self.activation_dropout), training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
if not self.normalize_before:
x = self.final_layer_norm(x)
return x
class Adaptor(nn.Module):
""" Adaptor for encoder with gated."""
def __init__(
self,
input_dim,
inner_dim,
activation_fn,
adaptor_dropout,
init_scale=1e-3,
):
super().__init__()
self.dense = nn.Linear(input_dim, inner_dim)
nn.init.normal_(self.dense.weight, std=init_scale)
nn.init.zeros_(self.dense.bias)
self.activation_fn = utils.get_activation_fn(activation_fn)
self.dropout = nn.Dropout(p=adaptor_dropout)
self.out_proj = nn.Linear(inner_dim, input_dim)
nn.init.normal_(self.out_proj.weight, std=init_scale)
nn.init.zeros_(self.out_proj.bias)
self.out_scale = 2.0
def forward(self, features, **kwargs):
x = features
# x = self.dropout(x)
x = self.dense(x)
x = self.activation_fn(x)
x = self.dropout(x)
x = self.out_proj(x).sigmoid() * self.out_scale
x = x.mul(features)
return x
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.0)
return m
|
Every day, more than 5,000 people commute to and from Wallacedene, a small settlement on the eastern edge of Cape Town. But you won't find it on official transit maps. It's simply a stop in the South African city's sprawling informal taxi network of more than 7,500 unregulated minibuses that shuttle people between the city's center and its outskirts on a daily basis.
Commuters have for decades navigated this network using only word of mouth. “People don’t really know how it works—they just know the few routes that they’re used to running,” says Madeline Zhu of the South African startup WhereIsMyTransport. Earlier this month, Zhu and her team published a map that visualizes 137 minibus routes alongside official rail and bus networks—a crucial first step in making public transit simpler for citizens to navigate and easier for cities to improve.
Informal transportation networks are common outside the US and Europe. People call them matatus in Nairobi, jeepneys in Manila, and peseros in Mexico City. In Cape Town, they're simply taxis. Whatever they're called, unofficial transit systems typically stem from income inequality. Cape Town's system started out as a way of transporting people from poor black communities into the city during apartheid. “The taxis are sort of a self organizing system that has sprung up around people's unmet need to get from place to place,” Zhu says.
For that reason, the buses always circumvented regulation and developed rules and logic based on market demand. They don't charge set fares or follow fixed routes. Stops can change depending on who’s riding that day, and good luck knowing when to transfer.
That creates no end of headaches for anyone trying to use the system, let alone understand it, improve it, or incorporate it into a formal transit network. Researchers from Columbia University and MIT recently mapped Nairobi’s matatu system. Another project mapped most of Mexico City’s peseros network. Similar efforts are underway in Cairo; Accara, Senegal; Santo Domingo, Dominican Republic; and Florianopolis, Brazil.
The recent boom in mapping is happening because it can—thank your smartphone's GPS—and because it must. “For a long time, cities thought they were going to replace these mini buses with formal buses, but there’s a growing recognition that that’s not going to happen,” says Jackie Klopp, a professor at Columbia’s Center for Sustainable Urban Development and co-founder of Digital Matatus, the project behind Nairobi’s matatu map.
Instead, experts say cities should integrate them with existing transportation options like rail and Bus Rapid Transit systems. That’s where mapping comes in. “The moment you realize that modern bus rapid transit is not the solution for everything, then the first thing you have to do to improve the informal bus system is to make it visible,” says Shomik Mehndiratta, a transportation analyst at the World Bank who worked on the peseros mapping project in Mexico City.
When WhereIsMyTransport started pondering mapping Cape Town’s taxi system more than eight years ago, the technology needed to capture the data needed to build a full-scale map simply didn't exist. “Now we all have little digital reorders in our hand all the time so it makes it a lot easier to do this,” says Sarah Williams, who leads MIT’s Civic Data Center and worked on the Digital Matatus project.
Last fall, WhereIsMyTransport hired 13 data collectors who rode buses for eight hours a day, tracking as many as 10 routes with an app called Collector. The tool gathered data like speed and location, and prompted the user to add information like major stops, wait times, geographic markers, fares, and the number of passengers. After three weeks and more than 5,500 miles, WhereIsMyTransport had tracked more than 1,000 routes, which it uploaded to its open platform alongside Cape Town's formal transit routes.
The company mapped only the routes that flow from the 10 busiest taxi hubs, so the map isn’t comprehensive, even if the data set is. “The real value of this project and projects like it is not in the map—it’s in the data being openly and dynamically available,” Zhu says. That creates its own set of challenges. The key to keeping Cape Town’s data useful is keeping it current. To ensure that, WhereIsMyTransport is exploring turning Collector into a crowdsourcing app or installing tracking devices on the taxis to gather real-time information. Eventually, the company hopes developers will use the data to build projects like Magic Bus, which uses an SMS app to let passengers pre-buy tickets for Nairobi's matatus.
All of the digital mapping projects hope to leverage technology to close the quality gap between the agile-but-flawed minibuses and more refined transit networks. "We've treated them as two completely different entities," Mehndiratta says. "What's interesting is how just mapping the informal starts bridging the difference between the two." Ultimately, the systems shouldn't be in competition—both have plenty to learn from each other. |
// Dependencies
import chalk from './chalk';
import fs from 'fs';
import path from 'path';
import Fuse from 'fuse.js';
import ErrorWithoutStack from './error-without-stack';
import { AppInformation, CommandSpec, InputObject, OrganizedArguments, Settings } from './types';
// Helpful utility functions
export default function utils(currentSettings: Settings) {
// Store an internal copy of the current settings
const settings = { ...currentSettings };
// Return the functions
return {
// Verbose log output helper function
verboseLog(message: string): void {
if (settings.verbose) {
console.log(chalk.dim.italic(`[VERBOSE] ${message}`));
}
},
// Retrieve app information
retrieveAppInformation(): AppInformation {
// Initialize
const app: AppInformation = { ...settings.app };
// Build path to package.json file
const pathToPackageFile = `${path.dirname(settings.mainFilename)}/${settings.packageFilePath}`;
// Handle if a package.json file exists
if (fs.existsSync(pathToPackageFile)) {
// Verbose output
utils(settings).verboseLog(`Found package.json at: ${pathToPackageFile}`);
// Get package
const packageInfo = JSON.parse(fs.readFileSync(pathToPackageFile).toString());
// Store information
app.name = app.name || packageInfo.name;
app.packageName = packageInfo.name;
app.version = app.version || packageInfo.version;
} else {
utils(settings).verboseLog(`Could not find package.json at: ${pathToPackageFile}`);
}
// Return info
return app;
},
// Get specs for a command
getMergedSpec(command: string): CommandSpec & { flags: {}; options: {} } {
// Break into pieces, with entry point
const pieces = `. ${command}`.trim().split(' ');
// Initialize
const mergedSpec: CommandSpec & { flags: {}; options: {} } = {
flags: {
version: {
shorthand: 'v',
description: 'Show version',
},
help: {
shorthand: 'h',
description: 'Show help',
},
},
options: {},
};
// Loop over every piece
let currentPathPrefix = path.dirname(settings.mainFilename);
pieces.forEach((piece, index) => {
// Append to path prefix
if (piece) {
currentPathPrefix += `/${piece}`;
}
// Get the command spec
const spec = utils(settings).files.getCommandSpec(currentPathPrefix);
// Build onto spec
if (typeof spec.flags === 'object') {
Object.entries(spec.flags).forEach(([flag, details]) => {
if (index === pieces.length - 1 || details.cascades === true) {
mergedSpec.flags[flag] = details;
}
});
}
if (typeof spec.options === 'object') {
Object.entries(spec.options).forEach(([option, details]) => {
if (index === pieces.length - 1 || details.cascades === true) {
mergedSpec.options[option] = details;
}
});
}
if (spec.passThrough) {
mergedSpec.passThrough = true;
}
if (index === pieces.length - 1) {
mergedSpec.description = spec.description;
mergedSpec.data = spec.data;
}
});
// Return spec
return mergedSpec;
},
// Organize arguments into categories
organizeArguments(): OrganizedArguments {
// Initialize
const organizedArguments: OrganizedArguments = {
flags: [],
options: [],
values: [],
command: '',
};
let previousOption: string | null = null;
let nextIsOptionValue = false;
let nextValueType: string | null = null;
let nextValueAccepts: string[] | null = null;
let reachedData = false;
let reachedPassThrough = false;
// Loop over every command
let currentPathPrefix = path.dirname(settings.mainFilename);
for (const argument of settings.arguments) {
// Verbose output
utils(settings).verboseLog(`Inspecting argument: ${argument}`);
// Collect pass-through arguments
if (reachedPassThrough) {
// Initialize if needed
if (!organizedArguments.passThrough) {
organizedArguments.passThrough = [];
}
// Store pass-through
organizedArguments.passThrough.push(argument);
continue;
}
// Skip option values
if (nextIsOptionValue) {
// Verbose output
utils(settings).verboseLog(`...Is value for previous option (${previousOption})`);
// Initialize
let value: string | number = argument;
// Validate value, if necessary
if (Array.isArray(nextValueAccepts)) {
const accepts: string[] = nextValueAccepts;
if (accepts.includes(value) === false) {
throw new ErrorWithoutStack(
`Unrecognized value for ${previousOption}: ${value}\nAccepts: ${accepts.join(', ')}`
);
}
}
if (nextValueType) {
if (nextValueType === 'integer') {
if (value.match(/^[0-9]+$/) !== null) {
value = parseInt(value, 10);
} else {
throw new ErrorWithoutStack(`The option ${previousOption} expects an integer\nProvided: ${value}`);
}
} else if (nextValueType === 'float') {
if (value.match(/^[0-9]*[.]*[0-9]*$/) !== null && value !== '.' && value !== '') {
value = parseFloat(value);
} else {
throw new ErrorWithoutStack(`The option ${previousOption} expects a float\nProvided: ${value}`);
}
} else {
throw new ErrorWithoutStack(`Unrecognized "type": ${nextValueType}`);
}
}
// Store and continue
nextIsOptionValue = false;
organizedArguments.values.push(value);
continue;
}
// Get merged spec for this command
const mergedSpec: CommandSpec = utils(settings).getMergedSpec(organizedArguments.command);
// Handle if we're supposed to ignore anything that looks like flags/options
if (reachedData && mergedSpec.data && mergedSpec.data.ignoreFlagsAndOptions === true) {
// Verbose output
utils(settings).verboseLog('...Is data');
// Append onto data
if (!organizedArguments.data) {
organizedArguments.data = ` ${argument}`;
} else {
organizedArguments.data += ` ${argument}`;
}
// Skip further processing
continue;
}
// Detect pass-through indication
if (argument === '--') {
// Error if this command does not accept pass-through arguments
if (!mergedSpec.passThrough) {
throw new ErrorWithoutStack('This command does not support pass-through arguments');
}
// Begin collecting pass-through arguments
reachedPassThrough = true;
continue;
}
// Skip options/flags
if (argument.startsWith('-')) {
// Check if this is an option
if (typeof mergedSpec.options === 'object') {
Object.entries(mergedSpec.options).forEach(([option, details]) => {
// Check for a match
const matchesFullOption = argument === `--${option.trim().toLowerCase()}`;
const matchesShorthandOption =
details.shorthand && argument === `-${details.shorthand.trim().toLowerCase()}`;
// Handle a match
if (matchesFullOption || matchesShorthandOption) {
// Verbose output
utils(settings).verboseLog('...Is an option');
// Store details
previousOption = argument;
nextIsOptionValue = true;
nextValueAccepts = details.accepts || null;
nextValueType = details.type || null;
organizedArguments.options.push(option);
}
});
}
// Handle flags
if (!nextIsOptionValue) {
// Initialize
let matchedFlag = false;
// Check if this is a valid flag
if (typeof mergedSpec.flags === 'object') {
Object.entries(mergedSpec.flags).forEach(([flag, details]) => {
if (argument === `--${flag.trim().toLowerCase()}`) {
// Verbose output
utils(settings).verboseLog('...Is a flag');
// Store details
matchedFlag = true;
organizedArguments.flags.push(flag);
} else if (details.shorthand && argument === `-${details.shorthand.trim().toLowerCase()}`) {
// Verbose output
utils(settings).verboseLog('...Is a flag');
// Store details
matchedFlag = true;
organizedArguments.flags.push(flag);
}
});
}
// Handle no match
if (!matchedFlag) {
throw new ErrorWithoutStack(`Unrecognized argument: ${argument}`);
}
}
// Skip further processing
continue;
}
// Get the command path
const commandPath = path.join(currentPathPrefix, argument);
// Check if that file exists
if (!reachedData && fs.existsSync(commandPath) && argument.replace(/[/\\?%*:|"<>.]/g, '') !== '') {
// Verbose output
utils(settings).verboseLog('...Is a command');
// Add to currents
currentPathPrefix += `/${argument}`;
organizedArguments.command += ` ${argument}`;
} else {
// Verbose output
utils(settings).verboseLog('...Is data');
// Store details
reachedData = true;
if (!organizedArguments.data) {
organizedArguments.data = argument;
} else {
organizedArguments.data += ` ${argument}`;
}
}
}
// Error if we're missing an expected value
if (nextIsOptionValue) {
throw new ErrorWithoutStack(`No value provided for ${previousOption}, which is an option, not a flag`);
}
// Handle if there's any data
if (typeof organizedArguments.data === 'string') {
// Get merged spec for this command
const mergedSpec = utils(settings).getMergedSpec(organizedArguments.command);
// Handle if data is not allowed
if (typeof mergedSpec.data !== 'object') {
// Get all commands in this program
const commands = utils(settings).getAllProgramCommands();
// Search for the best match
const fuse = new Fuse(commands, {
shouldSort: true,
threshold: 1,
tokenize: true,
includeScore: true,
includeMatches: true,
maxPatternLength: 32,
minMatchCharLength: 1,
});
const results = fuse.search(`${organizedArguments.command} ${organizedArguments.data}`.trim());
let bestMatch = null;
if (results.length && results[0].score && results[0].score < 0.6) {
bestMatch = results[0].matches[0].value;
}
// Determine command
const command = `${settings.usageCommand}${organizedArguments.command}`;
// Form error message
let errorMessage = `You provided ${chalk.bold(organizedArguments.data)} to ${chalk.bold(command)}\n`;
if (bestMatch) {
errorMessage += 'If you were trying to pass in data, this command does not accept data\n';
errorMessage += `If you were trying to use a command, did you mean ${chalk.bold(
settings.usageCommand
)} ${chalk.bold(bestMatch)}?\n`;
} else {
errorMessage += 'However, this command does not accept data\n';
}
errorMessage += `For more guidance, see: ${command} --help`;
// Throw error
throw new ErrorWithoutStack(errorMessage);
}
// Validate data, if necessary
if (mergedSpec.data.accepts) {
if (!mergedSpec.data.accepts.includes(organizedArguments.data)) {
throw new ErrorWithoutStack(
`Unrecognized data for "${organizedArguments.command.trim()}": ${
organizedArguments.data
}\nAccepts: ${mergedSpec.data.accepts.join(', ')}`
);
}
}
if (mergedSpec.data.type) {
if (mergedSpec.data.type === 'integer') {
if (organizedArguments.data.match(/^[0-9]+$/) !== null) {
organizedArguments.data = parseInt(organizedArguments.data, 10);
} else {
throw new ErrorWithoutStack(
`The command "${organizedArguments.command.trim()}" expects integer data\nProvided: ${
organizedArguments.data
}`
);
}
} else if (mergedSpec.data.type === 'float') {
if (
organizedArguments.data.match(/^[0-9]*[.]*[0-9]*$/) !== null &&
organizedArguments.data !== '.' &&
organizedArguments.data !== ''
) {
organizedArguments.data = parseFloat(organizedArguments.data);
} else {
throw new ErrorWithoutStack(
`The command "${organizedArguments.command.trim()}" expects float data\nProvided: ${
organizedArguments.data
}`
);
}
} else {
throw new ErrorWithoutStack(`Unrecognized "type": ${mergedSpec.data.type}`);
}
}
}
// Trim command
organizedArguments.command = organizedArguments.command.trim();
// Return
return organizedArguments;
},
// Construct a full input object
constructInputObject(organizedArguments: OrganizedArguments): InputObject {
// Initialize
const inputObject: InputObject = {
command: '',
};
// Get merged spec for this command
const mergedSpec = utils(settings).getMergedSpec(organizedArguments.command);
// Loop over each component and store
Object.entries(mergedSpec.flags).forEach(([flag]) => {
const camelCaseKey = utils(settings).convertDashesToCamelCase(flag);
inputObject[camelCaseKey] = organizedArguments.flags.includes(flag);
});
Object.entries(mergedSpec.options).forEach(([option, details]) => {
const camelCaseKey = utils(settings).convertDashesToCamelCase(option);
const optionIndex = organizedArguments.options.indexOf(option);
inputObject[camelCaseKey] = organizedArguments.values[optionIndex];
if (details.required && !organizedArguments.options.includes(option)) {
throw new ErrorWithoutStack(`The --${option} option is required`);
}
});
// Handle missing required data
if (mergedSpec.data && mergedSpec.data.required && !organizedArguments.data) {
throw new ErrorWithoutStack('Data is required');
}
// Store data
inputObject.data = organizedArguments.data;
// Store command
inputObject.command = organizedArguments.command;
// Store pass-through
if (organizedArguments.passThrough) {
inputObject.passThrough = organizedArguments.passThrough;
}
// Return
return inputObject;
},
// Get all commands in program
getAllProgramCommands(): string[] {
// Get all directories
const mainDir = path.dirname(settings.mainFilename);
let commands = utils(settings).files.getAllDirectories(mainDir);
// Process into just commands
commands = commands.map((file) => file.replace(`${mainDir}/`, ''));
commands = commands.map((file) => file.replace(/\.js$/, ''));
commands = commands.map((file) => file.replace(/\//, ' '));
// Return
return commands;
},
// Convert a string from aaa-aaa-aaa to aaaAaaAaa
convertDashesToCamelCase(string: string): string {
return string.replace(/-(.)/g, (g) => g[1].toUpperCase());
},
// File functions
files: {
// Return true if this path is a directory
isDirectory(path: string): boolean {
return fs.lstatSync(path).isDirectory();
},
// Return true if this path is a file
isFile(path: string): boolean {
return fs.lstatSync(path).isFile();
},
// Get child files of a parent directory
getFiles(directory: string): string[] {
if (!fs.existsSync(directory)) {
return [];
}
const allItems = fs.readdirSync(directory).map((name: string) => path.join(directory, name));
return allItems.filter(utils(settings).files.isFile);
},
// Get child directories of a parent directory, recursively & synchronously
getAllDirectories(directory: string): string[] {
if (!fs.existsSync(directory)) {
return [];
}
return fs.readdirSync(directory).reduce((files: string[], file: string) => {
const name = path.join(directory, file);
if (utils(settings).files.isDirectory(name)) {
return [...files, name, ...utils(settings).files.getAllDirectories(name)];
}
return [...files];
}, []);
},
// Get a command's spec
getCommandSpec(directory: string): CommandSpec {
// Error if directory does not exist
if (!fs.existsSync(directory)) {
throw new Error(`Directory does not exist: ${directory}`);
}
// List the files in this directory
const commandFiles: string[] = utils(settings).files.getFiles(directory);
// Error if not exactly one spec file
if (commandFiles.filter((path) => path.match(/\.spec.c?js$/)).length !== 1) {
throw new ErrorWithoutStack(
`There should be exactly one ${chalk.bold('.spec.js')} or ${chalk.bold('.spec.cjs')} file in: ${directory}`
);
}
// Get the file path
const specFilePath = commandFiles.filter((path) => path.match(/\.spec.c?js$/))[0];
// Return
try {
return require(specFilePath);
} catch (error) {
throw new ErrorWithoutStack(
`This spec file contains invalid JS: ${specFilePath}\n${chalk.bold('JS Error: ')}${error}`
);
}
},
},
};
}
|
/*!
* \brief Get the current value of a sensor and log it in the xLogsQueue.
*
* \param SensorId The sensor id of the sensor to get the value from.
*/
void v_datalog_AddSensorLog( eLogSourceId SensorId )
{
xLogDef *pxLog;
uxNbMsgsInLogsQueue = uxQueueMessagesWaiting( xLogsQueue );
if( DATALOG_LOGSQUEUE_HITHRESHOLD <= uxNbMsgsInLogsQueue )
{
vTaskSuspend( xLogToFileHndl );
vTaskResume( xLogToFileHndl );
}
pxLog = pxdatalog_log_alloc_init( DATALOG_ALLOC_DYNAMIC );
if( NULL != pxLog )
{
pxLog->id = SensorId;
if( false == b_sensor_get_value( pxLog ) )
{
vdatalog_log_free( pxLog );
return;
}
if( errQUEUE_FULL == xQueueSend( xLogsQueue, (void *)&pxLog, 0 ) )
{
vdatalog_log_free( pxLog );
vTaskSuspend( xLogToFileHndl );
vTaskResume( xLogToFileHndl );
}
}
} |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { DiffPageRoutingModule } from './diff-routing.module';
import { DiffPage } from './diff.page';
@NgModule({
imports: [CommonModule, IonicModule, DiffPageRoutingModule],
declarations: [DiffPage],
})
export class DiffPageModule {
}
|
Subsets and Splits