How to convert lambda filters with dynamic values to method references

Question: I have some Java code which filters a list based on some input. It currently uses a lambda, for example:
public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags) {
    List<ComplexObject> complexObjects = retrieveAllComplexObjects();
    return complexObjects
                .stream()
                .filter( compObject -> allowedTags.contains(compObject.getTag()))
                .collect(Collectors.toList());
}

What I want to do is to move the filter logic to another method to make it re-usable and easily unit testable. So I wanted to use a method reference in place of the lambda passed to the filter method. Easy to do if the filter logic is fairly static (i.e. list of allowed tags is known at compile time) but I can't figure out how to do this with dynamic data in the filter.
What I wanted was some way to use a method reference and then pass the second dynamic param i.e.
public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags) {
    List<ComplexObject> complexObjects = retrieveAllComplexObjects();
    return complexObjects
                .stream()
                .filter(this::filterByAllowedTags, allowedTags)
                .collect(Collectors.toList());
}

So is it possible to do what I want or am I possibly approaching this situation incorrectly?
Answer: I'd suggest passing in a Predicate as a parameter. That way the caller can filter based on any criteria it wants, including allowedTags or whatever:
public List<ComplexObject> retrieveObjectsFilteredBy(Predicate<ComplexObject> pred) {
    List<ComplexObject> complexObjects = retrieveAllComplexObjects();
    return complexObjects.stream()
        .filter(pred)
        .collect(Collectors.toList());
}

This would be called like so:
    List<String> allowedTags = ... ;
    List<ComplexObject> result =
        retrieveObjectsFilteredBy(cobj -> allowedTags.contains(cobj.getTag()));

But you could go even further, depending on how much refactoring you're willing to do. Instead of "retrieve" returning a List, how about having it return a Stream? And instead of the retrieve-filter method returning a List, how about having it return a Stream too?
public Stream<ComplexObject> retrieveObjectsFilteredBy2(Predicate<ComplexObject> pred) {
    Stream<ComplexObject> complexObjects = retrieveAllComplexObjects2();
    return complexObjects.filter(pred);
}

And the calling side would look like this:
    List<String> allowedTags = ... ;
    List<ComplexObject> result =
        retrieveObjectsFilteredBy2(cobj -> allowedTags.contains(cobj.getTag()))
            .collect(toList());

Now if you look at it carefully, you can see that the retrieve-filter method isn't adding any value at all, so you might just as well inline it into the caller:
    List<String> allowedTags = ... ;
    List<ComplexObject> result =
        retrieveAllComplexObjects2()
            .filter(cobj -> allowedTags.contains(cobj.getTag()))
            .collect(toList());

Of course, depending upon what the caller wants to do, it might not want to collect the results into a list; it might want to process the results with forEach(), or something else.
Now you can still factor out the filter into its own method, for testing/debugging, and you can use a method reference:
boolean cobjFilter(ComplexObject cobj) {
    List<String> allowedTags = ... ;
    return allowedTags.contains(cobj.getTag());
}

    List<ComplexObject> result =
        retrieveAllComplexObjects2()
            .filter(this::cobjFilter)
            .collect(toList());

If you don't want the filter to have the allowed tags built into it, you can change it from being a predicate into a higher-order function that returns a predicate instead:
Predicate<ComplexObject> cobjFilter(List<String> allowedTags) {
    return cobj -> allowedTags.contains(cobj.getTag());
}

    List<String> allowedTags = ... ;
    List<ComplexObject> result =
        retrieveAllComplexObjects2()
            .filter(cobjFilter(allowedTags))
            .collect(toList());

Which of these variations makes the most sense depends on what your application looks like and what kind of dynamicism you require in filtering.
Answer: How about the following? It extracts the predicate in a separate method to make it easily testable, and can be reused easily.
public Predicate<ComplexObject> tagAllowed(List<String> allowedTags) {
    return (ComplexObject co) -> allowedTags.contains(co.getTag());
}

public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags) {
    List<ComplexObject> complexObjects = retrieveAllComplexObjects();
    return complexObjects
                .stream()
                .filter(tagAllowed(allowedTags))
                .collect(Collectors.toList());
}

Answer: The problem with the method reference this::filterByAllowedTags is that it has the shape:
(ComplexObject, List<String>) -> boolean

But it's being passed into filter() which expects a lambda of the shape:
(ComplexObject) -> boolean

In other words, this::filterByAllowedTags can never be a Predicate, but it could be some alternate interface Predicate2. Then you'd also need an overload of filter which takes a Predicate2.
Eclipse Collections (formerly GS Collections) has the method select() which behaves just like filter(), and selectWith() which behaves like the overload I just described.
Using select():
public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags)
{
    // retrieveAllComplexObjects returns a MutableList, possibly FastList
    MutableList<ComplexObject> complexObjects = retrieveAllComplexObjects();
    // select() returns MutableList here which extends List
    return complexObjects.select(compObject -> allowedTags.contains(compObject.getTag()));
}

Using selectWith():
public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags)
{
    // retrieveAllComplexObjects returns a MutableList, possibly FastList
    MutableList<ComplexObject> complexObjects = retrieveAllComplexObjects();
    // select() returns MutableList here which extends List
    return complexObjects.selectWith(this::filterByAllowedTags, allowedTags);
}

private boolean filterByAllowedTags(ComplexObject complexObject, List<String> allowedTags)
{
    return allowedTags.contains(complexObject.getTag());
}

Note: I am a committer for Eclipse Collections.


What is this chord (spelled 2nd, 4th, 5th) and how is it used?

Question: For the piano/composers:
I compose music for the piano in my spare time, and one particular chord that has caught my attention (as one that I like a lot) is the D-F-G chord in C Major.
I have seen Mozart use this chord many times. In particular, his piano sonata in C (No.16 K.545). In both the first and second movements, he uses this chord at the beginning. In the first movement, he plays the I chord, then quickly switches to D-F-G, then back again. I don't know what that chord is. If I had to guess, I would say that it is a V7 chord second inversion without the 3rd? (D-F-G-B, excluding the B). In the second movement, you can see the same thing except in the key of G Major.
Link to the Music Sheet: Sonata in C Sheet Music
What interests me most about that chord in particular, is that it doesn't seem like a full chord change. It seems as though Mozart uses it in the middle of the I chord. It seems like some kind of composing "trick" to me. I have heard in the past about how it is possible to extend chord progressions by switching back and fourth between two chords. For example, ending with V, I, V, I [...] rather than just V, I. Perhaps Mozart was using a technique of some sort to lengthen the I chord and keep it interesting?
And as a last question about the "D-F-G" chord: Is there a particular name for a chord like that? I know that a Csus4 is C-F-G, and Csus2 is C-D-G. I had some thoughts that maybe D-F-G might really be some kind of ii chord variant.
Comment: I agree that it's a V7 second inversion.  The mediant of the V isn't required.
Comment: Well, also, the mediant of the V is in the right hand in that measure.
Comment: Sometimes a chord is a chord and sometimes it's counterpoint. A C chord moving up and back to D F G is more like a double upper neighbor than a chord change.
Comment: "C7 second inversion". Dies with confusion
Comment: One remark: in the 2nd mvt, m1, if it were `f# d c d` in l.h., together with r.h. `c - d` there would be a parallel fifth.
Comment: @MatthewRead - by the mediant, do you mean the third of the V of C, otherwise called B? If so, it's a very important note in that situation, being the leading note/tone, but in any case, the 3 of any chord is important! (Except of course, the omnipresent 'power chord!)
Answer: There are a few observations that can be made here.  First, as others have noted, the sonority is the dominant.  Always make sure to take the entire context (including both staves as well as the surrounding sonorities) into account when determining what to call a sonority.  In the first movement, as @moberhau mentioned, you do have all members of the dominant seventh chord.  The inversion simply facilitates pianistic voice-leading.  In the second movement, first measure, again there is a momentary shift to a dominant sonority in the lower staff only.  What about entire context?  I'm getting to that.
You made an observation that alternating chords can serve just to prolong one harmony.  Yes, that is what seems to be happening in both the places you mentioned.  The dominant is not truly structural, but rather it prolongs the tonic.  There is no larger-scale advancement of the form of the movement that occurs due to the dominant sonority there.
Finally, trust your ears.  Even if a particular note is missing or appears not to fit, what does the passage sound like?  In both cases you mention, I believe that the sonority sounds like a dominant "in passing," just to prolong the tonic.
Answer: It's called (since you ask ) G dominant 7 with no 3rd. In guitarspeak G7/D(no3)
Comment: @fdreger - since it's my answer, there's no need . Just comment.
Comment: I like how you classified G7/D(no3) as "guitarspeak"; it can be instantly interpreted as an interesting piece of additional context; and at the same time it conveys the fact that it would be unusual for someone interpreting Mozart's piece in academic context to ever use this name.
Comment: @fdreger - that was nearly 10 yrs ago! But it still stands. How else could it be termed, when the chord is G7 with no 3rd? Seems a lot of site visitors need labels - just like most of humanity.
Comment: Blame the algorithm :) Every once in a while I get drawn here by some "hot question" link. Today I found a question about chords, downvoted your answer, clicked on the "chord" tag just to see the type of question people ask... and voila, the first thing I clicked had your answer, almost identical to the one I downvoted, but perfectly worded. So I had a laugh, upvoted it (I believe that you have net +9 from me today, not that you care :) ) and took time to comment on the difference between "In guitarspeak it's G7(no3)" and " [...] F7(no3) - [...] is just what it is."
Comment: how strange, it doesn't allow me to add "@Tim" in the former comment. A bug?
Answer: A dominant (seventh) chord will generally contain the 3rd.   But you're only looking at the LH I think.  The melody in the RH is part of the chord too!   And as well as the 'rule' that says the 3rd is a defining element of a triad (particularly of a dominant triad) there's one that says that, BECAUSE it's so distinctive, it should only appear once in the musical texture. Rules are made to be broken.  But the 'harmony exercise' rules are applicable to a Mozart sonata, because of its period and its simplicity.
Comment: Apparently, the 3rd (B) is in the melody, so yes, it's not going to appear in the l.h.


