science and technology

あ〜こけしを量産したい。そして何よりこのこけし達が芸術過ぎて、なんてこったです。笑C...

この投稿をInstagramで見る あ〜こけしを量産したい。 そして何よりこのこけし達が芸術過ぎて、なんてこったです。笑 Cafe MoulinRougeさんさすがです。笑 2枚目は南が、青森で産んだこけし達す。 また青森で産みたいです。 I wanna make kokeshi. Saya mau buat kokeshi???????? #kokeshi #kokeshidoll #kyuranger #Repost @cafe_moulinrouge_aomo




science and technology

☆さぁ共に時を刻みませんか?

さぁ南圭介卓上カレンダー2020-21の通販が開始されましたので、思い切ってお近くに南を置いてみませんか?南のアマビエはもうご存知ですかな?まだという方は刮目宜しくお願い致します。さてさて中々会えない日が続きますが今宵も南圭介STYLEで22時頃からライブ配信出来たらなと思っています!時間前後してしまったら申し訳ない!そしてこちら南圭介STYLEから、イベント「花の◯組」の先行抽選販売も始まっているのでこちらの方も是非に!南圭介@keisukeminami73 さぁまもなく20時〜fanicon




science and technology

☆今宵もありがとうございました!!

ニコ生「トリプルゾーン」刮目ありがとうございました!!背景はお花見????!こういう状況下なので、少しでもお花見気分をとスタッフさんの粋な計らいで合成スクリーンでお届けしました^_^ゲストは森山栄治さん!!時間の都合で、写真が撮れなかったのですが、また会える事を信じて^_^さてさてこの度、南は明日3月20日(金)からdTVチャンネルのひかりTVチャンネル+で配信される【トリプルミッション!!!女優たちの夢、ドラマにしました ムショラジ編 】に佐津川透役として出演しますので刮目お願い致します!そしてそ




science and technology

陽はまた昇る。今日という日が人生で一番太陽と向き合った日かもしれない。とても楽しく...

この投稿をInstagramで見る 陽はまた昇る。 今日という日が人生で一番太陽と向き合った日かもしれない。 とても楽しく、温かかった。 いつもありがとうございます。 これからも我々を照らしてくださいませ。 The sunrise from here is so beautiful. Matahari terbit???????? #春分の日 #日の出 #石造鳥居 #sunrise #matahariterbit 南 圭介 keisuke Minami(@kei




science and technology

☆素敵な新年度はGAROから!

4/2日(木)放送スタート「GARO-VERSUS ROAD-」水瓶幸哉役で出演させていただきます!!水瓶幸哉という役に、キャストの皆さんに、スタッフの皆さんに出会えた事嬉しく思います!!そして15周年記念という南自身の芸能生活とほぼ同じ時間を歩んでいる作品に出会えた事にご縁を感じます!!新たなるGARO最後まで目が離せない作品となっています!!最後の最後まで刮目宜しくお願い致します!!おやとなると特撮シリーズ南がまだ出演していないのはウルトラマンシリーズのみということになるのでは?となるとウル




science and technology

青森県は南の中でもうりんご以上にこけし。好き。そしてまたこちらのメッセージを伝えたい...

この投稿をInstagramで見る 青森県は南の中で もうりんご以上にこけし。好き。 そしてまたこちらのメッセージを伝えたいのでRepostさせていただきました。 #Repost @cafe_moulinrouge_aomori with @get_repost ・・・ ひらめきスパークリング! キラメイレッド! 子供たち、いや、みんなが応援しているぞ ・ ・ そして、Wレッドのシシレッドとホウオウソルジャー、キュウレンジャーも応援しているぞ ・ ・ ヒーロ




science and technology

☆まだまだ配信中です!

ドラマ「ムショラジ」ありがとうございました!!まだまだ配信期間中ですので良かったら是非刮目宜しくお願いいたします!!実は今回初共演の永嶋柊吾氏と!この撮影をきっかけに一段と仲が深まりましたな。!!ありがたき!!草野イニさんと木幡竜さんともお写真を!!この撮影期間中は、去年の夏の終わり頃でして、小田原の街、街の方にはとてもとてもお世話になりました!ありがとうございました^_^中々外に出れない日が続きますが、この状況に屈せず、前向きにいきましょう!!是非皆さま体調には気をつけてくださいね!!そんな今




science and technology

GARO-VERSUS ROAD-ご視聴ありがとうございました!!新たなるGAROに...

この投稿をInstagramで見る GARO-VERSUS ROAD- ご視聴ありがとうございました!! 新たなるGAROに携われたこと、素敵なキャスト&スタッフの皆さんと出会えたこと、水瓶幸哉という役に出会えたこと、とても嬉しく思います。 GARO -VERSUS ROAD- これからどのように進むのか 最後の最後まで見逃せません! 今宵25時〜BS日テレの放送も宜しくお願い致します!! I'm in GARO. Saya muncul di GARO????




science and technology

☆のりこえましょう!

さてさて皆様いかがお過ごしですか?おうち時間のお供に、南足りてますか?油断できない状況が続きます。一丸となって乗り越えましょう!!そしてそして明日はなんとCSテレ朝チャンネルにてGWスーパー戦隊特別企画一挙放送宇宙戦隊キュウレンジャーも3話放送されます!皆さんリクエストありがとうございました!!おかげさまで、鳳ツルギも目を覚ませそうです。笑是非是非刮目宜しくお願い致します!!さらにはfanicon南圭介STYLEにて明日6日23時59分まで、先日のYouTube南圭介@keisukeminami




science and technology

Истоки и Подлинное, или мифы, которыми мы живем

Этой публикацией мы открываем серию колонок лингвиста Сергея Лёзова, профессора Института классического Востока и античности НИУ ВШЭ, занимающегося документацией угрожаемых диалектов арамейского языка.




