text:
# Emencia's Sphinx documentations

This is the repository to contains all Sphinx documentations projects created for Emencia.

The repository is a unique buildout project so you install it and can build one or all documentations.

Actually the buildout install Sphinx and some additional themes (like sphinx_bootstrap_theme or sphinx_rtd_theme) so a documentation can use them instead of the Sphinx's Builtin themes. But if you want you can use another theme, just remember to add its dependancies in the versions.cfg if your it need some ones.

• All documentation projects sources live in the projects/ directory;
• All builded documentation should have a symbolic link in builds/ directory that can be easily mounted on a webserver to publish the docs;

# Install

To install the buildout project just do the common :

make install

Actually, you will have to build all the project you want to publish and so enter in each project directory and build them, for example if you want to publish the toto project :

cd projects/toto
make html

# Usage

Remember to activate the virtual environnment before everything else (everytime you use it, not only after the first install) :

source bin/activate

Then you can enter in your documentation directory and use its Makefile to build the doc like this :

cd projects/mydoc
make html

If you need to use a Python interpreter that is aware of installed eggs, use eggedpy.

All common command-line scripts from Sphinx are available within the bin/ directory (like sphinx-quickstart, sphinx-builder, etc..) and aware of the installed eggs.

Also, in fact this is not required that your documentation project is a Sphinx project, it can be a simple unique RST document. Like for Sphinx, the common command-line scripts from docutils (like rst2html.py and others) are installed in the bin/ directory and aware of the installed eggs. But you will have to add Makefile with the html action to easily build your document in a _build/html directory like with a Sphinx project.

## Documentations index

In the builds/ directory there is a index.html generated from the command (only available from the base dir of the repository) :

make index

It will scan through the builds/ to find all directories that contains an index.html file and add their link to the HTML list.

## Add a new Sphinx documentation project

Use the interactive Sphinx quickstart command :

sphinx-quickstart

Answer to the question, note that if you execute this command from the root of the repository, the first question ask you if you want to create the project on the root (eg: .), this is wrong NEVER LET THIS HAPPEN, else specify a directory name (dont need to exists) for your project. Or if you prefer, create the directory before, enter to it, execute the quickstart command then you can let the default value for the first question.

When it's done, just go to the builds/ repository directory and make a symbolic link to the new documentation's HTML build directory (even if it doesn't exists yet) then re-generate the main builds index file to display the link to the new documentation.

### Example

We will create a new project called dummy using the quickstart command :

cd projects/
sphinx-quickstart

Watch below for answers to the interactive prompt :

Welcome to the Sphinx 1.2.3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]: dummy

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]:

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: Dummy doc
> Author name(s): Sarah Connor

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version: 1.0
> Project release [1.0]:

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]:

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> pngmath: include math, rendered as PNG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]: n

Creating file dummy/conf.py.
Creating file dummy/index.rst.
Creating file dummy/Makefile.

Finished: An initial directory structure has been created.

You should now populate your master file dummy/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

Ok it is created, now make the symbolic link :

cd builds
ln -s ../dummy/_build/html dummy

Then add a .gitignore file to never commit the builded HTML :

cd dummy
echo '_build' > .gitignore

Now build the HTML doc :

make html

cd ../
make index

And voila! Remember to commit your new project to the repository.

## Use the bootstrap theme within your documentation

You will need to edit the project's conf.py file, search for the line html_theme = 'default (probably around the line 101 on a fresh project) and replace it with the following code :

html_theme = 'default'
try:
import sphinx_bootstrap_theme
except ImportError:
pass
else:
html_theme = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'bootswatch_theme': "yeti",
}

Note the conditional import, this is to ensure compatibility if you move your documentation out of this repository, so you can build it without to install sphinx_bootstrap_theme.

See the sphinx_bootstrap_theme documentation to know all settings you can override.

Now you can rebuild your documentation, it will use the right theme.

## Use the RTD theme within your documentation

You will need to edit the project's conf.py file, search for the line html_theme = 'default (probably around the line 101 on a fresh project) and replace it with the following code :

html_theme = 'default'
try:
import sphinx_rtd_theme
except ImportError:
pass
else:
html_theme = "sphinx_rtd_theme"

html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

Note the conditional import, this is to ensure compatibility if you move your documentation out of this repository, so you can build it without to install sphinx_rtd_theme.

See the sphinx_rtd_theme documentation to know all settings you can override.

Now you can rebuild your documentation, it will use the right theme.

## Add a simple RST document

Like for Sphinx, the common command-line scripts from docutils (like rst2html.py and others) are installed in the bin/ directory and aware of the installed eggs.

This is free to your needs, but you will have to add a Makefile with the html action to easily build your document in a _build/html directory like with a Sphinx project.

The easy way is to copy projects/readme to a new name and use it to start your document.

Like for a Sphinx documentation project, you will have to add its symbolic link in the builds/ directory :