What control variables do we need for IV regression?

Question: I am running and IV regression and I need help on what control variables to include in the IV regression. I believe that I have to control for potential variable that are correlated with both the instrumental variable (Z) and the dependent variable (Y) so that exclusion restriction holds.
What else do I have to control for? In IV papers that I read, I see authors also use control variables that were use in the OLS regression (to prevent omitted variable bias = those correlated to both independent X and dependent variable Y) in the IV regression. If IV regression can solve omitted variable bias, why do we need to include those same variables from the OLS regression in the IV regression? Would we not get the same estimate from IV regression, if we do not include those control variables that were used in OLS?
Comment: One reason is that often we think that an instrument is valid conditional on some control variables. Another is that controls that explain the outcome but not the covariate of interest increase the statistical power of hypothesis tests on our coefficient of interest.
Answer: If IV regression can solve omitted variable bias, why do we need to include those same variables from the OLS regression in the IV regression?
If you can argue that your IV is as good as random then you don't need to include any other variables to remove the bias. In many cases (e.g. randomized controlled trials) this is satisfied by design. But when using instruments in observational studies, it is much harder to show that a instrument is plausibly exogenous. In such cases we relax the assumption and require the instrument to be random after conditioning on some observed variables. In such cases, the IV can remove the omitted variable bias only after the variations due to the observables have been controlled for. So you need to control for this observable characteristics.
Would we not get the same estimate from IV regression, if we do not include those control variables that were used in OLS?
Not necessarily. Firstly, if the IV is conditionally exogenous then not including the controls will bias your results. But what if the IV is perfectly random? Then you get unbiased estimates, but the precision of your estimate is determined by how much of the variation in the endogenous variable is explained by your instrument. Imagine your endogenous variable to have "good" variations and "bad" variations (these are the omitted variable correlations). The bad variation is what you want to get rid off, but you want to capture as much of the good variation as you can. Adding relevant variables will explain a larger part of the good variation and make your estimates more precise.
Another reason for getting different estimates when using control variables is the idea of Local Average Treatment Effect. Basically using IV allows you study the effect of only the part of the endogenous variable that the instrument can explain. Hence, adding more variables (which are assumed to be exogenous) will give you an effect closer to the average effect of the endogenous variable (please see mostly harmless econometrics).
What else do I have to control for?
I think this is a more philosophical question and depends on the scope of your research. If you have a exogenous instrument $I$ and your motive is to study the causal impacts of an endogenous $D$ on $Y$, then simply using these three will give you the local average treatment effect of $D$.


Check 3gp file is audio/video in Android?

Question: Im trying to get mimetype of video files using below code.
Porblem: I have a file saved as audio but its mimetype is video/3gpp and it is also playing
as Audio. . How to detect this kind of file which is audio but mimetype is video/3gpp in its
details so i can exclude it from list.
<code>fun getFileMimeType(url: String): String {

        var type: String = ""

        try {
            if (url.lastIndexOf(".") != -1) {
                val ext: String = url.substring(url.lastIndexOf(".") + 1)
                val mime = MimeTypeMap.getSingleton()
                type = mime.getMimeTypeFromExtension(ext)!!
            }

        } catch (e: Exception) {
        }

        return type

    }
</code>
Answer: Assuming this is a local file, you can use MediaMetadataRetriever to get Metadata information about the media file.
Specifically, you can check if the METADATA_KEY_HAS_VIDEO is set to true.
An example in Kotlin:
<code>        val metadataRetriever = MediaMetadataRetriever()
        metadataRetriever.setDataSource(context, Uri.fromFile(your3GPPFile))

        val hasVideoKey = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO)
        if (hasVideoKey == "yes") {
          //Include in your list or do whatever work
          //you need here
        }

</code>
You can also use ExoPlayer and load the file, and then get a list of the tracks using

player.getCurrentTrackGroups()

This will return an array of tracks which you can loop through and parse the format to check if they include a video track.
Comment: Thank you so much. Solved the issue using MediaMetadataRetriever
Comment: This is perfect. I needed it as a fallback for container formats such as 3gpp which always return video/3gpp even if the file only contains an audio track only.


A region in $\mathbb C$ minus countably many points is path-connected

Question: Edit: Someone marked my question as a duplicate of this. However, I am asking about proving this result for any open and connected set in the plane and when removing countably many points and not necessarily finite. I know how to prove it when removing finitely many points. Please reopen the question.
I want to prove that if $\Omega$ is a region in the complex plane and if $A$ is a countable subset then $\Omega - A$ is connected. Given $z_1$ and $z_2$ in $\Omega$ we must prove that there is some path in $\Omega$ joining $z_1$ to $z_2$.
Now in case $\Omega$ is the whole complex plane then this can be done by taking a line passing through $z_1$ which does not intersect $A$ and another passing by $z_2$ but neither parallel to the first line nor intersecting A. These two exist since at each point there are uncountable many such lines since if all lines, for instance passing by $z_1$, intersect $A$ then this would contradict the countability of $A$. Let $z_3$ be the intersection of the two lines and thus join $z_1$ to $z_2$ by joining $z_1$ to $z_3$ and then $z_3$ to $z_2$.
I am not sure how to prove the more general case. If we join $z_1$ to $z_2$ by a path $\gamma$ in $\Omega$, then we need to modify this path so that it does not pass by A. Any suggestions how?
Comment: @user3716267 This is false even in $\Bbb R$: If you remove all points $1/n$, $n\in\Bbb N$, $0$ is left in the set but has no neighborhood contained in the set, so the set is not open.
Comment: @CheerfulParsnip This is exactly how I proved it in case $\Omega$ is the whole complex plane since I can speak of two lines and their intersection there. But in my question $\Omega$ need not be the whole complex plane and that's where my problem specifically lies.
Comment: I deleted my comments and voted to reopen.
Comment: @CheerfulParsnip can you please elaborate? The way I proved it for finitely many points is by proving it for one point $a$ and then deduce by induction. To prove it for one point we join $z_1$ and $z_2$ by a path in $\Omega$ and assume it passes by $a$(if not then we are done). We take an open ball around $a$ contained in $\Omega$ and not containing or passing by $z_1$ and $z_2$. We replace the part of the path contained in this ball by the arc joining the first and last points of intersection between the path and the boundary of this ball and hence we get a path joining $z_1$ to $z_2$.
Comment: @CheerfulParsnip the thing is that when you remove finitely many points from $\Omega$ you will still have an open set and thus you can give such an open ball not passing or containing any points of that finite set. So how can I generalize it for countably many points when I can't guarantee that $\Omega$ remains open upon removing countably many points from it?
Comment: This is exactly the argument of the accepted answer to the duplicate.
Comment: Ah I see. I missed "Region in $\mathbb C$."
Comment: Isn't it true that you cannot turn an open set into a not-open set by removing countably-many points?  If you could, then there must be some point in the set with only countably-many points in its neighborhood, which seems impossible.
Comment: Ah, yeah, you can "pierce" the neighborhood cleverly.  It seems like you can only do this locally in a countable number of places though, so we should still be able to patch around it…
Comment: @user3716267 remove all rationals, no point admits an open neigbourhood
Answer: You can do a similar argument as in the case of $\Bbb C$. The important trick is to reduce to the following case:

Lemma. Let $X$ be a countable subset of the unit ball $B_1(0)$. Then $B_1(0)-X$ is path connected.

Proof:
Let $x,y\in B_1(0)-X$. For $z\in B_1(0)-X$ let $[x,z]$ and $[y,z]$ denote the paths $\{t x+(1-t)z\mid t\in[0,1]\}$ and $\{ty+(1-t)z\mid t\in[0,1]\}$. These paths are contained entirely $B_1(0)$ and if $z_1\neq z_2$ with $x-z_1$ and $x-z_2$ not proportional to each other then $[x,z_1]\cap [x,z_2] = \{x\}$.
So, since $X$ is countable, there are uncountably many $z$ for which both $[x,z]\cap X$ or $[y,z]\cap X$ are empty. Pick one $z$ for which it is empty and then $[x,z]\cup [y,z]$ gives a path from $x$ to $y$ in $B_1(0)-X$.
The above obviously also implies:

For any $\epsilon >0$ and $x\in \Bbb C$ and countable $X$ the ball $B_\epsilon(x)-X$ is path connected.

Now to show the statement you are interested in. $\Omega$ is open and connected, so it is path connected. Let $x,y\in \Omega-X$ and let $\gamma:[0,1]\to \Omega$ be a path connecting $x$ and $y$. Since the image of this path is compact and $\Omega$ is open there are $x_1,...,x_n$ and $\epsilon_1,...,\epsilon_n$ so that
$$\gamma([0,1])\subset\bigcup_{k=1}^n B_{\epsilon_k}(x_k)\subseteq \Omega$$
Now each of the $B_{\epsilon_k}(x_k)-X$ are path connected and the intersection of two neighbouring balls is non-empty. Hence their union is path connected and there is a path connecting $x\in \bigcup_{k=1}^n B_{\epsilon_k}(x_k) -X$ to $y$ which lies in the same set.
Comment: For the implication that $B_\epsilon \setminus X$ is our interval not just $[0,\epsilon]$?
Comment: I don't understand what you are asking, sorry.


stateNotifier for multiple states with riverpod

Question: I'm confused about how to use stateNotifier with riverpod. Most of the tutorials out there uses the counter example which is good but still not that clear to me. I'm trying to implement a stateNotifier with 2 states : isDrawerOpen and isDrawerColor which returns boolean result. Some functions will trigger the changes in those state. Below is what I have implemented and could really use some clarification.
import 'package:flutter_riverpod/all.dart';

class DrawerNotifier extends StateNotifier{

  DrawerNotifier() : super(false);

  bool isDrawerOpen = false;
  bool isDrawerColor = false;

  void toggleDrawer() {
    isDrawerOpen = !isDrawerOpen;
  }
  void toggleColor() {
    isDrawerColor = !isDrawerColor;
  }
}

final drawerProvider = StateNotifierProvider((_) => DrawerNotifier());

final isDrawerOpen = StateNotifierProvider((ref){
  final state = ref.watch(drawerProvider);
  return state.isDrawerOpen;
});

final isDrawerColor = StateNotifierProvider((ref){
  final state = ref.watch(drawerProvider);
  return state.isDrawerColor;
});

Answer: You can create a seperate state class as below(I am using the equattable package)
abstract class DrawerState extends Equatable {
  DrawerState();
  }
class IsDrawerOpen extends DrawerState {
 UserFetchInitial();

 @override
 List<Object> get props => [];
}
class IsDrawerClosed extends DrawerState {
 UserFetched();

 @override
 List<Object> get props => [];
}

Next, your drawerProvider will look like this. We will create a drawer Controller to control the state of the drawers.
final drawerProvider = StateNotifierProvider<DrawerController>((_) => DrawerNotifier());

Our DrawerController will look like this.
class DrawerController extends StateNotifier<DrawerState> {
  void changeDrawer(bool isDrawerOpened) {
   if(isDrawerOpened) {
      state = IsDrawerOpen();
    } else {
        state = IsDrawerClosed();
      }
  }
}

You can call the changeDrawer method anywhere in your UI using context.read(drawerProvider).changeDrawer(true);


How many square tiles can fit in an area of $1080 \times 1920$?

Question: What is the largest size that 35 square tiles can be, which fit in an area of $1080\times $1920?
Comment: Tiles of equal size, apparently?
Answer: If you accept rectangular tiles, you can fill the area by making tiles $\frac {1080}5 \times \frac {1920}7$ or $\frac {1080}7 \times \frac {1920}5$.  These are $216 \times 274\frac 37$ and $154\frac 27 \times 384$.  As you can see, in one direction the tile has a fractional dimension.  You could also use $1080 \times \frac {1920}{35}$ or $\frac {1080}{35} \times 1920$ tiles, but I suspect that is not what you are looking for.  For similar problems, you decide on the grid you want, starting by factoring the number of tiles, then divide the linear dimension by the corresponding factor.
In your title, you call for square tiles.  You can't fill that area with $35$ square tiles.  The best you can do is to use tiles with a side of $216$.  Five of them will fill the $1080$ dimension, but the other direction will be $7 \times 216=1512$ and you will have $408$ left uncovered.
Comment: I see nowhere in the question where the tiles are required to "fill". It just says "fit". I think the OP is trying to ask "What is the largest size that 35 square tiles can be, which still fit in this area?"
Comment: And by that I meant only to draw attention that readers can skip over the first part of the answer to the last part of the answer, which addresses that.


Attempt to invoke virtual method 'android.os.Looper android.os.Handler.getLooper()' on a null object reference

Question: A bit of a background here, I came from Ionic so I'm still a noob when it comes to java and android studio.
So I followed this article in medium and I stumbled a lot with declaring global variables specifically...
Here's my  code
public class MainActivity extends AppCompatActivity {
    private static final int CAMERA_REQUEST_CODE = 10001;
    int cameraFacing;

    CameraManager cameraManager;
    TextureView textureView;
    Size previewSize;
    String cameraId;
    Handler mHandler ;
    HandlerThread mHandlerThread ;
    CameraDevice.StateCallback stateCallback;
    CameraDevice cameraDevice;
    CameraCaptureSession cameraCaptureSession;
    CaptureRequest captureRequest;
    CaptureRequest.Builder captureRequestBuilder;
    TextureView.SurfaceTextureListener surfaceTextureListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);
        cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        cameraFacing = CameraCharacteristics.LENS_FACING_BACK;

        textureView = findViewById(R.id.texture_view);

        surfaceTextureListener = new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
                setUpCamera();
                openCamera();
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

            }
        };

        stateCallback = new CameraDevice.StateCallback() {
            @Override
            public void onOpened(CameraDevice cameraDevice) {
                MainActivity.this.cameraDevice = cameraDevice;
                createPreviewSession();
            }

            @Override
            public void onDisconnected(CameraDevice cameraDevice) {
                cameraDevice.close();
                MainActivity.this.cameraDevice = null;
            }

            @Override
            public void onError(CameraDevice cameraDevice, int error) {
                cameraDevice.close();
                MainActivity.this.cameraDevice = null;
            }
        };
    }
    private void createPreviewSession() {
        try {
            SurfaceTexture surfaceTexture = textureView.getSurfaceTexture();
            surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
            Surface previewSurface = new Surface(surfaceTexture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(previewSurface);

            cameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(CameraCaptureSession cameraCaptureSession) {
                            if (cameraDevice == null) {
                                return;
                            }

                            try {
                                captureRequest = captureRequestBuilder.build();
                                MainActivity.this.cameraCaptureSession = cameraCaptureSession;
                                MainActivity.this.cameraCaptureSession.setRepeatingRequest(captureRequest,
                                        null, mHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {

                        }
                    }, mHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        openBackgroundThread();
        if (textureView.isAvailable()) {
            setUpCamera();
            openCamera();
        } else {
            textureView.setSurfaceTextureListener(surfaceTextureListener);
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        closeCamera();
        closeBackgroundThread();
    }

    private void closeCamera() {
        if (cameraCaptureSession != null) {
            cameraCaptureSession.close();
            cameraCaptureSession = null;
        }

        if (cameraDevice != null) {
            cameraDevice.close();
            cameraDevice = null;
        }
    }

    private void closeBackgroundThread() {
        if (mHandler != null) {
            mHandlerThread.quitSafely();
            mHandler = null;
            mHandlerThread = null;
        }
    }
    private void setUpCamera(){
            try{
                for(String cameraId: cameraManager.getCameraIdList()) {
                    CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
                    if(cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == cameraFacing){
                        StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                        previewSize = streamConfigurationMap.getOutputSizes(SurfaceTexture.class)[0];
                        this.cameraId = cameraId;
                    }

                }
            } catch (CameraAccessException e){
                e.printStackTrace();
            }
    }
    private void openCamera(){
        try{
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                cameraManager.openCamera(cameraId, stateCallback, mHandler );
            }
        } catch (CameraAccessException e){
            e.printStackTrace();
        }
    }
    private void openBackgroundThread(){
        mHandlerThread  = new HandlerThread("camera_background_thread");
        mHandlerThread.start();
        mHandler  = new Handler(mHandler .getLooper());

    }
}

And here's the error I got from the Logcat
10-24 18:47:10.269 5694-5694/adprog.reese.com.adprog E/AndroidRuntime: FATAL EXCEPTION: main
    Process: adprog.reese.com.adprog, PID: 5694
    java.lang.RuntimeException: Unable to resume activity {adprog.reese.com.adprog/adprog.reese.com.adprog.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.os.Handler.getLooper()' on a null object reference
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3031)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3062)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5354)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.os.Handler.getLooper()' on a null object reference
        at adprog.reese.com.adprog.MainActivity.openBackgroundThread(MainActivity.java:200)
        at adprog.reese.com.adprog.MainActivity.onResume(MainActivity.java:139)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1241)
        at android.app.Activity.performResume(Activity.java:6107)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3020)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3062)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5354)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

