text:
Q: Control the dashed border stroke length and distance between strokes Is it possible to control the length and distance between dashed border strokes in CSS?
This example below displays differently between browsers:

div {
  border: dashed 4px #000;
  padding: 20px;
  display: inline-block;
}

I have a dashed border!

Big differences: IE 11 / Firefox / Chrome

Are there any methods that can provide greater control of the dashed borders appearance?

A: There's a cool tool made by @kovart called the dashed border generator.
It uses an svg as a background image to allow setting the stroke dash array you desire, and is pretty convenient.
You would then simply use it as the background property on your element in place of the border:
div {
  background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' stroke='black' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
  padding: 20px;
  display: inline-block;
}

A: .outline {
    outline: 48px dashed #d5fb62;
    outline-offset: -4px;
    overflow:hidden;
}

if overflow hidden not problem else outline 4 instead 48.

A: Short one: No, it's not. You will have to work with images instead.

A: Css render is browser specific and I don't know any fine tuning on it, you should work with images as recommended by Ham.
Reference: http://www.w3.org/TR/CSS2/box.html#border-style-properties

A: The native dashed border property value does not offer control over the dashes themselves... so bring on the border-image property!
Brew your own border with border-image
Compatibility: It offers great browser support (IE 11 and all modern browsers). A normal border can be set as a fallback for older browsers.
Let's create these
These borders will display exactly the same cross-browser!

Step 1 - Create a suitable image
This example is 15 pixels wide by 15 pixels high and the gaps are currently 5px wide.  It is a .png with transparency.
This is what it looks like in photoshop when zoomed in:

This is what it looks like to scale:

Controlling gap and stroke length
To create wider / shorter gaps or strokes, widen / shorten the gaps or strokes in the image.
Here is an image with wider 10px gaps:
 correctly scaled =
Step 2 - Create the CSS — this example requires 4 basic steps

*

*Define the border-image-source:
border-image-source:url("http://i.stack.imgur.com/wLdVc.png");

*Optional - Define the border-image-width:
border-image-width: 1;

The default value is 1. It can also be set with a pixel value, percentage value, or as another multiple (1x, 2x, 3x etc). This overrides any border-width set.

*Define the border-image-slice:
In this example, the thickness of the images top, right, bottom and left borders is 2px, and there is no gap outside of them, so our slice value is 2:
border-image-slice: 2;

The slices look like this, 2 pixels from the top, right, bottom and left:

*Define the border-image-repeat:
In this example, we want the pattern to repeat itself evenly around our div. So we choose:
border-image-repeat: round;

Writing shorthand
The properties above can be set individually, or in shorthand using border-image:
border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;

Complete example
Note the border: dashed 4px #000 fallback. Non-supporting browsers will receive this border.

.bordered {
  display: inline-block;
  padding: 20px;
  /* Fallback dashed border
     - the 4px width here is overwritten with the border-image-width (if set)
     - the border-image-width can be omitted below if it is the same as the 4px here
  */
  border: dashed 4px #000;

  /* Individual border image properties */
  border-image-source: url("http://i.stack.imgur.com/wLdVc.png");
  border-image-slice: 2;
  border-image-repeat: round;

  /* or use the shorthand border-image */
  border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;
}

/*The border image of this one creates wider gaps*/
.largeGaps {
  border-image-source: url("http://i.stack.imgur.com/LKclP.png");
  margin: 0 20px;
}

This is bordered!

This is bordered and has larger gaps!

A: Update
Thanks to kovart for this great tool try it
https://kovart.github.io/dashed-border-generator/

my answer was:
I just recently had the same problem.
I have made this work around, hope it will help someone.
HTML + tailwind

        Content goes here...

CSS
.dashed-border::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: calc(100% + 4px);
  transform: translateY(-50%);
  background-image: linear-gradient(to right, #333 50%, transparent 50%);
  background-size: 16px;
  z-index: 0;
  border-radius: 0.5rem;
}
.dashed-border::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: calc(100% + 4px);
  transform: translateX(-50%);
  background-image: linear-gradient(to bottom, #333 50%, transparent 50%);
  background-size: 4px 16px;
  z-index: 1;
  border-radius: 0.5rem;
}

A: In addition to the border-image property, there are a few other ways to create a dashed border with control over the length of the stroke and the distance between them. They are described below:
Method 1: Using SVG
We can create the dashed border by using a path or a polygon element and setting the stroke-dasharray property. The property takes two parameters where one defines the size of the dash and the other determines the space between them.
Pros:

*

*SVGs by nature are scalable graphics and can adapt to any container dimensions.

*Can work very well even if there is a border-radius involved. We would just have replace the path with a circle like in this answer (or) convert the path into a circle.

*Browser support for SVG is pretty good and fallback can be provided using VML for IE8-.

Cons:

*

*When the dimensions of the container do not change proportionately, the paths tend to scale resulting in a change in size of the dash and the space between them (try hovering on the first box in the snippet). This can be controlled by adding vector-effect='non-scaling-stroke' (as in the second box) but the browser support for this property is nil in IE.

.dashed-vector {
  position: relative;
  height: 100px;
  width: 300px;
}
svg {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
  width: 100%;
}
path{
  fill: none;
  stroke: blue;
  stroke-width: 5;
  stroke-dasharray: 10, 10;
}
span {
  position: absolute;
  top: 0px;
  left: 0px;
  padding: 10px;
}

/* just for demo */

div{
  margin-bottom: 10px;
  transition: all 1s;
}
div:hover{
  height: 100px;
  width: 400px;
}

  <svg viewBox='0 0 300 100' preserveAspectRatio='none'>
    <path d='M0,0 300,0 300,100 0,100z' />
  </svg>
  Some content

  <svg viewBox='0 0 300 100' preserveAspectRatio='none'>
    <path d='M0,0 300,0 300,100 0,100z' vector-effect='non-scaling-stroke'/>
  </svg>
  Some content

Method 2: Using Gradients
We can use multiple linear-gradient background images and position them appropriately to create a dashed border effect. This can also be done with a repeating-linear-gradient but there is not much improvement because of using a repeating gradient as we need each gradient to repeat in only one direction.

.dashed-gradient{
  height: 100px;
  width: 200px;
  padding: 10px;
  background-image: linear-gradient(to right, blue 50%, transparent 50%), linear-gradient(to right, blue 50%, transparent 50%), linear-gradient(to bottom, blue 50%, transparent 50%), linear-gradient(to bottom, blue 50%, transparent 50%);
  background-position: left top, left bottom, left top, right top;
  background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
  background-size: 20px 3px, 20px 3px, 3px 20px, 3px 20px;
}

.dashed-repeating-gradient {
  height: 100px;
  width: 200px;
  padding: 10px;
  background-image: repeating-linear-gradient(to right, blue 0%, blue 50%, transparent 50%, transparent 100%), repeating-linear-gradient(to right, blue 0%, blue 50%, transparent 50%, transparent 100%), repeating-linear-gradient(to bottom, blue 0%, blue 50%, transparent 50%, transparent 100%), repeating-linear-gradient(to bottom, blue 0%, blue 50%, transparent 50%, transparent 100%);
  background-position: left top, left bottom, left top, right top;
  background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
  background-size: 20px 3px, 20px 3px, 3px 20px, 3px 20px;
}

/* just for demo */

div {
  margin: 10px;
  transition: all 1s;
}
div:hover {
  height: 150px;
  width: 300px;
}

Some content

Some content

Pros:

*

*Scalable and can adapt even if the container's dimensions are dynamic.

*Does not make use of any extra pseudo-elements which means they can be kept aside for any other potential usage.

Cons:

*

*Browser support for linear gradients is comparatively lower and this is a no-go if you want to support IE 9-. Even libraries like CSS3 PIE do not support creation of gradient patterns in IE8-.

*Cannot be used when border-radius is involved because backgrounds don't curve based on border-radius. They get clipped instead.

Method 3: Box Shadows
We can create a small bar (in the shape of the dash) using pseudo-elements and then create multiple box-shadow versions of it to create a border like in the below snippet.
If the dash is a square shape then a single pseudo-element would be enough but if it is a rectangle, we would need one pseudo-element for the top + bottom borders and another for left + right borders. This is because the height and width for the dash on the top border will be different from that on the left.
Pros:

*

*The dimensions of the dash is controllable by changing the dimensions of the pseudo-element. The spacing is controllable by modifying the space between each shadow.

*A very unique effect can be produced by adding a different color for each box shadow.

Cons:

*

*Since we have to manually set the dimensions of the dash and the spacing, this approach is no good when the dimensions of the parent box is dynamic.

*IE8 and lower do not support box shadow. However, this can be overcome by using libraries like CSS3 PIE.

*Can be used with border-radius but positioning them would be very tricky with having to find points on a circle (and possibly even transform).

.dashed-box-shadow{
  position: relative;
  height: 120px;
  width: 120px;
  padding: 10px;
}
.dashed-box-shadow:before{ /* for border top and bottom */
  position: absolute;
  content: '';
  top: 0px;
  left: 0px;
  height: 3px; /* height of the border top and bottom */
  width: 10px; /* width of the border top and bottom */
  background: blue; /* border color */
  box-shadow: 20px 0px 0px blue, 40px 0px 0px blue, 60px 0px 0px blue, 80px 0px 0px blue, 100px 0px 0px blue, /* top border */
    0px 110px 0px blue, 20px 110px 0px blue, 40px 110px 0px blue, 60px 110px 0px blue, 80px 110px 0px blue, 100px 110px 0px blue; /* bottom border */
}
.dashed-box-shadow:after{ /* for border left and right */
  position: absolute;
  content: '';
  top: 0px;
  left: 0px;
  height: 10px; /* height of the border left and right */
  width: 3px; /* width of the border left and right */
  background: blue; /* border color */
  box-shadow: 0px 20px 0px blue, 0px 40px 0px blue, 0px 60px 0px blue, 0px 80px 0px blue, 0px 100px 0px blue, /* left border */
    110px 0px 0px blue, 110px 20px 0px blue, 110px 40px 0px blue, 110px 60px 0px blue, 110px 80px 0px blue, 110px 100px 0px blue; /* right border */
}

Some content

A: Stroke length depends on stroke width. You can increase length by increasing width and hide part of border by inner element.
EDIT: added pointer-events: none; thanks to benJ.
.thin {
    background: #F4FFF3;
    border: 2px dashed #3FA535;
    position: relative;
}

.thin:after {
    content: '';
    position: absolute;
    left: -1px;
    top: -1px;
    right: -1px;
    bottom: -1px;
    border: 1px solid #F4FFF3;
    pointer-events: none;
}

https://jsfiddle.net/ksf9zoLh/

A: I just recently had the same problem.
I managed to solve it with two absolutely positioned divs carrying the border (one for horizontal and one for vertical), and then transforming them.
The outer box just needs to be relatively positioned.

 {{Box content goes here}}

Note: i used tachyons in this example, but i guess the classes are kind of self-explanatory.

A: I think I've just found the definitive solution to this problem with the use of clip-path property. Basically all there is to add a dashed border then mask the excess.
The clip-path property also supports rounded corners so you can match it up with the border-radius and have custom dashed borders and rounded corners!

.demo {
  display: inline-flex;
  width: 200px;
  height: 100px;
  position: relative;
  clip-path: inset(0 round 30px 0 30px 0);
}

.demo::before {
  content: '';
  position: absolute;
  left: -7px;
  top: -7px;
  right: -7px;
  bottom: -7px;
  border: 8px dashed rgba(0, 0, 255, 0.3);
  border-radius: 37px 0 37px 0;
  box-sizing: border-box;
}

You could do this directly on the div itself of course without using the ::after pseudo element. But this would mean you have to clip into the div and it would end up smaller than it's initial size.