science and technology

Итальянские каникулы детей Чернобыля

Мало кто в России знает, какую роль сыграла Италия в помощи детям, пострадавшим от последствий чернобыльской аварии, — хотя если вы спросите знакомых из Беларуси, то наверняка среди них будет немало побывавших в Италии благодаря той или иной программе оздоровления. Всё началось с того, что в 1991 году ирландская активистка и адвокат Ади Роче, в ответ на просьбу о помощи белорусских врачей, создала благотворительную организацию Chernobyl Children's Project International…




science and technology

Фальшивые швы

В один из моих визитов в Москву в 1980 году я навещал семейство дяди, Анатолия Петровича Александрова. Дядя, в то время президент Академии наук СССР и директор Института атомной энергии, в один из вечеров рассказал о чрезвычайном происшествии на работе: на одной из атомных электростанций — подопечных Курчатовского института уже давно наблюдалось какое-то подозрительное «потение» заглушки трубопровода высокого давления. Речь шла о толстостенной трубе из нержавеющей стали с плоской крышкой, вложенной в трубу и вваренной по периферии толстым швом…




science and technology

Олег Коростелёв: хранитель памяти о русском зарубежье

20 марта 2020 года ушел из жизни Олег Анатольевич Коростелёв — российский литературовед, архивист, библиограф, один из крупнейших в России специалистов по русскому зарубежью. Я помню, каким поистине бесценным и увлекательным спутником он был, когда однажды мы пересеклись на одной из конференций в Париже. Мне тогда казалось, что рядом со мной идет не просто остроумный и блестящий собеседник, но близкий приятель большей части знаменитых персон русской эмиграции.




science and technology

Математика за Северным полярным кругом

Мы продолжаем публиковать интервью с участниками конференции «Интегрируемые системы и автоморфные формы», прошедшей в новом Математическом центре «Сириус» в Сочи в последнюю неделю зимы (см. репортаж «Охотники на спецфункции, или „Сириус“ накануне вируса»). Борис Кругликов, профессор Университета Тро́мсё — Арктического университета Норвегии, который расположен на 350 км севернее Полярного круга, рассказывает о своих исследованиях и специфике изучения царицы всех наук на родине Абеля и Софуса Ли. Беседовал Алексей Огнёв.




science and technology

Жизнь бунтаря (памяти Фримена Дайсона)

28 февраля в госпитале вблизи Принстона скончался Фримен Дайсон. Ему было 96 лет. Дайсон — автор интереснейших научных работ в области квантовой физики, физики твердого тела, биофизики, космонавтики и даже климатологии. Он полагал, что законы природы «построены таким образом, чтобы сделать Вселенную настолько интересной, насколько это возможно».




science and technology

«Спектр-РГ» совершил оборот вокруг точки Лагранжа

16 апреля 2020 года астрофизическая обсерватория «Спектр-РГ» стала первым отечественным космическим аппаратом, который облетел точку Лагранжа L2.




science and technology

Транснептуновое племя, или Казус Койпера

Недавно исполнилось 90 лет открытию Плутона. Это событие когда-то стало важной вехой в исследованиях периферии Солнечной системы. Плутон долгое время считался рядовой планетой, но в действительности оказался представителем другого племени, которое теперь совокупно именуется транснептуновыми объектами (ТНО), или поясом Койпера. Мы расскажем о необычной истории возникновения этого названия.




science and technology

В Центре света. Фотоника, терагерцы, оптические компьютеры и наноиглы

Интервью с Франко Купперсом (Franko Küppers), профессором, директором Центра фотоники и квантовых материалов (CPQM) Сколтеха, в свете нынешних обстоятельств вынуждено проводилось удаленно — по скайпу в режиме видеоконференции. Разговор шел о том, какими проектами занята научная группа профессора и о траекториях появления иностранных специалистов в российских институтах. Вопросы задавали Борис Штерн и Максим Борисов.




science and technology

Информация не должна знать границ

Мне часто приходится слышать, что наши тест-системы очень слабые, они не выявляют высокий процент заболевших. Я знаю, что это не так, потому что общаюсь с друзьями, которые работают в «Векторе». Но почему Роспотребнадзору нельзя официально выложить информацию о принципе работе тест-систем, о чувствительности наших тестов? Почему я, будучи ученым, должна узнавать информацию от «своих»? Такая закрытость порождает огромное количество конспирологических теорий…




science and technology

Декамерон‑2020, или Zoom-вечеринка во время чумы

Необычные социальные условия во время пандемии COVID-19 побуждают искать новые способы интеллектуального общения. И у нас есть хрестоматийный пример подобного поиска — это «Декамерон» Боккаччо. Как многие помнят, события «Декамерона» происходят во время чумы 1348 года. Чтобы ненадолго отвлечься от печальных мыслей, семь девушек и трое юношей уходят из Флоренции, охваченной эпидемией, собираются вместе в загородном имении и в течение десяти дней рассказывают друг другу истории…




science and technology

Александр Аузан: «Пандемия COVID‑19 — это плата за глобализацию»

Как меняется политическая повестка во время эпидемии? Сколько денег нужно на поддержку граждан и бизнеса? Какие активы падают, а какие, наоборот, растут? Ольга Орлова обсудила эти животрепещущие вопросы с экономистом Александром Аузаном в программе «Гамбургский счет» на Общественном телевидении России. Публикуем отредактированную расшифровку беседы.




science and technology

Внутриклеточный театр боевых действий