cd builds
ln -s ../dummy/_build/html dummy
`

Remember to commit your new project to the repository.


text:
### Maximum Sum subarray subarray array searching    Posted: 7 years ago Updated: 6 years ago Edit answers (1) views (3532)

Suppose you are given an integer array. How will you find the contiguous subarray with largest sum?

 Posted: 7 years ago 0 0 Edit The elements in the array are either all positive or positive and negative or all negative. We can use Kadane's algorithm as : Iterate through the array from beginning to end and keep track of the current subarray sum. If the current subarray sum is less than zero , the current subarray will be discarded in the computation of the the maximum sum subarray by initializing the current subarray sum to zero . Return the maximum sum subarray when finished iterating. The above algorithm will return zero when all the elements in the array is negative integers. The variable maximumSum represents the maximum sum. Time complexity = $$O(n)$$.public static int[] findMaxSumSubarray(int[] array){ /* Variables */ int maximumSum = 0; int currentSum = 0; int currentStartIndex = 1; int maximumStartIndex = 0; int maximumEndIndex = 0; /* Iterate through the array from beginning to end */ for(int currentEndIndex = 1; i < = array.length; currentEndIndex++){ /* Add the element at the current index to the currentSum and compare */ currentSum += array[currentEndIndex]; /* For positive integers */ if(currentSum > maximumSum) maximumSum = currentSum; maximumStartIndex = currentStartIndex; maximumEndIndex = currentEndIndex; /* For negative integers */ elseif(currentSum < 0) currentSum = 0; currentStartIndex = currentEndIndex + 1; } /* Return the largest sum subarray */ return Arrays.copyOfRange(array, maximumStartIndex, maximumEndIndex);}

format: plain


text:
# LESSON 3, ADDITION (PLUS +) AND SUBTRACTION (MINUS -)

### Signs

Plus sign “+”

⠰⠖

Dots 235-56

Minus sign “-”

⠰⠤

Dots 36-56

###Explanation

Braille computing signs are made up of two cells, a prefix, and a root. A prefix of any sign is usually located at the right column of dots of the cell. The prefix for most mathematial signs in Arabic braille is the fifth and sixth dots.

Note, the fifth and sixth dots are also used as a letter sign and used in the braille module 2 table as a sign of module 1.

The plus sign consists of two cells, the first cell contains the dots 56, and the second cell has the dots 235. The minus sign consists of the dots 56 in the first cell, followed by the dots 36 in the second cell.

A space is not required before or after the plus and minus signs, or before and after the mathematical signs in general. However, it is preferable to leave a space before and after the sign when teaching children mathematical signs to make it easier to recognize and identify them.

Mathematical signs end the number mode, so we have to type the number sign before the number that follows the mathematical sign. We also mention that the number mode is deactivated by keeping a space.

####Example 1

4+5

⠼⠙⠰⠖⠼⠑

####Example 1 (leaving a space to teach children)

4 + 5

⠼⠙⠀⠰⠖⠀⠼⠑

#### Example 2

6−2

⠼⠋⠰⠤⠼⠃

####Example 2 (with space)

6 − 2

⠼⠋⠀⠰⠤⠀⠼⠃

####Example 3

5+4−3

⠼⠑⠰⠖⠼⠙⠰⠤⠼⠉

#### Example 3 (with space)

5 + 4 − 3

⠼⠑⠀⠰⠖⠀⠼⠙⠀⠰⠤⠀⠼⠉

The plus and minus signs can be used in the middle of normal text content and not just between numbers. The same spaces that exist before or after the code are followed when converting to braille.

#### Example 4

Two + five

⠁⠹⠝⠁⠝⠀⠰⠖⠀⠭⠍⠎⠡

####Example 6

Choose + or −

⠁⠭⠞⠗⠀⠰⠖⠀⠌⠺⠀⠰⠤⠲

Important note: The hyphen is often used in computer environments as an alternative to the minus sign for easy entry from the keyboard. If the hyphen is used in the subtraction process, the braille coder/ translator will translate it into a hyphen sign according to braille module 1 table, as we mentioned, the hyphen sign in Arabic Braille is composed of the dots 36-36.

6-3

⠼⠋⠤⠤⠼⠉


text:
I’m hoping to eventually help out on projects that are working with Kubernetes, and I don’t mean writing yaml configs for apps (I’ve done this a few times before), but rather developing for Kubernetes. This is something that before last weekend, I had never done. But I love Go, and I was excited, so I dived in! This post will detail how I went about creating my first Kubernetes operator - the lolcow operator, which was a challenge presented to me by my long time friend and colleague Eduardo. I got it done in a little over a week, and that includes not actually working on it during the workweek, but the two weekends around it, so I’m pretty pleased. I also want to say thank you to @mogsie in the Kubernetes slack #kubebuilder channel for some of his good practices wisdom. There is a lot to learn in this space, and wisdom from those that are experienced is invaluable. Don’t care to read? Browse the ⭐ lolcow-operator ⭐ at the state when I wrote this article.

## Using the Operator

If you are a developer and just want to try things out, here is a quick summary of how to do that. The complete instructions are in README and I’ll abbreviate here. If you haven’t ever installed minikube, you can follow the install instructions here.

### 1. Build and Deploy

# Clone the source code
$git clone https://github.com/vsoch/lolcow-operator$ cd lolcow-operator

# Start a minikube cluster
$minikube start # Build the operator$ make

# How to make your manifests
$make manifests # And install. This places an executable "bin/kustomize"$ make install

I’ve been told that kind is a better tool to use, so I’ll try this next time. At this point we can apply a our lolcow config that has information about the greeting to show, and the port.

$bin/kustomize build config/samples | kubectl apply -f - lolcow.my.domain/lolcow-pod created  And finally we can run it! $ make run

### 2. View the Lolcow?

And you should be able to open the web-ui (when kubectl get svc shows the lolcow service is “ready” and not “pending”).

$minikube service lolcow-pod  Ha! At this point you might say, “Wait, that’s not the lolcow, that’s the Nyan cat!” and you are right. 🎨 Thank you 🎨 and shout out to eusonic for the css that drives this UI! I was able to take it and modify it into a containerized Flask application (with added text that can dynamically change). And it’s actually a container you can run isolated from this application, e.g.,: $ docker run -p 8080:8080 -it ghcr.io/vsoch/lolcow-operator  "Were you expecting someone else?"

 __________________________________
< Were you expecting someone else? >
----------------------------------
\   ^__^
\  (oo)\_______
(__)\       )\/\
||----w |
||     ||
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:8080
* Running on http://172.17.0.2:8080
Press CTRL+C to quit

You can see the container (an automated build from the repository) on GitHub packages. And a challenge for new folks! When you run the operator, try getting the name of the pod and seeing if you can figure out how to see logs and then see this same entrypoint (with your message).

### 3. Test the Operator

We are good so far that the operator has created the deployment and service, and we can see it in our browser. If you look at the operator logs, you’ll also see that it is giving you detail about state (with emojis, because I added emojis to code and I’m a monster 🤣). If you were to Control+C and restart the controller, you’d see the greeting hasn’t changed:

1.6611115156486864e+09	INFO	👋 No Change to Greeting! 👋: ...

But we want to test this. E.g., if we edit our control resource and change the greeting or port, we want it to be the case that the user interface is updated too! First to change the greeting, we can update the sample config:

apiVersion: my.domain/v1alpha1
kind: Lolcow
name: lolcow-pod
spec:
port: 30685
-  greeting: Hello, this is a message from the lolcow!
+ greeting: What, you've never seen a poptart cat before?

I made this change while it’s running (in a separate terminal) and then re-applied the config:

$bin/kustomize build config/samples | kubectl apply -f - lolcow.my.domain/lolcow-pod configured  The change might be quick, but if you scroll up you should see: 1.6611116913288918e+09 INFO 👋 New Greeting! 👋: ... "What, you've never seen a poptart cat before?": "Hello, this is a message from the lolcow!"}  and the interface should change too! And then we can do the same to change the port - first seeing that (without changes) updating the config reflects this state: 1.6611135948097324e+09 INFO 🔁 No Change to Port! 🔁:  And now to change it - let’s try one number higher: apiVersion: my.domain/v1alpha1 kind: Lolcow metadata: name: lolcow-pod spec: - port: 30685 + port: 30686  And then apply the config. ... "🔁 New Port! 🔁"  Refreshing the current browser should 404, and you should be able to tweak the port number in your browser and see the user interface again! Yay, it works! I can’t tell you how happy I was when this finally worked, there were many bugs that I had to work through that I’ll discuss shortly. ### 4. Cleanup When cleaning up, you can control+C to kill the operator from running, and then: # Make sure before deleting all services and pods these are the only ones running!$ kubectl delete pod --all
$kubectl delete svc --all$ minikube stop

And that’s it! You can also delete your minikube cluster if you like.

## What’s Happening?

So I’m not an expert, but I can talk generally about what the operator is doing. First, I think it’s called an operator in reference to a human operator. Before we had operators, it was up to humans to deploy things and then manage state changes. From the RedHat site:

A Kubernetes operator is an application-specific controller that extends the functionality of the Kubernetes API to create, configure, and manage instances of complex applications on behalf of a Kubernetes user.

So given that you have some set of pods / services / deployments (anything Kubernetes related?) that you want to manage, I imagine an operator being like a continuous loop that is constantly checking the current state, comparing it to some desired state, and then adjusting as needed. The extra config file that we created is called a custom resource (CR) that helps the user (me or you!) to manage that state. In our case, we cared about the lolcow greeting, and the port it’s deployed on, and I explicitly chose these two things to have a variable to watch and update for each of the deployment and service.

If I understand correctly, operators help in the case when an application has a state. A stateless app (in a container) doesn’t need any kind of special management, because you can just deploy it and re-create it. But something like a database couldn’t just be recreated (without messing something up). Since we are always moving toward a desired state, this is why the main function of a controller is called “Reconcile,” which is another term to describe that. Finally, this article offers a nice definition of operators and controllers. TLDR: an operator is a kind of controller, but not necessarily vice versa. A cool place to browse (to get a sense of different kinds of operators) is the Operator Hub.

## Design Decisions

You can read my entire development process (starting from zero to this application) in the README, and here I briefly want to share some design decisions that I started to make. I suspect this set will change as I learn more.

### Named APIs

The original template had just one API, and organized by versions. I anticipate that if an application wants to have more than one named API, it makes sense to introduce another level of organization there, so that’s what I did.

api/
└── lolcow        (- lolcow api namespace
└── v1alpha1
├── groupversion_info.go
├── lolcow_types.go
└── zz_generated.deepcopy.go

I realized that if we want more than one controller (likely), we should have subdirectories in controllers too. I mirrored the kueue design and made one called “core.”

controllers/
├── core
│   └── core.go
└── lolcow
├── deployment.go
├── lolcow_controller.go
├── service.go
└── suite_test.go

### Named Packages

By default, we didn’t have any packages. But what if the API needs some custom (and shared) logic? I was thinking that there are probably two cases here - importing the guts of the thing that you want to control, or defining it here. For the latter, I decided to try creating a pkg directory.

\$ tree pkg/
pkg/
└── lolcow
└── lolcow.go

For my lolcow operator, this is overkill. But if different versions of an API might want to use shared code, this would be helpful. And indeed there could be other reasons to have nicely organized packages. I also noticed that some operators (like kueue put a lot of the controller logic under the pkg directory. I think this is something that could be done if there is a lot of additional code to add to the operator, and the top level gets crowded. However, given that many people are using this common SDK to generate the template, I decided to leave as is, so it would be more easily recognized (and thus easier to develop).

### Naming

In most examples using an API, the names were like mydomainv1alpha1 to reference the API package, and I suspect this is done to maintain some sense of namespacing the APIs. Maybe it could even be that more than one version is used per application? Since my application is just using one and isn’t expected to be extended or changed, I opted for something simple like api.

## Bugs

So what prevented me from finishing this entirely the first weekend? The bugs, of course! 🐛 I’ll review them here briefly, in case anyone else runs into them. I suspect they will, because when you haven’t done this before there is really no way to know these things unless you stumble on it, add the right thing by accident, or (what I don’t do) read an entire book before writing a line of code.

#### Service / Deployment Detection

For the longest time, the original service and deployment would start (because they were not found) but they would continue to be not found and sort of spiral into a chain of error messages. This took me many evenings to figure out, but it comes down to these (sort of hidden) lines at the top of the controllers file:

//+kubebuilder:rbac:groups=my.domain,resources=lolcows,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=my.domain,resources=lolcows/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=my.domain,resources=lolcows/finalizers,verbs=update
//+kubebuilder:rbac:groups=my.domain,resources=deployments,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=my.domain,resources=pods,verbs=get;list;watch;create;
//+kubebuilder:rbac:groups=my.domain,resources=services,verbs=get;list;watch;create;update;patch;delete

I honestly didn’t even notice they were there at first. The template only had the first three (for lolcows) and I needed to add the last three, giving my controller permission (RBAC refers to a set of rules that represent a set of permissions) to interact with services and deployments. I think what was happening before is that my controller couldn’t see them, period, so of course the Get always failed. I found this page and this page useful for learning about this. Another important note (that I didn’t do here) is that you can namespace these, which I suspect is best practice but I didn’t do for this little demo. The other bit that seemed important was to say that my controller owned services and deployments:

func (r *LolcowReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&api.Lolcow{}).
Owns(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
// Defaults to 1, putting here so we know it exists!
WithOptions(controller.Options{MaxConcurrentReconciles: 1}).
Complete(r)
}

Another level of detail that I didn’t get into was Events, which I suspect gives you better control (and could also be a source of error if you aren’t watching the right ones). I didn’t get a chance to play around with different derivations of the above yet, because as soon as the above worked I was 😁.

#### Pod Names

For some reason, at one point I switched my name from ‘lolcow-sample’ to ‘lolcow-pod’, and although I thought I cleaned everything up, whenever I’d create the cluster again it would show me two pods made, one lolcow-pod and one lolcow-sample. I had to try resetting and “starting fresh” multiple times (e.g., deleting stuff in bin and reinstalling everything) until kubectl get pod didn’t show the older and new name. If you run into errors about not finding a service, it could be that somewhere the older name is still being created or referenced, so it’s a good sanity check to do.

## Summary

What a fun time working on this! Despite the complexity, because I love Go so much, it was truly a pleasure to debug. What I learned most from this experience is that details are really important. The smallest detail about a permission/scope, or how you configure your operator can mean it won’t work as you expect, and it takes a lot of careful testing to even get it working.

Now some caveats - this is my first time doing any kind of development for Kubernetes, and this is a very basic intro that doesn’t necessarily reflect best practices. For example, I’m just using the default namespace, and I’m aware that for a more realistic setup we’d want to be using more controlled namespaces. But I think this is a good start? When I’m newly learning something, my main goal is to get it to work (period!) and then to slowly learn better practices over time (and use them as a standard). I suspect future me will look at this and wonder what I was thinking? Anyway, I hope this has been useful to you!

Suggested Citation:
Sochat, Vanessa. "My First Kubernetes Operator." @vsoch (blog), 21 Aug 2022, https://vsoch.github.io/2022/kubernetes-lolcow-operator/ (accessed 24 Dec 22).


text:
# Images off the page in multicols environment

Before my question, some background information.

I’ve created an algorithm (not latex) which will generate a catalog for a collection of books dynamically. A user supplies information to query an SQL database to retrieve book information and also defines the structure of the catalog in an XML file. Finally, through a series of automated steps, .tex files are generated which are then run through latex to create the catalog PDF file.

Everything works well except for adding images in which through trial and error I’ve discovered that the package picins works easily and well with the multicol package and looks great too. The only trouble I am encountering is that it appears that the picins package does not calculate when an image will appear off the page, so from time to time images appear off the page in the catalog.

Since these catalogs are generated automatically, the less human interaction the better. Adding \columnbreak prior to a paragraph which is textwrapped by parpic, does fix the issue, however performing this manually is not a solution since there are hundreds (perhaps thousands) of books which will make up each catalog.

Surrounding the paragraph and image in a \parbox will keep the image from going off the page; however it creates a lot of white space and adds pages to the catalog. Since this catalog will be printed, extra pages means more money, so white space must be kept to a minimum.

I'm quite stuck on a solution, I aplogize but my questions are broad. I appreciate your suggestions.

Would it make sense / is it possible to calculate the lines remaining in a column and use the ifthen package to insert a \columnbreak automatically?

Is there a better solution than picins which works nicely with the multicol package that will automatically break the column if the image will not fit?

The MWE is as follows:

\documentclass[english]{book}
\usepackage{multicol}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{graphicx}
\usepackage{picins}
\usepackage{blindtext}

\setlength{\columnsep}{0.375in}

\begin{document}
\begin{multicols*}{2}
\noindent\blindtext[5]\\
\pichskip{.25in}\noindent\parpic[sr][r]{\includegraphics[width=2in]{dog.png}\picskip{15}}
\blindtext
\end{multicols*}
\end{document}

Dog image (for testing purposes):

The output:

-

Here is a solution that should fit in with your automation.

The needspace package provides a command \needspace{<length>} which checks to see whether there is <length> left in the column or on the page, otherwise it issues a \break. This allows the text to roll over into another column/page. In that sense you can modify your code to the following:

<preamble>
...
\usepackage{needspace}% http://ctan.org/pkg/needspace
...
\begin{document}
...
\setbox0=\hbox{\includegraphics[width=2in]{dog.png}}% Store image in \box0
\needspace{\ht0}% Need at least the height of \box0
\pichskip{.25in}\noindent\parpic[sr][r]{\usebox0}% Insert image
Lorem ipsum...

This is the output that is generated using this fix:

-
This is an excellent solution. Thank you very much. –  Doug Aug 26 '11 at 14:36


text:
# Examples

We use one synthetic example and one field data example to demonstrate the interpolation effect using the proposed approach. The first synthetic example is a combination of linear reflectors, curved reflectors and faults. The original data and decimated data with 30% randomly removed traces are shown in Figures 3a and 3b, respectively. After based POCS and FPOCS, and seislet based POCS and FPOCS, the reconstructed data and their corresponding error sections using different approaches are shown in Figures 4 and 6, respectively. In this paper, we use the percentile thresholding strategy (Chen et al., 2014a). The percentile thresholding refers to using a constant percentage of maximum coefficients during the iterations. For the first example, 15 % coefficients are preserved during the iterations. The percentile thresholding refers to using a constant percentage of maximum coefficients during the iterations. We zoom in the frame boxes as shown in Figures 3 and 4, and show the zoomed sections in Figure 8 for better comparison. In order to numerically compare the performance, we use the signal-to-noise ratio (SNR): , which is widely used in the literature to numerically measure the data recovery error (Liu et al., 2009a; Yang et al., 2015). We plot the SNR diagram of the first example in Figure 9. As can be seen from the comparison of different approaches, the seislet based POCS and FPOCS obviously perform better than based POCS and FPOCS, according to both SNR comparison and visual observation. It should be mentioned that the superior performance of FPOCS algorithm depends on the parameter selection (percentage of coefficients in the transformed domain) in the percentile thresholding strategy. Figure 9 shows the performances of different algorithms using the best selected parameter (the percentage is 15 %), while Figure 10 shows the performance of different algorithms using inappropriate parameter (the percentage is 20 %). It is obvious that in Figure 10, both seislet based FPOCS and based FPOCS go through an SNR increasing and then decreasing process. Thus, when using the FPOCS algorithm in practice, we might need to have several parameters tuning process in order to select the best parameter. The reconstructed results using FPOCS and POCS are nearly the same. From the convergence diagram, we can confirm that the FPOCS and POCS converge to the same SNR but FPOCS converges much faster. Figure 11a shows the amplitude comparison for the 175th trace (as highlighted in Figures 3a, 4b and 4d). It is also obvious that the seislet based FPOCS approach can obtain better performance than the based FPOCS approach. In addition to the SNR comparison, we also use another newly developed way to measure the recovery performance: the local similarity. The local similarity was initially used to measure the signal reconstruction in the noise attenuation problem (Chen and Fomel, 2015). Here, we borrow the same way to numerically measure the data reconstruction performance. Appendix A gives a short review of the local similarity and its calculation. We use the local similarity in two ways: 1) to calculate the local similarity between the true data and the reconstructed data; 2) to calculate the local similarity between the true data and the estimation error. The higher the former similarity is, the better reconstruction performance is, since such similarity measure the correctness. However, the higher the latter similarity is, the worse reconstruction performance is, since such similarity magnifies the error. Figure 5 shows the local similarity between the true dataset and the reconstructed data. The two similarity maps on the bottom row obviously contains fewer anomalies than that on the top row, indicating that the two - based approaches cause more error than the seislet based approaches. Please note that the the maximum local similarity is 1, which means that the two compared signals are exactly the same. Figure 7 shows the local similarity between the true dataset and the reconstruction error. The two similarity maps on the bottom show small values while the two maps on the top row show high-value anomalies, further confirming the superior performance using the seislet-based approach. Figure 11b shows the local similarity comparison (between the reconstructed trace and the true trace), which again confirms that the reconstructed trace using the seislet-based approach is much more similar to the true data.

In order to compare the difference between IST and POCS (or between FPOCS and FISTA). We do two experiments with clean and noisy irregularly sampled datasets, respectively. For the clean data case, we use the same synthetic example as shown in Figures 3a and 12a. We reconstruct the missing data with seislet POCS, seislet FPOCS, seislet IST, seislet FISTA, and show the convergence diagrams in terms of SNR in Figure 12b. It is obvious that both seislet POCS and seislet FPOCS obtain better converged results than seislet IST and seislet FISTA, which results from the fact that in POCS based methods the sampled clean data components help constrain the model during the inversion. However, for the noisy data case, as shown in Figure 12c, the convergence diagrams show opposite performance compared with the clean data case. Both seislet POCS and seislet FPOCS obtain better converged results than seislet IST and seislet FISTA. This phenomenon results from the fact that during the inversion, the IST based methods can help remove the random noise iteratively while the POCS based approaches maintain the random noise in the known data components. The conclusion from these two experiments can guide us to decide which type of method (POCS or IST) to use in practice according to the level of noise existing in the seismic data: for relatively noisier dataset, the IST (FISTA) method can be superior because during the thresholding process, the extra random noise will be attenuated gradually; for relatively cleaner dataset, the POCS (FPOCS) method can be superior because the known sampled data help constrain the spatial coherency during the inversion. Currently, we do not have ways to quantify the noise level acceptable for FPOCS. It might be an interesting topic for future investigation.. The next field data example is from a marine survey, with high data quality, thus we keep using the POCS based approach for comparison

The second example is a field data example, as shown in Figures 13a. The incomplete data by randomly removing 30% traces is shown in Figure 13b. The reconstructed results for the field data example are shown in Figures 14. For the field data example, 18 % coefficients are preserved during the iterations. The error sections using different approaches are shown in Figure 16. It is obvious that the reconstructed data using seislet based approach are much more coherent than based and have less reconstruction error. We also show zoomed sections in Figure 18 for better comparison. The SNR diagrams are shown in Figure 19. It also shows a similar conclusion that is consistent with that from the previous synthetic example: the seislet-based approaches can obtain better reconstruction performance and the the FPOCS can obtain much faster convergence. Because transform is a global transform, based approaches will cause artifacts outside the main data structure, as can be seen at the top of Figure 14b. Since the seislet transform is a local transform, it will not cause such artifacts. Figure 20a shows the amplitude comparison for the 48th trace (as highlighted in Figures 13a, 14b and 14d). It is obvious that the seislet based FPOCS has less reconstruction error compared with the based FPOCS. Figure 15 shows the local similarity between the true field data and the reconstructed datasets. The two similarity maps on the bottom row have relatively smaller values than that on the top row, indicating that the seislet based approaches can obtain more accurate reconstructed results. The low-value anomalies in the deep-water part are caused by the low-amplitude (nearly zero) deep-water reflections and should not be taken into the consideration in evaluating different performance. Figure 17 shows the local similarity between the true dataset and the reconstruction error. The two similarity maps on the bottom show small values while the two maps on the top row show high-value anomalies, further confirming the superior performance using the seislet-based approach. Figure 20b shows the local similarity comparison for the field data example (between the reconstructed trace and the true trace), which further confirms the aforementioned conclusions.

sigmoid-1,sigmoid-zero-0
Figure 3.
(a) Synthetic data. (b) Decimated synthetic data with 30% removed traces.

data-pocs-fft-0,data-fpocs-fft-1,data-pocs-seis-0,data-fpocs-seis-1
Figure 4.
(a)-(d) Reconstructed sections corresponding to POCS with - thresholding, FPOCS with - thresholding, POCS with seislet thresholding and FPOCS with seislet thresholding.

simi-pocs-fft,simi-fpocs-fft,simi-pocs-seis,simi-fpocs-seis
Figure 5.
Local similarity between the reconstructed sections with the true data using different approaches. (a) - POCS. (b) - FPOCS. (c) Seislet POCS. (d) Seislet FPOCS.

diff-pocs-fft,diff-fpocs-fft,diff-pocs-seis,diff-fpocs-seis
Figure 6.
(a)-(d) Reconstruction error sections corresponding to Figures 4a-4d, respectively.

simi-diff-pocs-fft,simi-diff-fpocs-fft,simi-diff-pocs-seis,simi-diff-fpocs-seis
Figure 7.
Local similarity between the error sections with the true data using different approaches. (a) - POCS. (b) - FPOCS. (c) Seislet POCS. (d) Seislet FPOCS.

data-z,data-zero-z,data-pocs-fft-z,data-fpocs-fft-z,data-pocs-seis-z,data-fpocs-seis-z
Figure 8.
Zoomed sections. (a) True data. (b) Decimated data. (c) POCS with - thresholding. (d) FPOCS with - thresholding. (e) POCS with seislet thresholding. (f) FPOCS with seislet thresholding.

snrs
Figure 9.
SNR comparison of the synthetic example, when the best parameter is selected.

snrs0
Figure 10.
SNR comparison of the synthetic example, when the inappropriate parameter is selected.

trace-comp,tsimi-comp
Figure 11.
(a) Amplitude comparison. (b) Local similarity comparison. Black solid line denotes the true trace. Red dot dashed line denotes FPOCS with seislet thresholding. Green dashed line denotes FPOCS using - thresholding. Note that the amplitude using seislet thresholding is much closer to the true amplitude and the local similarity using seislet thresholding is much closer to the maximum similarity: 1.

sigmoid-zero,istpocs-snrs,sigmoidn-zero,istpocsnoise-snrs
Figure 12.
(a) Clean synthetic data. (b) Comparison of POCS (FPOCS) and IST (FISTA) of clean data in terms of SNR. (c) Noisy synthetic data. (d) Comparison of POCS (FPOCS) and IST (FISTA) of noisy data in terms of SNR.

sean-1,sean-zero-0
Figure 13.
Field data example. (a)True field data. (b) Decimated field data with 30 % removed traces.

sean-pocs-fft-0,sean-fpocs-fft-1,sean-pocs-seis-0,sean-fpocs-seis-1
Figure 14.
Field data example. (a)-(d) Reconstructed sections corresponding to POCS with - thresholding, FPOCS with - thresholding, POCS with seislet thresholding and FPOCS with seislet thresholding. Note the artifacts caused by the - based methods, as pointed out by the arrows.

sean-simi-pocs-fft,sean-simi-fpocs-fft,sean-simi-pocs-seis,sean-simi-fpocs-seis
Figure 15.
Field data example. Local similarity between the reconstructed sections with the true data using different approaches. (a) - POCS. (b) - FPOCS. (c) Seislet POCS. (d) Seislet FPOCS.

sean-diff-pocs-fft,sean-diff-fpocs-fft,sean-diff-pocs-seis,sean-diff-fpocs-seis
Figure 16.
Field data example. (a)-(d) Reconstruction error sections corresponding to Figures 14a-14d, respectively.

sean-simi-diff-pocs-fft,sean-simi-diff-fpocs-fft,sean-simi-diff-pocs-seis,sean-simi-diff-fpocs-seis
Figure 17.
Field data example. Local similarity between the error sections with the true data using different approaches. (a) - POCS. (b) - FPOCS. (c) Seislet POCS. (d) Seislet FPOCS.

sean-z,sean-zero-z,sean-pocs-fft-z,sean-fpocs-fft-z,sean-pocs-seis-z,sean-fpocs-seis-z
Figure 18.
Zoomed sections of the field data example. (a) True data. (b) Decimated data. (c) POCS with - thresholding. (d) FPOCS with - thresholding. (e) POCS with seislet thresholding. (f) FPOCS with seislet thresholding.

sean-snrs
Figure 19.
SNR comparison of the field data example.

sean-trace-comp,sean-tsimi-comp
Figure 20.
Field data example. (a) Amplitude comparison. (b) Local similarity comparison. Black solid line denotes the true trace. Red dot dashed line denotes FPOCS with seislet thresholding. Green dashed line denotes FPOCS using - thresholding. Note that the amplitude using seislet thresholding is much closer to the true amplitude and the local similarity using seislet thresholding is much closer to the maximum similarity: 1.

2020-04-11


text:
Baker-Campbell-Hausdorff formula: prime divisors of denominators - MathOverflow most recent 30 from http://mathoverflow.net 2013-05-24T01:59:54Z http://mathoverflow.net/feeds/question/43445 http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://mathoverflow.net/questions/43445/baker-campbell-hausdorff-formula-prime-divisors-of-denominators Baker-Campbell-Hausdorff formula: prime divisors of denominators Vipul Naik 2010-10-24T23:41:50Z 2010-10-27T22:50:00Z
Consider the Baker-Campbell-Hausdorff formula (Wikipedia page):

$$Z(X,Y) := X + Y + \frac{1}{2}[X,Y] + \frac{1}{12}[X,[X,Y]] - \frac{1}{12}[Y,[X,Y]] + \dots$$

Many sources, including the Wikipedia page, have an explicit expression for the terms, so the question I'm asking should be answerable just from that expression.

For a prime p and a natural number n, denote by $f(p,n)$ the largest k such that, if we truncate the formula to terms that involve products of length at most $n$, then one or more of the denominators is divisible by $p^k$. Note that this truncation is valid when we are working in a situation of nilpotency class $n$.

It's pretty easy to see that $f(p,n) = 0$ for $n < p$, and is nonzero for $n \ge p$.

My question: Is there a direct explicit expression for $f(p,n)$ (or a sandwiching of it between two fairly close expressions)? For instance, inspection of the first few terms suggests that $f(2,n) = n - 1$, but I'm not sure how to derive this from the general expression.

Analogue: In the power series for the exponential $e^x$, the analogue to $f(p,n)$ is the sum $[n/p] + [n/p^2] + [n/p^3] + \dots$ where $[]$ denotes the greatest integer function.

UPDATE: Chapter 3 of the Springer Lecture Notes by Klass, Leedham-Green, and Plaskett (access online if you have an a university subscription) contains some estimates. However: (i) I'm not sure all the numerical calculations there are correct, since they don't agree with others I have seen, (ii) the authors aren't concerned about the precise growth of $f(p,n)$ -- they only care that it grows slowly enough that the series converges under certain conditions.


text:
# ndgrid

Rectangular grid in N-D space

## Description

example

[X1,X2,...,Xn] = ndgrid(x1,x2,...,xn) replicates the grid vectors x1,x2,...,xn to produce an n-dimensional full grid.

example

[X1,X2,...,Xn] = ndgrid(xg) specifies a single grid vector xg to use for all dimensions. The number of output arguments you specify determines the dimensionality n of the output.

## Examples

collapse all

Create a 2-D grid from the vectors [1 3 5 7 9 11 13 15 17 19] and [2 4 6 8 10 12].

[X,Y] = ndgrid(1:2:19,2:2:12)
X = 10×6

1     1     1     1     1     1
3     3     3     3     3     3
5     5     5     5     5     5
7     7     7     7     7     7
9     9     9     9     9     9
11    11    11    11    11    11
13    13    13    13    13    13
15    15    15    15    15    15
17    17    17    17    17    17
19    19    19    19    19    19

Y = 10×6

2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12
2     4     6     8    10    12

Evaluate and plot the function

${x}_{1}{e}^{-{x}_{1}^{2}-{x}_{2}^{2}}$

over the gridded domain

$-2<{x}_{1}<2$ and $-2<{x}_{2}<2$.

Create a grid of values for the domain.

[X1,X2] = ndgrid(-2:.2:2);

Evaluate the function over the domain.

Z = X1 .* exp(-X1.^2 - X2.^2);

Generate a mesh plot of the function.

mesh(X1,X2,Z)

In R2016b and later releases, this task does not require the use of ndgrid. Instead, you can construct the grid using implicit expansion with these commands:

x = -2:.2:2;

Z1 = x.' .* exp(-(x.').^2 - x.^2);

Create a 2-D grid and calculate some function values on the grid. Interpolate between the assigned values to refine the grid.

Create a coarse grid for $\left(x,y\right)$ in the range $\left[-5,5\right]$.

[X,Y] = ndgrid(-5:0.5:5);

Calculate some function values on the grid and plot the function.

f = sin(X.^2) * cos(Y.^2);
surf(X,Y,f)

Interpolate between the points using a more refined grid and plot the result.

[X1,Y1] = ndgrid(-5:0.125:5);
F = interpn(X,Y,f,X1,Y1,'spline');
surf(X1,Y1,F)

## Input Arguments

collapse all

Grid vectors, specified as vectors containing grid coordinates for each dimension. The grid vectors implicitly define the grid. For example, in 2-D:

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Complex Number Support: Yes

Grid vector for all dimensions, specified as a vector containing grid coordinates. ndgrid uses xg as the grid vector for each dimension.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Complex Number Support: Yes

## Output Arguments

collapse all

Full grid representation, returned as separate arrays. For each output array Xi, the ith dimension contains copies of the grid vector xi.

collapse all

### Convert Between meshgrid and ndgrid Formats

meshgrid and ndgrid create grids using different output formats. Specifically, the first two dimensions of a grid created using one of these functions are swapped when compared to the other grid format. Some MATLAB® functions use grids in meshgrid format, while others use ndgrid format, so it is common to convert grids between the two formats.

You can convert between these grid formats using pagetranspose (as of R2020b) or permute to swap the first two dimensions of the grid arrays. For example, create a 3-D grid with meshgrid.

[X,Y,Z] = meshgrid(1:4,1:3,1:2);

Now transpose the first two dimensions of each grid array to convert the grid to ndgrid format, and compare the results against the outputs from ndgrid.

Xt = pagetranspose(X);
Yt = pagetranspose(Y);
Zt = pagetranspose(Z);
[Xn,Yn,Zn] = ndgrid(1:4,1:3,1:2);
isequal(Xt,Xn) & isequal(Yt,Yn) & isequal(Zt,Zn)
ans =

logical

1

Using pagetranspose is equivalent to permuting the first two dimensions while leaving other dimensions the same. You can also perform this operation using permute(X,[2 1 3:ndims(X)]).

## Version History

Introduced before R2006a


text:
# Can I test the property to be an epimorphism of sheaves on a sort of 'generalized covers' of representables?

Let $C$ be a Grothendieck-site with finite limits (perhaps I have to assume that the topology it defines is subcanonical, but it would be nice if I wouldn't have to) and let $T=Shv(C)$ denote the category of sheaves on it.

Let $f:F\to G$ be a morphism in $T$ and suppose that for all $X\in T$ there exists objects $Y_{i,X}\in T$ and an epimorphism $\coprod Y_{i,X}\to X$ in $T$ such that the map of sets $$(*)\hspace{3em}Hom_T(Y_{i,X},f):Hom_T(Y_{i,X},F)\to Hom_T(Y_{i,X},G)$$ is surjective. How can I deduce that $f:F\to G$ is an epimorphism of sheaves?

Remark: I am pretty sure, that this is true since if for every representable $X$ the $Y_{i,X}$ would be representable, they would cover $X$ and condition (*) would imply that $f$ is an epimorphism of sheaves. However, I cannot show this when the $Y_{i,X}$ are not representable. I have tried to write them as a colimit of representables $Y_{i,X}=colim_\alpha Y_{i,X}^\alpha$ and use $Hom_T(Y_{i,X},f)\cong \lim_\alpha Hom_T(Y^\alpha_{i,X},f)$ but I don't get further.

-
Well, if the condition holds for all $X$, then in particular it holds for $X = G$. So choose $q_i : Y_i \to G$ such that $q : \coprod_i Y_i \to G$ is an epimorphism and $(*)$ holds. Then there must exist $p_i : Y_i \to F$ such that $q_i = f \circ p_i$, by hypothesis, and so if $p : \coprod_i Y_i \to F$ is the induced morphism, then $q = f \circ p$. But $q$ is an epimorphism, so $f$ must be as well.


text:
# Before This, I May Hide; After This, I'm Fortified

Riddle me this:

Flames are home to one of mine;
Of truth and suffering, I exist;
Up when dark my phases shine;

Faith included, they bring luck;
Other weathers granted me;
Under sabbath, honour struck;
Romans ended with a vee.

What am I?

Add a plural and any number can be made, but this clue might be just for the math enthusiasts.

Inspired by other answers and adding some more clues, I believe you are

the number four (4).

Flames are home to one of mine;

Fire is one of the four classical elements.

Of truth and suffering, I exist;

This refers to the Four Noble Truths in Buddhism.

Up when dark my phases shine;

There are four principal phases of the moon.

There are four points on a compass.

Faith included, they bring luck;

Four-leaf clovers are said to bring luck.

Other weathers granted me;

There are four seasons, each of which has different types of weather (roughly) associated with it: sun in summer, rain in fall, snow in winter, et cetera.

Under sabbath, honour struck;

Using the Philonic division, the Fourth Commandment of the Ten is: Remember the sabbath day, to keep it holy. Under the Augustinian division, the Fourth Commandment is: Honour thy father and thy mother, the only commandment to mention honour.

Romans ended with a vee.

Using Roman numerals, four is written as IV, which ends with a V.

the first letters of both verses of the riddle spell out four.

Add a plural and any number can be made, but this clue might be just for the math enthusiasts.

The emphasized parts together quite literally point to the number four.

Additionally, I believe this refers to the mathematical fact that any number $x$ can be obtained by taking $4 + 4y$ (namely by taking $y = \frac{x - 4}{4}$). This is adding a multiple of four to four, i.e. adding fours to four, i.e. add the plural of four to itself. As the line says, a clue for math enthusiasts.

Finally, the title: Before This, I May Hide; After This, I'm Fortified. As jafe already noted,

Four hides in the pronunciation of before. It can thus be said that four hides before the word this.
It hides in a similar fashion in fortified.
More precisely, compare four (/fɔː/), before (/bɪˈfɔː/) and fortified (/ˈfɔː.tɪ.faɪ/).

I'd like to believe that there is another clue in the title.

It says May Hide, not just Hide. This could refer to May 4, also known as Star Wars day.

• $(+1)$ Hahah, you are a legend. Your answer is correct, and all your reasonings are correct. In the "sabbath" line, I never knew there were different divisions, though, and that Rot13(ol fnlvat "haqre fnoongu", V zrnag gur pbzznaqzrag haqre gur sbhegu, juvpu vf gur svsgu, gnyxvat nobhg ubabhe.) Well done, nonetheless! I also thought it rare to see somebody pick up the secret hidden clue in the title that you mentioned in the very last line. Great answer! $\;\color{green}{\checkmark}$ – Mr Pie Jul 30 '18 at 23:07
• Thanks! I thought you might have meant that with the sabbath clue, but found out about the divisions when looking it up. So, I also learned something thanks to your riddle :-) I'm really happy to hear that the hidden clue in the title is intentional! – Just a student Jul 31 '18 at 5:12
• Otherwise, I would have wrote, "Before This, I Can Hide". Glad you enjoyed the riddle :D – Mr Pie Jul 31 '18 at 5:17

Are you

The number four? Or Fire is one of the four elements.

Flames are home to one of mine;

Four-est, fires

Of truth and suffering, I exist;

The Four noble truths (Thanks to comments!)

Up when dark my phases shine;

The four main phases of the moon (Thanks to comments!)

4 directions, North, East, South, West.

Faith included, they bring luck;

Four Leafed Clover Thanks to comments!)

Other weathers granted me;

The four seasons (Thanks to comments!)

Under sabbath, honour struck;

The Fourth Commandment Tells everyone to take a Sabbath (Thanks to comments!)

Romans ended with a vee.

The Roman numeral for 4 is IV

Also

The first letter of each line spells FOUR FOUR. And the title has the word for/Four hidden.

Thanks to the people who helped in the comments.

Wrong Old Guess

Are you a

Volcano

Flames are home to one of mine; Of truth and suffering, I exist;

Hot Magma

Up when dark my phases shine; Read a compass, I insist.

After a massive eruption, the sky can become dark?

Faith included, they bring luck; Other weathers granted me;

I am not sure.

Under sabbath, honour struck; Romans ended with a vee.

Mount Vesuvius erupted on the Roman city of Pompeii and Romans ended with a Vee for Vesuvius.

• $(+1)$ Great answer! Unfortunately, that is not it. If you explain the latter half of the second line, the third line and the title/hints, and I might award you the "Alternative Answer Bounty ($50$ Rep)". Hint: Rot13(Gur nafjre vf uvqqra va gur evqqyr.) – Mr Pie Jul 30 '18 at 3:14
• Truth and suffering could refer to rot13(sbhe aboyr gehguf). Also, a rot13(sbhe-yrns pybire) brings luck. – Jafe Jul 30 '18 at 6:39
• Has to be. Especially considering the italicised words at the end of the question... – Isaac Reefman Jul 30 '18 at 7:27
• @jafe you are correct! You can put that into an answer and I will upvote, though the second and fourth line need work :) – Mr Pie Jul 30 '18 at 9:56
• Read what I commented above. The new answer is correct, but the reasoning for the first line is not, though it can pass as an alternative. However, if you want to find the correct reasoning, think of Rot13(Nevfgbgyr.) – Mr Pie Jul 30 '18 at 9:59

The number four

Flames are home to one of mine;

Fire is one of the four elements

Of truth and suffering, I exist;

The four noble truths of Buddhism

Faith included, they bring luck;

A four-leaf clover brings luck

Title - Before This, I May Hide; After This, I'm Fortified

"Before this" has "fore" (four) before "this". "After this, I'm fortified" has "for" (four) after "this".

• $(+1)$ Good answer, but it does not explain some of the other lines, and links provided would have made it a better answer. Nonetheless, your answer is correct and so are your reasonings :) – Mr Pie Jul 30 '18 at 23:26


text:
# How to find conditional Lyapunov exponents

For a synchronized ODE system,I wanted to know if there is a program code in MATLAB available for plotting the conditional Lyapunov exponent. For example, synchronization of identical Rossler system with a coupling term $F$ present in both the response and the driver.The $F$ is not a coefficient of any variable. This is where I have a problem.

• Do we have to include the coupling in the jacobian matrix and if yes how?
• How to plot the Lyapunov exponent as a function of different values of $F$?

Thank you for any help.

• Can you explain what a "synchronized ODE system" is? Jan 19 '12 at 6:04
• Well,in the case of Rossler system if the response asymptotically follows the dynamics of the driver in the presense of an external coupling term F,then the system (response+driver) is said to be identically synchronized.
– SKM
Jan 22 '12 at 8:02
• Can you provide the equations or a link? Jan 22 '12 at 13:32
• The synchronization has to be done,i mean the system has to be constructed with the appropriate controller.I found this link for calculating lyapunov exponent for the unsynchronized case :mathworks.com/matlabcentral/fileexchange/… . I am trying to modify this code for the synchronized case. Upon synchronization,we take into consideration only the response system. So,in the program we shall have the sameset of equations but one of the equation will have an external forcing term say 5*F where F is a sine wave(for my case).How to calculate J?
– SKM
Jan 22 '12 at 20:40


text:
Rating:

# Russian threesome, re, 5 solves, 500p

> Interested in the hot secret hidden in my basement? That's right, it's stored on this old computer. Unfortunately it stopped working a long time ago. However I've got an emulator that simulates this machine and I even was able to dump it's magnetic drum into a file. I'm sure that way extracting the juicy data should be easy, right?

As the description stated, we got two files: a compiled emulator and image of a magnetic drum. Reversing the emulator was the first part of the
challenge.

As it turns out, the emulated architecture is pretty interesting. It uses balanced ternary encoding for everything, organized into 9-trit mini-words ("trytes"),
two of which make a word. There are 27 words in a sector. The whole drum is composed of 36 sectors.

The machine contains a few registers and memory objects:
- sectors X, Y, Z - three of drum sectors can be loaded into memory at the same time,
- accumulator (A), used generally as tryte-sized object,
- secondary accumulator (B), used for multiplication etc.
- program counter (PC), five-trit sized (selects X/Y/Z, one of 27 words, one of trytes; must not have -1 as LSB)
- flag (F), one trit of last operation sign
- indirection register (V), five-trit sized

Program counter always increments after the instruction, even if it was a jump (so jump target is actually one after what is encoded). All instructions
are tryte-sized and have the same composition: 3-trit opcode, 5-trit immediate, 1-trit indirection flag. If indirection flag is non-zero, the
indirection register is added to immediate field. This behavior allows for indirect indexing, for example A = [V+20] (other than by using V, all instructions

The machine has a few allowances for IO: audio (interprets X/Y/Z as speaker tones), puts and gets (reads or writes string into X/Y/Z). The machine
has specific charset, where bytes lower than 128 are ASCII and 128-255 are custom Russian characters.

There is quite a few opcodes, but they are mostly variations of the same:

X/Y/Z = drumsector n
audio X/Y/Z
puts X/Y/Z
gets X/Y/Z
drumsector n = X/Y/Z
shift A, Tn
mov Tn, A
mov V, Tn
mov V, pc+Tn
mov Tn, V
jmp Tn
mov Tn, pc
jneg Tn
jzer Tn
jpos Tn
halt
and A, Tn
mov B, Tn
sub A, Tn
mov A, Tn
mov A, Tn + A * B
mul A, Tn

There are no instructions for loading a register with a constant, so instead the constants are store in memory and loaded as Tn.

Now that the emulator is reversed, we wrote a disassembler and reversed the drum code.

Since the machine lacks convenient stack, or even call/ret instructions, these are implemented in software in sector 1. This sector is loaded most
of the time into sector X and allows simpler sector switching. Sector Y is devoted to currently executed code, and sector Z to data being operated on.

Running the emulator we see a menu and admin panel protected by a password. Reversing the code shows it calculates a simple hash based on
256-byte substitution table - though due to architecture quirks this takes hundreds of instructions and many thousands of cycles. The hash was
reversible, so we wrote a script to calculate the inverse, which when put into the emulator got us the flag:

[email protected]:~\$ ./emulator magnetic_drum.img
Добро пожаловать!

Меню:
1. Коробейники
2. Сведения
3. Админка
4. Остановить
3
Введите пароль: Кто хочет много знать, тому мало спать.
flag{put_your_trits_inside_my_drum}

Original writeup (https://github.com/p4-team/ctf/tree/master/2020-10-23-hacklu/russian_threesome).