A: This will make an orange and gray border using the class="myclass" on the div.
.myclass {
    outline:dashed darkorange  12px;
    border:solid slategray  14px;
    outline-offset:-14px;
}


text:
Q: Is there a way to detect that a select tag will act as a drop down or a popup window? The <select> tag on all desktop browser and most mobile browsers when clicked on will have a drop down of all the options. On most mobile browser instead of a drop down it will have a popup window with all the options.
Is there a way to detect if the select tag in the browser will drop down or have a popup window?

A: No I don't think that's possibile, but you can detect what kind of web browser the client uses and decide based on this criteria.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I check the checkboxes? I'm using logic to check my checkboxes. The functionality allows you to check the parent checkbox and all the children are checked. You can also check or uncheck an individual checkbox. My problem is that after implementing this logic, the checkboxes don't work. When I click on them, they are not marked.
export default function UserList() {
  const [page, setPage] = useState(1);

  const { data, isLoading, isFetching, error } = useUsers(page);

  const [isCheckAll, setIsCheckAll] = useState(false);
  const [isCheck, setIsCheck] = useState([]);

  const handleSelectAll = (e) => {
    setIsCheckAll(!isCheckAll);
    setIsCheck(data.users.map((li) => li.id));
    if (isCheckAll) {
      setIsCheck([]);
    }
  };

  const handleClick = (e) => {
    const { id, checked } = e.target;
    setIsCheck([...isCheck, id]);
    if (!checked) {
      setIsCheck(isCheck.filter((item) => item !== id));
    }
  };

  console.log({isCheck});

  async function handlePrefetchUser(userId: string) {
    await queryClient.prefetchQuery(
      ['user', userId],
      async () => {
        const response = await api.get(`users/${userId}`);

        return response.data;
      },
      {
        staleTime: 1000 * 60 * 10,
      }
    );
  }

  return (
    <Box>

      <Flex my="6" maxWidth={1480} mx="auto" w="94%">
        <Sidebar />

        <Box flex="1" borderRadius={8} bg="gray.800" p="8" overflow="hidden">
          <Flex mb="8" justify="space-between" align="center">
            <Heading size="lg" fontWeight="normal">
              Alunos
              {!isLoading && isFetching && (
                <Spinner size="sm" color="gray.500" ml="4" />
              )}
            </Heading>

            <HStack spacing={4}>
              <NextLink href="/users/create" passHref>
                <Button as="a" size="sm" fontSize="sm" colorScheme="orange">
                  <Icon as={RiAddLine} fontSize="20" />
                </Button>
              </NextLink>

              <NotificationModal />

              <Button
                as="a"
                size="sm"
                fontSize="sm"
                colorScheme="blue"
                cursor="pointer"
              >
                <Icon as={CgImport} fontSize="20" />
              </Button>
            </HStack>
          </Flex>

          {isLoading ? (
            <Flex justify="center" align="center">
              <Spinner />
            </Flex>
          ) : error ? (
            <Flex justify="center">
              <Text>Falha ao obter dados dos usuários.</Text>
            </Flex>
          ) : (
            <>

                      <Checkbox
                        colorScheme="orange"
                        onClick={handleSelectAll}
                        isChecked={isCheckAll}
                      />

                    Alunos
                    Ações
                    {/* 	 */}

                  {data.users.map((user, index) => (

                        <Checkbox
                          key={user.id}
                          colorScheme="orange"
                          onClick={handleClick}
                          isChecked={isCheck.includes(user)}
                        />

A: I guess problem is that you are trying to get id form event object, and event does not have it.
const { id, checked } = e.target;

Second thing is that you are storing ids im state but then you are trying to check if that state includes user object.
isChecked={isCheck.includes(user)}

You should pass that id to handleChange function.
<Checkbox
  key={user.id}
  colorScheme="orange"
  onClick={(e) => handleClick(e, user.id)}
  isChecked={isCheck.includes(user.id)}
/>

Then you van change handleChange to something like this
const handleClick = (e, id) => {
  const { checked } = e.target;

  if (checked) {
    setIsCheck((prev) => [...prev, id])
  } else {
    setIsCheck((prev) => prev.filter((item) => item !== id));
  }
};


text:
Q: Confused about $O_X$ ideals and closed subschemes I am trying to understand a passage in Mumford's Red Book (Section II. 5, page 146 in the old version). Let $X$ be a scheme,  $Q$ is a subsheaf of $O_X$ such that for all $U$, $Q(U)$ is an ideal in $O_X(U)$, (I assume he means open $U$ here) and we call such an object an $O_X$- ideal.
The part I am trying to understand is the following: We claim that $Q$ determines the closed subschemes up to canonical isomorphisms. For first of all, $Y = \{ x \in X : Q_x \neq O_X \}$, the sequence
$$
0 \to Q_x \to O_{x,X} \to O_{x, Y} \to 0
$$
is exact, and secondly $O_Y$ extended by zero is canonically isomorphic to the cokernel of $Q \to O_X$. Thus a closed subscheme is really just an $O_X$-ideal.
I am struggling to see how this explains $Q$ determines closed subschemes.
I have been trying to understand parts of this so I have asked couple related question, but it seems that I am getting more confused...  I would greatly appreciate clarification about this. Thank you very much!

A: Let $X$ be a scheme, and let $\mathcal{I}$ be a quasi-coherent sheaf of ideals on $X$. Let $Z$ be the support of the quotient $\mathcal{O}_X / \mathcal{I}$, that is
$$ Z=\{x \in X \ | \ (\mathcal{O}_X/\mathcal{I})_x \neq 0 \}.$$
The set $(Z,\mathcal{O}_X/\mathcal{I})$ is a sub-ringed space of $X$. Let $U\subset X$ be a open subset such that $(U,\mathcal{O}_X|_U)\simeq (Spec A,\widetilde{A})$ is affine. Hence $\mathcal{I}|_U$ has the form $\widetilde{I}$, that is it is associated to an ideal $I$ of $A$. Then $(Z\cap U,\mathcal{O}_X/\mathcal{I}|_U) \simeq (Spec (A/I), \widetilde{A/I})$.
Note that the inclusion map $i : (Z,\mathcal{O}_X/\mathcal{I}) \to (X,\mathcal{O}_X)$ is a closed immersion, as the map $\mathcal{O}_X \to i_*(\mathcal{O}_X/\mathcal{I})$ is surjective (on a point $p\in Spec(A)$ it is given by $A_p \to (A/I)_p$).


text:
Q: jquery vertical align when page loads with image's display set to none? I am using JQuery Cycle to produce a slideshow of images.  The plugin uses display:none to hide the images that aren't being shown yet, with the first image automatically having display:block on page load.  I have this bit of JQuery code to vertically center my images inside the slideshow container, which works....for the very first image.
(....inside a (document.ready(function()......)

$('.variable').load(function() {
var imgHt= $('.variable').height();
var half= imgHt/2;
$('.variable').css("top", "50%");
$('.variable').css("margin-top", "-" + half + "px");

});
I tried this code without the .load(function() as well, and it's not working correctly.  The browser will display top:50% and margin-top:0px or it will display height:correct half height of image, and not display top:50%.  Weird.
I'm assuming here that JQuery does not see image dimensions when its display is set to none.  Is there a workaround to this?
P.S. These images are generated from a database, so no, I do not know the image's height beforehand.  Which is why I'm using JQuery in the first place.

A: The browser won't calculate the size of any element with display: none. The usual workaround is to show the element and use margins or absolute positioning to move the element (or more likely its container) somewhere thousands of pixels off the left side of the screen. Then the boxes will be calculated, you can do your manual positioning, then hide and remove the margin.
However, since you're using a plugin, this may not work very well. In this case, I think you're better off modifying the plugin to display the images as you want them. It might be possible with just CSS, but that depends on the box elements used by the plugin and the styles it applies (via CSS or JS) on the boxes and the image itself.


text:
Q: Messed up my grub install. Can I fix it? I had a dual-boot EFI-based Windows/Linux system, with grub2 pointing to an Ubuntu 18.04 /root partition in /dev/sda6.
I tried installing Ubuntu 20.04 in /dev/sda5, which was a spare partition. This install went okay, but hung on the grub-install phase. After that, grub no longer works. I just get a grub> prompt. I can escape out to the boot manager and boot Windows, but grub is hosed.
So, I booted the live Ubuntu 18.04 flash drive and attempted to rerun grub-install for the original 18.04 system in /dev/sda6 by mounting /dev/sda6 on /mnt and running
sudo grub-install --boot-directory=/mnt/boot /dev/sda
That resulted in this message

Installing for i386-pc platform.
grub-install: warning: this GPT partition label contains no BIOS Boot Partition; embedding won't be possible.
grub-install: warning: Embedding is not possible.  GRUB can only be installed in this setup by using blocklists.  However, blocklists are UNRELIABLE and their use is discouraged..
grub-install: error: will not proceed with blocklists.

Is there any way to fix this. It looks like something has messed up my partition table (or something), but the partitions themselves are okay. I can mount them and examine them under the live USB. I specifically asked UBU 20.04 to install grub in the partition device (/dev/sda5) rather than on the disk device (/dev/sda). Was that wrong?
I suppose, as long as /home is preserved (it's in /dev/sda8), I'm okay with something that wipes out my old 18.04 /root...

A: I fixed it by reinstalling ubuntu 20.04 and letting it put a new grub loader into /dev/sda.  The 20.04 grub installer detected my 18.04 system, so now I can boot either one.
Interestingly (?), the second install also appeared to hang for a long time during the update-grub phase (same as the first install did).  But when I went to power the box down to get out of it, I didn't hold down the power button.  The single press of the power button triggered a clean shutdown of the installer - rather than a forced one.  Maybe that difference is why grub now works - I don't know.


text:
Q: Using PCA to obtain the eigenfaces I have 10 face images and each image have 56x46 pixel.
I am trying to obtain the eigenface using PCA, but there is some problems.
Here is my matlab code
function a01_v2()
load facedata.mat;

S=[];
 mean=zeros(56,46,'double');
for i=1:1:10
    S=[S,facedata{1,i}];
    mean=mean+double(facedata{1,i});
end
mean=mean/10;

%figure,imshow(S);
S=reshape(S,10,2576);

S=double(S);

figure,imshow(uint8(mean));
c=cov(S);
[v,d]=eigs(c,9);
figure,imshow(uint8(reshape((v(:,1)),56,46)));

end


text:
Q: Can't create excel file, in accordance with template Point of problem:
1. I have a list of objects and i need to export them in excel file. Each Object must be on one separate sheet and sheet is made of template.
 My algorithm:
   1. Created excel template file in project
   2. For each object of list, copy template sheet in excel file and fill content.
For this purpose, i created ExcelWorker worker class and pass list of object to AutomateExcelImpl method. The problem is that app. throws. an exception on
oXL.Workbooks[1].Worksheets.Copy(sheet);
 I googled it but almost broke my head digging this issue.
Please, help.
using JiraExample.Entities.Projects;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace JiraExample.Helpers
{
    class ExcelWorker
    {
        public static void AutomateExcel()
        {
            //AutomateExcelImpl();

            // Clean up the unmanaged Excel COM resources by forcing a garbage
            // collection as soon as the calling function is off the stack (at
            // which point these objects are no longer rooted).

            GC.Collect();
            GC.WaitForPendingFinalizers();
            // GC needs to be called twice in order to get the Finalizers called
            // - the first time in, it simply makes a list of what is to be
            // finalized, the second time in, it actually is finalizing. Only
            // then will the object do its automatic ReleaseComObject.
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        public static void AutomateExcelImpl(List<ProjectDescription> projects)
        {
            object missing = Type.Missing;

            try
            {
                // Create an instance of Microsoft Excel and make it invisible.

                Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
                oXL.Visible = false;

                // Create a new Workbook.

                Microsoft.Office.Interop.Excel.Workbook oWB = oXL.Workbooks.Add(1);

                foreach (ProjectDescription project in projects)
                {
                    createContent(project, oXL);
                }

                // Save the workbook as a xlsx file and close it.

                Console.WriteLine("Save and close the workbook");

                string fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample2.xlsx";
                oWB.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook,
                    missing, missing, missing, missing,
                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                    missing, missing, missing, missing, missing);
                oWB.Close(missing, missing, missing);

                // Quit the Excel application.

                Console.WriteLine("Quit the Excel application");

                // Excel will stick around after Quit if it is not under user
                // control and there are outstanding references. When Excel is
                // started or attached programmatically and
                // Application.Visible = false, Application.UserControl is false.
                // The UserControl property can be explicitly set to True which
                // should force the application to terminate when Quit is called,
                // regardless of outstanding references.
                oXL.UserControl = true;

                oXL.Quit();
                AutomateExcel();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution2.AutomateExcel throws the error: {0}",
                    ex.Message);
            }
        }
        private static void createSheet(Microsoft.Office.Interop.Excel.Application oXL, ProjectDescription project)
        {
            Worksheet sheet = getTemplate();
            oXL.Workbooks[1].Worksheets.Copy(sheet);
        }

        private static Worksheet getTemplate()
        {
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.Visible = false;
            string path = (Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Template.xlsx");
            Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(path,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            // The key line:
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

            return worksheet;
        }

        private static void createContent(ProjectDescription project,Microsoft.Office.Interop.Excel.Application oXL)
        {
            createSheet(oXL, project);
        }
    }
}


text:
Q: How to construct Spring's dependency graph without refreshing the context? Is there any way to construct Spring's bean dependency graph without doing refresh() to a context? By using the BeanDefinitions gathered by the Spring Readers or so
I want to build the dependency graph for an application with the minimum waste of memory/time.
Thanks!

A: Java IDEs have support to draw spring dependency graph either innately or via plug-ins.

*

*In eclipse, with Spring Source Tool Suite installed, you could view dependency graph by selecting spring configuration (xml) files in Spring Explorer view and right-clicking and selecting "Open dependency graph".

*In IntelliJ IDEA, you could view it by right clicking the configuration files and selecting Diagrams -> Show Diagram.


text: Q: Are there negative performance effects when collecting performance data in IIS? I'm using Windows Server 2019 with IIS version 10.0.17763.1, where I count the incoming GET requests to my website using the Performance monitor. As sample interval I have chosen 15 seconds. Now I want to know whether there are any negative performance effects on my website if I run this monitoring over days, weeks or even months.


text:
Q: What does a pair of vertical pipes mean within a function, as related to computational complexity? I'm reading Some connections between nonuniform and uniform complexity classes and trying to understand what the vertical pipes mean within h(|x|).

Let S be a subset of {0,1}* . Let h : N -> {0,1}* where N is the set of
natural numbers. Define S : h = { w x : x is an element of S and w = h (|x|) } .
Next let S be any collection of subsets of {0,1}* and let F be any
collection of functions from N to N.

A: I think the correct way to interpret this is that h is a function that maps a boolean string x by its length to another boolean string w in {0,1}*.

A: In the context of strings - and $x$ is a string because it's an element of $\{0, 1\}^\star$ - the notation $|x|$ means "the length of $x$."


text:
Q: Read directory contents using Javascript locally I have a standard folder structure for a web app.

*

*css

*js

*img

*asetts

*lib

index.html
Inside my assets folder I have a bunch of plain text files and I would like to first be able to list the filenames using Javascript, so I can store the URI's in the model, and read from them later on the in the application.  I want all of this happening client side.

A: (Client-side) JavaScript does not have access to the file system like that.
This is not possible without some kind of browser plugin.

A: You can read the textfiles in the local folder.
function read()
{
    var xHR = new XMLHttpRequest();
    //replace textfile_url with the relative url of your text file
    xHR.open("GET", "textfile_url", true);
    xHR.onreadystatechange = function ()
    {
        if(xHR.readyState === 4)
        {
            //all your text is in the next line
            var text = xHR.responseText;

        }
    }

    xHR.send();
}


text:
Q: SwiftUI: Create own TextField and change the content programmatically I created my own TextField with the following tutorial:https://www.youtube.com/watch?v=9kfbJVqqTKc&t=17s. Every things works fine but I added a feature to refresh the content of the TextField. The problem is that when I set the content programmatically, the function textViewDidChange() is not called in the coordinator. This causes the whole TextField to collapse, which means that the placeholder no longer disappears when I type something and it doesn't automatically get bigger. When you get to the point where a new line should be created, the text is simply deleted for whatever reason.
Is there a way to fix this problem?
Code:
import SwiftUI

struct CustomTextField: View {
var title: String
@Binding var text: String
var isFocused: Binding<Bool>?

@State var height: CGFloat = 20

var onCommit: (() -> ())?

init(_ title: String, text: Binding <String>, isFocused: Binding<Bool>? = nil, onCommit: (() -> ())? = nil){
    self.title = title
    self._text = text
    self.isFocused = isFocused
    self.onCommit = onCommit
}
var body: some View {
    ZStack(alignment: .topLeading){
        Text(title)
            .foregroundColor(Color.secondary.opacity(text.isEmpty ? 0.5 : 0))
            .animation(nil)
        CustomTextFieldRep(text: $text, isFocused: isFocused, height: $height, onCommit: onCommit)
            .frame(height: height)
    }
}
}

struct CustomTextFieldRep: UIViewRepresentable{

@Binding var text: String
var isFocused: Binding<Bool>?
@Binding var height: CGFloat
var onCommit: (() -> ())?

func makeUIView(context: Context) -> UITextView {
    let uiView = UITextView()

    uiView.font = UIFont.preferredFont(forTextStyle: .body)
    uiView.backgroundColor = .clear
    uiView.text = text
    uiView.delegate = context.coordinator
    uiView.textContainerInset = .zero
    uiView.textContainer.lineFragmentPadding = 0

    return uiView
}

func updateUIView(_ uiView: UITextView, context: Context) {
    if uiView.text != text{
        uiView.text = text

        let size = uiView.sizeThatFits(CGSize(width: uiView.frame.width, height: CGFloat.greatestFiniteMagnitude))
        height = size.height
    }

    if let isFocused = isFocused?.wrappedValue{
        if isFocused && !uiView.isFirstResponder{
            uiView.becomeFirstResponder()
        }else if !isFocused && uiView.isFirstResponder{
            uiView.resignFirstResponder()
        }
    }
}

func makeCoordinator() -> Coordinator {
    Coordinator(rep: self)
}

class Coordinator: NSObject, UITextViewDelegate{

    var rep: CustomTextFieldRep

    internal init(rep: CustomTextFieldRep){
        self.rep = rep
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if let onCommit = rep.onCommit, text == "\n"{
            onCommit()
            return false
        }

        return true
    }

    func textViewDidChange(_ textView: UITextView) {
        rep.text = textView.text

        let size = textView.sizeThatFits(CGSize(width: textView.frame.width, height: CGFloat.greatestFiniteMagnitude))
        rep.height = size.height
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        rep.isFocused?.wrappedValue = true
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        rep.isFocused?.wrappedValue = false
    }
}
}

I think the problem can be fixed if I call the textViewDidChange() function in the coordinator itself. However, I don't know how to do that.
Thanks in advance
EDIT:
How I implemented my custom TextField:
struct View: View{
@ObservedObject private var addUebungVM = AddÜbungViewModel()
enum Focus{
    case name, beschreibung
}

@State var focus: Focus? = .name

var nameFocusBinding: Binding<Bool>{
    $focus.isEqual(to: .name)
}

var beschreibungFocusBinding: Binding<Bool>{
    $focus.isEqual(to: .beschreibung)
}

var body: some View{
    CustomTextField(placeholderName, text: $addUebungVM.übungName, isFocused: nameFocusBinding, onCommit: saveNewÜbung)
      .alignmentNewExercise()
      .styleTextField()
}

private func saveNewÜbung(){
    if !addUebungVM.übungName.isEmpty{
        DispatchQueue.main.async{
            addUebungVM.übungName = " "
            addUebungVM.übungBeschreibung = " "
            placeholderName = NSLocalizedString("nächsteÜbungString", comment: "")
            focus = .name
        }
    }
}
}

EDIT 2:
Thinks I found out:
When the view appears the first time:
-everything works great
After the first reset...

*

*When I call the second reset over the keyboard-button "return" it works when the text isn't longer than a normal line, but when I call
the reset over a "normal" button it doesn't work at all

*the placeholder is no longer displayed

*when the text I type gets longer than a normal line and the text box should gets bigger, the text gets lost

A: I am using your code and refreshing the content through the state variable as below:
struct ContentView: View {
    @State var text = ""
    @State var isFocused = true
    var body: some View {
        CustomTextField("Initial text", text: $text, isFocused: $isFocused) {
            print("done")
            let t = DispatchTime.now() + 2.0
            DispatchQueue.main.asyncAfter(deadline: t) {
                text = "Changed text"
            }
        }
    }
}

is this the solution to your problem?


text:
Q: PyInstaller и вечные мучения. Почему вылезает ошибка? Скомпилил .py в .exe через pyinstaller
пишет local variable referenced before assigment
хотя в .py и .py.exe всё работает
Что делать, как быть?
код
import requests as rq
from tkinter import *
from tkinter import messagebox
import tkinter.ttk as ttk
import os
import time
import zipfile
import wget
import shutil

def show_message():

    loginreq = rq.post("https://www.kooft.site/login/", data={'n':name.get(),'pwd':pwd.get()})
    if 'Неверный пароль' in loginreq.text:
        messagebox.showerror(" f ", "Не удалось войти в аккаунт")
    else:
        file = open('gamedo.txt', 'w')
        f = file.write(name.get() + '/' + pwd.get())
        messagebox.showinfo(" Успешный вход ", "Перезапустите GameDo")

root = Tk()
root.title("gd")
root.geometry("300x250")

file = open('gamedo.txt', 'r')
f = file.read()
if not f:
    name = StringVar()
    pwd = StringVar()

    name_label = Label(text="Введите логин и пароль от аккаунта")
    name_label.grid(row=1, column=4, sticky="w")

    name_entry = Entry(textvariable=name)
    name_entry.place(relx=.5, rely=.1, anchor="c")

    pwd_entry = Entry(textvariable=pwd)
    pwd_entry.place(relx=.5, rely=.2, anchor="c")

    message_button = Button(text="Click Me", command=show_message)
    message_button.place(relx=.5, rely=.5, anchor="c")
else:
    n = f.split('/')[0]
    pwd = f.split('/')[1]
    messagebox.showinfo("logged in", f[0])
    qreq = rq.post('https://www.kooft.site/checkgames/', data={'user':f.split('/')[0]})

    frame = Frame(root)
    frame.grid()
    combobox = ttk.Combobox(frame,values = qreq.text.split(',') ,height=3)
    combobox.set(qreq.text.split(',')[0])
    combobox.grid(column=0,row=0)
    def play():
        try:

            game = qreq.text.split(',')[combobox.current()].replace("'", "")
            if qreq.text.split(',')[combobox.current()] in qreq.text.split(',') and os.path.exists(os.getcwd()+game ):

                 print(game)
                 vnew = rq.post('https://www.kooft.site/gamev', data={'game':game}).text
                 vnow = open(game+'/version.txt', 'r').read()
            if vnew == vnow:
                pts = os.getcwd()+os.getcwd()[2]+game+os.getcwd()[2]+"Windows"+os.getcwd()[2]+game+".exe"
                os.startfile(pts)
            else:
                shutil.rmtree(os.getcwd()+os.getcwd()[2]+game, ignore_errors=True)
                dl = wget.download("http://f0299148.xsph.ru/"+game+".zip", os.getcwd() )
                print(dl)
        except FileNotFoundError:
            print('download it')
            wget.download("http://f0299148.xsph.ru/"+game+".zip", os.getcwd() )
            print('dload')
            os.makedirs(os.getcwd()+os.getcwd()[2]+game)
            ex = zipfile.ZipFile(os.getcwd()+os.getcwd()[2]+game+".zip", 'r')
            ex.extractall(os.getcwd()+os.getcwd()[2]+game)
            ex.close()

    message_button = Button(text="Play", command=play)
    message_button.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

A: *

*

if qreq.text.split(',')[combobox.current()] in qreq.text.split(',') and
    os.path.exists(os.getcwd()+game ):
    print(game)
    vnew = rq.post('https://www.kooft.site/gamev', data={'game':game}).text
    vnow = open(game+'/version.txt', 'r').read()
if vnew == vnow: # vnew и vnow объявлены в другом блоке кода и недоступны здесь
    #...

*

try:
    game = qreq.text.split(',')[combobox.current()].replace("'", "")
except FileNotFoundError:
    print('download it')
                                  # то же самое с переменной game
    wget.download("http://f0299148.xsph.ru/"+game+".zip", os.getcwd())


text:
Q: MPVolumeView change size of Airplay icon I have an MPVolumeView on one of my views, which comes up with an Airplay icon when there are other output sources available. That's all fine, but the icon is tiny, no matter how big I set the frame for MPVolumeView it doesn't get any bigger.
Anyone know how to increase the size of the airplay icon?

A: I did this to just show the icon and increase its size:
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:CGRectMake(255, 12, 30, 25)] autorelease];
volumeView.showsVolumeSlider = NO;
volumeView.showsRouteButton = YES;
volumeView.transform = CGAffineTransformMakeScale(1.5, 1.5); // increase size by 50%

A: At least for now, all you can do is crawling the subviews and manually set the size. It's probably not a good idea, as subview hierarchy is suspect to change, and even if you set a bigger frame for the icon, it won't get bigger (or if contentMode is set to stretch, you get a blurred icon)
You may even be able to manually replace the icon with a larger one that you provide in your app, but let me say this again, it's not a good idea.

A: Crawling the subviews and using constraints I've manage to replicate the behaviour of AVRoutePickerView, which resizes icon image according to its containing view.
Although it's needed to use a custom icon via setRouteButtonImage(second image). If not, it uses 2 ImageView that don't show the ion resized (first image).
Code and View Hierarchy attached next:
class ViewController: UIViewController {

    @IBOutlet weak var airplayView: MPVolumeView!

    override func viewDidLoad() {
        super.viewDidLoad()
        airplayView.showsRouteButton = true
        airplayView.showsVolumeSlider = false
        airplayView.setRouteButtonImage(UIImage(named: "airplay"), for: .normal)
        for view in airplayView.subviews {
            if let button = view as? UIButton {
                button.imageView?.contentMode = .scaleAspectFit
                button.translatesAutoresizingMaskIntoConstraints = false
                NSLayoutConstraint(item: button,
                                   attribute: NSLayoutConstraint.Attribute.bottom,
                                   relatedBy: NSLayoutConstraint.Relation.equal,
                                   toItem: airplayView,
                                   attribute: NSLayoutConstraint.Attribute.bottom,
                                   multiplier: 1,
                                   constant: 0).isActive = true
                NSLayoutConstraint(item: button,
                                   attribute: NSLayoutConstraint.Attribute.trailing,
                                   relatedBy: NSLayoutConstraint.Relation.equal,
                                   toItem: airplayView,
                                   attribute: NSLayoutConstraint.Attribute.trailing,
                                   multiplier: 1,
                                   constant: 0).isActive = true
                NSLayoutConstraint(item: button,
                                   attribute: NSLayoutConstraint.Attribute.top,
                                   relatedBy: NSLayoutConstraint.Relation.equal,
                                   toItem: airplayView,
                                   attribute: NSLayoutConstraint.Attribute.top,
                                   multiplier: 1,
                                   constant: 0).isActive = true
                NSLayoutConstraint(item: button,
                                   attribute: NSLayoutConstraint.Attribute.leading,
                                   relatedBy: NSLayoutConstraint.Relation.equal,
                                   toItem: airplayView,
                                   attribute: NSLayoutConstraint.Attribute.leading,
                                   multiplier: 1,
                                   constant: 0).isActive = true
            }
        }
    }
}


text:
Q: How to get the screen position of an active workbook? I would center a form in an ActiveWorkbook, how to get the screen/window position of the workbook?

A: C# example..
private void setFormPos(Form frm)
{
   int top = Application.Top + Application.PageSetup.TopMargin + Application.PageSetup.HeaderMargin + Application.Commandbars["Ribbon"].Height;
   int left = Application.Left + Application.PageSetup.LeftMargin;
   frm.Left = (left / 2);
   frm.Top = (top / 2);
}

A: Didn't find a good solution but found an acceptable one:
int top = Application.Top + Application.PageSetup.TopMargin + Application.PageSetup.HeaderMargin + Application.Commandbars["Ribbon"].Height;
int left = Application.Left + Application.PageSetup.LeftMargin;

Form popup = new Form{ Top = top, Left = left, StartPosition = FormStartPosition.Manual, Width=400, Height=300};
popup.Show();


text:
Q: ¿Cómo manejar metaCharacters en un input y que los cuente como uno solo en el maxlength? Tengo un <input> donde debo aceptar un máximo de 10 caracteres, es decir, tener un maxlength de 10 caracteres, pero dentro de este debo ingresar Meta Caracteres (especie de código por ejemplo [:heart:]) que mi página interpreta como un icono de corazón, por ejemplo. También puedo ingresar texto y demás.
El problema:
Cuando coloco un código (o Meta Caracteres), por ejemplo [:heart:] ya el <input> me cuenta 9 caracteres! y solo puedo escribir uno más y ya.
Mi pregunta:
¿Cómo puedo hacer para que este código (o Meta Caracteres) me lo cuente como uno solo y así poder ingresar 9 caracteres más?

A: Aquí te dejo un código para manejar meta caracteres y que el largo del String no exceda los indicados en la función, puedes manejar varios meta caracteres colocandolos en la matriz meta[], tales como: black (spades ♠), red (hearts ♥), blue (diamonds ♦) y green (clubs ♣).
.
Ejemplo:

function meta(event,maxlength) {
 var el  = event.target,

  // MetaCharacters: black (spades ♠), red (hearts ♥), blue (diamonds ♦)
  // and green (clubs ♣)
  meta = {0:{code:"[:spades:]"  , char:"♠"}, // Elementos++
          1:{code:"[:heart:]"   , char:"♥"},
          2:{code:"[:diamonds:]", char:"♦"},
          3:{code:"[:clubs:]"   , char:"♣"},
          length:4,       // Numero de Elementos
          maxlength:12},  // length del Elemento con máximo tamaño
  len = 0,
  warning = false,
  ss  = el.selectionStart,
  se  = el.selectionEnd,
  key = event.key;

 if(key.length != 1) {
  key = "";
  if(event.key == "Backspace") {
   ss = el.selectionStart - 1;
  } else if(event.key == "Delete") {
   se = se + 1;
  }
 }
 val = el.value.substr(0,ss) + key + el.value.substr(se);
 for (var x = meta.maxlength; x > 0; x--) {
  for (var y = meta.length-1; y >= 0; y--) {
   if (meta[y].code.length >= x) {
    tmp = val.split(meta[y].code.substr(0,x)).join(meta[y].char);
    if (x != meta[y].code.length && tmp != val)
     warning = true;
    val = tmp;
   };
  };
 };
 if (warning || val.length>maxlength) {
  el.classList.add("warning");
 } else {
  el.classList.remove("warning");
 }
 console.log(val);
 if (key && val.length>maxlength)
  event.preventDefault();
};
.warning {
 color:red;
}
<input onkeydown="meta(event,10)">

Espero esto te sirva, Saludos!! ;))...

A: Prueba esto. No diferencia entre mayúsculas y minúsculas. Se puede copiar y pegar:

// Javascript
function maxlength() {
    var txtIni=document.getElementById("input1").value;
    var txt=txtIni;
    while(txt.length
        - (txt.match(/\[:heart:\]/gi) || []).length
        - (txt.match(/\[:heart:/gi) || []).length
        - (txt.match(/\[:heart/gi) || []).length
        - (txt.match(/\[:hear/gi) || []).length
        - (txt.match(/\[:hea/gi) || []).length
        - (txt.match(/\[:he/gi) || []).length
        - (txt.match(/\[:h/gi) || []).length
        - (txt.match(/\[:/gi) || []).length
        - (txt.match(/\[:foo:\]/gi) || []).length
        - (txt.match(/\[:foo:/gi) || []).length
        - (txt.match(/\[:foo/gi) || []).length
        - (txt.match(/\[:fo/gi) || []).length
        - (txt.match(/\[:f/gi) || []).length>10){
        txt=txt.slice(0, -1);
    }
    if(txt!==txtIni)
        document.getElementById("input1").value=txt;
};
document.getElementById("input1").onkeyup = maxlength;
function recortar() {
    var txtIni=document.getElementById("input1").value;
    var txt=txtIni;
    while(txt.length
        - (txt.match(/\[:heart:\]/gi) || []).length*('[:heart:]'.length-1)
        - (txt.match(/\[:foo:\]/gi) || []).length*('[:foo:]'.length-1)>10){
        txt=txt.slice(0, -1);
    }
    if(txt!==txtIni)
        document.getElementById("input1").value=txt;
};
document.getElementById("input1").onblur = recortar;
// JQuery
$('#input2').on('keyup', function () {
    var txtIni=$(this).val();
    var txt=txtIni;
    while(txt.length
        - (txt.match(/\[:heart:\]/gi) || []).length
        - (txt.match(/\[:heart:/gi) || []).length
        - (txt.match(/\[:heart/gi) || []).length
        - (txt.match(/\[:hear/gi) || []).length
        - (txt.match(/\[:hea/gi) || []).length
        - (txt.match(/\[:he/gi) || []).length
        - (txt.match(/\[:h/gi) || []).length
        - (txt.match(/\[:/gi) || []).length
        - (txt.match(/\[:foo:\]/gi) || []).length
        - (txt.match(/\[:foo:/gi) || []).length
        - (txt.match(/\[:foo/gi) || []).length
        - (txt.match(/\[:fo/gi) || []).length
        - (txt.match(/\[:f/gi) || []).length>10){
        txt=txt.slice(0, -1);
    }
    if(txt!==txtIni)
        $(this).val(txt);
}).on('blur',function(){
    var txtIni=$(this).val();
    var txt=txtIni;
    while(txt.length
        - (txt.match(/\[:heart:\]/gi) || []).length*('[:heart:]'.length-1)
        - (txt.match(/\[:foo:\]/gi) || []).length*('[:foo:]'.length-1)>10){
        txt=txt.slice(0, -1);
    }
    if(txt!==txtIni)
        $(this).val(txt);
});
<script         src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<input id="input1" type="text" style="width: 500px;">
<input id="input2" type="text" style="width: 500px;">

Saludos.


text:
Q: Highcharts update grouped data point color Is there any way to update the color of a single point in a grouped data set?  I can't seem to find a way to reliably set the colors.
A fiddle can be found here demonstrating the issue.

A: Points are grouped during the rendering process of the chart so they cannot be specifically targeted via constructor options (because we don't know which points will be generated by Highcharts algorithms).
What is more, Higcharts doesn't allow performing update function on the grouped point.
As a workaround your can change the CSS of point's SVG element:
chart.series[0].groupedData[0].graphic.css({
    color: 'red'
});

Live demo: http://jsfiddle.net/BlackLabel/9ey2yq3u/
API reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#css


text:
Q: How to recover home folder? Cloned partition recovered other directories like /etc/ but not /home I have two linux partitions on my laptop (one ubuntu and one garuda). Ubuntu was giving me problems so I installed Garuda to check it out. The Garuda partition filled up so I used KDE partition manager to shrink the ubuntu partition so I could expand the Garuda.
Then, Ubuntu wouldn't mount and would not boot as it said the fs was wrong size. I ran fsck on the partition and hit yes to pretty much everything. This included force rewriting blocks it said it couldn't reach and removing inodes, etc. Probably a mistake in hindsight.
Now, I got a external hard drive and cloned the Ubuntu partition using "sudo dd if=/dev/nvme0n1p5 of=/dev/sda1 conv=noerror,sync". The external hard drive mounted without problem but it does not have /home/ folder, only folders such as /etc/.
I don't think there's many files I cant get back from a git repo, but it would be nice to have access to the /home folder so I can grab everything, remove the ubuntu partition, and resize garuda.
Thanks in advance!

A: I figured it out. I kind of followed https://unix.stackexchange.com/questions/129322/file-missing-after-fsck but
I copied the partition to an external drive using dd. Then mounted the external drive (which just worked even though I could not mount the original ubuntu partition). Then I went into the lost+found folder on the partition and used "find" to search for a file I know I had in my home folder and it found that file. I am not able to access all my documents etc.


text:
Q: MongoDB Charts – chart cumulative growth? Using MongoDB Charts, how can I chart cumulative growth? Using the _id value of a document which contains the information of when it was created, I'd like to chart the number of documents in my database over time. E.g., if in July 10 documents were created, and in August another 10 were created, then the chart should display 10 for July and 20 for August.
It's easy to bin document creation dates per months (see below example), but I'd like to turn this into a cumulative growth chart. MongoDB Charts can use Mongo aggregation pipelines, if that helps…

A: I've already answered similar question some time ago here however it would be good to walk you through entire solution.
Yes, you need an aggregation to reshape your data. To get started you need to convert your ObjectId values into Dates using $toDate operator. Using $dateToString will allow you to categorize these dates by day. Then you can $group them and count.
To calculate the "cummulative" part you need to get them all into single document (grouping by null), This will allow you to run $map on $range of numbers that will be representing array indexes (0,1,2 etc). For each index you take corresponding date to the output and $sum $slice -ed array of values.
The rest is easy as you just need to run $unwind to get single document per day and $replaceRoot to get rid of nested document in your final result.
[
    { $addFields: { "date": { $dateToString: { format: "%Y-%m-%d", date: { $toDate: "$_id" }} } }},
    { $group: { _id: "$date", count: { $sum: 1 } } },
    { $sort: { _id: 1 } },
    { $group: { _id: null, days: { $push: "$_id" }, counts: { $push: "$count" } } },
    { $project: {
        days: {
            $map: {
                input: { $range: [ 0, { $size: "$days" } ] },
                in: { _id: { $arrayElemAt: [ "$days", "$$this" ] }, cumGrowth: { $sum: { $slice: [ "$counts", 0, { $add: [ "$$this", 1 ] } ] } } }
                }
            }
        }
    },
    { $unwind: "$days" },
    { $replaceRoot: { newRoot: "$days" } },
    { $sort: { _id: 1 } },
]

Using Mongo Charts you just need to map output fields into X and Y axis


text:
Q: Vertically Centering one side of a Multiline equation I have a long PDE which I wish to write in the form F(phi)=0; however, it is too long to be written on a single line. As of now I have it written in my LaTex document simply using:
\begin{align*}
\phi_t + e^{-x}\phi_x - e^{-x}\phi + \Lambda e^{-x} \phi_z - 9 \mathcal{M} \mathcal{E} \phi^2\phi_z^2 + 6 \mathcal{M} \mathcal{E} \phi \phi_z^2 - 3 \mathcal{M} \mathcal{E} \phi^3 \phi_{zz} + 3 \mathcal{M} \mathcal{E} \phi^2 \phi_{zz} \\
 - \frac{1}{2} \mathcal{M} \mathcal{E} \phi_z^2 - \frac{1}{2} \mathcal{M} \mathcal{E} \phi \phi_{zz} + \mathcal{E} \epsilon^2 \phi_z \phi_{zzz} + \mathcal{E} \epsilon^2 \phi \phi_{zzzz} = 0
\end{align*}

which works fine enough showing:

However, ideally I would like for it to print something closer to

where the "=0" is centered between the two lines on the left hand side. Is this possible in LaTex?

A: You can use aligned for such formulars:
\documentclass{article}

\usepackage{amsmath}

\begin{document}

\[
  \begin{aligned}
\phi_t + e^{-x}\phi_x - e^{-x}\phi + \Lambda e^{-x} \phi_z - 9 \mathcal{M}
    \mathcal{E} \phi^2\phi_z^2 + 6 \mathcal{M} \mathcal{E} \phi \phi_z^2 - 3
    \mathcal{M} \mathcal{E} \phi^3 \phi_{zz} + 3 \mathcal{M} \mathcal{E}
    \phi^2 \phi_{zz} \\
 - \frac{1}{2} \mathcal{M} \mathcal{E} \phi_z^2 - \frac{1}{2} \mathcal{M}
    \mathcal{E} \phi \phi_{zz} + \mathcal{E} \epsilon^2 \phi_z \phi_{zzz} +
    \mathcal{E} \epsilon^2 \phi \phi_{zzzz}
  \end{aligned}
  \enskip = 0
\]
\end{document}

See, e.g., section 3.7 of the amsmath user's guide for more information about building blocks.


text:
Q: Only root can log in to Mariadb on Centos 7 I just installed Centos 7 and LAMP stack. However, I only can log in to Mariadb as root even though there is another user. I've been using MySQL for a couple of decades but I can't figure this out.
Basically everything seems to be all right and exactly the same user configuraiton worket fine with MySQL and previous centos 6.10.
This another user (ie. John) can't log in to mariadb from cli neither can he login from phpmyadmin locally or remotelly. Only the root user can access databases.
I've tried third user, with the same result.
All three have the following hosts with same privileges:
%, localhost, ::1 and "host.domain.fi". And yes, I have committed the "flush privileges" sql-command.
I've even tried super complex passwords with no help. Only response is "ERROR 1045 (28000): Access denied for user 'test'@'localhost' (using password: YES)".
Only difference in the creation of users is that root user was created with mysql_secure_installation and others with phpmyadmin.
Anyone, ideas? This obviously is quite a hazard for secure use of my mariadb.

A: I do not see in your question any reference to the GRANT command you used to create the user. Did you used it? If not, try entering with root and then execute the following
GRANT ALL ON your_db_name.* TO 'test'@'localhost';


text:
Q: Как избавиться от приставки #!/ в адресной строке шаблона Наткнулся на этот шаблон link text
и ни как не могу избавиться от "приставки" (#!/), которая автоматом добавляется в адресной строке после index.html . Я как бы нашел в каком файле происходитработа скрипта по "приклеиванию" (#!/) это файл switcher.js . Все мои попытки что то проделать с кодом в этом файле по изменению или удалению (#!/) приводят к неполному отбражению контента страницы сайта! Подскажите, как избавиться от этой приставки (#!/) в адресной строке сайта или же если не избавиться, то хотя бы заменить #!/ на /site/ ????
A: Вообще-то # - это якорь, очень часто используется на сайтах с динамической загрузкой страниц, т.к. его изменение не требует рефреша страницы. Вот и в Вашем случае js-движок использует document.location.hash для навигации на сайте. !/page_more или !/home - это так сказать адрес открытой страницы. При заходе на страницу js читает этот хэш и определяет какой контент показать. Всё что можно привести к более эстетичному виду, это убрать !/
A: Абсолютно согласен с @t0di. В этой статье, вы даже  сможете уловить суть этих манипуляций. Могу только добавить, что "избавиться от этой приставки (#!/)" можно несколькими путями:

*

*Убрать hash-навигацию, переписав часть скрипта, отвечающего за вывод информации из БД. Потратите уйму времени, прежде, чем получите нормальный результат.

*
Убрать вывод хэша в адресную строку. В этом случае, у вас строка изменяться вообще не будет, но перестанет работать "история", т.е кнопки "назад"(на предыдущую страницу)/"вперед"(на следующую страницу). Исправляется достаточно легко: найти строку/строки, где будет примерный код и закоментить её:
location.hash = someVar // someVar - или переменная, или какое-то стринговое значение
// !!!Не перепутать с
var someVar = location.hash // так получаете хэш

*
Вариант третий - это использовать HTML5 History API. Решение достойное, но т.к. вы, насколько я понимаю, далеки от программирования, то времени вы потратите на решение этой задачи - значительно больше, чем в варианте первом.
P.S. Думаю, что вам надо расслабиться )) И получать удовольствие от того, что сайт у вас работает без перезагрузок, а к этому сейчас многие стремяться.


text:
Q: Correlate calls across async boundaries? I need to correlate calls made across async methods for a monitoring tool (mostly timing information on a per high level request).
For example - for a web server request, I'd like to know how much time was spent in MethodA, MethodC and MethodH each, where some of these may by in a call hierarchy between themselves.
If there were no async methods involved (and assuming a single threaded app), a ThreadLocal<T> with a request life time would basically work, but given that an async call may get despatched by any thread this is not an option.
On the full framework I could have used HttpContext, but this isn't available in .NET core.
Outside of passing a context parameter down to each monitored method (whether manually or via AOP of some sort), what are the options?

A: This seems like AsyncLocal is the most appropriate solution. AsyncLocal is an abstraction over the ExecutionContext that was added for this sort of scenario. Updates to it effect child async calls across async boundaries and any parts of the parent resumed to from this method, but not any async calls that where started before the update and are still ongoing.
This is used in OpenTracing for this exact use case. You set the AsyncLocal on entering a Request Handler, and then clear it on exit:
class Example
{
    static AsyncLocal<string> requestId = new AsyncLocal<string>();

    static async Task Handler()
    {
        requestId.Value = GetRequestId();
        await DoWork();
        requestId.Value = null;
     }
}


text:
Q: Can we stop recommending the Dragon Book, please? People ask "how do I learn compilers" in some form or other every few weeks. Someone immediately replies "read the dragon book". This is very bad advice for a compiler newbie (see discussion)
If you find yourself in this position, please recommend "Engineering a Compiler" by Keith Cooper/Linda Torczon, or "Modern Compiler Implementation in X" (where X should probably be Java, maybe C), by Andrew Appel. These are excellent introductions to compiler for beginners.
Please also vote down answers where the answerer says only "read the Dragon Book", without a qualifying remark.

Discussion:
The Dragon Book is a very thorough book, with detailed discussion of theory (especially about parsing). However, this level of detail and theory does not make it a good introductory book. In contrast, the books above present very clearly how to build a compiler, avoiding theory where it is not useful. This makes them superior recommendations for beginners.
The Dragon Book is best suggested for intermediate compiler authors, though they are likely to know of it already.
Partial list of questions so answered

*

*How to create a compiler in vb.net

*Learning Resources on Parsers, Interpreters, and Compilers

*https://stackoverflow.com/questions/411682/introduction-to-static-analysis

*https://stackoverflow.com/questions/1156363/create-a-compiler-for-windows

*Compilers and beyond

*Suggestions for writing a programming language?

*Interesting compiler projects

*https://stackoverflow.com/questions/10216/what-are-the-best-resources-on-designing-a-new-language

*What is the good approach to build a new compiler?

*Bootstrapping a language

*What happens when I compile?

*Compiler design resources

*Need Help Understanding Compilers/HLL->Assembly

*Unable to understand compilers' main optimizations

*How do C/C++ compilers work?

*https://stackoverflow.com/questions/424796/are-there-any-compiler-lectures-available-via-video

*Learning how programming languages work

*https://stackoverflow.com/questions/1177652/taking-a-compilation-course-in-undergraduate-cs-studies-useful

A:
While the Dragon Book is certainly very thorough, it is not very clear, or easy to learn from. That was probably acceptable in 1986, or whenever you read it way back when, but there are actual good compiler books now, especially for beginners.

People can recommend what they want to recommend. If you don't like an answer, if you think it doesn't answer the question or offer what the asker needs - then downvote it. Simple.

A: I kinda get your point, it's like people recommending the Knuth books to someone wanting to get started with programming. Whilst iconic, the Knuth books are not the best place to kick things off for a beginner.
I'd probably recommend The Dragon Book as an option for the novice once he or she has acquired the basics from more up-to-date and accessible texts.

A: The problem here is answerers blindly referring users to "the dragon book" not having read it themselves.
The full solution to the problem is don't recommend books you haven't read just because you saw someone else recommend them 20 years ago. Let someone who actually knows the field and has read the books recommend something instead. This is a classic example of people jumping to get rep by just pasting in a standard answer that they actually know nothing about.
If you have read "the dragon book" and you like it, of course you should be free to recommend it if you want to, but if you haven't read it, just leave the question for someone else to answer.

A: David, Let's assume you've read all the books you are talking about. (I happen to have read none of them, so won't comment on the suitability of each).
Why don't you write a review of each, (as one article), compare and contrast and draw a conclusion as to which is better for certain types of readers.
Then on each question where you disagree with the recommendation of "the dragon book" post a summary of your conclusions that are relevant to the particular question, (a link to the full review if it's too long to fit nicely in the answer), and your recommendation of your preferred book. Users tend to like answers that have taken the time to explain in detail the pros and cons of both sides. Others will see your review, and perhaps if it is good and people agree they will also link to it. Perhaps others interested in the area will take time to read both books and draw their own conclusions, and up vote your answer.
Ultimately then you have worked towards promotion of the best outcome - that of full disclosure of available information along with community agreement on the most suitable answer.

A: This is completely bizarre that we're starting a backroom discussion to pre-determine what the correct answer should or should not be to a particular class of questions.
This is a (hopefully) ill-fated attempt at a cyber-version of the good ol' boys network.

A: People are free to suggest whatever they feel is the best, just as you are free to comment on how wrong they may be and you are even allowed to downvote them.
I don't see why you should be making a post on meta about this to try and change people's minds.
Make your own suggestions and if you don't agree with others, vote them down and maybe people will start to see your way. There is nothing wrong with what they are doing in making their suggestions for the book.

A: Up and down votes are your best friend in this situation. Vote and explain your reasoning. Your opinion is just one of many.
I saw this same kind of thing with an Operating Systems class in my undergrad degree. The book assigned by the professor was one of the more popular OS books. Very dry, to the point, and was not aimed at beginners. It was still a great book though and an excellent class choice. It was not an easy book for people to start with, but it was still a great resource.
That doesn't make it a bad recommendation in any way though. Lots of CS books tend to not be beginner friendly.  They are advanced topics and require a vast array of knowledge to comprehend and understand well.


text:
Q: Tricky conceptual question: ball sliding and rolling down incline We all are familiar with the classic ball rolling down the incline exercise in rotational dynamics. Here is quite a tricky conceptual problem:

You have an incline of fixed height, but the angle of inclination may vary.  Consider the total kinetic energy $K$ of the ball at the bottom of the incline. Describe the graph of $K$ vs. the angle of inclination $\theta$. We can assume for simplicity that the static and kinetic friction coefficient are the same.

Here are some conceptual observations. Now, for $\theta < \theta_s$ where $\theta_s$ is the minimum angle at which the ball slips, friction does not do any work on the ball (rolling friction), so $K=mgh$ (the graph is a straight line) But for $\theta > \theta_s$, the ball both slips and rolls, so some of the kinetic energy is lost to slipping. Thus we should the graph to decrease. As $\theta$ increases, the friction force decreases (it is proportional to $\cos(\theta)$, so we should expect the graph to increase after some point. For $\theta=90$, we are back to $K=mgh$. I also suspect that we have some quadratic-like behavior for $\theta_s<\theta<90$, but I don't know exactly how to quantify the behavior of the ball in this region as it is both slipping and rolling, which makes things somewhat complicated.
One might naively say that the energy lost due to slipping is $fd$ where $f$ is the friction force and $d$ is the distance along the incline which the ball travels. However I believe this is not the case, as the effective distance over which friction acts, call it $d_{eff}$ is less than $d$, and depends on the relationship between the angular velocity and the translational velocity of the ball.
Note really that this problem can be solved if one has a clear understanding of the mechanics for rolling and slipping scanrios, so it may be helpful to say a few things about this.

A: The dynamics of a ball rolling down an incline is interesting. Let's start by figuring out the forces that come into play for the non-slipping case (mass m, radius R, angle of ramp $\theta$):

If we consider the motion of the ball as a rotation about point $P$, then the torque is given by
$$\Gamma = mgR\sin\theta$$
and the moment of inertia about $P$ is the moment of inertia about $C$ plus $mR^2$ (from the parallel axes theorem). Since $I=\frac25 mR^2$ for a sphere, that means that the moment of inertia about P is
$$I_P = \frac75 mR^2$$
The angular acceleration, $\dot{\omega}$ is
$$\dot{\omega} = \frac{\Gamma}{I_P} \\
= \frac{mgR\sin\theta}{\frac75 mR^2}\\
= \frac57 \frac{g\sin\theta}{R}$$
We can now compute the response force $f_f$ along the surface, since the torque that appears about the center $C$ should give the same acceleration:
$$f_f\ R=I_C\ \dot\omega = \left(\frac25 mR^2\right)\left( \frac57 \frac{g\sin\theta}{R}\right)\\
f_f = \frac27 m g \sin \theta$$
Checking for consistency, the linear acceleration of the center of mass is given by the net force, so
$$\begin{align}
m a &= f_a - f_f \\
&= mg \sin \theta - \frac27 m g \sin \theta \\
&= \frac57 mg \sin\theta\\
a &= \frac57 g \sin \theta
\end{align}$$
Of course without slipping, we know that $\dot\omega R = a$, and indeed this expression for $a$ agrees with the earlier one for $\dot\omega$.
Now we add sliding motion. Clearly, the sphere will slide when $f_f > \mu f_n$, which means
$$\frac27 mg \sin \theta > \mu m g \cos \theta\\
\mu < \frac27 \tan \theta$$
Note that this is much lower than the usual condition for sliding when there is no rolling.
If the force of friction is less than the $f_f$ needed to maintain rolling contact, we know it is constant at
$$f_f = \mu m g \cos \theta$$
We can now compute the acceleration of the ball down the slope:
$$\begin{align}
a &= \frac{f_a - f_f}{m}\\
&= g \left(\sin \theta - \mu \cos \theta\right)
\end{align}$$
The distance $d$ from top to bottom, given a constant height $h$, is
$$d = \frac{h}{\sin \theta}$$
so the time taken is
$$\begin{align}
 t &= \sqrt{\frac{2d}{a}}\\
&=\sqrt{\frac{2h}{g \sin\theta (\sin\theta - \mu\cos\theta)}}
\end{align}$$
and at that point the velocity is
$$\begin{align}
v &= at\\
&=\sqrt{2ad}\\
&=\sqrt{\frac{2g \left(\sin \theta - \mu \cos \theta\right)h}{\sin\theta}}
\end{align}$$
And the kinetic energy is
$$\begin{align}E &= \frac12 m v^2 \\
&= m g h \frac{\left(\sin \theta - \mu \cos \theta\right)}{\sin\theta}\\
&= mgh(1-\mu\cot\theta)
\end{align}$$
The rolling kinetic energy is given by the rotational velocity of the ball. With a constant torque $\Gamma$ and time $t$, the energy is
$$\begin{align}
E &= \frac12 I\omega^2\\
&= \frac12 I \left(\frac{\Gamma t}{I}\right)^2\\
&= \frac{\Gamma^2 t^2}{2I}\\
&= \frac{f_f^2 R^2}{\frac45 m R^2} \frac{2h}{g \sin\theta (\sin\theta - \mu\cos\theta)}\\
&= \frac{\mu^2 m^2 g^2 \cos^2\theta R^2}{\frac45 m R^2} \frac{2h}{g \sin\theta (\sin\theta - \mu\cos\theta)}\\
&= \frac{5 \mu^2 m g h\cos^2\theta}{2 \sin\theta (\sin\theta - \mu\cos\theta)}
\end{align}$$
Plotting these for a couple of values of $\mu$, you get the following (note - this is updated - there was a factor 2 missing in my expression for $t$):

When the sphere starts slipping, you lose energy. As the ramp angle increases, the degree of slip becomes greater and so more energy is lost in heat. As the ramp becomes steeper still, the energy dissipated will become less, until there is none when the ramp is vertical.

A: Here is the approach:
Rolling and slipping simultaneously is not much different from rolling without slipping. All the equations are the same except you can't use $a=R\alpha$. Here is the method for solving the problem:

*

*Friction: $f=\mu mg\cos(\theta)$

*Torque to find angular acceleration: $\tau=I\alpha=fR$

*Linear acceleration: $ma=mg\sin(\theta)-f$

*Final linear speed: $v_{cm}^2=2ad$ where $d=H/\sin(\theta)$.

*Final angular speed: $w=\alpha t$ where $t$ is the time it takes to roll to the bottom. Note that we can't use $w^2=2\Delta\theta\alpha$ because we don't know $\Delta\theta$, because the ball is rolling AND slipping.

*Find the time $t$: $d=0.5at^2$.

*Total kinetic energy: simply use $K_{rot}=0.5Iw^2$ and $K_{tr}=0.5mv^2$.
The final formula is nasty but plugging into Wolfram Alpha we can visualize the graph.


text:
Q: Reorder customer details in WooCommerce email notifications I am trying to change the order of the customer details fields displayed in the Woocommerce mail sent to both customer and admin after purchase (table name: addresses).
I checked the file responsible of outputting the billing & shipping fields which is plugins/woocommerce/templates/email-customer-details.php but the customer details are outputted only through a foreach loop and the variable $fields is not even there.
<?php foreach ( $fields as $field ) : ?>

<?php echo wp_kses_post( $field['label'] ); ?>: <?php echo wp_kses_post( $field['value'] ); ?>

<?php endforeach; ?>

So, where to change the order of the fields? In particular, I'd like to display the state before the zipcode.

A: There is an available filter hook for that.
It's  included in WC_Emails customer_details() method, which is used to call the template email-customer-details.php on all related main email templates.
You can use it this way (where $fields is the array of fields that you want to sort):
add_filter( 'woocommerce_email_customer_details_fields', 'filter_email_customer_details_fields', 10, 3 );
function filter_email_customer_details_fields( $fields, $sent_to_admin, $order ) {
    // Do something

    return $fields;
}

For usage, see those related on StackOverFlow


text:
Q: ASP.NET Core 2.0 Identity I've found quite a few tutorials for ASP.NET Identity but they don't seem to relate to ASP.NET Core 2.0 Identity. I'm not sure if this is because the Identity component is a different version or not.
I want to change the table names, add additional properties and change the keys to integers.
I'm looking for some direction that specifically relates to ASP.NET Core 2.0 Identity, all the older information seems to relate to older versions.
For reference, I've been using this post so far, but it leaves me with loads of errors regarding integers in the controller class and suggests customization isn't really possible...

A:
add additional properties and change the keys to integers.

public class User : IdentityUser<int>
{
    public string MyCustomProperty { get; set; }
}

I'm not aware how you can change Identity's table names though.
Also, you don't need to use Identity at all
Also Identity system uses Entity Framework Core by default, if you need something else, some different ORM library or third party client to work with your data you need to adapt it for your needs.
See Custom storage providers for ASP.NET Core Identity
Here is reference on how to port Identity from 1.x to 2.0. So you can just take the tutorial you have found and port it according to this.


text:
Q: Как исключить наложение групп захвата в регулярном выражении? Имеется следующее регулярное выражение:
var regex = "^.*?"
          + "(?:(?=.*?message.+?(?<msg>[0-9]+)))?"
          + ".*?"
          + "(?:(?=.*?part.+?(?<part>[0-9]+)))?"
          + ".*?"
          + "(?:(?=.*?order.+?(?<order>[0-9]+)))?"
          + ".*?$";

И строки, которые обрабатываются этим выражением:
abc part is created (message 42)
abc (message 42) part.id=24
abc order.id=123, (message 42) part.id=321
[message 42] Part with id 34 added to Order 22
abc Order (id=3, part.id=56) is generated "message 42"
Can't create order, becasue part 4 not found
Order 5 cannot be created because a part is missing

То есть какое-то ключевое слово (в приведённом примере part, order и message), а затем число, которое ассоциируется/захватывается соответствующей группой. Важно то, что выражение позволяет захватывать группы вне зависимости от их положения в строке.
Проблема в том, что при отсутствии числа у первой группы число "захватывается" у следующей. В примере выше это происходит:

*

*в первой строке, где группы part и message захватывают одно и то-же число 42;

*в предпоследней, где группы order и part захватывают одно и то-же число 4;

Каким образом можно исключить наложение групп? Внедрить каким-то образом негативные/позитивные опережающие/ретроспективные проверки?

*

*Пример работы выражения на regex101

*Предыстория вопроса

A: Если вербализировать ту идею которую подал @Stanislav Volodarskiy то получится примерно такой код возвращающий в данном случае массив массивов где подмасив состоит из ключевого слова и значения:

const strings = [
"abc part is created (message 42)",
"abc (message 42) part.id=24",
"abc order.id=123, 5 (message 42) 5 part.id=321 5",
"[message 42] Part with id 34 added to Order 22",
"abc Order (id=3, part.id=56) is generated \"message 42\"",
"Can't create order, becasue part 4 not found",
"Order 5 cannot be created because a part is missing"]

for (const str of strings){
    const temp = []
    for (const spart of str.matchAll(/part|message|order|[0-9]+/gi)){
      temp.push(spart) //собираем только те части которые нам интересны
    }
    const merge = temp.join(' ').toLowerCase() // стандартизируем вывод
    console.log(
       Array.from(merge.matchAll(/(?<name>\w+)\s(?<val>\d+)/g))
         .map(e => (Object.values({...e.groups}))) // создаем подмасивы из пар
         .toString() // для компактного вывода [[k1, v1], [k2, v2], ...]
    )
}

Для компактности вывода в консоли сниппета пришлось пожертвовать квадратными скобками
[ [ 'message', '42' ] ]
[ [ 'message', '42' ], [ 'part', '24' ] ]
[ [ 'order', '123' ], [ 'message', '42' ], [ 'part', '321' ] ]
[ [ 'message', '42' ], [ 'part', '34' ], [ 'order', '22' ] ]
[ [ 'order', '3' ], [ 'part', '56' ], [ 'message', '42' ] ]
[ [ 'part', '4' ] ]
[ [ 'order', '5' ] ]

В третью строку я специально добавил три 5 чтобы посмотреть на корректность работы алгоритма
Вариант через регулярку (нужна донастройка)
Основная идея - использовать негативный просмотр ?!,
Указываем какие группы мы не ожидаем в этом месте (?!.*order.*)|(?!.*part.*)
Код:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        //final String regex = "^.*?(?:(?=.*?message.+?(?<msg>[0-9]+)))?.*?(?:(?=.*?part.+?(?<part>[0-9]+)))?.*?(?:(?=.*?order.+?(?<order>[0-9]+)))?.*?$";

        final String regex = "^.*?(?:(?=.*?message(?:(?!.*order.*)|(?!.*part.*)|(?:[.]id=|[ ]))(?<msg>[0-9]+)))?"
         + ".*?(?:(?=.*?part(?:(?!.*order.*)|(?!.*message.*)|(?:[.]id=|[ ]))(?<part>[0-9]+)))?"
         + ".*?(?:(?=.*?order(?:(?!.*part.*)|(?!.*message.*)|(?:[.]id=|[ ]))(?<order>[0-9]+)))?.*?$";

        final String string = "abc part is created (message 42)\n"
             + "abc (message 42) part.id=24\n"
             + "abc order.id=123, (message 42) part.id=321\n"
             + "[message 42] Part with id 34 added to Order 22\n"
             + "abc Order (id=3, part.id=56) is generated \"message 42\"\n"
             + "Can't create order, becasue part 4 not found\n"
             + "Order 5 cannot be created because a part is missing";

        final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            System.out.println("Group message" + ": " + matcher.group("msg"));
            System.out.println("Group part" + ": " + matcher.group("part"));
            System.out.println("Group order" + ": " + matcher.group("order"));
        }
    }
}

Вывод:
Full match: abc part is created (message 42)
Group message: 42
Group part: null
Group order: null

Full match: abc (message 42) part.id=24
Group message: 42
Group part: 24
Group order: null

Full match: abc order.id=123, (message 42) part.id=321
Group message: 42
Group part: 321
Group order: 123

Full match: [message 42] Part with id 34 added to Order 22
Group message: 42
Group part: null // нужно доработать регулярку для with id
Group order: 22

Full match: abc Order (id=3, part.id=56) is generated "message 42"
Group message: 42
Group part: 56
Group order: null // нужно доработать регулярку для (id=3

Full match: Can't create order, becasue part 4 not found
Group message: null
Group part: 4
Group order: null

Full match: Order 5 cannot be created because a part is missing
Group message: null
Group part: null
Group order: 5

Пример доработки регулярки для конкретных случаев:

*

*для Part with id будет | with id |

*для Order (id=3 будет | \\(id=|  экранируем скобку

Вся регулярка:
     final String regex = "^.*?(?:(?=.*?message(?:(?!.*order.*)|(?!.*part.*)|(?:[.]id=| with id | \\(id=|[ ]))(?<msg>[0-9]+)))?"
 + ".*?(?:(?=.*?part(?:(?!.*order.*)|(?!.*message.*)|(?:[.]id=| with id | \\(id=|[ ]))(?<part>[0-9]+)))?"
 + ".*?(?:(?=.*?order(?:(?!.*part.*)|(?!.*message.*)|(?:[.]id=| with id | \\(id=|[ ]))(?<order>[0-9]+)))?.*?$";


text:
Q: Which process is getting exited and why is close(0) call followed after exit(0) if (log_daemon) {
    pid_t pid;
    log_init();

    pid = fork();
    if (pid < 0) {
        log_error("error starting daemon: %m");
        exit(-1);
    } else if (pid)
        exit(0);

    close(0);
    open("/dev/null", O_RDWR);
    dup2(0, 1);
    dup2(0, 2);

    setsid();

    if (chdir("/") < 0) {
        log_error("failed to set working dir to /: %m");
        exit(-1);
    }
}

I have above c program, and couldnt figure out what does the exit(0); do in this case, which process does it exit? and what does the close(0); is followed for? Will the close(0); even execute?
Is this code just to test whether a child process can be created?
UPDATE:
ok, I got it from this question Start a process in the background in Linux with C.
Basically, close(0); does is closes current standard input for child process and opens /dev/null as input device. This way child process will behave as a deamon and will not read anything from terminal or standard input.

A: The fork returns the process id in the parent process, and 0 in the child process.  The main calling process is exiting becausepid == 0 so if (pid) is true in the parent, and false in the child.  The child then proceeds to close(0), etc.


text:
Q: Variance and asymptotic normality of $\frac{1}{n-1}\sum_{i=1}^{n-1}(x_{i+1}-x_i)^2$, where $X \sim \mathcal{N}(0,1)$ Consider a length $n$ vector $\mathbf{x}$ containing $n$ i.i.d. observations $\{x_i\}_{i=1}^n$ of a standard normal random variable $X$. Let $\mathbf{z}$ be a length $n-1$ vector whose entries are $z_i = x_{i+1}-x_i$. I have a statistic $s(\mathbf{z}) = \frac{1}{n-1}\sum_{i=1}^{n-1}(z_i)^2$ that is meant to measure how close to sorted a given permutation of random samples is, and I want to know its properties under the null hypothesis where the order is random, for the purpose of calculating a $p$-value.
I have two questions:

*

*Is $s(\mathbf{z})$ asymptotically normal?

*What is the variance of $s(\mathbf{z})$  ?

Both of these questions would be easy if the entries of $\mathbf{z}$ were i.i.d., but I have been getting stuck with the fact that they are dependent. For instance, the value of $x_{i+1}-x_i$ depends on the value of $x_{j+1}-x_j$ since $i \neq j$.
For 1., the answer seems to be "yes" based on simulations, but I'm having trouble proving this.
For 2., I thought of estimating the variance by calculating the sample variance of the squared pairwise Euclidean distances of the entries of $\mathbf{x}$, which would work if each $z_i$ were a random sample drawn from $\{x_i - x_j\}_{i,j \in \{1,\ldots,n\}}$, but this is not the case due to the dependence mentioned above. I have found empirically from simulations that dividing this pairwise distance-based estimate by 2 gives the correct result within simulation error, but this might be a lucky coincidence.

A: TLDR; $s(z)$ is asymptotically normal, and its variance is $\frac {12} {n-1}$ according to CLT for Markov chains. It can be shown that the distribution is a special case of generalized $\chi^2$ distribution.
Markov Chain approach, asymptotics and variance
The sequence $z_i$ is Markov chain because once you know $z_i$ the value of $z_{i+1}$ doesn't depend on $z_k$ where $k<i$. Therefore, Markov chain CLT is applicable. Here's how we apply it.
The sum, or any linear combination of normal r.v.s, is a r.v. itself. Knowing that $z_i\sim\mathcal N(0,2)$ or $z_i\sim\sqrt 2\space \mathcal N(0,1)$, we know that $z_i^2\sim 2\space\chi^2_1$, see the definition of $\chi^2$ distribution. Thus, $\sigma_z^2=\operatorname{var}[z_i^2]=2^2\times 2=8$.
Markov chain CLT states:
$$\sqrt{n-1}(s(z)-\mu)\sim\mathcal N(0,\sigma^2),$$
where $\mu=E[z_i^2]$ and $\sigma^2  = \sigma_z^2 + 2\sum_{k=1}^\infty \operatorname{cov}( z_{1}^2, z_{1+k}^2)=8+2\times 2=12$.
Hence $\operatorname{var}[s(z)]=\frac{12}{n-1}$
Here's the proof by simulation (Python):
import numpy as np
n = 51
s = np.mean(np.diff(np.random.randn(10000,n))**2,axis=1)
vars = np.var(s)
print(vars)
print(12/(n-1))

Output:
0.23526746023519335
0.24

Note, that if $z_i^2$ weren't correlated then $s(z)$ would have been from scaled $\chi^2$ distribution with variance $\frac 8 {n-1}$. However, due to  overlapping terms $x_i$ in $z_i$ and $z_{i+1}$ we had to apply modified CLT to obtain the asymptotic distribution of $s(z)$.
Acknowledgements:
My initial answer, which I updated a few times already, did not account for correlation, which was pointed out by @Sextus Empiricus. Also, I used this answer for $\operatorname{cov}( z_{1}^2, z_{1+k}^2)$, where the correlation $\rho=\operatorname{corr}[z_i,z_{i+1}]=-1/2$ and we know that correlation disappears between $z_i$ and $z_j$ when $|i-j|>1$.
The distribution
Let's start with independent row vector of randoms $X'=(x_1,\dots,x_n)$. We get the row vector of differences $Z'$ aby pplying Toeplitz matrix $B'$ as follows $Z'=X'B'$, where
$$B' = \begin{bmatrix} {-1} & 0&\dots & 0 &0\\
 1 & -1 & \dots&0 & 0  \\
 0 & {1}& \dots & 0& 0\\
 \vdots & \vdots & \vdots & \vdots & \vdots \\
 0& 0 & \dots & 1 & -1 \\
 0& 0 & \dots & 0 & {1}
\end{bmatrix}$$
Your quantity then is a quadratic form
$$s(z)=\frac 1 {n-1} X'B'BX$$
where $B'B$ has a form of a tridiagonal Toeplitz matrix:

Let's apply eigen decomposition $B'B=P'\Lambda P$ then we have:
$$s(z)=\frac 1 {n-1} X'P'\Lambda PX=\frac 1 {n-1} Y'\Lambda Y$$
where $Y=PX\sim\mathcal N(0,I_{n-1})$, i.e. each $Y_i$ (principal component) is an independent normal.
Hence, $$s(z)=\frac 1 {n-1} \sum_{i=1}^{n-1}\lambda_i Y_i^2$$
where $Y_i^2\sim\chi^2_1$ and $\lambda_i$ are eigenvalues. The eigenvalues of Toeplitz tridiagonal matrices are known to form a sine wave and easy to find, see "The Eigenproblem of a Tridiagonal P-Toeplitz Matrix" by Gover .
So the distribution can be seen as a linear combination of $\chi^2$ variables or a generalized $\chi^2$ distribution.
Miscellaneous
We can define a row vector $V'=(x_1,z_1,\dots,z_{n-1})$, then it can be obtained by applying a matrix $D'$ to the original observations $V'=X'D'$, the matrix $B'$ above is the subset of columns of $D'$:

The matrix $D'D$ looks like this:

We can get the matrix $U'$ that recovers the original vector from $V$ as follows: $X'=V'U'$, and $U'=D'^{-1}$.
The matrix $U'$ is upper unit triangular, meaning $u_{ij}=1_{i\ge j}$:

Matrix $A=U'U$, which appears in the quadratic form, has a very interesting form: $a_{ij} = n+1-min(i,j)$, e.g. $n=5$:

A: Small pedantic note: Below I changed the coefficient into $1/\sqrt{n-1}$ otherwise the limiting distribution will be a degenerate distribution (zero variance). In that case one would also need to subtract the mean of the $z_i^2$. That means, only a scaled and shifted sum like $\sum_{i=1}^{n-1} \frac{(x_{i+1}-x_i)^2-1}{\sqrt{n-1}}$ will approach a normal distribution.
Distribution of $s(\mathbf{z})$ as a linear sum of chi-squared variables
The sum $s(\mathbf{z}) = \frac{1}{\sqrt{n-1}}\sum_{i=1}^{n-1}(z_i)^2$ is similarly distributed as the sum $s(\mathbf{y}) = \frac{1}{\sqrt{n-1}}\sum_{i=1}^{n-1}(y_i)^2$ where the $y_i$ are $n-1$ independent normally distributed variables with variance $\lambda_i = 2 + 2 \cos(\frac{i}{n}\pi)$ $$s(\mathbf{z}) \sim  s(\mathbf{y}) \quad \text{where} \quad y_i \sim N\left(0,\lambda_i \right)$$
Consequences:

*

*The variance of $s(\mathbf{z})^2$ is equal to $1/\sqrt{n-1}$ times the sum of the  variances of the individual terms $y_i^2$ (which relate to scaled $\chi_{(1)}^2$ distributions or to gamma distributions).
For the individual terms which are the squares of normal distributed variables we have
$$\begin{array}{rcl}
\text{var}(y_i^2) &=& 2 \text{var}(y_i)^2  \\
   &=&2\left( 2 + 2 \cos\left(\frac{i}{n}\pi\right)\right)^2 \\
&=& 12 + 4\cos\left(2\frac{i}{n}\pi\right) + 16 \cos\left(\frac{i}{n}\pi\right) \end{array}$$
and for the sum
$$\begin{array}{rcl}
\text{var}[s(\mathbf{z})^2] &=& \frac{1}{n-1}  \sum_{i=1}^{n-1}12 + { 4\cos\left(2\frac{i}{n}\pi\right)} \overbrace{ + 16 \cos\left(\frac{i}{n}\pi\right)}^{\substack{\text{these terms cancel}\\\text{ due to  symmetry}}} \\
&=& \frac{1}{n-1} ( \sum_{i=1}^{n-1}12  + 4 \underbrace{\sum_{i=1}^{n-1}\cos\left(2\frac{i}{n}\pi\right))}_{=-1}  \\& =& \frac{12(n-1) -4}{n-1} \\&\approx& 12
\end{array}$$
where we used this to derive that the sum of cosines is equal to -1.

*We can not express the probability density function in a closed-form but we can express the cumulants of the distribution $\kappa_k(s(\mathbf{z}))$ in terms of the cumulants of a single chi-squared variable $\kappa_k(\chi_{(1)}^2)$. For increasing $n$ the 1st order cumulant will go to infinity (so to make the limiting distribution a normal distribution you should not only change the factor $1/(n-1)$ but also subtract the mean), the 2nd cumulant will approach to $12$ and the other, higher order cumulants, will approach zero, which means that you approach a normal distribution.
$$\kappa_k(s(\mathbf{z})) = \kappa_k(\chi_{(1)}^2)\frac{1}{\sqrt{n-1}^k} \sum_{i=1}^{n-1} \lambda_i^k \approx \kappa_k(\chi_{(1)}^2)\frac{n-1}{\sqrt{n-1}^k} \int_0^1  ( 2 + 2 \cos(x\pi))^k dx$$
Maybe there is a more direct way to use some version of the CLT for a sum of independent variables that only differ by a scaling constant instead of manually computing the cumulants. But I couldn't find one.
Why is it equivalent to a sum of chi-squared variables?
(see also here Show that the distribution of $x'Ax$ is linear combination of chi-squared)
Example for $n=3$
In the case of $n=3$ then the $z_1$ and $z_2$ are distributed like a multivariate normal distribution with a negative correlation. Geometrically it looks like an elongated shape.

n <- 10^4
set.seed(1)
x <- matrix(rnorm(3*n),3)
z1 <- x[2,]-x[1,]
z2 <- x[3,]-x[2,]
plot(z1,z2, xlab = expression(z[1]), ylab = expression(z[2]))

We can express the square in terms of alternative variables $Y_1 = \sqrt{0.5}(Z_1-Z_2) \sim N(0,3)$ and $Y_2 = \sqrt{0.5}(Z_1+Z_2) \sim N(0,1)$
$$Z_1^2 + Z_2^2 = 0.5(Z_1-Z_2)^2 + 0.5(Z_1+Z_2)^2  = Y_1^2 + Y_2^2$$
Note that the $Y_i$ are independent. So the distribution is similar to the distribution of a sum of independent squared normal distributed variables, but with different variance.
Generalized for all $n$
More generally $z_i$ is a multivariate normal distribution (any linear combination of the $z_i$ is a linear combination of the $x_i$ which is a normal distributed variable).
The variance of each $z_i$, being the sum of two standard normal variables, is $2$. The covariance of two neighbouring variables  is $-1$ (which you can find with covariance of sums). So the covariance matrix is like:
$$\Sigma = \begin{bmatrix} {2} & -1 & 0 & \dots & 0 &0\\
-1 & 2 & -1 & 0& \dots & 0  \\
0 & -1 & {2}& \dots & 0& 0\\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
0 & 0& 0 & \dots & {2} & -1 \\
0 & 0& 0 & \dots & -1 & {2}
\end{bmatrix}$$
In this general case we can do the same as for $n=3$ and restate the
dependent $z_i^2$ as a sum of independent squared normal variables $y_i^2$. We use the same geometrical interpretation and rotate the distribution (keeping the radial distance invariant) and the distribution of $z_i$ is equivalent to rotated $y_i$ which have a variance that relate to the eigenvalues of the covariance matrix $\Sigma$. These eigenvalues will be in between 0 and 4 (see more about that below).
These eigenvalues follow a cosine function
$$\lambda_i = 2 + 2 \cos(\frac{i}{n}\pi)$$
for $1\leq i\leq n+1$. Which can be derived from the general description of eigenvalues of triadagonal Toeplitz matrices (as mentioned by Aksakal in the comments, you can see previous edits of this post for an alternative derivation of that relation with cosines)


text:
Q: Python Selenium Button Won't Click I'm trying to click this Go button but it hasn't been working.
Here's the HTML:

I've tried the following:
driver.find_element_by_xpath('//*[@id="DERIVED_SSS_SCL_SSS_GO_1"]').click()
driver.find_element_by_xpath("//a[contains(@href,'win1')]").click()
driver.find_element_by_id('DERIVED_SSS_SCL_SSS_GO_1').click()

Any help is appreciated.
Thanks.
EDIT: Included more HTML to hopefully be able to narrow down my issue.
I must be missing something contained in here.

Group Box

<select name="DERIVED_SSS_SCL_SSS_MORE_ACADEMICS" id="DERIVED_SSS_SCL_SSS_MORE_ACADEMICS" size="1" class="PSDROPDOWNLIST" style="width:132px; ">
<option value=""> </option>
<option value="4010">Academic Planner</option>
<option value="3010">Academic Requirements</option>
<option value="2015">Apply/Cancel Graduation</option>
<option value="SFU4">Appointment Booking</option>
<option value="SFU5">Confirmation of Enrollment</option>
<option value="2050">Course History</option>
<option value="SFU7">Credential Completion Letter</option>
<option value="1002">Enrollment Activity</option>
<option value="1020">Exam Schedule</option>
<option value="SFU1">Link to SFU Canvas</option>
<option value="SFU2">Prev. Requested Reports</option>
<option value="SFU6">Transcript: Advising</option>
<option value="SFU3">Transcript: Official</option>
<option value="2035">Transcript: Unofficial</option>
<option value="2025">Transfer Credit: Report</option>
<option value="9999" selected="selected">other academic...</option>
</select>

A: Try this code and lets see if it works-
 element = driver.find_element_by_id("DERIVED_SSS_SCL_SSS_GO_1")
 driver.execute_script("arguments[0].click();", element)

update
element = driver.find_element_by_xpath('//*[@id="DERIVED_SSS_SCL_SSS_GO_1"]/img')
driver.execute_script("arguments[0].click();", element)

A: from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

selector = "//a[@id='DERIVED_SSS_SCL_SSS_GO_1']"

Try this firstly:
element = WebDriverWait(driver, 5).until(
    EC.visibility_of_element_located((By.XPATH, selector))
)
element.click()

if it doesn't work, give this a chance:
element = WebDriverWait(driver, 5).until(
    EC.element_to_be_clickable((By.XPATH, selector))
)
element.click()


text:
Q: Is it possible to trace the password the application is attempting to use to connect? I have an application attempting to connect to SQL Server. The application connects using a SQL Server account. The password for this account was accidentally changed. Now the application is attempting to connect to SQL Server using the wrong password.
Login failed for user ''. Reason: Password did not match that for the login provided. [CLIENT: ]
Ideally, we can just change the account/password the application is using to connect. If this were not an option, is it possible to trace the password the application is attempting to use to connect?

A: The short answer is you can't see the password being used to connect.  That being said, you can restore a backup copy of the master database to a test instance, get the hashed password, and then apply it with the HASHED option of ALTER LOGIN.
The password hash can be retrieved from the restored master database with:
SELECT LOGINPROPERTY('your-sql-login', 'PasswordHash');

The password can then be applied to the other instance, substituting the value from the script above:
ALTER LOGIN your-sql-login
WITH PASSWORD = 0x01000CF35567C60BFB41EBDE4CF700A985A13D773D6B45B90900 HASHED;