Нынешняя коронавирусная инфекция — это две болезни. Первая — вирусная инфекция верхних дыхательных путей — проходит практически без проявлений. Она запускает глубокое поражение легких, которое в основном уже развивается самостоятельно. Первую стадию можно было бы лечить антивирусными препаратами, но в отсутствие симптомов совершенно непонятно, кого именно лечить. Вторая стадия — тяжелая болезнь, острое воспаление легких — не лечится. Антивирусные препараты на нее почти не действуют, поскольку от вируса она уже не зависит.




science and technology

Коронавирусы: кто съел летучую мышь?

Во второй видеолекции из серии «Коронавирус: новые данные», прочитанной 11 апреля, профессор Нетёсов подчеркнул, насколько важно сейчас диагностировать бессимптомное носительство коронавируса. Он рассказал о таксономии семейства коронавирусов и сравнил летальность нового вируса с теми, что ранее вызывали эпидемии атипичной пневмонии, «свиного» и обычного сезонного гриппа.




science and technology

Пришелец в короне

SARS-CoV-2 на сегодняшний день можно сравнить с человеком, случайно попавшим в незнакомую цивилизацию: он может кого-то смертельно обидеть, вызвать волнения или даже убить просто по незнанию. В реальности вирусу выгодно, чтобы его хозяин продолжал жить, активно перемещаться, общаться и заражать новых особей. Так что будем надеяться, что постепенно, в результате новых мутаций в геноме вируса, это заболевание станет проходить мягче…





science and technology

«Мир Адама существует благодаря изменчивости»

О том, как идет работа над фильмами и спектаклями, как расколдовываются табу и как зреет замысел, почему так мало пьес и сценариев о жизни ученых, рассказал ТрВ-Наука режиссер Владимир Мирзоев. Беседовала Наталия Демина.




science and technology

Эпидемия — время реформ

Занялось разбором подведомственного хозяйства наше правительство: например, несколько десятков педвузов были переданы из Минобрнауки в Минпросвещение. И это, коллеги, очень правильно. Всем давно известно: ума нет — иди в пед. Пусть эти педвузы, где науки никакой нет, готовят педагогов для школ не в нашем министерстве! Но самое важное, конечно, происходит в моем родном университете. В пору эпидемии у Виктора Антоновича дошли наконец руки до крупной реформы МГУ.




science and technology

Психология — очень живая и забавная наука

Научно-популярная книга комиксов? Да, такой жанр — в оригинальном, а не переводном виде — теперь появился на рынке российской научно-популярной литературы. Полина Кривых, психофизиолог, лектор, рассказала нашей газете о своей книге комиксов «Где мои очки, и другие истории о нашей памяти» (М.: Бомбора, 2020), подготовленной совместно с замечательной художницей Мариной Евлановой, а также о новом проекте, посвященном Ig Nobel Prize.




science and technology

Заразительные слова

Слово зараза в наше время чаще всего употребляется в переносном значении, шутливом, одушевленном, как, например, язва. Конечно, развитие переносных значений — очень распространенный тип языковых изменений, но в этом клане однокоренных родственников они процветают как-то образцово пышно. Как будто перезаражались друг от друга. Источник (он же родитель) слова зараза — глагол заразить, т. е. ‘передать’: в прямом смысле — болезнь, а метафорически — увлеченность чем-либо…




science and technology

Антарктида через 50 лет

Алексей Екайкин, гляциолог, полярник, вед. науч. сотр. лаборатории изменений климата и окружающей среды Арктического и антарктического научно-исследовательского института (ААНИИ), продолжает серию научных прогнозов, начатых в ТрВ № 300 и 301. Его «машина времени» переместилась на полвека вперед и увидела будущее шестого континента и всей антарктической науки.




science and technology

Лакомый кусок

В настоящее время в самом сердце Санкт-Петербурга, на стрелке Васильевского острова, в историческом здании Северного пакгауза Биржи, построенного в 1832 году под руководством архитектора И. Ф. Лукини, где с сороковых годов ХХ века размещаются учреждения Академии наук, ведутся нешуточные баталии с участием нескольких академических институтов, Министерства науки и высшего образования и Национального исследовательского университета информационных технологий, механики и оптики (НИУ ИТМО).




science and technology

Географы будущего станут лучше понимать прошлое

Продолжаем публиковать прогнозы ученых о том, что будет с их областью науки в далеком будущем. Сотрудники Института географии РАН — гляциологи, палеоклиматологи, экономгеографы и почвоведы — заглянули на несколько десятилетий вперед.




science and technology

Олимпиада-призрак: Токио-1940

Олимпиадам в Японии мистически не везет — токийскую из-за пандемии коронавируса перенесли на июль 2021 года. В ХХ веке Токио дважды подавал заявки на проведение летних олимпиад. Первая из них (1940 года) не состоялась, вторая (1964 года) была успешно проведена. Процесс выдвижения токийской кандидатуры и ход подготовки к Играм позволяют понять особенности политической и культурной ситуации в довоенном и послевоенном мире, а также оценить тот огромный путь, который проделала Япония за это время.




science and technology

Май-1945: поиски Гитлера и последующие годы умолчания

Накануне 9 Мая вышло в свет дополненное и обновленное издание книги писательницы и военного переводчика Елены Ржевской «Берлин, май 1945». Переводчик Любовь Сумм, внучка Елены, рассказала ТрВ-Наука, как шла работа над книгой. Беседовала Наталия Демина.




science and technology

Заявление Клуба «1 июля» о реформе МГУ

Клуб «1 июля» выражает глубокую озабоченность сообщениями о планируемой реформе Московского государственного университета — первого во всех смыслах высшего учебного заведения страны, служащего образцом и моделью университетского образования для всей России. Планируемые изменения структуры и программ МГУ поставят окончательную точку в череде разрушительных преобразований системы высшего образования, начатых уже много лет назад без ясного смысла и целей и вопреки мнению ученых и преподавателей.




science and technology

С завтрашнего дня вы работаете дистанционно