And the problematic code
private void openBackgroundThread(){
    mHandlerThread  = new HandlerThread("camera_background_thread");
    mHandlerThread.start();
    mHandler  = new Handler(mHandler.getLooper());

}

Any help would be greatly appreciated!
Answer: Maybe the line below is the issue...
mHandler  = new Handler(mHandler .getLooper()); // this line

You might wanted this i suppose. Not sure but try it....
mHandler  = new Handler(mHandlerThread.getLooper());

Answer: What worked for me was shared here, Jules Colle's answer: How to call a method after a delay in Android
For reasons I don't follow, possibly tied to not being in the UI thread, I also could not use Looper. The below worked very well for me. "Use the java native Timer instead"
new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        // this code will be executed after 2 seconds
    }
}, 2000);

Answer: For Xamarin (MAUI) the first "Looper null reference Android" possible fix would be to wrap your code inside a nice
 Device.BeginInvokeOnMainThread(async () =>
            {
               //... your failing code here
            });


SQL Server cannot connect after reboot and locked

Question: I have a remote sql server connection and was in the middle of updating some value with begin and commit tran command. However, before it finished, the query got canceled and the table is locked. After several attempt to restart the database, the table is still locked and then we restarted the machine.
It is worse now that we cannot even connect to the server from management studio. There are few different errors that shows up when I tried to connect such as the connection timeout, server not known and the most common one that shows up is cannot generate SSPI context.
It can't be domain issue since I can connect just fine before on the same network with same user account. Does anyone know how to resolve this?
Comment: Offtopic, should be on serverfault.
Comment: What is showing up in the SQL ErrorLog?
Comment: There is nothing in the ErrorLog suprisingly :(
Answer: Why was the query cancelled? Was it a big query? What actions were taken after the query was cancelled? How long did you wait before restarting?
The reason I ask is that, when a query gets cancelled the database immediately starts rolling back the transaction. If the query had done a significant amount of changes before the cancellation, it might take a long time to rollback (explaining why the table would be locked). This is when things typically go from bad to worse, because developers get impatient and do things like restart the service/server. Then, when the database engine starts up, the database goes into recovery mode, rolling back all transactions that were open during the restart.
Can you remote into the machine? If so, check services to verify the database engine is running. If so, can you connect to localhost via management studio (remoted in). If not, start it. If you can't start it, try starting in single user mode.
Comment: Hi Brian, Thanks for the respond. I can remote to the machine and the service is running. However I cannot connect to the to the server even from the local machine. We decided to migrate the database to other server, but what's funny is that the server that is stuck can't even be deleted. Messed up...
Answer: Keeping in mind what @brian said, the other thing you should do is make sure you have a good recent backup. And then take another one for good measure.


E-mail sent from domain A on server in domain B is bounced by recipient

Question: I have an old Windows 2003 Enterprise Server running Microsoft Exchange. The server is in the domain networking-consultancy.com. The server hosts mail for that domain and also for two other domains, greenmountvillage.org.uk and tottington-dcs.org.uk. Mail sent from greenmountvillage.org.uk from this server is being bounced as follows:
<code>"There was a SMTP communication problem with the recipient's email server.  Please contact your system administrator.
SERVER-01.networking-consultancy.com #5.5.0 smtp;554 bounce 1
recips: Denied [CS]
[fe350d75.0.2891422.00-2332.5771308.s17p02m031.mxlogic.net] (Mode:
normal)"
</code>
Can anyone please explain what the problem is and how to fix it?
Perhaps I should add that I am not an expert when it comes to servers. I specialised in telecommunications. Thanks.
Answer: Error 554 you got usually means that message was rejected because sender's server is seen as unreliable. With additional note - fe350d75.0.2891422.00-2332.5771308.s17p02m031.mxlogic.net, it's safe to assume that recipient is using Mcafee email protection which uses their own reputation system to decide what email should or shouldn't be accepted. It's best to contact recipient and ask them to consult Mcafee support to look into this case and make adjustments.


How to update a value using where clause in strapi 4

Question: I have a collection type "Order" which has a field called order_id.
how to write a where clause to update the order where order_id is "1234", how to achieve this functionality in strapi 4
Thanks
Answer: You didn't mention which approach you'd like to use, so:

Here's the section in the docs using REST API: https://docs.strapi.io/dev-docs/api/rest#update-an-entry
Here's the section in the docs using the Entity Service API: https://docs.strapi.io/dev-docs/api/entity-service/crud#update
Here's the section in the docs using the Query Engine API: https://docs.strapi.io/dev-docs/api/query-engine/single-operations#update


ActiveRecord: Adding condition to ON clause for includes

Question: I have a model offers and another historical_offers, one offer has_many historical_offers.
Now I would like to eager load the historical_offers of one given day for a set of offers, if it exists. For this, I think I need to pass the day to the ON clause, not the WHERE clause, so that I get all offers, also when there is no historical_offer for the given day.
With
    Offer.where(several_complex_conditions).includes(:historical_offers).where("historical_offers.day = ?", Date.today)
I would get
SELECT * FROM offers
LEFT OUTER JOIN historical_offers
ON offers.id = historical_offers.offer_id
WHERE day = '2012-11-09' AND ...

But I want to have the condition in the ON clause, not in the WHERE clause:
SELECT * FROM offers
LEFT OUTER JOIN historical_offers
ON offers.id = historical_offers.offer_id AND day = '2012-11-09'
WHERE ...

I guess I could alter the has_many definition with a lambda condition for a specific date, but how would I pass in a date then?
Alternatively I could write the joins mysqlf like this:
Offer.where(several_complex_conditions)
  .joins(["historical_offers ON offers.id = historical_offers.offer_id AND day = ?", Date.today])

But how can I hook this up so that eager loading is done?
Comment: A [related question](http://stackoverflow.com/questions/15691558/refining-the-inner-join-when-using-includes-in-activerecord/17737833#17737833) received more attention, but none gave exactly what you are looking for.
Answer: After a few hours headscratching and trying all sorts of ways to accomplish eager loading of a constrained set of associated records I came across @dbenhur's answer in this thread which works fine for me - however the condition isn't something I'm passing in (it's a date relative to Date.today).  Basically it is creating an association with the conditions I wanted to put into the LEFT JOIN ON clause into the has_many condition.
has_many :prices, order: "rate_date"
has_many :future_valid_prices,
    class_name: 'Price',
    conditions: ['rate_date > ? and rate is not null', Date.today-7.days]

And then in my controller:
@property = current_agent.properties.includes(:future_valid_prices).find_by_id(params[:id])


Alguem consegue me explicar porque o 'u' no range, quando eu faço u-=1 ele conta no debug e quando vai pro range ele sobe de 1 pra 3

Question:     for u in range(5):
      posicao_atual=lista[i][u]
      if posicao_atual=='0':
        distancia+=1
      elif posicao_atual=='B' or posicao_atual=='A' or posicao_atual=='C' or posicao_atual=='D' :
        visitadas.append(lista[i][u])
        i-=1
        u-=1```

Comment: Não é assim que um iterador funciona no Python; talvez você esteja acostumado com o formato de repetição usado na linguagem C com o incremento à variável passada como valor inicial, mas aqui não é o caso. Independente de qualquer alteração no valor de `u` durante cada iteração do *loop*, o valor seguinte da coleção resultante da função `range(5)` é atribuído novamente à variável `u` na próxima iteração.
Answer: Isso acontece porque o for simplesmente itera na sequência, então, independente da operação que você fizer com o 'u', quando o for voltar para o início ele simplesmente vai pegar o próximo elemento que estava na sequência. Então como você falou, em certo momento da execução do seu programa temos:
u == 2

E você realiza a seguinte operação:
u -= 1

Essa operação de fato faz com que o u vire 1 naquele momento. Todavia, não altera o próximo elemento da sequência, que continua sendo 3 e, portanto, o próximo a ser atribuído ao valor de u. Se você quiser uma estrutura que tenha esse efeito teria que ser utilizado o while, visto que ele não itera sobre uma sequência, e sim sobre uma variável de controle. Então, transformando esse código em while:
u = 0
while u < 5:
    posicao_atual=lista[i][u]
    if posicao_atual=='0':
        distancia+=1
    elif posicao_atual=='B' or posicao_atual=='A' or posicao_atual=='C' or
        posicao_atual=='D' :
        visitadas.append(lista[i][u])
        i-=1
        u-=1

    u += 1

Nesse caso, o código de fato surtiria o efeito que você estava esperando.
Adendo:
Isso faria com que o código na próxima iteração do while utilizasse o u como sendo 2, visto que somamos 1 no final. Se quiser que o u seja 1, é só adicionar um:
continue

na linha seguinte a
u -= 1

Isso vai pular direto para a próxima iteração, sem realizar o:
u += 1

Você pode encontrar mais informações sobre o uso do for e do while clicando aqui.
Comment: vlw mano!!!!!!!


Chart.js | Trouble refreshing line chart with "setInterval"

Question: Wondering if anyone can help me out please.
I'm having trouble getting a Chart.js LineChart (with AJAX data) to refresh every "X" seconds. I've tried to put the code below in a function inside a setInterval and eventhough it does refresh, it redraws itself in a "zoomed-in" manner...
I want the chart to refresh itself every 10 seconds.
Code:
<code>        $.ajax({
            type: "POST",
            url: '@Url.Action("ChartRT")',
            contentType: "application/json",
            dataType: "json",
            success:
            function (chartsdata_RT) {
                var aData = chartsdata_RT;
                var aLabels = aData.map(c => c.Period);
                var aDatasets1 = aData.map(c => c.FAILED);
                var aDatasets2 = aData.map(c => c.OTHER);
                var aDatasets3 = aData.map(c => c.DELIVERED);
                var aDatasets4 = aData.map(c => c.PENDING);
                var dataT = {
                    labels: aLabels,
                    datasets: [
                        {
                            label: "FAILED",
                            data: aDatasets1,
                            borderColor: '#ff0000',
                            backgroundColor: "rgba(255, 0, 0, 0.3)",
                            fill: 'true'
                        },
                        {
                            label: "OTHER",
                            data: aDatasets2,
                            borderColor: '#3366ff',
                            backgroundColor: "rgba(32, 162, 219, 0.3)",
                        },
                        {
                            label: "DELIVERED",
                            data: aDatasets3,
                            borderColor: '#009900',
                            backgroundColor: "rgba(0, 102, 0, 0.3)",
                        },
                        {
                            label: "PENDING",
                            data: aDatasets4,
                            borderColor: '#ff9900',
                            backgroundColor: "rgba(255, 153, 219, 0.3)",
                        }

                    ]
                };

                var ctx = $("#chart_last2hours").get(0).getContext("2d");
                ctx.canvas.height = "50";
                var myNewChart = new Chart(ctx, {
                    type: 'line',
                    data: dataT,
                    options: {
                        legend: {
                            display: true,
                            position: 'right',
                            fullWidth: false,
                            labels: {
                                fontColor: '#484848',
                                fontsize: 10,
                                boxWidth: 20,
                                padding: 5,
                                lineWideth: 0
                            }
                        }

                    }

                });
            }

        });
</code>
Comment: Make sure when you are creating the chart again that you are destroying the old one. If you have it in a div I have found that you have to clear the div or it begins to clutter (at least within SharePoint it did for me). Without deleting the old chart you write "over" the other chart but it will still remember the data points causing weird results when you hover over the chart (it will seizure going back and forth between new data and old data lines).
Answer: ended wrapping the above code in a function (drawChartRT). I then:
1) Call the function drawChartRT() to draw the LineChart.
2) Inside a setInterval remove and add the canvas and call the function drawChartRT().
<code>    drawChartRT();
    setInterval(function () {
        $("canvas#chart_last2hours").remove();
        $("#chartdiv_rt").append('<canvas id="chart_last2hours" height="200"></canvas>');
        var div = document.getElementById("chart_last2hours");
        //console.log(div);
        drawChartRT();
    }, 10000);
</code>
Works like a charm!
Thanks. José


What are the subgroups of $Z_{3^2}$

Question: Need to find all the subgroups of $Z_{3^2}$. Is $Z_{3^2}$ same as the Elementary abelian group (the product $Z_3\times Z_3$)?
Comment: As others have said, the answer is no. And the elementary abelian group order 9 is the direct product ${\mathbb Z}_3 \times {\mathbb Z}_3$, and not the free product ${\mathbb Z}_3 * {\mathbb Z}_3$.
Answer: $\mathbb Z_{3^2} = \mathbb Z_{9} \neq \mathbb Z_3\times \mathbb Z_3$ and clearly, $\mathbb Z_9$ cyclic (and so all its subgroups are cyclic).
Now, use the fact that for cyclic groups of order $n$, the converse of Lagrange's Theorem holds: For every positive integer $m$ such that $m\mid n$, there exists a unique subgroup of order $m$.
So to find the subgroups of $\mathbb Z_9$, for each positive integer that divides 9, determine the corresponding subgroup: there are exactly three integers dividing $9$: $1, 3, 9$. The subgroup of order $1$ is of course, the trivial group $\{0\}$. The subgroup of order $3$ must be $\mathbb Z_3$, and the subgroup of order $9$ is $\mathbb Z_9$ itself.
Comment: Thanks. But the question I wanted to prove is slightly different. I realised it now. Sorry for that. So I had to post it as another question. Please help. http://math.stackexchange.com/questions/669688/what-are-the-subgroups-of-z-32-under-multiplication
Answer: For any $n$, the set of all subgroups of $\mathbb{Z}_n = \langle x \rangle$ can be shown to be the set $\{ \langle x^d \rangle: d | n\}$.  Every subgroup of a cyclic group is a cyclic group generated by the smallest positive power (denoted by $x^d$ here) of $x$ that is in the subgroup.  Notice that $\langle x^d \rangle$ is isomorphic to $\mathbb{Z}_{n/d}$, and that as $d$ runs over the divisors of $n$, so does $n/d$.  Thus, the set of all subgroups of $\mathbb{Z}_n$ is isomorphic to  $\{\mathbb{Z}_d: d | n\}$.  More specifically, the subgroups of $\mathbb{Z}_9=\langle x \rangle$ are $\langle x^d \rangle$, where $d$ equals 1, 3 or 9, which are the subgroups $\mathbb{Z}_9, \{1,x^3,x^6\} \cong \mathbb{Z}_3$, and the trivial group $\{1\}$, respectively.
Comment: Thanks for the help. But the question I wanted to prove is slightly different. I realised it now. Sorry for that. So I had to post it as another question. Please help. http://math.stackexchange.com/questions/669688/what-are-the-subgroups-of-z-32-under-multiplication
Answer: The lattice of subgroups of $\mathbb Z_m$ is isomorphic to the lattice of divisors of $m$ via the canonical homomorphism $\mathbb Z \to \mathbb Z_m$ whose kernel is $m\mathbb Z$.
Recall that the lattice of subgroups of $\mathbb Z$ is isomorphic to the lattice $\mathbb N$ under divisibility.

What are the subgroups of $Z_{3^2}$


Is a random walk i.i.d.?

Question: Assuming that we have an AR(1) process:
$$X_t=\rho X_{t-1}+\varepsilon_t,\quad\varepsilon\sim IIDN(0,1)$$
And further assuming that $\rho=1$ and $X_0=0$ we have a random walk process:
$$X_t=\sum_{i=1}^t\varepsilon_t$$
Is this process i.d.d.?
If yes/no why is that the case?
Comment: What do you mean by "Is this process i.i.d.?" Clearly $X_t$ and $X_{t+1}$ are not independent.
Comment: @EB3112, this should be an answer.
Comment: Hi @Rstrobaek. A random walk is not i.i.d. First of all, a random walk is non-stationary. Stationarity provides the 'identical' aspect of an i.i.d. Furthermore, a random walk exhibits dependency. To evoke something along the lines of independence, you would require the time series to exhibit something like weak dependency/ergodicity. However, as a comment, this is simply a sketch of the issue. I am sure you'll get a more complete answer
Comment: Hi @RichardHardy. I appreciate you saying so. However, @@Dave has provided a much more complete account than my scant version. However, I agree that intuition goes very far.
Comment: @EB3112 Your comment addresses points not raised explicitly in my answer and would be worth having in an answer.
Comment: I am voting to close this question as it is unclear what is meant with 'is this process i.i.d?'. The example by Dave shows that there's correlation, but with another interpretation one could get non-correlated results (eg repeatedly generate random walks and each random walk will be independent).
Answer: Let's look at a simulation.
library(ggplot2)
set.seed(2023)

# Length of each time series
#
N <- 100

# Number of times to simulate
#
R <- 1000

# Function to create the time series
# (I don't remember the syntax for the built-in function)
#
time_series <- function(rho, x0, N, mu = 0, sigma = 1){

  # Blank vector to hold the time series
  #
  ts <- rep(NA, N)

  # Declare the first value
  #
  ts[1] <- x0

  # Autoregressive series with additive noise
  #
  for (i in 2:N){
    ts[i] <- rho*ts[i - 1] + rnorm(1, mu, sigma)
  }

  return(ts)
}

# Data frame to hold the fifth and sixth values of the time series
#
d <- data.frame(ts5 = rep(NA, N), ts6 = rep(NA, N))

# Simulate R-many time series, storing the 5th dnd 6th values
#
for (i in 1:R){
  ts <- time_series(1, 0, N)
  d[i, ] <- c(ts[5], ts[6])
}

# Plot the 5th and 6th values against each other to note the correlation
#
ggplot(d, aes(x = ts5, y = ts6)) +
  geom_point() +
  xlab("Time 5") +
  ylab("Time 6")

The visual evidence convinces me of a correlation. We can also do a formal hypothesis test of the correlation via cor.test(d$ts5, d$ts6) to get a p-value $\approx 0$.
This makes sense. By defining the time series as autoregressive, you are specifying the sixth point as being equal to the fifth point plus some noise, so there is certainly going to be some dependence between the two points.
If you want to be rigorous about the math, calculate the covariance between consecutive points, knowing that a random variable will be correlated with a linear combination of itself and the Gaussian error term.
(My selection of the 5th and 6th points was arbitrary but sufficient to show the lack of independence. If the 5th and 6th points are correlated, then the time series is not IID.)
Also, the "identical" part of $IID$ is violated. As you go further out in the series, the variance increases, as each subsequnt time step adds an additional noise term.
Comment: Here is another simulation, creating a similar image, but it uses iid multivariate normal distributed variables `n = 10^3; x = MASS::mvrnorm(n, c(0,0), matrix(c(4,4,4,5),2)); plot(x)`.
Comment: @SextusEmpiricus I'm not following the connection to the time series question, other than your plot looking like mine. Could you please elaborate?
Comment: The vectors that you simulated can be considered as iid vectors. To show that, I simulated them directly from the distribution $$\begin{bmatrix}x_5\\x_6\end{bmatrix} \underset{iid}{\sim} \mathcal{N} \left( \boldsymbol{\mu} = \begin{bmatrix}0\\0\end{bmatrix}, \boldsymbol{\Sigma} = \begin{bmatrix}4 & 4 \\ 4 & 5\end{bmatrix}  \right)$$

Is a random walk i.i.d.?


Why do small objects have to preverse colimits from directed sets, rather than colimits from semilattices?

Question: Let $\kappa$ be a regular cardinal. Let $\mathcal C$ be a category. Let $A : \mathcal C$ be an object of $\mathcal C$. As best I can tell, we say that $A$ is a small object of $\mathcal C$ if, for all $\kappa$-directed preorders $\mathcal J$ and diagrams $D : \mathcal J \to \mathcal C$ such that $D$ has a colimit in $\mathcal C$, we have an isomorphism between $\mathrm{colim}_X\ \mathrm{Hom}_\mathcal{C}(A, D(X))$ and $\mathrm{Hom}_\mathcal{C}(A, \mathrm{colim}_X D(X))$. (It perhaps makes sense to demand that $\mathcal C$ has all such limits, I can't tell from the nlab page whether that's standard.)
Now, define a $\kappa$-semilattice to be a preorder equipped with least upper bounds for any $\kappa$-indexed set of objects. (Contrast with the definition of a $\kappa$-directed preorder, which is equipped with mere upper bounds for any $\kappa$-indexed set of objects.)
Question: Why does the definition of a small object quantify across $\kappa$-directed preorders, instead of $\kappa$-semilattices? Is it just because $\kappa$-directions are a bit more general? Is it because it makes some of the small-$\kappa$ edge-cases work out in some desired fashion? Is it a mere convenience?
In particular, my intuitions say that if we ignore some of the small-$\kappa$ edge-cases, then the two definitions should work out to basically the same thing, but I'm not sure if I'm failing to visualize a way in which something goes terribly wrong if you use the semilattice version and $\kappa$ is particularly large.
(Note that by "small-$\kappa$" I mean 0, 1, and 2, which we may or may not consider regular cardinals depending on our choice of definition.)
Answer: If $J$ is a directed preorder, let $\bar J$ be the free cocompletion of $J$ under finite joins. There is a canonical functor $J\to \bar J$ which is cofinal, since a cocone under a diagram $F:\bar J\to \mathcal C$ is canonically determined by its restriction to $J$. Meanwhile every functor $J\to \mathcal C$ extends canonically to $\bar J$, assuming $\mathcal C$ has finite coproducts. Thus, assuming $\mathcal C$ has finite coproducts, then it has directed colimits if and only if it has colimits of diagrams indexed by sup-semilattices, and we have also the analogous claim for functors out of $\mathcal C$ preserving such colimits. Thus in a $\mathcal C$ with finite coproducts, an object is $\aleph_0$-small if and only if its homs out commute with colimits indexed by sup-semilattices. The generalizations to uncountable cardinals hold as well.
However, it is not unusual that we want to consider directed colimits in a category $\mathcal C$ lacking finite coproducts-this is more or less the subject of finitely accessible categories. In this case it is not clear that we can extend a $J$-indexed diagram to $\bar J$ as we needed above. That's no problem for $\kappa=\aleph_0$-in fact, a category has and a functor preserved directed colimits if and only if it preserves colimits of chains, that is, functors indexed by ordinals. As totally ordered sets, chains certainly have finite coproducts. This result is 1.7 in Adamek and Rosicky's book on locally presentable categories.
However, it is not the case that general $\kappa$-directed colimits can be constructed from colimits of $\kappa$-filtered chains (which would be the kind of chains forming $\kappa$-semilattices in your sense.) So it seems conceivable that there may exist, say, a category (necessarily lacking $\kappa$-small coproducts) in which there is some object homs out of which commute with colimits over $\aleph_1$-semilattices but not over all $\aleph_1$-directed preorders. It is easy to imagine that whether such a category and object exist is an open question, but I don't know for sure. I also agree with Mark that the canonical diagram shouldn't be a $\kappa$-semilattice in general in an accessible category, although it is in a locally presentable category and in the main examples of non-presentable accessible categories that come to mind.
So in summary, nothing goes wrong for $\aleph_0$-small objects, but something might go wrong for larger $\kappa$; it seems at best not obvious whether this is the case. That, together with the fact that focusing on $\kappa$-semilattices doesn't give any immediate simplification to the theory, seems sufficient to justify sticking with $\kappa$-directed sets in general.
By the way, a $\kappa$-directed preorder should have upper bounds for subset of cardinality less than $\kappa$, so you probably want to define a $\kappa$-sup-semilattice analogously. For instance an $\aleph_0$-sup-semilattice is then just a sup-semilattice.
Answer: Let's first see why we would call such objects small.
Concrete example: let $\kappa = \omega$ (the countable cardinal) and work in the category $\mathbf{Set}$ of sets. Then a set $A$ is $\omega$-presentable ("$\omega$-compact" on the page you linked) precisely when $|A| < \omega$, i.e. precisely when $A$ is finite.
To see this, note that an isomorphism $\operatorname{colim}_X \operatorname{Hom}(A, D(X)) \cong \operatorname{Hom}(A, \operatorname{colim}_X D(X))$, for an $\omega$-directed diagram $D$, means precisely that any arrow $A \to \operatorname{colim}_X D(X)$ will factor through the diagram in an essentially unique way. That is, it factors as $A \xrightarrow{f_Y} D(Y) \to \operatorname{colim}_X D(X)$ where $Y$ is some object in our $\omega$-directed preorder. The "essentially unique" requirement means that if $f$ factors through both $f_Y: A \to D(Y)$ and $f_{Y'}: A \to D(Y')$, then there is $Y, Y' \leq Z$ in the preorder such that $D(Y \leq Z) f_Y = D(Y' \leq Z) f_{Y'}$.
Now suppose $A$ is finite and let $f: A \to \operatorname{colim}_X D(X)$ be a function. We have to show that it factors through the diagram. Since $A$ is finite, we can write $A = \{a_1, \ldots, a_n\}$. For each $1 \leq i \leq n$ there is $X_i$ such that $f(a_i) \in D(X_i)$. This is because a colimit in $\mathbf{Set}$ is just (a quotient of) a union. Since the diagram is $\omega$-directed, there must be some $Y$ that is the upper bound of $\{X_1, \ldots, X_n\}$. Hence $f$ factors through $D(Y)$.
Conversely, suppose $A$ is $\omega$-presentable. Let $\mathcal{P}_\text{fin}(A)$ be the set of finite subsets of $A$. This becomes an $\omega$-directed diagram when we consider the inclusions between those subsets. Since clearly $A = \operatorname{colim} \mathcal{P}_\text{fin}(A)$, we must have that the identity $Id_A$ factor through the diagram. But then it factor through a finite set, so $A$ must be finite.

So let's look at the proof strategy. In the forward direction ($A$ finite implies $A$ $\omega$-presentable) we had an arrow $f$ into some $\omega$-directed colimit. We were able to piece together the image of $A$ under $f$ already in the diagram itself, and that is precisely what we want. We want to say that $A$ contains so little information, that if we send that information into a colimit (think: "a union"), then all bits of information can already be pieced together inside the diagram of that colimit. This is the intuition why we do not require least upper bounds in the diagram.

These kinds of objects play a central role in locally presentable categories and the more general accessible categories (where indeed the existence of $\kappa$-directed colimits is assumed for some big enough $\kappa$). One important property there is that every object can be built as a $\kappa$-directed colimit of $\kappa$-presentable objects (much like we did with $A = \operatorname{colim} \mathcal{P}_\text{fin}(A)$ before). In general these diagrams will not be $\kappa$-semilattices.
Comment: @Nate Finally I should mention that in all this we do not really consider finite $\kappa$. For $\kappa = 2$  we would just be looking at any colimit indexed by any non-empty poset (or preorder), because any subset of size $\leq 1$ trivially has an upper bound. For $2 < k < \omega$ the notions of $k$-directed and $\omega$-directed are equivalent. For a finite set $\{a_1, \ldots, a_n\}$ in some 3-directed poset we can find an upper bound $b_1$ of $a_1$ and $a_2$, then an upper bound $b_2$ of $a_3$ and $b_1$, and continue this to obtain an upper bound of $\{a_1, \ldots, a_n\}$.
Comment: @Nate You're right, more is needed. The "every map factors through" condition says that colim Hom(A,D(X)) to Hom(A,colim D(X)) is surjective. To say it's injective, you also need to assert that if f: A to colim D(X) factors through f',f'':A to D(X'),D(X''), then f' and f'' are equalized when mapped to D(X''') for some X''' an upper bound of X' and X''. This condition is redundant if, as is common, all the maps in the values of D, as well as the legs of the colimiting cocone, are mono.
Comment: @Nate I did indeed forget to mention that the factorisation must be essentially unique, which is precisely what Kevin spelled out. I added that to my post. I mostly wanted to indicate why this is the right definition to work with. Kevin's answer makes a good point about two different cases when we could consider $\kappa$-semilattices. I also do not know any concrete counterexamples for the more general case.
Comment: Thanks @KevinCarlson also for pointing this out.
Comment: @Nate I know no examples of the plain surjectivity condition holding for arbitrary directed colimits, unless the bijectivity condition holds. It's good to have in mind that an $\aleph_0$-small object in the typical categories of abstract algebra is precisely a finitely presentable (group, ring, etc.) We can say that an object in such a category is finitely *generated* if and only if it satisfies the surjectivity condition for all filtered colimits of monomorphisms, but then again the injectivity is automatic, so might as well require bijectivity.
Comment: A 2-small object, in the standard definition, is sometimes called "tiny", or "small-projective", and this is a useful notion-for instance a presheaf category is precisely a cocomplete category with a strong generator consisting of tiny objects. So I don't know that I agree than $\emptyset$ "should" be 2-small. In any case, it's true that one usually exclusively considers small objects relative to an infinite regular cardinal.
Comment: @Nate You're right, I take that back about 2-small. Turns out I know no reason to consider 2-smallness in either the bijectivity or surjectivity forms. No, I don't claim the injectivity is automatic in any case for general directed diagrams, just that an object is "surjectivity-$\kappa$ small with respect to directed diagrams of monomorphisms" if and only if it's "$\kappa$-small with respect to directed diagrams of monomorphisms," which is sometimes called being $\kappa$-generated.
Comment: Thanks! I found this comment helpful, but I don't think it quite answers my question. The first part sounds to me like it's arguing for "it's a convenience" (ie, "the directed version most closely matches the style of the proofs we want"), whereas the last part ("in general these diagrams will not be $\kappa$-semilattices") sounds like it's arguing for "something goes wrong if you use semilattices in general". Do you know whether the definition is the same (modulo edge cases) but less convenient in the semilattice case? If not, can you point more precisely to what goes wrong? Thanks!
Comment: Also, I don't quite follow the argument that we have an isomorphism if every Hom(A, colim D) factors through Hom(A, D(X)) for some X. Perhaps I'm just being daft, but suppose we have an (a : colim_X Hom(A, D(X))), and we pull an (a' : Hom(A, D(X'))) out of the disjoint union, and turn it into a (b : Hom(A, colim D)) in the natural way. Then we run our factorizer to get an (a'' : Hom(A, D(X'')). How do we know that a' ~ a'' under the quotient? I think that's false in general, so we must be using some property of directed diagrams, but it's not clear to me which one. (Or is this omega-specific?)
Comment: @KevinCarlson thanks! Do you know off the top of your head how to repair the argument in the OP for general D (ie, when not everything is mono)? Alternatively, why don't we say $A$ is $\kappa$-small whenever colim Hom(A, D(X)) to Hom(A, colim D(X)) is surjective?
Comment: For instance, IIUC, if we allow finite regular cardinals, the empty set is not 2-small if we require isomorphism (let J be the diagram w/ only 2 objs), but it is 2-small if we require only surjection. This is an edge case, obv, but if we want to make arguments like the one in the OP w/out worrying too much about injectivity, and if it degrades nicer in the edge cases (∅ obviously "should" be 2-small), then I start to suspect that it's a more natural def'n. (Ofc, I don't know how much we rely on the injectivity of the map between homs in practice.)
Comment: Thanks! @Kevin, I don't quite understand what you mean by "then again the injectivity is automatic" -- is there something I'm missing about how satisfying the surjectivity condition for all filtered colimits of monomorphisms implies satisfying the injectivity condition for all filtered colimits in full generality?
Comment: Also, I thought that the tiny objects were the 0-small objects, not the 2-small objects (b/c their homs preserve all small colimits, including the empty diagram, and the empty diagram is not 2-filtered). Am I wrong?


Tree shakable icon component

Question: I am creating a custom design system on top of ChakraUI and bootstrap icons.
Bootstrap icons contains 1000+ svg icons.
I created an abstract Icon component to have abstraction over the icon name, that seems IMO more convenient.
However, I am not sure this module will be tree-shaked, and I can't figure out how to change the implementation to make it tree-shakable.
Icon.tsx
import React from 'react'
import * as bootstrapIcons from '@emotion-icons/bootstrap'

// Union of all icon names: 'Alarm' | 'Circle' | 'Square' ...
type IconNames = keyof typeof bootstrapIcons

export const Icon: FC<{name: IconNames}> = ({name}) => {
  const Icon = bootstrapIcons[name]

  return (

      <Icon style={{...}} />

  )
}

App.tsx
import React from 'react'
import { Icon } from './Icon'

const App = () => {
  return

    <Icon name="Alarm" />

}

Answer: Astrix imports cannot be tree shaken.
Generally when it comes to Icons you can have a Sprite Sheet or Tree Shaking but not both.
To make this particular library tree shake out icons you'll have to change your imports and usage to look like this (haven't tested but should work).
import { Alarm } from '@emotion-icons/bootstrap/Alarm';

const Use = () => <Alarm/>

There's definitely a caveat here where it would be possible to build a build-time plugin that changes...
<Icon name="Alarm"/>
 // to.
import { Alarm } from '@emotion-icons/bootstrap/Alarm';
<Alarm/>

and removes the import.
The reason why astrix imports can't be tree shaken is because javascript is a very dynamic language and static analysis of which keys are used is sometimes very difficult.
Consider the following code
import * as bootstrapIcons from '@emotion-icons/bootstrap'

bootstrapIcons["mralA".reverse()] // which icons should be tree shaken?
const Icons = new Proxy(bootstrapIcons) // which icons should be included? using proxy traps.
const SubSet = PullSubset(bootstrapIcons) // which icons should be included? no matter what the implementation of PullSubset is it will be impossible to preform static analysis on it to determine which icons have been used.

Comment: You example will work, but then I will lose the abstraction on top of icons. This abstraction allow me to only apply specific brand colors to icons..

An idea, would be to do something like this:
`` - However this approach is not convenient, because I will not have Icon props constraint with typescript, and I need to import specific icons each time I need to use Icon
Comment: You'll need to find another way to achieve this abstraction because again static analysis cannot tree shake this import pattern. One solution could be to import explicitly each Icon you're using into Icon.tsx an every time you need a new Icon add a new import statement to Icon.tsx
Comment: I see your point.

What if I write the following:
`import { Alarm } from '@emotion-icons/bootstrap'`
`import { Icon } from '../Icon'`

`const App = () => {
  return
}`
- Sorry for indent..
Comment: The behavior here is outside the scope of a single comment, but almost always again this wont tree shake, yes its not using astrix however commonjs dictates that the second you import a file all the exports that live in that file will end up in your bundle. There are some caveats to this but they are unlikely to apply here. https://webpack.js.org/guides/tree-shaking/ with the phrase "Ensure no compilers transform your ES2015 module syntax into CommonJS modules"

Tree shakable icon component


The intuition behind slant asymptotes

Question: I'm asking this question to get a better understanding of oblique asymptotes.
As regards vertical asymptotes, I know that they represent the numbers that make a function undefined.  An example of this is a $0$ in the denominator, or a negative argument to a square root since that would return a complex number.
For horizontal asymptotes, I know that if the degree of the numerator is greater than the degree of the denominator of a rational function, there are no horizontal asymptotes because as x tends to infinity, the result of the function keeps getting larger and larger.  Also, if the degree of the denominator is greater than the degree of the numerator, there is a horizontal asymptote at $y = 0$ because as $x$ gets larger and larger, the value of the denominator greatly exceeds the value of the denominator and thus the value gets closer and closer to $0$.  And finally, if the degrees are equal, the horizontal asymptote will be $y = \frac{n}{d}$ where $n$ are the leading coefficients on the numerator and denominator respectively.
But for slant asymptotes, my book just says that they will exist only when the degree of the numerator is exactly one more than that of the denominator (and that you need to divide the polynomials to find the equation of the line of the slant asymptote).
My question is, why is it that slant asymptotes only occur when the degree of the numerator is exactly one more than that of the denominator?
Comment: "oblique asymptotes" is the more traditional terminology. :)
Comment: I used both because I wasn't sure which one is most widely used.
Answer: Just to elaborate on Michael Hardy's answer a little bit...
Suppose we have a rational function written like $f(x)=\frac{p(x)}{q(x)}$. Performing the long division $p(x)\div q(x)$ gives you a different way of writing the same function,  $$f(x)=a(x)+\frac{r(x)}{q(x)},$$ as a polynomial plus a rational function whose numerator's degree is smaller than its denominator's degree. (To be more specific, $a(x)$ has degree equal to the degree of the original numerator $p(x)$ minus the degree of the denominator $q(x)$. The degree of $r(x)$ is smaller than that of $q(x)$ because $r(x)$ is the remainder of the long division.)
As you already understand, $\frac{r(x)}{q(x)}$ tends to zero as $x$ tends to infinity, because the degree of the numerator is smaller than the degree of its denominator. That means that as $x\rightarrow\infty$, the function $f(x)$ tends towards the polynomial $a(x)$.
If $p(x)$ has degree exactly one more than that of $q(x)$, then $a(x)$ has degree one: it's a line. We call this line a slant or oblique asymptote of $f(x)$. If the degree of $p(x)$ is more than one higher than that of $q(x)$, then $a(x)$ is a quadratic, or a cubic, or whatever, but it's not a line. So $f(x)$ doesn't have a slant asymptote in this direction. (We still might say something like $f(x)$ asymptotically approaches a(x).)
Hopefully this explains why asymptotes only occur when the degree of the numerator is exactly one more than that of the denominator. It also might give you a hint for how you can find slant asymptotes of functions that aren't rational: if you can rewrite your function as a line plus something that goes to zero, you've got yourself an asymptote!
Answer: It is not true that a rational function always has a vertical asymptote when there's a $0$ in the denominator.  When there are $0$s in both the numerator and denominator, then it often---in fact usually---happens that there is no vertical asymptote, but rather the function approaches a finite limit.  When there is a $0$ in the denominator and something else in the numerator, then there's a vertical asymptote.
As for slant asymptotes, do long division.  For example suppose you have
$$
f(x) = \frac{18x^5 + 2x^4-91x^3 + \cdots}{3x^4 + 11x^3 -10x^2 + \cdots}
$$
Then do long division:
$$
\begin{array}{ccccccccccccccccccc}
& & 6x & {} + \tfrac{-64}{3} \\  \\
3x^4 + 11x^3 -10x^2 + \cdots & {\Big)} & 18x^5 & {}+ 2x^4 & {} - 91x^3 & {} +\; \cdots \\
& & 18x^5 & {} + 66x^4 & {} - 60 x^3 & {} +\; \cdots \\  \\  \\
& & & {} - 64x^4 & {} -31x^3 & {} + \;\cdots \\
& & & {} -64x^4 & {} -\tfrac{704}{3}x^3 & {} + \;\cdots  \\  \\  \\
& & & & \tfrac{611}{3} x^3 & {} +\;\cdots
\end{array}
$$
Then
$$
f(x) = \underbrace{6x - \frac{64}{3}} + \underbrace{\frac{\frac{611}{3}x^3+\cdots}{3x^4 + 11x^3 -10x^2 + \cdots}}
$$
The graph of
$$
y = 6x - \frac{64}{3}
$$
is a slanted line.
The remaining expression
$$
\frac{\frac{611}{3}x^3+\cdots}{3x^4 + 11x^3 -10x^2 + \cdots}
$$
approaches $0$ as $x$ approaches $\pm\infty$.
Answer: If you try performing the division of the two polynomials, you'll note that you can always separate your rational function into a "linear" portion and a "rational" portion, where the numerator's degree is less than the denominator. This is akin to decomposing improper fractions as mixed numbers (integer + proper fraction). As $x$ increases in magnitude, the rational portion goes to zero (why?), and in that range, the linear part of your function dominates. Hence the oblique asymptotes you observe.
Answer: For $\frac{f}{g}$, with degree of $f = m$ > degree of $g=n$, dividing will give you a polynomial of degree $m - n$, and a remainder.
If $m-n =1$, then you have a linear polynomial (plus remainder).

The intuition behind slant asymptotes