Ксения Гилярова: «В последний раз я была на работе в понедельник, 16 марта. Когда я пришла после занятий на кафедру, нам объявили: «Отныне вы ведете пары дистанционно, дорогие преподаватели». Хорошо помню растерянность на лицах коллег в этот момент: большинство из нас никогда не преподавали онлайн, да и с компьютером дружат не все — мы гуманитарии, и многие не такие молодые. К счастью, одна моя коллега уже умела работать с некоторыми программами и тут же взялась всех обучить…»




science and technology

«Пытаюсь задавать больше вопросов и придумывать побольше интерактивных схем»

Пожалуй, главным вызовом была боязнь оказаться малозначительным дополнением к своей собственной презентации, которую я практически с тем же успехом мог бы выслать студентам без озвучивания. В формате онлайн-лекции я не вижу аудитории, не ощущаю ее обратной реакции (не скучно ли? сработала ли попытка оживить изложение?), не уверен, что меня слушают (а иногда и что меня слышат в принципе). Не сразу, но постепенно начал осознавать, что у формата онлайн-лекций для преподавателя есть и определенные плюсы.




science and technology

Вышка на удаленке

В воскресенье 15 марта 2020 года Минобр­науки рекомендовало вузам перейти на удаленный режим работы. Весь понедельник появлялись новости о том, как тот или иной университет последовал рекомендации. «Ну а мы-то когда?» — думал я. Приказ по НИУ ВШЭ вышел ближе к ночи. Во вторник, в 10:30, у меня стояла лекция, и я уж собрался писать письмо студентам о том, как она будет проходить…




science and technology

Пожалуйста, не выдумывайте Швецию

Пётр Савельев, выпускник биолого-почвенного факультета СПбГУ, программист, живет сейчас в Швеции, недалеко от Стокгольма. Волею судеб ему приходится также работать с коммунальным хозяйством, со статистикой, связанной с ЖКХ, с нормативно-правовыми актами в этой области. Для ТрВ-Наука он рассказал, что́ на самом деле происходит в Швеции во время пандемии.




science and technology

Сверхмощные лазеры — 2070

Уверен, что ближайшие десятилетия станут периодом максимального расцвета для лазеров сверхвысоких пиковых мощностей. Во-первых, рекордно достигнутая мощность продолжит расти. Это, в частности, может быть реализовано за счет свежей идеи, предложенной в Институте прикладной физики РАН и буквально в последние пару лет подтвержденной экспериментально…




science and technology

COVID-19: гонка вооружений

Каким образом вирус SARS-CoV-2 корректирует ошибки при транскрипции своего генома? Как эта способность связана с безуспешностью клинических испытаний ремдесивира? И можно ли считать эти испытания окончательно проваленными? На вопросы Юлии Черной отвечает Дмитрий Жарков, член-корр. РАН, директор Центра перспективных биомедицинских исследований НГУ, зав. лабораторией геномной и белковой инженерии Института химической биологии и фундаментальной медицины СО РАН.




science and technology

Александр Шень об удаленном режиме работы

В апреле я участвовал только в онлайн-семинарах, и в этом качестве опыт скорее положительный: вполне можно что-то обсуждать, и даже можно писать на электронной доске, если участвуют два-три человека. А уж для традиционных докладов со слайдами и вопросами пос­ле доклада (если отвлечься от того, что это вообще не лучше видеозаписи) никаких проблем нет. Но есть проблема обратной связи…




science and technology

О переименовании улицы Тимофеева-Ресовского в Екатеринбурге

В редакцию пришло письмо двух ученых, рассказывающее о тревожном событии: улица одного из крупнейших научных центров России — города Екатеринбурга потеряла имя выдающегося российского генетика Н. В. Тимофеева-Ресовского. Начат сбор подписей против этого решения главы Екатеринбурга А. Г. Высокинского. Этим письмом редакция обращается к руководству города с вопросом: уважаемый Александр Геннадьевич, что происходит? Почему с улицы города стерто имя замечательного ученого и гражданина?




science and technology

Разгадать «формулу» света

Международная группа ученых впервые создала стабильно светящиеся растения, перенеся в них ДНК из биолюминесцентных грибов. Статья была опубликована в Nature Biotechnology и привлекла внимание не только научного сообщества, но и мировых СМИ. В научную группу вошли исследователи из московского биотехнологического стартапа «Планта», Института биоорганической химии РАН (ИБХ), станции искусственного климата «Биотрон» и Института науки и технологий Австрии. Об их прекрасном, прежде всего эстетически, научном результате рассказывает научный журналист Александра Борисова.





science and technology

Leo Zovic: Places, Peeps And Plagues

(in-package #:cl-pestilence)

;;   This is _not_ a simulation. It's just a game. And any resemblance
;; to any world, real or imaginary, is entirely coincidental.

;;   You can copy/paste this post in its entirety into a Common Lisp
;; REPL and play around with it if you like. I'm documenting it where
;; possible, but it's just a small toy to poke at for the moment.

;;   I've been thinking a lot about asymmetric multiplayer games and
;; <gestures wildly to world at large> all this.
;; I'm not actively _trying_ to model it accurately, but it's probably
;; obvious what's been consuming my thoughts lately.

;;   Let's get right into this. I'll explain as I go, and tie a few things
;; together neatly at the end. I hope. Regardless, there will absolutely
;; be a repo sometime fairly soon.

;; A place can be tagged arbitrarily, and can contain occupants.
;; They also collect points.

(defclass place ()
  ((tags :initarg :tags :initform nil :accessor tags)
   (occupants :initarg :occupants :initform nil :accessor occupants)
   (points :initform 0 :accessor points)))

(defun place? (thing)
  (eq (find-class 'place) (class-of thing)))

(defun place (&key tags occupants)
  (make-instance 'place :tags tags :occupants occupants))

(defun gen-place ()
  (let ((tag (pick '(:apartment-building :house :cottage
		     :office-building :factory :store
		     :cafe :lounge :theater))))
    (place :tags (list tag))))

(defmethod details ((place place))
  (format nil "====================~%~a {~{~a~}}~%~{  ~a~^~%~}~%"
	  (first (tags place))
	  (rest (tags place))
	  (mapcar #'details (occupants place))))

(defmethod show ((place place))
  (format nil "~20@a ~5a [~{~a~}]~%"
	  (first (tags place)) (points place)
	  (mapcar #'show (occupants place))))

;; A peep goes places.
;; They have
;;  - their daily routine (a list of places to visit)
;;  - their todo (the part of their routine they still need to do;
;;                they are currently at the first place in this list)
;;  - their health (a number from 0 to 100)
;;  - a list of plagues
;; Finally, they _also_ collect points.

(defclass peep ()
  ((routine :initarg :routine :initform (list) :accessor routine)
   (todo :initarg :todo :initform nil :accessor todo)
   (health :initarg :health :initform 100 :accessor health)
   (plagues :initform nil :accessor plagues)
   (points :initform 0 :accessor points)))

(defun peep? (thing)
  (eq (find-class 'peep) (class-of thing)))

(defun peep (&key places)
  (make-instance 'peep :routine places :todo places))

(defun health->string (health)
  (cond ((>= health 90) "@")
	((>= health 80) "0")
	((>= health 70) "O")
	((>= health 50) "o")
	((>= health 30) ":")
	((>= health 1)  ".")
	(t "☠")))

(defmethod details ((peep peep))
  (format nil "[~a ~3d [~{ ~a~^ ->~}]]"
	  (health->string (health peep)) (health peep)
	  (mapcar
	   (lambda (place) (first (tags place)))
	   (routine peep))))

(defmethod show ((peep peep)) (health->string (health peep)))

;; A world is a list of places, occupied by peeps. The world we start
;; peeps in also determines their routine.

(defun gen-world (&key (num-places 20) (num-peeps 100))
  (let ((places (loop repeat num-places collect (gen-place))))
    (loop repeat num-peeps
       do (let* ((routine (loop repeat 5 collect (pick places)))
		 (peep (peep :places routine)))
	    (push peep (occupants (first routine)))))
    places))

(defmethod details ((world list))
  (format nil "~%~{~a~}~%" (mapcar #'details world)))

(defmethod show ((world list))
  (format nil "~%~{~a~}~%" (mapcar #'show world)))

(defmethod all-peeps ((world list))
  (loop for place in world append (all-peeps place)))

(defmethod all-peeps ((place place))
  (loop for o in (occupants place) if (peep? o) collect o))

;; `tick!`ing a world means moving every peep through their routine once.
;;   We `tick!` each peep, then `tick!` each place until all the peeps are
;; done. Then we reset their routines.
;; You can think of this as a turn in the game.

(defmethod tick! ((world list))
  (let ((peeps (all-peeps world)))
    (loop while peeps
       do (setf peeps
		(loop for p = (pop peeps) while p
		   for res = (tick! p)
		   if res collect res))
       do (mapc #'tick! world)
       do (format t "~a" (show world)))
    (loop for p in (all-peeps world)
       do (setf (todo p) (routine p))))
  world)

;; Don't worry about the details of how to `tick!` peeps or places yet.

;;   Ok, here's where it gets a bit darker. Although we _did_
;; foreshadow this in the definition of `peep`. And also in the title
;; of the accompanying blog post.

;; A plague is another living thing.
;; It has
;;  - a host (a peep that it's infecting)
;;  - a signature (a token representing its lineage and strain)
;;  - health (how well it's doing inside its host)
;;  - virulence (how likely it is to spread to another host)
;;  - efficiency (how efficient they are at feeding)
;;  - reproduce (a function that returns a new instance to push into a new host)
;;  - and a strategy (a function, possibly closed, that takes
;;    itself and its host peep and mutates)

;; Plagues do not collect points; they score differently.

(defclass plague ()
  ((host :initarg :host :initform nil :accessor host)
   (signature :initarg :host :initform "SIG" :accessor signature)
   (health :initarg :health :initform 10 :accessor health)
   (virulence :initarg :virulence :initform 10 :accessor virulence)
   (efficiency :initarg :efficiency :initform 0.2 :accessor efficiency)
   (reproduce
    :initarg :reproduce
    :initform
    #'plague
    :reader reproduce)
   (strategy
    :initarg :strategy
    :initform
    (lambda (plague peep)
      (feed! plague peep 30))
    :reader strategy)))

(defun plague ()
  (make-instance 'plague))

;; Plagues can `feed!` on peeps or plagues. To feed means to
;; take away some of the targets' health and add some to your own.

(defmethod feed! ((self plague) (peep peep) (amount integer))
  (decf (health peep) amount)
  (incf (health self) (* (efficiency self) amount)))

(defmethod feed! ((self plague) (plague plague) (amount integer))
  (decf (health plague) amount)
  (incf (health self) (* (efficiency self) amount)))

;; Plagues can also `infect!` peeps by `reproduce`ing into them.

(defmethod infect! ((self plague) (peep peep))
  (unless (infected-by? self peep)
    (let ((child (funcall (reproduce self))))
      (setf (host child) peep)
      (push child (plagues peep)))))

(defmethod infected-by? ((self plague) (peep peep))
  (member (signature self) (mapcar #'signature (plagues peep))
	  :test #'string=))

;;  `tick!`ing a plague causes it to weaken and also carry out its strategy.
;; This models the background effect of the immune system of its host.

(defmethod tick! ((plague plague))
  (decf (health plague) 1)
  (funcall (strategy plague) plague (host plague))
  plague)

;;  `tick!`ing a peep means moving them to their next place, and also
;; `tick!`ing any plagues they may have contracted. Also, peeps are
;; resilient; they heal a small amount each time they tick (to a
;; maximum of 100).
;;  If a peep dies, they no longer move. And their plagues probably
;; won't do well. Peeps like to go places. They score points for each
;; place they go to.

(defun dead? (thing) (>= 0 (health thing)))

(defmethod tick! ((peep peep))
  (unless (dead? peep)
    (let ((location (pop (todo peep))))
      (incf (points peep))
      (setf (occupants location) (remove peep (occupants location)))
      (push peep (occupants (or (first (todo peep)) (first (routine peep)))))
      (setf (health peep) (min 100 (+ 5 (health peep))))
      (mapc #'tick! (plagues peep))
      (unless (empty? (todo peep))
	peep))))

;; `tick!`ing a place causes it to score for each `peep` present. And it causes
;; any `plague`s on present `peep`s to try to `infect!` other nearby peeps.
;; Places also lose points for each dead peep they contain.

(defmethod tick! ((place place))
  (incf (points place) (length (occupants place)))
  (loop for peep in (all-peeps place)
     if (dead? peep)
     do (decf (points place) 2)
     else do (loop for plague in (plagues peep)
		do (loop for victim in (remove peep (all-peeps place))
		      if (>= (virulence plague) (random 100))
		      do (infect! plague victim))))
  place)

;;  So, now we've got the basic framework of the game in place. There are three
;; players in this game: places, peeps and plagues.
;;   A plague player automatically loses if they are completely cured, and
;; automatically wins if they manage to kill everyone. That's fairly simple.
;;   A place player wins if they manage to cure the plague. They automatically
;; lose if all the peeps die. Also, fairly simple.
;;   A peep player is trying to survive. If they manage to make it some numer
;; of turns before dying, then we have to score the game instead of declaring
;; an outright winner regardless of game state.

;;   A peep player's score is the total number of points plus remaining health
;; on all of their peeps, minus the number of active plagues on said peeps.
;;   A plague player's score is the total number of health of their plagues,
;; with a multiplier equal to the number of places fully infected by
;; their plague.
;;   A place player's score is the total number of points in their places.

(defun score (world)
  (list :peep (let ((score 0))
		(loop for p in (all-peeps world)
		   unless (dead? p)
		     do (incf score (+ (health p) (points p)))
		   do (decf score (length (plagues p))))
		score)
	:place (let ((score 0))
		 (loop for p in world
		    do (incf score (points p)))
		 score)
	:plague (let ((score 0))
		  (loop for victim in (all-peeps world)
		     do (loop for p in (plaguesvictim)
			   do (incf score (max 0 (health p)))))
		  (loop for target in world
		     if (every
			 (lambda (victim)
			   (not (empty? (plagues victim))))
			 (all-peeps target))
		     do (setf score (* 2  score)))
		  score)))

;;   I think that's all I've got for now. This is definitely an idea I want
;; to run with. At the moment, it's just a tiny, in-repl proof-of-concept,
;; and not particularly fun, but I'm going to try developing it further with an
;; eye towards turning it into an actual web game playable from this site.

;; As always, I'll let you know how it goes.

(defun pick (lst)
  (nth (random (length lst)) lst))

(defun empty? (lst)
  (null lst))




science and technology

Wimpie Nortje: Database migration libraries for PostgreSQL.

It may be tempting at the start of a new project to create the first database tables manually, or write SQL scripts that you run manually, especially when you first have to spend a significant amount of time on sifting through all the migration libraries and then some more to get it working properly.

Going through this process did slow me down at the start of the project but I was determined to use a migration tool because hunting inexplicable bugs that only happen in production just to find out there is a definition mismatch between the production and development databases is not fun. Using such a tool also motivates you to write both the setup and teardown steps for each table while the current design is still fresh in your mind.

At first I considered a standalone migration tool because I expect them to be very good at that single task. However, learning the idiosyncrasies of a new tool and trying to make it fit seamlessly into my development workflow seemed like more trouble than it is worth.

I decided to stick with a Common Lisp library and found the following seven that work with PostgreSQL and/or Postmodern:

I quickly discounted Crane and Mito because they are ORM (Object Relational Mapper) libraries which are way more complex than a dedicated migration library. Development on Crane have stalled some time ago and I don't feel it is mature enough for frictionless use yet. Mito declares itself as being in Alpha state; also not mature enough yet.

I only stumbled onto cl-mgr and Orizuru-orm long after making my decision so I did not investigate them seriously. Orizuru-orm is in any case an ORM which I would have discounted because it is too complex for my needs. CL-mgr looks simple, which is a good thing. It is based on cl-dbi which makes it a good candidate if you foresee switching databases but even if I discovered it sooner I would have discounted it for the same reason as CL-migrations.

CL-migrations looks very promising. It is a simple library focusing only on migrations. It uses clsql to interface with the database which bothered me because I already committed to using Postmodern and I try to avoid adding a lot of unused code to my projects. The positive side is that it interfaces to many different databases so it is a good candidate if you are not committed to using Postmodern. It is also a stable code base with no outstanding bug reports.

The two projects I focused on was Postmodern-passenger-pigeon and Database-migrations because they both use Postmodern for a database interface.

Postmodern-passenger-pigeon was in active development at the time and it seemed safer to use than Database-migrations because it can do dry runs, which is a very nice feature when you are upgrading your production database and face the possibility of losing data when things go awry. Unfortunately I could not get it working within a reasonable amount of time.

I finally settled on Database-migrations. It is a small code base, focused on one task, it is mature and it uses Postmodern so it does not pull in a whole new database interface into my project. There are however some less positive issues.

The first issue is a hindrance during development. Every time the migrations ASDF system (or the file containing it, as ASDF prefers that all systems be defined in a single file) is recompiled it adds all the defined migrations to the migrations list. Though each one will only be applied once to the DB it is still bothersome. One can then clear the list with (setf database-migrations::*migrations* nil) but then only newly modified migration files will be added. The solution then is to touch the .asd file after clearing the migrations list.

The second negative point is quite dangerous. The downgrade function takes a target version as parameter, with a default target of 0. This means that if you execute downgrade without specifying a target version you delete your whole database.

I am currently using Database-migrations and it works well for me. If for some reason I need to switch I will use cl-migrations.

Using Database-migrations

To address the danger of unintentionally deleting my database I created a wrapper function that does both upgrade and downgrade, and it requires a target version number.

Another practical issue I discovered is that upgrades and downgrades happen in the same order as they are defined in the migration file. If you create two tables in a single file where table 2 depends on table 1 then you can not revert / downgrade because Database-migrations will attempt to delete table 1 before table 2. The solution here is to use the def-queries-migration macro (instead of def-query-migration) which defines multiple queries simultaneously . If you get overwhelmed by a single definition that defines multiple tables the other option is to stick with one migration definition per file.




science and technology

Quicklisp news: April 2020 Quicklisp dist update now available

New projects:

  • anypool — General-purpose pooling library — BSD 2-Clause
  • avl-tree — An implementation of the AVL tree data structure. — MIT
  • cl-aubio — Aubio bindings for Common Lisp — GPLv3
  • cl-interval — Intervals, interval trees — NewBSD, LLGPL
  • cl-liballegro — Allegro 5 game programming library bindings for Common Lisp — Allegro 5 - http://alleg.sourceforge.net/license.html
  • cl-mime-from-string — A one function library to return a mime-type based on the file extension found at the end of a string. ie abc.txt -> text/plain. The common types implemented are from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types — MIT
  • cl-telegram-bot — Telegram Bot API, based on sovietspaceship's work but mostly rewritten. — MIT
  • dns-client — A client for the DNS protocol. — zlib
  • feeder — RSS, Atom and general feed parsing and generating — zlib
  • perceptual-hashes — Perceptual hash algorithms for images — 2-clause BSD
  • portable-condition-system — A portable condition system for Common Lisp — CC0
  • ten — Template System for Common Lisp — MIT
  • trivial-custom-debugger — Allows arbitrary functions to become the standard Lisp debugger — MIT
  • trivial-with-current-source-form — Helps macro writers produce better errors for macro users — GPLv3
  • vom-json — A json-formatted logger for vom — MIT
  • vp-trees — Perceptual hash algorithms for images — 2-clause BSD
Updated projects3b-bmfont3bgl-shader3bmd3bza-cl-loggeralexandriaaprilasync-processbdefbpccldocchungacl+sslcl-anacl-capstonecl-cffi-gtkcl-collidercl-containerscl-environmentscl-gamepadcl-gservercl-inotifycl-marklesscl-packcl-patternscl-pythoncl-rdkafkacl-shlexcl-sparqlcl-strcl-tuicl-utilscl-webkitclinenoiseclipcloser-mopconcrete-syntax-treecroatoancserial-portdartscltoolsdefenumdeploydexadordiff-match-patchdissectdjuladoubly-linked-listeasy-routeseclectorescalatorfast-generic-functionsfast-ioflexi-streamsflexichainfloat-featuresfsetfuccfunctional-treesfxmlgendlgraphgtirbhu.dwim.computed-classhu.dwim.defhu.dwim.perechu.dwim.presentationhu.dwim.quasi-quotehu.dwim.walkerhu.dwim.web-serverhunchentoot-multi-acceptorironcladkeystonelispqrliterate-lispmaidenmaxpcmcclimmmapmodularizemutilitynodguinumclnumpy-file-formatoriginosicatoverlordparachutepatchworkpetalisppetriphoe-toolboxplumppolicy-condpolisherpostmodernpzmqqtoolsquilcqvmroanrpcqs-graphvizs-http-clients-http-servers-sysdepss-utilssanity-clausescalplsealable-metaobjectsselselect-fileserapeumsketchskippy-renderersnappysoftdrinkspinneretstaplestumpwmsucleswank-clientswank-crewtootertrace-dbtrivial-featurestrivial-file-sizevgplotwoo.

Removed projects: cl-password-store, fomus, rfc3339-timestamp, rpc4cl.

All the removed projects are removed because they no longer build. For the first two (cl-password-store and fomus), I was unable to get a response from the authors. The other two (rfc3339-timestamp, rpc4cl) the author was responsive, but has abandoned the projects.

To get this update, use (ql:update-dist "quicklisp"). Enjoy!

A number of people support Quicklisp with a monthly contribution through PayPal. I recently set up a Quicklisp Patreon page as an alternative - if you are interested in supporting Quicklisp, feel free to check it out.




science and technology

ABCL Dev: ABCL 1.6.1 Springs Forth

As augured, the Bear is pleased to join fellow open ANSI Common Lisp implementations CCL, ECL, and SBCL in publishing a new release around the online advent of the thirteenth European Lisp Symposium, ELS2020.

The ABCL 1.6.1 binaries and signatures are now available with their associated CHANGES.

Thanks to everyone involved in continuing to further the progress of our implementation.




science and technology

Timofei Shatrov: Previewing images in and out of SLIME REPL

As any Common Lisp coder knows, a REPL is an incredibly useful tool. It can be used not just for development, but for running all sorts of tasks. Personally, I don't bother making my Lisp tools into executable scripts and just run them directly from SLIME. As such, any operation that requires leaving the REPL is quite inconvenient. For me, one such operation was viewing image files, for example in conjunction with my match-client:match tool. So lately I've been researching various methods to incorporate this functionality into the normal REPL workflow. Below, I present 3 methods that can be used to achieve this.

Open in external program

This one's easy. When you want to view a file, launch an external process with your favorite image viewer. On Windows a shell command consisting of the image filename would launch the associated application, on Linux it's necessary to provide the name of the image viewer.

(defvar *image-app* nil) ;; set it to '("eog") or something

(defun view-file-native (file)
  (let ((ns (uiop:native-namestring file)))
    (uiop:launch-program (if *image-app*
                             (append *image-app* (list ns))
                             (uiop:escape-shell-token ns)))))

Note that uiop:launch-program is used instead of uiop:run-program. The difference is that launch- is non-blocking - you can continue to work in your REPL while the image is displayed, whereas run- will not return until you close the image viewer.

Also note that when the first argument to run/launch-program is a string, it is not escaped, so I have to do it manually. And if the first argument is a list, it must be a program and a list of its arguments, so merely using (list ns) wouldn’t work on Windows.

Inline image in REPL

The disadvantage of the previous method is that the external program might steal focus, appear on top of your REPL and disrupt your workflow. And it's well known that Emacs can do everything, including viewing images, so why not use that?

In fact, SLIME has a plugin specifically for displaying images in REPL, slime-media. However it’s difficult to find any information on how to use it. Eventually I figured out that SWANK (SLIME’s CL backend) needs to send an event :write-image with appropriate arguments and slime-media's handler will display it right in the REPL. The easiest way is to just send the file path. The second argument is the resulting image's string value. If you copy-paste (sorry, "kill-yank") it in the repl, it would act just like if you typed this string.

(swank::send-to-emacs '(:write-image "/path/to/test.png" "test"))

You can even send raw image data using this method. I don't have anything on hand to generate raw image data so here's some code that reads from a file, converts it to a base64 string and sends it over SWANK.

(with-open-file (in "/path/to/test.png" :direction :input  :element-type '(unsigned-byte 8))
                (let* ((arr (make-array (file-length in) :element-type '(unsigned-byte 8)))
                       (b64 (progn (read-sequence arr in) (cl-base64:usb8-array-to-base64-string arr))))
                  (swank::send-to-emacs `(:write-image ((:data ,b64 :type swank-io-package::png)) "12345"))))

Note that the first argument to :write-image must be a list with a single element, which is itself a plist containing :data and :type keys. :data must be a base64-encoded raw image data. :type must be a symbol in swank-io-package. It’s not exactly convenient, so if you’re going to use this functionality a helper function/macro might be necessary.

Image in a SLIME popup buffer

Inline images are not always convenient. They can’t be resized, and will take up as much space as is necessary to display them. Meanwhile EMACS itself has a built-in image viewer (image-mode) which can fit images to width or height of a buffer. And SLIME has a concept of a “popup buffer” which is for example used by macroexpander (C-c C-m) to display the result of a macro expansion in a separate window.

Interestingly, slime-media.el defines an event :popup-buffer but it seems impossible to trigger it from SWANK. It is however a useful code reference for how to create the popup buffer in ELisp. This time we won’t bother with “events” and just straight up execute some ELisp code using swank::eval-in-emacs. However by default, this feature is disabled on Emacs-side, so you’ll have to set Emacs variable slime-enable-evaluate-in-emacs to t in order for this method to work.

Also Emacs must be compiled with ImageMagick for the resizing functionality to work.

Anyway, the code to view file in the popup buffer looks like this:

(defun view-file-slime (file &key (bufname "*image-viewer*"))
  (let ((ns (namestring file)))
    (swank::eval-in-emacs
     `(progn
        (slime-with-popup-buffer (,bufname :connection t :package t)
          (insert-image (create-image ,ns))
          (image-mode)
          (setf buffer-file-name ,ns)
          (not-modified)
          (image-toggle-display-image))
        ;; try to resize the image after the buffer is displayed
        (with-current-buffer ,bufname (image-toggle-display-image))))))
    ))

Arriving to this solution has required reading image-mode’s source code to understand what exactly makes image-mode behave just like if the image file was opened in Emacs via C-x C-f. First off, image-mode can be a major and a minor mode - and the minor mode is not nearly as useful. slime-with-popup-buffer has a :mode keyword argument but it would cause image-mode to be set before the image is inserted, and it will be a minor mode in this case! Therefore (image-mode) must be called after insert-image.

Next, the buffer must satisfy several conditions in order to get image data from the filename and not from the buffer itself. Technically it shouldn’t be necessary, but I couldn’t get auto resizing to work when data-p is true. So I set buffer-file-name to image’s filename and set not-modified flag on.

Next, image-toggle-display-image is called to possibly resize the image according to image-mode settings. It's called outside of slime-with-popup-buffer for the following reason: the buffer might not yet be visible and have any specific dimensions assigned to it, and therefore resizing will do nothing.

Here’s an example of how calling this function looks in Emacs.

The position of the popup buffer depends on whether the original Emacs window is wide enough or not. I think it looks better when it’s divided vertically. Use M-x image-transform-fit-to-height or M-x image-transform-fit-to-width to set up the auto-resizing method (it gets remembered for future images). Unfortunately there’s no way to fit both height and width, at least with vanilla Emacs. I prefer fit-to-width because in case the image is too tall, it is possible to scroll the image vertically with M-PgDn and M-PgUp from the other buffer. Unlike other image-mode buffers, this buffer supports a shortcut q to close itself, as well as various SLIME shortcuts, for example C-c C-z to return to the REPL.

That's it for now, hope you enjoyed this overview and if you happen to know a better way to display images in Emacs, I would be interested to hear about it.