text:
Q: What's the difference between "grep -e" and "grep -E" I have a file test.txt, in which there are some formatted phone numbers. I'm trying to use grep to find the lines containing a phone number.
It seems that grep -e "[0-9]{3}-[0-9]{3}-[0-9]{4}" test.txt doesn't work and gives no results. But grep -E "[0-9]{3}-[0-9]{3}-[0-9]{4}" test.txtworks. So I wonder what's the difference between these 2 options.
According to man grep:

-E, --extended-regexp
               Interpret pattern as an extended regular expression (i.e. force
               grep to behave as egrep).
-e pattern, --regexp=pattern
               Specify a pattern used during the search of the input: an input
               line is selected if it matches any of the specified patterns.
               This option is most useful when multiple -e options are used to
               specify multiple patterns, or when a pattern begins with a dash
               (`-').

But I don't quite understand it. What is an extended regex?

A: Here is a simple test:
$ cat file
apple is a fruit
so is orange
but onion is not

$ grep -e 'but' -e 'fruit' file #Allows you to pass multiple patterns explicitly
apple is a fruit
but onion is not

$ grep -E 'is (a|not)' file #Allows you to use extended regular expressions like ?, +, | etc
apple is a fruit
but onion is not

A: The -e option to grep simply says that the following argument is the regular expression.  Thus:
grep -e 'some.*thing' -r -l .

looks for some followed by thing on a line in all the files in the current directory and all its sub-directories.  The same could be achieved by:
grep -r -l 'some.*thing' .

(On Linux, the situation is confused by the behaviour of GNU getopt() which, unless you set POSIXLY_CORRECT in the environment, permutes options, so you could also run:
grep 'some.*thing' -r -l .

and get the same result.  Under POSIX and other systems not using GNU getopt(), options need to precede arguments, and the grep would look for a file called -r and another called -l.)
The -E option changes the regular expressions from 'basic' to 'extended'.  It can be used with -e:
grep    -e "[0-9]{3}-[0-9]{3}-[0-9]{4}" test.txt
grep -E -e "[0-9]{3}-[0-9]{3}-[0-9]{4}" test.txt

The ERE option means the same regular expressions, more or less, as used to be recognized by the egrep command, which is no longer a part of POSIX (having been replaced by grep -E, and fgrep by grep -F).

A: As you mentioned, grep -E is for extended regular expressions whereas -e is for basic regular expressions. From the man page:
EDIT: As Jonathan pointed out below, grep -e "specifies that the following argument is (one of) the regular expression(s) to be matched."

Basic vs Extended Regular Expressions
In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose
         their  special  meaning;  instead use the backslashed versions \?, \+, \{,
         \|, \(, and \).
Traditional egrep did not support the {  meta-character,  and  some  egrep
         implementations  support \{ instead, so portable scripts should avoid { in
         grep -E patterns and should use [{] to match a literal {.
GNU grep -E attempts to support traditional usage by assuming  that {  is
         not special if it would be the start of an invalid interval specification.
         For example, the  command  grep -E '{1'  searches  for  the  two-character
         string  {1  instead of reporting a syntax error in the regular expression.
         POSIX.2 allows this behavior as an extension, but portable scripts  should
         avoid it.

But man pages are pretty terse, so for further info, check out this link:
http://www.regular-expressions.info/posix.html
The part of the manpage regarding the { meta character though specifically talks about what you are seeing with respect to the difference.
grep -e "[0-9]{3}-[0-9]{3}-[0-9]{4}"

won't work because it is not treating the { character as you expect.  Whereas
grep -E "[0-9]{3}-[0-9]{3}-[0-9]{4}"

does because that is the extended grep version — or the egrep version for example.


text:
Q: Why do computer architecture textbooks prefer MIPS architecture? I have read a lot of computer architecture textbooks, and I wonder why most of them (if not all) used MIPS as the architecture to teach. Why MIPS and not Intel or AMD or something else? What makes the architecture suitable for teaching?

A: The MIPS architecture is derived from an architecture specifically designed at Stanford for educational use and for research into CPU ISAs and architectural implementations.  Early academic RISC architecture were designed such that they could be implemented (included layout) by small teams of graduate or upper-division students (not the cast of thousands involved in current Intel CPUs.)  Thus MIPS may have basic features more compatible with textbook pedagogical explanations, and less legacy-derived "stuff" that isn't, compared with other commercial architectures.
MIPS may also have more available open source implementations very similar to it than other RISC or currently popular architectures.

A: Intel and AMD have a large share of the Desktop market. Other processor families are much more common in devices outside that fairly small area of influence. MIPS is also a RISC architecture which are generally thought of as being easier to learn. You learn a small number of commands that can be combined orthogonally a multitude of ways similar to UNIX style piping.
Computer Architecture books that are educational rather than specificational are generally geared toward concepts rather than specific implementation details and thus tend to be more likely to use RISC over CISC simply because there's less to teach in order to understand the instruction set.
I do expect a convergence with ARM though as it is an extremely widely used architecture that is also RISC so I'd think it will show up in architecture books soon enough.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use single object instance for class to set the multiple member value? Curretly i am using below code to set the DateRanges Class member variables.
       DateRanges DateRanges1 = new DateRanges();
       DateRanges DateRanges2 = new DateRanges();
       DateRanges DateRanges3 = new DateRanges();

        DateRanges1.Label = "Last Week";
        DateRanges1.Range = Lastweek;
        this.dateRange.Ranges.Add(DateRanges1);
        DateRanges2.Label = "Last 1 Month";
        DateRanges2.Range = Lastmonth;
        this.dateRange.Ranges.Add(DateRanges2);
        DateRanges3.Label = "Last 2 Months";
        DateRanges3.Range = Last2month;
        this.dateRange.Ranges.Add(DateRanges3);

I want to reduce the code in this. is there any way to do this.
Here DateRanges, class that have label(string type), ranges(object) members.
this.daterange.ranges is my custom component property.
Thanks for any help.

A: To make this code cleaner, I'd suggest:

*

*Renaming Lastmonth etc to follow .NET naming conventions

*Not bothering with any separate variables (but if you do, make them follow .NET naming conventions too)

*Renaming DateRanges to DateRange (as it only appears to be a single date range)

*Creating a constructor for DateRange accepting the range and the label

You can then have:
dateRange.Ranges.Add(new DateRange(LastWeek, "Last Week"));
dateRange.Ranges.Add(new DateRange(LastMonth, "Last 1 Month"));
dateRange.Ranges.Add(new DateRange(Last2Months, "Last 2 Months"));

Or possibly (depending on the type of Ranges):
// Here AddRange would be expected to accept IEnumerable<DateRange>
dateRange.Ranges.AddRange(new[] {
    new DateRange(LastWeek, "Last Week"),
    new DateRange(LastMonth, "Last 1 Month"),
    new DateRange(Last2Months, "Last 2 Months")
});

Both of those are considerably cleaner IMO than using an object initializer and an unconventional local variable name.
If you're doing this around the same code you're initializing dateRanges, you could just use:
dateRanges = new FooBar // Whatever the type actually is
{
    // Other properties as well
    Ranges =
    {
        new DateRange(LastWeek, "Last Week"),
        new DateRange(LastMonth, "Last 1 Month"),
        new DateRange(Last2Months, "Last 2 Months")
    }
};

A: You can have only one variable instead of 3 variables:
    var DateRanges = new DateRanges {
        Label = "Last Week",
        Range = Lastweek
    };
    this.dateRange.Ranges.Add(DateRanges);

    DateRanges = new DateRanges {
        Label = "Last 1 Month",
        Range = Lastmonth
    };
    this.dateRange.Ranges.Add(DateRanges);

    DateRanges = new DateRanges {
        Label = "Last 2 Months",
        Range = Last2month
    };
    this.dateRange.Ranges.Add(DateRanges);


text:
Q: Find and replace with Greek letters returns question mark in ArcGis 10.3 When I try to replace values in a field with Greek Characters they appear as it should be in attribute, but when I save the edits and re open the attribute I see question mark.
The same thing happens also in Qgis 2.8.1.
I use windows 7 x64 ultimate.
On an other machine which runs windows 8.1 and ArcGis 10.2.1 I see the replaced Greek letters and after reopen the attribute but when I export the attribute in .dbf I don't see anything.
How can I fix this problem?

A: There are multiple reason for this problem and here are some tips.
If you are using Shape file make sure dbf is encoded in proper encoding i.e. UTF-8 or 1253 and you have install the keyboard language support (Greek) to windows as well. You can find these steps here.
http://www.howtogeek.com/howto/12578/add-keyboard-languages-to-xp-vista-and-windows-7/
My personal preference for this kind of stuff is FileGeoDB format. Once everything is OK in FileGeoDB then I export it to shapfile using write encoding setting in the registry.
You must read the following ESRI paper which explains how ArcGIS deal with the DBF encoding.
http://support.esri.com/cn/knowledgebase/techarticles/detail/21106
hope that helps.


text:
Q: Stacking multiple Transformations of the same Type in Css I want some transformations which are all targeting the same property to stack on top of each other.
Given my example below: If the button is clicked multiple times, the effects should add up. The box should then also move faster to the right according to the frequency of the clicks.

const clickHandler = () => {box.classList.add("move-box");}
.box{
width: 50px;
padding: 10px;
margin-top: 50px;
border: 1px solid black;
}

.move-box {
margin-left: 100px;
transition: margin-left 0.5s linear;
}
<button onclick="clickHandler()">Go over there</button>

Alright

A: Maybe you can pass a parameter in your function for the speed and use it in your css instead of using a static value or maybe increment it with every click.

A: You can set css value dynamically by javascript
(note: you should put transition: margin-left 0.5s linear; in .box)

const clickHandler = () => {
  const left = +box.dataset.left
  box.style.marginLeft = left + "px";
  box.dataset.left = left + 100;
}
.box {
  width: 50px;
  padding: 10px;
  margin-top: 50px;
  border: 1px solid black;
  transition: margin-left 0.5s linear;
}
<button onclick="clickHandler()">Go over there</button>

Alright


text:
Q: How to make resizable div, resizable from sides? I have this code from codepen, It makes a resizable div that resizes from corners:

body,
html {
  background: black;
}
.resizable {
  background: white;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 100px;
  left: 100px;
}

.resizable .resizers{
  width: 100%;
  height: 100%;
  border: 3px solid #4286f4;
  box-sizing: border-box;
}

.resizable .resizers .resizer{
  width: 10px;
  height: 10px;
  border-radius: 50%; /*magic to turn square into circle*/
  background: white;
  border: 3px solid #4286f4;
  position: absolute;
}

.resizable .resizers .resizer.top-left {
  left: -5px;
  top: -5px;
  cursor: nwse-resize; /*resizer cursor*/
}
.resizable .resizers .resizer.top-right {
  right: -5px;
  top: -5px;
  cursor: nesw-resize;
}
.resizable .resizers .resizer.bottom-left {
  left: -5px;
  bottom: -5px;
  cursor: nesw-resize;
}
.resizable .resizers .resizer.bottom-right {
  right: -5px;
  bottom: -5px;
  cursor: nwse-resize;
}

function makeResizableDiv(div) {
  const element = document.querySelector(div);
  const resizers = document.querySelectorAll(div + ' .resizer')
  const minimum_size = 20;
  let original_width = 0;
  let original_height = 0;
  let original_x = 0;
  let original_y = 0;
  let original_mouse_x = 0;
  let original_mouse_y = 0;
  for (let i = 0;i < resizers.length; i++) {
    const currentResizer = resizers[i];
    currentResizer.addEventListener('mousedown', function(e) {
      e.preventDefault()
      original_width = parseFloat(getComputedStyle(element, null).getPropertyValue('width').replace('px', ''));
      original_height = parseFloat(getComputedStyle(element, null).getPropertyValue('height').replace('px', ''));
      original_x = element.getBoundingClientRect().left;
      original_y = element.getBoundingClientRect().top;
      original_mouse_x = e.pageX;
      original_mouse_y = e.pageY;
      window.addEventListener('mousemove', resize)
      window.addEventListener('mouseup', stopResize)
    })

    function resize(e) {
      if (currentResizer.classList.contains('bottom-right')) {
        const width = original_width + (e.pageX - original_mouse_x);
        const height = original_height + (e.pageY - original_mouse_y)
        if (width > minimum_size) {
          element.style.width = width + 'px'
        }
        if (height > minimum_size) {
          element.style.height = height + 'px'
        }
      }
      else if (currentResizer.classList.contains('bottom-left')) {
        const height = original_height + (e.pageY - original_mouse_y)
        const width = original_width - (e.pageX - original_mouse_x)
        if (height > minimum_size) {
          element.style.height = height + 'px'
        }
        if (width > minimum_size) {
          element.style.width = width + 'px'
          element.style.left = original_x + (e.pageX - original_mouse_x) + 'px'
        }
      }
      else if (currentResizer.classList.contains('top-right')) {
        const width = original_width + (e.pageX - original_mouse_x)
        const height = original_height - (e.pageY - original_mouse_y)
        if (width > minimum_size) {
          element.style.width = width + 'px'
        }
        if (height > minimum_size) {
          element.style.height = height + 'px'
          element.style.top = original_y + (e.pageY - original_mouse_y) + 'px'
        }
      }
      else {
        const width = original_width - (e.pageX - original_mouse_x)
        const height = original_height - (e.pageY - original_mouse_y)
        if (width > minimum_size) {
          element.style.width = width + 'px'
          element.style.left = original_x + (e.pageX - original_mouse_x) + 'px'
        }
        if (height > minimum_size) {
          element.style.height = height + 'px'
          element.style.top = original_y + (e.pageY - original_mouse_y) + 'px'
        }
      }
    }

    function stopResize() {
      window.removeEventListener('mousemove', resize)
    }
  }
}

makeResizableDiv('.resizable')

How i make it resizes from sides?
It should have a circle at the midle of right, left, bottom, right and top side and resize from there.
Here is the link from the original pen:
Medium: Making a resizable div
Probably there will be need to four new ifs and to four new css classes but im not sure.

A: I adjusted the positioning and class titles to place the handles on the sides, then removed the scripting from each one that allowed both directions to be adjusted.

function makeResizableDiv(div) {
  const element = document.querySelector(div);
  const resizers = document.querySelectorAll(div + ' .resizer')
  const minimum_size = 20;
  let original_width = 0;
  let original_height = 0;
  let original_x = 0;
  let original_y = 0;
  let original_mouse_x = 0;
  let original_mouse_y = 0;
  for (let i = 0;i < resizers.length; i++) {
    const currentResizer = resizers[i];
    currentResizer.addEventListener('mousedown', function(e) {
      e.preventDefault()
      original_width = parseFloat(getComputedStyle(element, null).getPropertyValue('width').replace('px', ''));
      original_height = parseFloat(getComputedStyle(element, null).getPropertyValue('height').replace('px', ''));
      original_x = element.getBoundingClientRect().left;
      original_y = element.getBoundingClientRect().top;
      original_mouse_x = e.pageX;
      original_mouse_y = e.pageY;
      window.addEventListener('mousemove', resize)
      window.addEventListener('mouseup', stopResize)
    })

    function resize(e) {
      if (currentResizer.classList.contains('right')) {
        const width = original_width + (e.pageX - original_mouse_x);

        if (width > minimum_size) {
          element.style.width = width + 'px'
        }
      }
      else if (currentResizer.classList.contains('left')) {
        const width = original_width - (e.pageX - original_mouse_x)
        if (width > minimum_size) {
          element.style.width = width + 'px'
          element.style.left = original_x + (e.pageX - original_mouse_x) + 'px'
        }
      }
      else if (currentResizer.classList.contains('top')) {

        const height = original_height - (e.pageY - original_mouse_y)
        if (height > minimum_size) {
          element.style.height = height + 'px'
          element.style.top = original_y + (e.pageY - original_mouse_y) + 'px'
        }
      }

      else if (currentResizer.classList.contains('bottom'))       {
        const height = original_height + (e.pageY - original_mouse_y)
        if (height > minimum_size) {
          element.style.height = height + 'px'
        }

      }
    }

    function stopResize() {
      window.removeEventListener('mousemove', resize)
    }
  }
}

makeResizableDiv('.resizable')
body,
html {
  background: black;
}
.resizable {
  background: white;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 100px;
  left: 100px;
}

.resizable .resizers{
  width: 100%;
  height: 100%;
  border: 3px solid #4286f4;
  box-sizing: border-box;
}

.resizable .resizers .resizer{
  width: 10px;
  height: 10px;
  border-radius: 50%; /*magic to turn square into circle*/
  background: white;
  border: 3px solid #4286f4;
  position: absolute;
}

.resizer.top {
  left: 50%;
  top: -5px;
  cursor: ns-resize;
  transform: translate(-7px, 0px);
}

.resizer.right {
  right: -5px;
  bottom: 50%;
  cursor: ew-resize;
  transform: translate(0px, 5px);
}

.resizer.bottom {
  left: 50%;
  bottom: -5px;
  cursor: ns-resize;
  transform: translate(-7px, 0px);
}

.resizer.left {
  left: -5px;
  bottom: 50%;
  cursor: ew-resize;
  transform: translate(0px, 5px);
}


text:
Q: Unnecessary horizontal scrollbar I'm trying to build an asp.net mvc view with a jquery datatable. My datatable contains only one filed (role name), and the delete/update/show buttons links.
the problem is that an unnecessary horizontal scroll bar is displayed :

How can i avoid this unnecessary scroll bar ?
Below is a snippet of my view :

 Roles management

    <fieldset class="col-md-10 col-md-offset-1 ">
        <legend>Liste des rôles </legend>

                            Designation role

                        @foreach (var item in Model)
                        {

                                    @item.Name

                        }

                <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action("Create", "Role")'">
                     Ajouter un role
                </button>

    </fieldset>

Thanks a lot for your help.

A: Try to add this css:
overflow-x:hidden

to the div that wraps the fieldset.


text:
Q: Function check number return to image in javascript How to create function replace number to image?
Example: var dd="123"
I want to create function replace value of dd to image.
if 1=image1
if 2=image2
if 3=image3

How to do that? Please provide coding.

A:
function imageReplace ( str ) {
    var arr = str.split('');
    var returnArr = new Array();
    for(var i in arr ){
        returnArr.push("image"+arr[i]);
    }
    return returnArr;
}
I think thats what your looking for

A: Hard to answer because of the lack of expected flow control, but something like this:
function concatFilename(str,index)
{
   return 'image'+str[index];
}

Usage:
var dd = 'abc123';
for (var i=0; i < dd.length; i++)
{
  console.log(concatFilename(dd, index));
}

Or... easier:
dd[2] = 'c';

A: Does dd contain a single number, to be converted as a whole? If so:
var dd = '123';
dd.replace(/([\d]+)/, /image$1/);  // 'image123'

If you want each digit to be converted:
var dd = '123';
dd.replace(/([\d])/, /image$1/);  // 'image1image2image3'

Hope that helps. :)
Honestly, I'm assuming you almost certainly want the first of the two. (If in doubt, ask yourself -- what behavior do you expect if you're on image 10 or 11?)

A: var getImages = function(s) {
  var images=[], ss=(""+s).split(''), len=ss.length, i;
  for (i=0; i<len; i++) {
    images.push("image" + ss[i] + ".gif");
  }
  return images;
};
getImages(123); // => ["image1.gif", "image2.gif", "image3.gif"]
getImages(42); // => ["image4.gif", "image2.gif"]
getImages(0); // => ["image0.gif"]

[Edit] or perhaps something like this?
var getImageNames = function(s) {
  return (""+s).split('').map(function(x) {
    return '"image'+x+'.gif"';
  }).join(' ');
}
getImageNames(123); // => '"image1.gif" "image2.gif" "image3.gif"'

A: You can use a regular expression to replace each digit with an image tag:
dd = dd.replace(/(\d)/g, '');

This also works on a string containing numbers, like "Page 12 of 42" is turned into "Page  of ".


text:
Q: how to wait for promise resolve rxjs filter In my observable source I receive events in which I want to filter for a certain async operation.
For instance:
s$.pipe(
    map((x) => x + 1),
    filter((x) => alreadyExist(x)))
  .subscribe(...)

When alreadyExist is an async operation,
(checking if the value exist in a persistent storage) which returns a boolean.
Assume alreadyExist return a promise which resolve to a boolean,
how can I wait on the return?
Note that I need the value not to change.
Doing async-await didn't work and the subscribe executed before the filter returned.

A: If alreadyExist returns a boolean you can use mergeMap that will wait for its result and if it's true than it'll map it into the original x value. When it's false then it's just filtered out by filter.
s$.pipe(
    map((x) => x + 1),
    mergeMap(x => from(alreadyExist(x)).pipe(
      filter(Boolean),
      mapTo(x),
    )),
  )
  .subscribe(...)

A: You can try with my suggestion - Using switchMap pipe
let isAlreadyExist = false; // "global" variable :)
s$.pipe(
    map((x) => x + 1),
    switchMap(async (x) => {
      isAlreadyExist = await alreadyExist(x); // make sure alreadyExist is a promise func
      return x; // "do" do nothing with your data
    }),
    filter((x) => isAlreadyExist)) // isAlreadyExist is value of alreadyExist func
  .subscribe(...)

or you can read about defer of RxJS Observable.


text:
Q: Is it possible to speed up this join? The values table has millions of rows and doing this join on the indexes is quite slow (7s).
Is it possible to speed this up?
select *
from (
    select
      instance.Name, Date, Value,
      instance.Category, instance.CreatedDate
      from ValuesTable ValuesTable
    join (
        select
          max(IDX) ID,
          CreatedDate,
          max(ModelsTable.Category) Category,
          max(InstanceTable.Name) Name,
          max(ModelsTable.Region) Country
        from InstanceTable
        join ModelsTable ModelsTable
          on ModelsTable.ModelID = InstanceTable.ModelID
        where InstanceTable.RunCategory = 'Scenario'
          and CreatedDate = GETDATE()
        group by InstanceTable.Name, ModelsTable.Category,
          InstanceTable.CreatedDate
      ) instance on instance.ID=ValuesTable.IDX
) a

A: First, I would simplify the query a bit by getting rid of the first subquery.  And clarify it using table aliases:
select i.Name, i.Date, i.Value,  i.Category, i.CreatedDate,
       instance.id, instance.CreatedDate, instance.Category,
       instance.Name, instancy.Country
from ValuesTable i join
     (select max(IDX) as ID, CreatedDate,
             max(m.Category) as Category,
             max(i.Name) as Name,
             max(m.Region) as Country
      from InstanceTable i join
           ModelsTable m
           on m.ModelID = i.ModelID
      where i.RunCategory = 'Scenario' and
            i.CreatedDate = GETDATE()
      group by i.Name, m.Category, i.CreatedDate
     ) instance
     on i.ID = instance.IDX;

Then, this is highly unlikely to do anything useful.  The problem is:
i.CreatedDate = GETDATE()

GETDATE() is a non-standard function.  But in every database that I know of that supports it, the function returns a time as well as a date.  You probably intend:
i.CreatedDate = cast(GETDATE() as date)

or:
i.CreatedDate >= cast(GETDATE() as date)

You probably want to convert it to a date for the aggregation as well.
Then, you want indexes on:
InstanceTable(RunCategory, CreatedDate)
ModelsTable(ModelId)
ValuesTable(id)


text:
Q: Apache access log not logging content-length for data served via PHP I have a php script that handles files downloads, it sends content-length header properly and the browsers receive it. But in the Apache access log they show up as "-".
In the past this used to work, the bytes showed up on the log, but this is no longer the case.
PHP Script Requests
Web Browser -> Nginx -> Apache -> PHP-FPM
https://serverpilot.io/docs/how-serverpilot-configures-your-lamp-stack/
Log entry, where "-" is %b (the file size in bytes)
218.200.***.*** - - [29/Dec/2020:00:49:02 +0100] "GET /dll.php?file=File.zip&key=109237902 HTTP/1.0" 200 -

Worth noting that if the file is downloaded directly, then the size is logged.
EDIT: Log format:
LogFormat "%a %l %u %t \"%r\" %>s %b" common


text:
Q: How can I join strings from VecDeque in Rust? This is what I'm trying to do, but it doesn't work:
use std::collections::VecDeque;

let mut x: VecDeque<String> = VecDeque::new();
x.push_back("bye".to_string());
x.push_front("hello".to_string());
x.join(" "); // doesn't compile!

I'm expecting hello bye as a result.
What is the right way?

A: The simplest option is probably to convert the VecDeque .into() a Vec, though as the documentation says:

This never needs to re-allocate, but does need to do O(n) data movement if the circular buffer doesn't happen to be at the beginning of the allocation.

so ymmv on the efficiency front.
Alternatively, add a dependency on itertools which has a number of nice utilities including a join method (and also for your case a helper join function so you don't even need to convert the collection to an iterator).


text:
Q: Pass Value From Controller to Model CodeIginter Using Stored Procedure I have a problem with Codeigniter. I try to pass value from view to controller and it works. But there is a problem when it passing from controller to model. It didn't return any value into View.
Here is my controller:
 public function Edit2G() {
                $id = $this->uri->segment(3);
                $this->load->model("main_model");
                $data['fetch_data_2G_where'] = $this->main_model->fetch_data_2G_id($id);
                $data['id'] = $id;
                $data['title'] = "Update Data 2G";

                $this->load->view('templates/header');
                $this->load->view("pages/Update2G", $data);
                $this->load->view('templates/footer');
            }

Here is Model
 function fetch_data_2G_id($id)
     {
         $get_2G_data_stored_proc = "CALL Get_2G_Data(?)";
         $data = array( 'id' =>$id);
         $query = $this->db->query($get_2G_data_stored_proc, $data);
         $result = $query->result_array();
         return $get_2G_data_stored_proc;
     }

And this is my View

<?=$title ?>

<?=$id ?>

<?php echo $fetch_data_2G_where['id'];?>
 //This is a test
<?php echo form_open('posts/update'); ?>
<input type="hidden" name="id" value="<?php //echo $fetch_data_2G_where['id']; ?>">

    Site ID
    <input type="text" class="form-control" name="title" placeholder="add title" value="<?php //echo $fetch_data_2G_where['site_name'];?>">

This is the stored procedure result
id, id_site, site_name, bsc_name, bcf_id, vlan1, vlan2, status,status_vlan

'1', 'COK008', 'Combat Batylon754','FBTIMIKA-1','BCF-0112', '3677', '3137', '', 'Metro E'

This in Error That I got

A PHP Error was encountered Severity: Warning
Message: Illegal string offset 'id'
Filename: pages/Update2G.php
Line Number: 3
Backtrace:
File: C:\xampp\htdocs\DapotTimika\application\views\pages\Update2G.php
  Line: 3 Function: _error_handler
File: C:\xampp\htdocs\DapotTimika\application\controllers\Pages.php
  Line: 46 Function: view
File: C:\xampp\htdocs\DapotTimika\index.php Line: 315 Function:
  require_once

What I am missing?
PS: the stored procedure only has one parameter (id) to return / get data

A: in your controller print_r the below line
$data['fetch_data_2G_where'] = $this->main_model->fetch_data_2G_id($id);
echo "
"; print_r($data['fetch_data_2G_where']);

just to see what's the result your query returning. then from your result you can analyse and get the desired results in view.

A: Thank You Guys for the answer, I found the answer.
I Forgot to parse return value from model into array. The code in model and controller is fine.
here is my view code
<?php
        if($fetch_data_2G_where->num_rows() > 0)
        {
            foreach($fetch_data_2G_where->result_array() as $data)
            {
        ?>

            <input type="hidden" name="id" value="<?php echo $data['id']; ?>">

            Site ID
            <input type="text" class="form-control" name="site_id" value="<?php echo $data['id_site'];?>">
<?php } ?>

Here is the Result


text:
Q: Android - Creating a notification from a SMS BroadcastReceiver My program uses a BroadcastReceiver to scan for SMS (which works and can create a toast message based on text content). But I would like for this to fire off a notification (just like the system generated ones, but I am going to dynamically drive this based upon the content. So far I have tried the following code after I have recieved the SMS and filtered for my application:
    Notifier notice = new Notifier();
    Intent noticeIntent = new Intent(context, Preferences.class);
    notice.setNotice(context, noticeIntent,noticeId ,
    R.drawable.gong_icon, "Gong Text", true);

which then calls the class
public class Notifier extends Activity{
public class Notifier extends Activity{
    private int count;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    // Proven working Notification call

from this point I call a piece of notification code that I have tested and is working.
But when I run the above code I recieve an error so I have tried to debug with adb.
When I run adb catlob I receive this error:
java.lang.RuntimeException: Unable to start receiver co
m.mattwinder.android.gong.SmsReceiver: java.lang.IllegalStateException: System s
ervices not available to Activities before onCreate()
Please help!


text:
Q: Weird behavior when using websockets I have written a simple websocket server/ client.
The server is written using C# (System.Net.WebSockes) and client is javascript
(although server technology is irrelevant because I have tested it with signalr and got the same error during the handshake of websocket transport).
The problem is that:
1- on some clients I can easily connect to server and works very well.
2- on some other clients I get an error code 1006 during handshake
      and in these clients when I turn on a proxy app such as PSiphon it can connect to the server. However, it gets disconnected after about 6 seconds.
I'm really super confused, and finally after hours of trying I have decided to put a question here.
I don't think that it`s related to code, but I put it here anyway.
    var url = 'ws://' + location.host + '/socket';
    var socket = new WebSocket(url);

Update 1: i have contacted system administrator (Hosting Company) and they said it might be because of the ISP of clients. if that`s the case i would appreciate any tip to make sure if there is some kind of proxy server that causes the trouble?
Update 2: as @vtortola mentioned i created a self signed certificate and added to website (IIS and Plesk). there was some improvement but still getting disconnections
Thanks in advance..

A: It smells like proxy issues to me. Use secure connections (wss://) and check if it gets better. Basically, if some of your clients are behind proxies, the WebSocket connections can misbehave in many unexpected ways.
How HTML5 Web Sockets Interact With Proxy Servers.


text:
Q: ggplot geom_boxplot by grouping rows Here is my data;

What I tryna get is something like this ;

axis y should represent the column 'yogunluk', x-axis should show each 'deney' boxplot for every 'yogunluk'. I mean, imagine a vector includes these values for the first row of my data c(7,8,15,11,9,10) one of the boxplots is supposed to be drawn for these values. I couldn't even imagine how to set that kind of mapping in geom_boxplot.

A: This is one option, to first reshape the data and then feed it to ggplot2.
library(tidyr)
library(dplyr)
library(ggplot2)

dat=data.frame(yogunluk=c(5,10,15,20),
               deney1=c(7,12,14,19),
               deney2=c(8,17,18,25),
               deney3=c(15,13,19,22),
               deney4=c(11,18,17,23),
               deney5=c(9,19,16,18),
               toplam=c(60,94,102,127),
               ortlama=c(10,15.6,17,21.16),
               sd=c(2.8,2.8,1.7,2.6),
               var=c(8,7,3,6.9))

d=pivot_longer(dat, cols=deney1:deney5)
d=d %>% group_by(yogunluk) %>% summarize(mea=mean(value)) %>% right_join(d)

ggplot(d) +
  geom_boxplot(aes(yogunluk, value, group=yogunluk), fill="#3792cb", width=1) +
  geom_line(aes(yogunluk, mea)) +
  geom_point(aes(yogunluk, mea), size=3, pch=3) +
  ggtitle("Boxplot of 5;10;...") +
  ylab("Data") +
  xlab("") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))

A: I've tried to recreate as close as possible what you are showing as your example plot, both because it is fun to do and because it can demonstrate some elements of how to organize your data and how to build a plot with ggplot2.
Data Wrangling
First, your data is not in what is called Tidy Data format.  (here is the recreation):
yourData <- data.frame(
  yogunluk = c(5,10,15,20),
  deney1 = c(7,12,14,19),
  deney2 = c(8,17,18,25),
  deney3 = c(15,13,19,22),
  deney4 = c(11,18,17,23),
  deney5 = c(9,19,16,18),
  deney6 = c(10,15,18,20),
  toplam = c(60,94,102,127)
)

You should consider that you have a value for every deney in your dataset at a given yoguluk.  If we think this way, you will need to "gather" all those columns for deney (deney1, deney2, deney3,...) and their respective values into two new columns:  one to identify "which" deney you are talking about and one for the value.  We will use the gather() function from tidyr to push these together, but you can also use functions like pivot_longer():
library(dplyr)
library(tidyr)
library(ggplot2)

yourData <- yourData %>%
  select(yogunluk, deney1,deney2,deney3,deney4,deney5,deney6) %>%
  gather(deney, value, -yogunluk)

Note that we are first only selecting the columns for yogunluk and deney1, deney2,..., and disregarding the summary statistic columns.  The reason is because we will be summarizing that data within the actual ggplot2 functions.  The alternative approach is to summarize the data beforehand, then plot that.  It's kind of up to you, but I find that it's nicer to do it this way when you might show both individual data points as well as their summaries (like the average of a group of data) in the same plot.
The Plot
Now that your data is formatted correctly, I'm going to create the plot.  I'm assuming you actually switched what you meant for the x and y axes - the x axis is on the bottom, so left to right, we will assign specific yourData$yogunluk values, whereas the values themselves for each deney... will be used to create the boxplots along the y axis.
I'll show you the code and the plot, then explain a bit how each part works under that:
ggplot(yourData, aes(x=factor(yogunluk), y=value)) +
  geom_boxplot(width=0.5, fill='dodgerblue3', alpha=0.5) +
  stat_summary(geom='point', shape=10, size=5) +
  stat_summary(geom='line', aes(group=1)) +

  labs(y='Data', x='Yogunluk', title='Boxplot of Something') +

  theme_classic() +
  theme(
    plot.background = element_rect(fill='gray90'),
    plot.margin = margin(30,30,30,30),
    plot.title.position = 'plot',
    plot.title = element_text(hjust=0.5, size=16)
  )

Discussion on Plot Code
I've broken the plot code into parts intentionally (and usually do so on my own plots) just so that I can keep track of the various "parts" of the plot itself.  I'll explain each part in turn.
Plot area and geoms
The first part is defining the plot aspects, main aesthetics, and geoms.  This covers all the stuff that's added to the plot based on the dataset yourData.  Note first that I refer to factor(yogunluk) rather than just yogunluk.  Why?  Because yourData$yogunluk is a class of int - a continuous variable, and here we are wanting to plot this as a discrete variable.  In order to create a boxplot that is grouped by yogunluk, the act of grouping by definition is making our x axis discrete.  So... we can just force it to be this way by asking ggplot2 to consider this column to be a factor.
The geom_boxplot() code is pretty straightforward.
The stat_summary() commands are taking place of using geom_point() and geom_line().  Why use stat_summary?  Because note we don't have summarized data.  You can understand it this way:  geom_point() would treat the dataset by plotting each point/line/observation in the data separately.  If we wanted to plot a geom_point() on sumamrized data (like the mean()) you would use stat_summary().  This first calculates a summary statistic (default is mean_se()), then use that to replace the y aesthetic.  In this case, stat_summary(geom='point') will calculate the mean_se() of each set of yourData$value, grouped by factor(yourData$yogunluk).  That mean is used as the new y aesthetic.
The extra note on stat_summary(geom='line'...) is that we're assigning a group aesthetic = 1.  Why?  This is so that ggplot2 treats the whole thing as one "group".  Otherwise, ggplot2 will just compute the average for each discrete value of yogunluk (which is what we want), but will not know that it needs to connect all these points.  Assigning group=1 just tells ggplot2 that "all these points should be part of the same group... so draw a line connecting them, please.".
Labels
Pretty straightforward I think.
Theme Elements
Also pretty straightforward.  For a full list of theme elements, just check out this reference.


text:
Q: How to disconnect iPhone from WIFI without 'forgetting' it? My internet connection died whilst my router still continued to work (so I could still pick up wifi but had no internet connection). I wanted to tether my laptop to my phone so I could use 4G instead, but my phone was still connected to the shody WIFI.
I couldnt just turn off the WIFI on my phone as then my laptop would not be able to tether. I didnt want to 'forget' my WIFI connection as I do not know the password.
Is there anyway to simply disconnect from a WIFI signal?

A: Turn off auto-join.  I've searched for this several times and always thought it was a stupid design by apple but I finally worked it out.
In your iPhone settings, turn WiFi off then back on again. If it connects to your home WiFi automatically, click on the i (information) symbol next to the connection. Turn off the 'auto-join' option. Then you can turn WiFi off then on again to drop the connection without forgetting it.
As the original post I'm replying to is five years old now maybe I'm the only one dumb enough to still be having this problem. But maybe not.  :)

A: So I'm assuming you're tethering your laptop to your phone via wifi from some app? Can you just turn wifi off, then go to the tethering app and enable tethering? If wifi is off I imagine it should turn it on and switch to it's tethering mode.
Also, a note: The phone should stay connected to the cellular network while wifi is on.

A: You could use Bluetooth or USB to tether your connection to the laptop. That would allow to deactivate wifi and let the iPhone connect to cellular.

A: You don't actually have to turn off Wifi.  Here's what I do when my cable modem drops:

*

*Settings > Personal Hotspop -> turn to on

*on my laptop, click the WIFI icon in the tray to open the "Currently Connected to" Dialog.

*Sometimes at this point I have to use the refresh Icon in the top right of that dialog a few times to get my iPhone's SSID to show up, sometimes turning the personal hotspot on/off on the phone is what works.  This is the tricky step but if you play with it, the phones SSID will show up in the laptop.

*Connect to the SSID for the phone when it appears.  The phone will drop it's connection to the router and start tethering the laptop.

When your ready to return, just turn off the personal hotspot on the phone and the phone will re-join the routers network.

A: Turn off "Handoff" in "General" and turn off "Calls on other devices" and try, it worked for me.


text:
Q: Updating Gmail drop-down suggestions I have observed that when I use the Gmail API to delete a message, the deleted message still shows up in the drop-down suggestions in the search bar. If the drop-down suggestion is chosen, the UI responds with an error banner:

The conversation no longer exists.

Is there any way to prevent the drop-down suggestion from listing entries that yield this error? Is it an issue with Gmail's search index?
Further details:
I know how to remove the drop-down suggestions; this is not what I want. I want it to not display deleted messages. I've also seen discussion that Gmail Offline may cause this issue. However, I have observed it happening without this feature enabled.


text:
Q: Adding multiple XmlElement.LastChild.InnerText I have a function where I want to add multiple 'values' to a node. Here is function:
 private void GetCategory(DataRow reader, XmlElement myNode)
    {
        foreach (DataRow categoryRow in reader.GetChildRows("Article_Category"))
        {
            myNode.LastChild.InnerText = categoryRow["CATEGORY_NAME"].ToString();
        }
    }

myNode.OuterXml looks like this:
<field itemid="{2C16342E-7662-432B-9895-5EDB15914D7F}" language="en" version="1"
fieldid="{1F5956D6-EABE-4F74-A248-B25B7EE90350}" name="Categories" title=""
type="Multilist" source="/sitecore/content/data/Categories" section="Content"
tooltip=""><value>US</value></field>

I wanted to look something like this:
<field itemid="{2C16342E-7662-432B-9895-5EDB15914D7F}" language="en" version="1"
fieldid="{1F5956D6-EABE-4F74-A248-B25B7EE90350}" name="Categories" title=""
type="Multilist" source="/sitecore/content/data/Categories" section="Content"
tooltip=""><value>US</value><value>China</value><value>India</value></field>

I added this function:
 foreach (DataRow categoryRow in reader.GetChildRows("Article_Category"))
        {
            var newNode = myNode.OwnerDocument.CreateElement("Value");
            newNode.InnerText = categoryRow["CATEGORY_NAME"].ToString();
            myNode.AppendChild(newNode);

        }

Its does not work becoz this is how my XML looks like:
 <field itemid="{9259D344-3500-4887-9CDF-F00876F20F2B}" language="en" version="1"
 fieldid="{1F5956D6-EABE-4F74-A248-B25B7EE90350}" name="Country" title=""
 type="Multilist" source="/sitecore/content/data/Countries" section="Content"
 tooltip=""><value /><Value>Currency Markets</Value></field>

THere is a 'value' tag which does not lets add up.

A: Your current code overwrites the Text of the LastChild. You need to add nodes,
    //untested
    foreach (DataRow categoryRow in reader.GetChildRows("Category"))
    {
      //myNode.LastChild.InnerText = categoryRow["CATEGORY_NAME"].ToString();

        var newNode = myNode.OwnerDocument.CreateElement("value");
        newNode.InnerText = categoryRow["CATEGORY_NAME"].ToString();
        myNode.AppendChild(newNode);
    }


text:
Q: How renew greenlock-express certificates forcefully at any time? I have CA certificates files in "greenlock.d/live/URL_PATH/". It's expiration date is Aug 2022.
But I want to renew them right now to check whether they are renewing or not. Please suggest me how can I renew them at any time?
What I have done:
I have tried number of solutions like:

*

*Tried Some commands

*Changing renewal time ("renewAt") in "greenlock.d/config.json"

Code:
app.js
'use strict';

var app = function(req, res) {
    res.end('Hello, Encrypted World!');
};

module.exports = app;

server.js
'use strict';

var beapp = require('./app.js');

require('greenlock-express')
    .init({
        packageRoot: __dirname,
        maintainerEmail: "EMAIL_ID",
        configDir: './greenlock.d',
        cluster: true
    })
    // .serve(beapp);
    .ready(httpsWorker);
function httpsWorker(glx) {
    var httpsServer = glx.httpsServer(null, beapp);
    httpsServer.listen(443, "0.0.0.0", function () {
        console.info("Listening on ", httpsServer.address());
    });
}

greenlock.d/config.json
{
  "defaults": {
    "store": {
      "basePath": "./greenlock.d",
      "module": "greenlock-store-fs"
    },
    "challenges": {
      "http-01": {
        "module": "acme-http-01-standalone"
      }
    },
    "renewOffset": "-45d",
    "renewStagger": "3d",
    "accountKeyType": "EC-P256",
    "serverKeyType": "RSA-2048",
    "subscriberEmail": "EMAIL_ID"
  },
  "sites": [
    {
      "subject": "URL_PATH",
      "altnames": [
        "URL_PATH"
      ],
      "renewAt": 1
    }
  ]
}

A: *

*Run these commands sequencially:

*

*npm init

*npm install --save greenlock-express@v4

*npx greenlock init --config-dir ./greenlock.d --maintainer-email
'jon@example.com'

*npx greenlock add --subject example.com --altnames example.com

*node server.js

Reference : https://www.npmjs.com/package/greenlock-express#1-create-your-project


text:
Q: Error: Input array is longer than number of columns in this table powershell I am trying to load 160gb csv file to sql and I am using powershell script I got from Github and I get this error
    IException calling "Add" with "1" argument(s): "Input array is longer than the number of columns in this table."
At C:\b.ps1:54 char:26
+ [void]$datatable.Rows.Add <<<< ($line.Split($delimiter))
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

So I checked the same code with small 3 line csv and all of the columns match and also have header in first row and there are no extra delimiters not sure why I am getting this error.
The code is below
<# 8-faster-runspaces.ps1 #>
# Set CSV attributes
$csv = "M:\d\s.txt"
$delimiter = "`t"

# Set connstring
$connstring = "Data Source=.;Integrated Security=true;Initial Catalog=PresentationOptimized;PACKET SIZE=32767;"

# Set batchsize to 2000
$batchsize = 2000

# Create the datatable
$datatable = New-Object System.Data.DataTable

# Add generic columns
$columns = (Get-Content $csv -First 1).Split($delimiter)
foreach ($column in $columns) {
[void]$datatable.Columns.Add()
}

# Setup runspace pool and the scriptblock that runs inside each runspace
$pool = [RunspaceFactory]::CreateRunspacePool(1,5)
$pool.ApartmentState = "MTA"
$pool.Open()
$runspaces = @()

# Setup scriptblock. This is the workhorse. Think of it as a function.
$scriptblock = {
   Param (
[string]$connstring,
[object]$dtbatch,
[int]$batchsize
   )

$bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($connstring,"TableLock")
$bulkcopy.DestinationTableName = "abc"
$bulkcopy.BatchSize = $batchsize
$bulkcopy.WriteToServer($dtbatch)
$bulkcopy.Close()
$dtbatch.Clear()
$bulkcopy.Dispose()
$dtbatch.Dispose()
}

# Start timer
$time = [System.Diagnostics.Stopwatch]::StartNew()

# Open the text file from disk and process.
$reader = New-Object System.IO.StreamReader($csv)

Write-Output "Starting insert.."
while ((($line = $reader.ReadLine()) -ne $null))
{
[void]$datatable.Rows.Add($line.Split($delimiter))

if ($datatable.rows.count % $batchsize -eq 0)
{
   $runspace = [PowerShell]::Create()
   [void]$runspace.AddScript($scriptblock)
   [void]$runspace.AddArgument($connstring)
   [void]$runspace.AddArgument($datatable) # <-- Send datatable
   [void]$runspace.AddArgument($batchsize)
   $runspace.RunspacePool = $pool
   $runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }

   # Overwrite object with a shell of itself
  $datatable = $datatable.Clone() # <-- Create new datatable object
}
}

# Close the file
$reader.Close()

# Wait for runspaces to complete
while ($runspaces.Status.IsCompleted -notcontains $true) {}

# End timer
$secs = $time.Elapsed.TotalSeconds

# Cleanup runspaces
foreach ($runspace in $runspaces ) {
[void]$runspace.Pipe.EndInvoke($runspace.Status) # EndInvoke method retrieves the results of the asynchronous call
$runspace.Pipe.Dispose()
}

# Cleanup runspace pool
$pool.Close()
$pool.Dispose()

# Cleanup SQL Connections
[System.Data.SqlClient.SqlConnection]::ClearAllPools()

# Done! Format output then display
$totalrows = 1000000
$rs = "{0:N0}" -f [int]($totalrows / $secs)
$rm = "{0:N0}" -f [int]($totalrows / $secs * 60)
$mill = "{0:N0}" -f $totalrows

Write-Output "$mill rows imported in $([math]::round($secs,2)) seconds ($rs rows/sec and $rm rows/min)"

A: Working with a 160 GB input file is going to be a pain. You can't really load it into any kind of editor - or at least you don't really analyze such a data mass without some serious automation.
As per the comments, it seems that the data has some quality issues. In order to find the offending data, you could try binary searching. This approach shrinks the data fast. Like so,
1) Split the file in about two equal chunks.
2) Try and load first chunk.
3) If successful, process the second chunk. If not, see 6).
4) Try and load second chunk.
5) If successful, the files are valid, but you got another a data quality issue. Start looking into other causes. If not, see 6).
6) If either load failed, start from the beginning and use the failed file as the input file.
7) Repeat until you narrow down the offending row(s).

Another a method would be using an ETL tool like SSIS. Configure the package to redirect invalid rows into an error log to see what data is not working properly.


text:
Q: Jest Setup with Next.js fails after it seems to add a react import to index.test.js Hi I have been stewing over this for the last couple of days. I realise this is a common error with various solutions.
I have the dreaded:
Jest encountered an unexpected token
/__tests__/index.test.js:16
    import React from "react";
    ^^^^^^
SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)

I have read a few posts and the docs in next and jest.
package.json:
    {
  "name": "some-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest --watch"
  },
  "dependencies": {
    "next": "12.1.6",
    "react": "18.1.0",
    "react-dom": "18.1.0"
  },
  "devDependencies": {
    "@babel/plugin-syntax-jsx": "^7.17.12",
    "@babel/preset-env": "^7.18.2",
    "@babel/preset-react": "^7.17.12",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@types/jest": "^28.1.3",
    "@types/node-fetch": "^2.6.2",
    "babel-jest": "^28.1.1",
    "eslint": "8.16.0",
    "eslint-config-next": "12.1.6",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^28.1.1",
    "jest-environment-jsdom": "^28.1.1",
    "node-fetch": "^3.2.6",
    "ts-jest": "^28.0.5",
    "typescript": "^4.7.4"
  },
  "description": "This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).",
  "main": "jest.config.js",
  "repository": {
    "type": "git",
  },
  "author": "",
  "license": "ISC",
  "bugs": {
  },
}

index.test.js:
import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
import '@testing-library/jest-dom'
import React from "react";

describe('Home', () => {
  it('renders a h', () => {
    render(<Home />)

    const link = screen.getByRole('link', {
      name: "Library",
    })

    expect(link).toHaveAttribute('href', '/storage-area')
  })
});

jest.config.js:
module.exports = {
  collectCoverage: true,
  // on node 14.x coverage provider v8 offers good speed and more or less good report
  coverageProvider: 'v8',
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
    '!<rootDir>/out/**',
    '!<rootDir>/.next/**',
    '!<rootDir>/*.config.js',
    '!<rootDir>/coverage/**',
  ],
  moduleNameMapper: {
    // Handle CSS imports (with CSS modules)
    // https://jestjs.io/docs/webpack#mocking-css-modules
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

    // Handle CSS imports (without CSS modules)
    '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',

    // Handle image imports
    // https://jestjs.io/docs/webpack#handling-static-assets
    '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/__mocks__/fileMock.js`,

    // Handle module aliases
    '^@/components/(.*)$': '<rootDir>/components/$1',
  },
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  testEnvironment: 'jsdom',
  transform: {
    // Use babel-jest to transpile tests with the next/babel preset
    // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
    '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel', '@babel/preset-react',"@babel/preset-env" ]}],
  },
  transformIgnorePatterns: [
    '/node_modules/',
    '^.+\\.module\\.(css|sass|scss)$',
  ],
}

As I mentioned in the title the it seems that the error message suggests that the import is added by Next.js to the end of the index.test.js.

A: This was a problem due to the tests folder being nested in the directory above the root directory of the project. By the time I figured this out I had manipulated the jest.config.js transform: presets array property to contain imports that it didn't require in the standard jest/next setup.


text:
Q: Show that $ \frac{x^2}{(x^2+y^2)^{3/4}} $ is continuous on $\mathbb{R}^2$. I tried with polar coordinates, I found the limit is infinite (which is not true the graph show it's 0). I tried to majorate with something who has for limit 0 but still impossible.
with polar coordinates :
For $r > 0$ and $t \in [0,2\pi[ $, let $x=r\cos(t)$ and $y=r\sin(t)$, we have $$\frac{x^2}{(x^2+y^2)^{3/4}}=\frac{r^2\cos(t)^2}{(r^2\cos(t)^2+r^2\sin(t)^2)^{3/4}}=\frac{r^2\cos(t)^2}{(r^2)^{3/4}}=\frac{r^2}{r^{6/4}}\cos(t)^2=\sqrt{r}\cos(t)^2$$

A: As suggested by @MartinR, consider the inequality $x^{2} \leq x^{2} + y^{2}$ and apply the squeeze theorem:
\begin{align*}
0\leq \frac{x^{2}}{(x^{2} + y^{2})^{3/4}} \leq \frac{x^{2} + y^{2}}{(x^{2} + y^{2})^{3/4}} = (x^{2} + y^{2})^{1/4} \xrightarrow[]{(x,y)\to(0,0)} 0
\end{align*}
Hopefully this helps!


text:
Q: PHP preg_match_all search and replace I have tried about a million different regexes and I just can't wrap my head around this one (admittedly a lot of regex is out of my grasp).
In my text I have variables like this:
{{$one}}
{{$three.four.five}}
{{$six.seven}}

And I have an array with all the replaces for them (the index for 'one' is 'one' etc) but some may be missing.
I want to replace from the array if it exists and if not leave the text alone.
What regex can I use to preg_match_all of the variables in $text in the snippet below, replace from $replace where appropriate and echo out to the browser?
<?php
    $replaces = array('testa.testb.testc' => '1', 'testc.testa' => '2', 'testf' => '3');
    $text = '{{$testa.testb.testc}}
{{$testc.testa}}
{{$testf}}
{{$aaaaa}}
';

    preg_match_all('/\{\{\$(\w+)\}\}/e', $text, $matches);

    foreach($matches as $match)
    {
        $key = str_replace('{{$', '', $match);
        $key = str_replace('}}', '', $key);

        if(isset($replaces[$key]))
            $text = str_replace($match, $replaces[$key], $text);
    }

    // I want to end up echo'ing:
    //   1
2
3
{{$aaaaa}}

    echo $text;
?>

http://codepad.viper-7.com/4INvEE
This:
'/\{\{\$(\w+)\}\}/e'

like in the snippet, is the closest I have gotten.
It has to work with the does in the variable names too.
Thanks in advance for all the help!

A: This is a very good case for using preg_replace_callback() but first let's polish your regex:

*

*Get rid of the e modifier, it's deprecated and you don't need it since we're going to use preg_replace_callback()
/\{\{\$(\w+)\}\}/

*We don't need to escape {{}} in this case, PCRE is smart enough to tell that they are not meant as quantifiers
/{{\$(\w+)}}/

*Since you got dots in your input, we need to change \w otherwise it will never match. [^}] is perfect since it means match anything except }
/{{\$([^}]+)}}/

*I tend to use different delimiters, this is not required:
#{{\$([^}]+)}}#

Let's get to serious business, the use identifier is going to be of great help here:
$replaces = array('testa.testb.testc' => '1', 'testc.testa' => '2', 'testf' => '3');
$text = '{{$testa.testb.testc}}
{{$testc.testa}}
{{$testf}}
{{$aaaaa}}
';

$output = preg_replace_callback('#{{\$([^}]+)}}#', function($m) use ($replaces){
    if(isset($replaces[$m[1]])){ // If it exists in our array
        return $replaces[$m[1]]; // Then replace it from our array
    }else{
        return $m[0]; // Otherwise return the whole match (basically we won't change it)
    }
}, $text);

echo $output;

Online regex demo
Online php demo

A: Well you are just using $matches and not $matches[0], that's why the code you posted does not work.
And your regex doesn't count the . with the \w, so let'z try with [\w.]+
(I used $matches[1] that contains directly the key we need, and then we don't need to use str_replace 2 times more)
$replaces = array('testa.testb.testc' => '1', 'testc.testa' => '2', 'testf' => '3');
$text = '{{$testa.testb.testc}}
{{$testc.testa}}
{{$testf}}
{{$aaaaa}}
';

preg_match_all('/\{\{\$([\w.]+)\}\}/', $text, $matches);

var_dump($matches[1]);

foreach($matches[1] as $match)
{
    if(isset($replaces[$match]))
    {
        $text = str_replace('{{$'.$match.'}}', $replaces[$match], $text);
    }
}

echo $text;

This works and returns :
1
2
3
{{$aaaaa}}

A: You don't need to use a regex for that since you are only dealing with fixed strings:
$replaces = array('testa.testb.testc' => 1, 'testc.testa' => 2, 'testf' => 3);
$keys = array_map(function ($item) {
    return '{{$' . $item . '}}'; }, array_keys($replaces));
$trans = array_combine($keys, $replaces);

$result = strtr($text, $trans);

Note that array_map is not needed if you write the replaces array like this:
$trans = array('{{$testa.testb.testc}}' => 1, '{{$testc.testa}}' => 2, '{{$testf}}' => 3);

A: You can also use T-Regx library which has automatic delimiters.
Use replace()->by()->mapIfExists():
$output = pattern('{{\$([^}]+)}}')
    ->replace('{{$testa.testb.testc}}
{{$testc.testa}}
{{$testf}}
{{$aaaaa}}
')
    ->all()
    ->by()
    ->group(1)
    ->mapIfExists([
       'testa.testb.testc' => '1',
       'testc.testa' => '2',
       'testf' => '3'
    ]);
});

echo $output;

This code does exactly what @HamZa answer's, but with T-Regx :)


text:
Q: Sort list of dictionaries in Python according to another list I have a list of dictionaries:
a = [{"id": 5, "data": "data1"}, {"id": 2, "data": "data2"}, {"id": 10, "data": "data3"}, {"id": 121, "data": "data4"}]

and a list of IDs:
ids_order = [10, 2, 5, 121]

I would like to reorder my list of dictionaries a so that my new list new_a have its dictionaries with value of the key "id" following the list ids_order:
new_a = [{"id": 10, "data": "data3"}, {"id": 2, "data": "data2"}, {"id": 5, "data": "data1"}, {"id": 121, "data": "data4"}]

Is there an efficient way to do it with the sort function? So far I am making a double loop to get the correct element, which is not especially the best. However, I couldn't find anything that could match with the sort function.

A: you can make a temporary mapping temp of ids to dictionary which can later be used to select according to the given order.
temp = {d["id"]: d for d in a}
new_a = [temp[i] for i in ids_order]
print(new_a)

Output:
[{'id': 10, 'data': 'data3'}, {'id': 2, 'data': 'data2'}, {'id': 5, 'data': 'data1'}, {'id': 121, 'data': 'data4'}]

A: ids_order = [10, 2, 5, 121]
int_order = [a[i]['id'] for i in range(4)]
ind_change = [int_order.index(ids_order[i]) for i in range(4)]

new_a = [a[i] for i in ind_change]
print(new_a)

A: I solved the problem by making a nested comprehension list. It works, though I don't know if it's scalable with big lists.
new_a = [[feat for feat in a if feat["id"] == i][0] for i in ids_order]

Note: there's the [0] to avoid a list of list.


text:
Q: Second order non linear ODE - hard to solve integral makes me think I need a different substitution I have this here ODE:
$$xy'' = y' + x((y')^2 + x^2)$$
Naturally, I'd try this substitution first: $$y' = p, p=p(x)$$
The equation then transforms into $$xp' = p+x(p^2+x^2)$$
Dividing it by $x$, I get
$$p' = \frac{p}{x} + p^2 + x^2$$
Which is a Riccati equation with the solution: $$p = x \cdot \tan{(\frac{x^2}{2}+C_1)}$$
The thing is, if I substitute back $y'=p$, the integral on the right side is not an easy one to solve, and even if I do solve it with WolframAlpha the solutions are not the same as if I plug in the second-order equation directly. It makes me wonder if I should have tried another substitution/method.
Any help will be appreciated!

A: $$y' = x \cdot \tan{\left(\frac{x^2}{2}+C\right)}$$
$$\dfrac {dy}{du}\dfrac {du}{dx} = x \cdot \tan(u)$$
$$\dfrac {dy}{du} =  \tan(u)$$
Where $u=\dfrac {x^2}{2}+C$ then integrate.
$$y=-\ln |\cos u |+K$$

A: You have now a formula of the form
$$
y'(x)=f(u(x))u'(x)
$$
with $f(u)=\tan(u)$ and $u(x)=\frac{x^2}2+c$. This the gives that
$$
y(x)=F(u(x))+d,
$$
where $F'=f$, here $F(u)=-\ln|\cos(u)|$

A: Let $y'=xz$. The equation becomes
$$xz+x^2z'=xz+x(x^2z^2+x^2),$$ which is separable:
$$\frac{z'}{z^2+1}=x$$ or $$\arctan z=\frac{x^2}2+c$$ and $$y'=x\tan\left(\frac{x^2}2+c\right)$$ as you found.

Now the integral is not difficult:
$$\int x\tan\left(\frac{x^2}2+c\right)dx=\int \tan\left(u+c\right)du=-\log(\cos(u+c))+c'\\
=-\log\left(\cos\left(\frac{x^2}2+c\right)\right)+c'.$$


text:
Q: How to convert a var which contains Long to an Long[] I have the following:
var resourceids = racks.Select(a => a.Technology.IT360ID.Value);
var resource = repository.GetResources(resourceids);

But i am not sure how i can convert the var resourceids to long[] as my repository method accept long[]

A: Assuming a.Technology.IT360ID.Value is a long then resourceids is actually an IEnumerable<long>.  So you just need to convert it using ToArray():
var resourceids = racks.Select(a => a.Technology.IT360ID.Value).ToArray();
var resource = repository.GetResources(resourceids);

Remember that var is not a "type" - it just lets the compiler determine the type versus declaring it explicitly.
This may be a case where it's better to explicitly declare the type versus using var:
long[] resourceids = racks.Select(a => a.Technology.IT360ID.Value).ToArray();
var resource = repository.GetResources(resourceids);

A: The method Select will return IEnumerable<long>. So, to convert to long[], you can call ToArray() which forces immediate query evaluation and returns an array that contains the query results:
var resourceids = racks.Select(a => a.Technology.IT360ID.Value)
                       .ToArray();

var resource = repository.GetResources(resourceids);


text:
Q: Could you help me set up my CI URI routing? I can't seem to get my routing to work correctly. Right now to reach my main page I need to go to www.website.com/core I would like this to be only website.com to get to the core.
The second issue I am having is I con not being able to retrieve any css and other files stored in the assets folder. Could you please take a look at my configs and tell me which parts I should adjust? I don't even mind moving the assets folder to a different place on the server, I just really want to get this to work.
the hierarchy on to access CI is as follows
(root)/www/application/OBS/controllers...

My css, js and other assets are stored in
(root)/www/assets/OBS/css/style.css... //example rout to css

In CI I am trying to use
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/OBS/css/core_css.css" />

to link the styles and assets and
<a href="<?php echo base_url('detail/'$id) ?>">

to link to functions from views
My htaccess looks like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]

In the CI's config I have set the following:
$config['base_url'] = 'website.com/core'; //core is used as home/main
$config['index_page'] = '';

And finally in the CI's index.php I have set:
$application_folder = 'application/OBS';

Thank you all for reading and in advance for your replies.

A: Try this ,
set your base_url to website.com only
//application/config/config.php
$config['base_url'] = 'website.com';

Then on routes set the default controller to core
//application/config/routes.php
$route['default_controller'] = "core";


text:
Q: Is distance preserved in sublattices? Let $L$ be a locally finite (every interval in $L$ is finite) and graded (there exists a rank function $\rho:L\rightarrow \mathbb{Z}$ such that $\rho(x)=\rho(y)+1$ whenever $x$ covers $y$) lattice.
Is it true that for every finite (induced) sublattice $S$ of $L$ ($S$ preserves the meet and join of $L$) the distance between vertices in the (underlying undirected graph of the) Hasse diagram of $S$ is equal to the distance between them in the Hasse diagram of $L$?
A simple proof/counter example would be appreciated.
Edit:
As @William Elliot answered below, a sublattice does not preserve distances, I intended $S$ to be convex...
Let $S$ be some interval $[u,v]$ in $L$ (it can be shown that it is a sublattice as needed).
Is the distance preserved in this case?

A: Consider the lattice 0 < a,b < 1 and the sublattice {0,1}.


text:
Q: How to change row/column states with animation in Flutter? I am using rows and columns in my layout and load some data from the internet to display information inside my rows and columns.
I want to design a dynamic loading page in such a way that every loaded data makes a particular widget visible with an animation (by moving the other widgets around smoothly).
I am currently using if clauses inside my layouts and calling setState() when new data is retrieved.
Column(
  children: [
    SomeWidget(),
    if (data != null)
      DataWidget(),
    AnotherWidget(),
  ],
),

How can I insert widgets between other widgets in rows/columns with animation after some data is retrieved?

A: Flutter already has tons of useful widgets which you can use for this implementation. I believe that the AnimatedList widget solves your problem. I have added the widget of the week video and a basic example below.
Widget of the Week - AnimatedList
Example:
import 'package:flutter/material.dart';

class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  /// The global key to access the animated list.
  final _animatedListKey = GlobalKey<AnimatedListState>();

  List<String> _items = [];

  @override
  void initState() {
    // Set the items that should be display.
    _items = ['A', 'B', 'D', 'E', 'F'];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Example')),
      body: AnimatedList(
        key: _animatedListKey,
        initialItemCount: _items.length,
        itemBuilder: (context, index, animation) {
          return SlideTransition(
            position: animation.drive(
              // Tween that slides from right to left.
              Tween(begin: Offset(1.0, 0.0), end: Offset(0.0, 0.0)),
            ),
            // Simply display the letter.
            child: ListTile(title: Text(_items[index])),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          // The item to insert.
          final _item = 'C';

          // Add, sort, and retrieve the index of the inserted item.
          List<String> _temp = _items..add(_item);
          _temp.sort();
          final _index = _temp.indexOf(_item);

          // Update the state and start the animated list animation.
          setState(() {
            _items.insert(_index, _item);
            _animatedListKey.currentState?.insertItem(_index);
          });
        },
      ),
    );
  }
}

A: you can always use AnimatedSwitcher to animate between widgets, just setState and change _widget:
AnimatedSwitcher(
  duration: Duration(milliseconds: 200),
  transitionBuilder: (Widget child, Animation<double> animation) {
    var tween=Tween<Offset>(begin: Offset(1, 0), end: Offset(0, 0))
     return SlideTransition(
       child: child,
       position: tween.animate(animation),
    );
  },
  child: _widget,
)

OR using flutter_staggered_animations with Column & Row showing animation
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: AnimationLimiter(
          child: Column(
            children: AnimationConfiguration.toStaggeredList(
              duration: const Duration(milliseconds: 375),
              childAnimationBuilder: (widget) => SlideAnimation(
                horizontalOffset: 50.0,
                child: FadeInAnimation(
                  child: widget,
                ),
              ),
              children: YourColumnChildren(),
            ),
          ),
        ),
      ),
    );
  }


text:
Q: Valgrind memory deallocation I have been working on a school project and I seem to be not correctly deallocating all memory. I don't know where I missed to use free.
My code looks like this
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAXFILENAME 20

typedef struct tNode{
        int Deg;
        int Val;
        int* Neigh;
} *tNodePtr;

typedef struct tGraph{
        int Num;
        tNodePtr* Nodes;
} *tGraphPtr;

void GInit(tGraphPtr G, const char *FNum)
{
        char FileName[MAXFILENAME];
        char *FileNamePrefix = "Graph";
        char *FileNamePostfix = ".txt";
        FILE *FilePtr;
        int FileBrowser;
        int i, j, k, countNeigh;
        char *line;
        char c;

        strcpy(FileName, FileNamePrefix);
        strcat(FileName, FNum);
        strcat(FileName, FileNamePostfix);

        FilePtr = fopen(FileName, "r");

        if(!FilePtr)
                printf("Can't open file \"%s\"\n", FileName);
        else
        {
                if(!fscanf(FilePtr, "%d", &FileBrowser))
                        printf("fscanf error 1!\n");

                G->Num = FileBrowser;
                G->Nodes = malloc(G->Num * sizeof *(G->Nodes));
                if(G->Nodes == NULL)
                {
                        printf("Memory allocation error 1!\n");
                        return;
                }

                for(i = 0; i < G->Num; i++)
                {
                        G->Nodes[i] = malloc(sizeof *(G->Nodes[i]));
                        if(G->Nodes[i] == NULL)
                        {
                                printf("Memory allocation error 2!\n");
                                return;
                        }
                }

                line = malloc((2*G->Num + 1) * sizeof *line );
                if(line == NULL)
                {
                        printf("Memory allocation error 3!\n");
                        return;
                }

                i = 0;
                if(!fscanf(FilePtr, "%c", &c))
                        printf("fscanf error 2!\n");

                while(!feof(FilePtr))
                {
                       if(fgets(line, 2*G->Num + 1, FilePtr) == NULL)
                         printf("fgets error 1!\n");

                        countNeigh = 0;
                        j = 0;
                        while(line[j] != '\0')
                        {
                                if(line[j] == '1')
                                        countNeigh++;
                                j++;
                        }
                        G->Nodes[i]->Deg = countNeigh;
                        G->Nodes[i]->Val = i;
                        G->Nodes[i]->Neigh = malloc(countNeigh * sizeof *(G->Nodes[i]->Neigh));
                        if(G->Nodes[i]->Neigh == NULL)
                        {
                                printf("Memory allocation error 4!\n");
                                return;
                        }

                        j = 0;
                        k = 0;
                        while(line[j] != '\0')
                        {
                                if(line[j] == '1')
                                {
                                        G->Nodes[i]->Neigh[k] = j/2;
                                        k++;
                                }
                                j++;
                        }

                        i++;
                }

                free(line);
        }

        fclose(FilePtr);
}

void GPrint(const tGraphPtr G)
{
        int j, k;
        int i;

        printf("Graph demonstration:\n");
        for(j = 0; j < G->Num; j++)
        {
                printf("I'm Node: %d , my degree is: %d and my neighbours are:\t", G->Nodes[j]->Val, G->Nodes[j]->Deg);
                for(k = 0; k < G->Nodes[j]->Deg; k++)
                        printf("%3d", G->Nodes[j]->Neigh[k]);
                printf("\n");
        }

        for(i = 0; i < G->Num; i++)
        {
                free (G->Nodes[i]->Neigh);
                free (G->Nodes[i]);
        }

        free (G->Nodes);
}

void GDelete(tGraphPtr G)
{

}

int main(int argc, char *argv[])
{

        tGraphPtr TmpGraph;
        char *FNum;
        FNum = "1";

        TmpGraph = malloc(sizeof *TmpGraph);
        if(TmpGraph == NULL)
        {
                printf("Memory allocation error 5!\n");
                return -1;
        }

        GInit(TmpGraph, FNum);

        GPrint(TmpGraph);

        free (TmpGraph);

        return(0);
}

Memory leakage reported by Valgrind:
eva ~/Algoritmy/Euler> gcc -g Euler.c -o Euler
Euler.c:166:2: warning: no newline at end of file
eva ~/Algoritmy/Euler>  valgrind --leak-check=yes --show-reachable=yes  ./Euler
==39575== Memcheck, a memory error detector
==39575== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==39575== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==39575== Command: ./Euler
==39575==
Graph demonstration:
I'm Node: 0 , my degree is: 2 and my neighbours are:      1  3
I'm Node: 1 , my degree is: 4 and my neighbours are:      0  2  4  5
I'm Node: 2 , my degree is: 4 and my neighbours are:      1  3  4  5
I'm Node: 3 , my degree is: 2 and my neighbours are:      0  2
I'm Node: 4 , my degree is: 2 and my neighbours are:      1  2
I'm Node: 5 , my degree is: 2 and my neighbours are:      1  2
==39575==
==39575== HEAP SUMMARY:
==39575==     in use at exit: 4,096 bytes in 1 blocks
==39575==   total heap usage: 17 allocs, 16 frees, 37,101 bytes allocated
==39575==
==39575== 4,096 bytes in 1 blocks are still reachable in loss record 1 of 1
==39575==    at 0x100688B: malloc (in /usr/local/lib/valgrind/vgpreload_memcheck-amd64-freebsd.so)
==39575==    by 0x130CC7A: ??? (in /lib/libc.so.7)
==39575==    by 0x130CB34: ??? (in /lib/libc.so.7)
==39575==    by 0x130C81D: ??? (in /lib/libc.so.7)
==39575==    by 0x12E1538: puts (in /lib/libc.so.7)
==39575==    by 0x400DA5: GPrint (Euler.c:122)
==39575==    by 0x400F44: main (Euler.c:161)
==39575==
==39575== LEAK SUMMARY:
==39575==    definitely lost: 0 bytes in 0 blocks
==39575==    indirectly lost: 0 bytes in 0 blocks
==39575==      possibly lost: 0 bytes in 0 blocks
==39575==    still reachable: 4,096 bytes in 1 blocks
==39575==         suppressed: 0 bytes in 0 blocks
==39575==
==39575== For counts of detected and suppressed errors, rerun with: -v
==39575== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The file Graph1.txt I am reading from is an incidence matrix with number of nodes at the beginning. There is no newline character on the end.
6
0 1 0 1 0 0
1 0 1 0 1 1
0 1 0 1 1 1
1 0 1 0 0 0
0 1 1 0 0 0
0 1 1 0 0 0

Thank you for advice.
John.

A: I am pretty sure this is an internal buffer used by printf() and is nothing to worry about (and is certainly not a problem with your code).
See this for a detailed explanation of what "still reachable" means in valgrind.


text:
Q: intersection between exponential and polylogarithmic functions It's possible to solve this equation without using Lambert function or any numerical method, but only with ordinary algebra?
$n^{k}lg_2(n) \le k^n$ with $k,n>0, k \in \mathbb{R}$
For $k=\frac{4}{3}$, the calculator says that the solution is $n \ge 22.78$, but I need to prove it, and I'm stuck applying properties of exponential and logarithmic functions.

A: I can squeeze you a small solution under a more restricted value of $k$. Perhaps you can use this to satisfy yourself in the general problem. I found it irritating to manage the case when $0 < k < 1$ but I am sure you can use my method below to whip something up.
For a given $k \geq 1$, and assume $n \geq 1$, we have $k \leq k^n$ so if we can satisfy $n^k \log_2(n) \leq k$ we can definitely satisfy the original inequality. Additionally, $n^k \log_2(n) \leq n^{k+1}$ whenever $\log_2(n) \leq n$ (which is always when $n > 0$). So if we can solve $n^{k+1} \leq k$ then we can definitely solve the original inequality. If we take the base-$k$ logarithm of both sides we get $(k+1) \log_k(n) \leq 1$, or
$$\log_k(n) \leq \frac{1}{k+1} \\
n \leq k^{\frac{1}{k+1}}$$
For instance, if $k=\frac{4}{3}$ then $\frac{4}{3}^{\frac{3}{4}} > 1.2$ and we can set $n = \frac{6}{5}$.


text:
Q: Returning a list of keys with ModelState errors How can I return a list/array of all keys that have an error?
I have tried to do the below, but it says I can't have that sort of expression for some reason.
ModelState.ToList(item => item.Value.Errors.Count > 0)

A: var errors = from modelstate in ModelState.AsQueryable().Where(f => f.Value.Errors.Count > 0) select new  {  Title = modelstate.Key  };

A: Count is a method. You need ()s after is. But I'd prefer Any, anyway:
from item in ModelState
where item.Value.Errors.Any()
select item.Key


text:
Q: Karaf Cellar: Issue installing Kar file -> Maven can not find artifact Currently, I have two cellar nodes, with the same configuration in the same group.
I configured maven in the node A with a local repository in my network, reachable for both nodes. For this, I edited "org.ops4j.pax.url.mvn.localRepository" in the file "/karaf/etc/org.ops4j.pax.url.mvn.cfg".
Then I try to install a Kar file in the cluster through following command:
cluster:kar-install [group] [path_to_kar_file]

All the features and bundles are installed in noda A without problems. But node B has problems somehow finding the artifact:
CELLAR FEATURE: failed to add repository URL mvn:com.myproject/myproject-feature-cluster/3.5.0-SNAPSHOT/xml/features.
java.io.IOException: Error resolving artifact com.myproject:myproject-feature-cluster:xml:features:3.5.0-SNAPSHOT:
    [Could not find artifact com.myproject:myproject-feature-cluster:xml:features:3.5.0-SNAPSHOT in defaultlocal (file:////WL300348/Users/zunigal/eRVS/m2/repository/), Could not find artifact com.myproject:myproject-feature-cluster:xml:features:3.5.0-SNAPSHOT in sonatype.snapshots.deploy (https://oss.sonatype.org/content/repositories/snapshots/),
    Could not find artifact com.myproject:myproject-feature-cluster:xml:features:3.5.0-SNAPSHOT in ops4j.sonatype.snapshots.deploy (https://oss.sonatype.org/content/repositories/ops4j-snapshots/),
    Could not find artifact com.myproject:myproject-feature-cluster:xml:features:3.5.0-SNAPSHOT in spring-ebr-repository (http://repository.springsource.com/maven/bundles/external/)

I also tried adding the localRepository in the list of org.ops4j.pax.url.mvn.repositories but nothing changed.
Karaf Version: 4.1.5
Cellar Version: 4.1.3

A: you can use Apache Karaf Cave on Node A and create a repository which will be available via http as well. Afterwards, you can add new repository url in your Node B configuration. When you install a new bundle/feature then cellar will download from new repository on Node B.


text:
Q: Discord window.localStorage is undefined. How to get access to the localStorage on Discord page? When I run window.localStorage on https://stackoverflow.com it returns the localStorage but when I use the same command on Discord page it returns undefined every time.
Is there something that Discord is doing to remove their localStorage from the client side? And if so, is there a way to change the localStorage before it is removed, prevent it from being removed or any other way to somehow access it before it is undefined?
Anything help?

A: Like user AkiraMiura has already mentioned - "Discord" page developers had deleted the window.localStorage property. They had done it like follows (citate from Reddit post):

How does Discord hide localStorage?
  ....
(function()
{
    var privateLocalStorage = window.localStorage;
    delete window.localStorage;
    console.log(privateLocalStorage);
}());
console.log(window.localStorage); //undefined

They create a closure where all of their local storage operations are and copy localStorage to a variable and then delete the object from the window.

But we can use localStorage from iframes
If you want to restore use the localStorage on Discord page then you can take it from a new iframe with iframe.src = 'about:blank'; This gives you the possibility to work with stored items for "Discord" page. You could write:
window.localStorage = iframe.contentWindow.localStorage;

after iframe load, but this localStorage object is from iframe and because of this you do not need to write it so - better is like in my code below.
The following code you can put on "Discord" page in developer console and you will get in console output something like this:

"45235333...WKDrSWDKIS"

Do not forget to login on "Discord" page before! (you don't need to have to be logged in on this page even).
Code
var iframe = document.createElement('iframe');
iframe.onload = function()
{
    //Iframes must be appended to the DOM in order to be loaded
    //Iframes do not load immediately nor synchronously
    //now (after load) we can use iframe.contentWindow:
    //window.localStorage = iframe.contentWindow.localStorage; //you can use it, but better is like:
    var ifrLocalStorage = iframe.contentWindow.localStorage;
    //But DO NOT: "document.body.removeChild(iframe);" because after it access on 'Storage' will be denied
    console.log(ifrLocalStorage.getItem('fingerprint'));
    //OUTPUT: "45235333...WKDrSWDKIS"
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);

Good luck!

A: You can still obtain access programmatically. They've deleted window.localStorage. This is an own-property of window instances, but it's not a data property, it's an accessor. The accessor's get function will return the localStorage value associated with any appropriate receiver (this arg)*. Deleting the localStorage accessor has no impact on whether the object itself exists, so all you'll need to do to access it again is find another get localStorage() function. Fortunately, you can obtain one many ways — every Window object gets created with one.
// If we create an <iframe> and connect it to our document, its
// contentWindow property will return a new Window object with
// a freshly created `localStorage` property. Once we obtain the
// property descriptor, we can disconnect the <iframe> and let it
// be collected — the getter function itself doesn't depend on
// anything from its origin realm to work**.

function getLocalStoragePropertyDescriptor() {
  const iframe = document.createElement('iframe');
  document.head.append(iframe);
  const pd = Object.getOwnPropertyDescriptor(iframe.contentWindow, 'localStorage');
  iframe.remove();
  return pd;
}

// We have several options for how to use the property descriptor
// once we have it. The simplest is to just redefine it:

Object.defineProperty(window, 'localStorage', getLocalStoragePropertyDescriptor());

window.localStorage.heeeeey; // yr old friend is bak

// You can also use any function application tool, like `bind` or `call`
// or `apply`. If you hold onto a reference to the object somehow, it
// won't matter if the global property gets deleted again, either.

const localStorage = getLocalStoragePropertyDescriptor().get.call(window);

If this is an arms race thing, the party interested in hiding localStorage could attempt patching every method and accessor throughout the DOM that could return a reference to a window object whose localStorage property has not already been deleted. That's harder to do than might be obvious. Even if they succeeded, though, the final word will remain on the user side: a browser extension's manifest can declare a content script that will be evaluated before any other code when the document loads. Even a CSP can't prevent it. (On one hand this sucks ... on the other, without that capability, adblocking extensions could never work.)
The Storage API, whether sessionStorage or localStorage, isn't meant for holding sensitive data. It's not protected at all. An attempt to hide it is a hint that it may be getting misused — you might want to be careful about entering sensitive data on that site if its authors are under the impression that deleting the property is providing some kind of security.

* An appropriate receiver here would be any window object that hasn't had storage disabled by the user (e.g. Safari incognito) and which has a 'non-opaque' origin (meaning for example that it doesn't work in the browser's about:blank page, since storage needs to be associated with a normal origin).
Aside: bonus curio regarding global branded attributes.
** It doesn't depend on its origin realm normally, anyway. Properties created from Web IDL attributes on [Global] interfaces can exhibit a unique behavior when the receiver is null or undefined, though, where the origin realm can become significant. If we were to call the get function with no receiver, e.g.
const { get } = getLocalStoragePropertyDescriptor();
get(); // ... null?

...then it would, instead of throwing a TypeError like is typical, return null. In fact, all platform attributes, not just those on [Global] interfaces, have a default receiver. The default receiver, which kicks in if the given receiver is null or undefined, is the global object of the realm where the function was created. What's different for the [Global] case is that this default can actually be, and usually is, a valid receiver — i.e. it can be an object that really does implement the interface whose attribute this is (any other functions would still end up throwing the same TypeError, so you'd never know about this default receiver).
In that example, it defaults to the window object from the original iframe. It tries to grab its localStorage object, but because the iframe is long gone, it instead returns null. I'm not actually sure where that last behavior is specified. I'm guessing it's not specified, actually, since it contradicts the IDL definition for the attribute. It makes sense though (it's gotta do something), and it's what Chrome does. In Firefox, attempting this leads to an internal engine error, suggesting this edge case might just not have gotten a lot of consideration.

A: Found on reddit. TL;DR, they move their window.localStorage to another variable then delete window.localStorage.
One way I found to get the localStorage (Although Manually) is as follows:
1: goto %AppData%/discord/Local Storage/
2: open https_discordapp.com_0.localstorage in SQLite Studio
3: goto https_discordapp.com_0 > Tables > ItemTable and double click it.
4: under the Data tab double click a value and read/convert the hex data removing every other 00 hex.


text:
Q: Is there a way to use JSONP with a Delphi DataSnap REST server? It appears that there is no way to implement a JSONP (JSON with Padding) solution using DataSnap, but I want to throw this question out here in case someone has solved this problem.
Background: JSONP is a mechanism that exploits the cross site referencing capability of the HTML script element to overcome the same origin policy of the XmlHttpRequest class. Using an XmlHttpRequest you can only obtain data (JSON objects) from the same domain that served the HTML document. But what if you want to retrieve data from multiple sites and bind that data to controls in the browser?
With JSONP, your src attribute of the script element does not reference a JavaScript file, but instead references a Web method (one that can reside on a different domain from which the HTML was retrieved). This Web method returns the JavaScript.
The script tag assumes that the returned data is a JavaScript file and executes it normally. However, what the Web method actually returns is a function call with a literal JSON object as its parameter. Assuming that the function that is called is defined, the function executes and can operate on the JSON object. For example, the function can extract data from the JSON object and bind that data to the current document.
The pros and cons of JSONP have been argued extensively (it represents a very serious security problem), so it is not necessary to repeat that here.
What I am interested in is if anybody out there has figured out how to use JSONP with Delphi's DataSnap REST servers. Here's the problem, as I see it. A typical JSONP usage may include a script tag that looks something like this:
<script type="application/javascript" src="http://someserver.com/getdata?callback=workit"> </script>

The getdata Web method would return a call something like the following:
workit({"id": "Delphi Pro", "price":999});

and the workit function might look something like this:
function workit(obj) {
  $("#namediv").val(obj.id);
  $("#pricediv").val(obj.price);
}

The issue is that DataSnap does not seem capable of returning a simple string like
workit({"id": "Delphi Pro", "price":999});

Instead, it is wrapped, like the following:
{"result":["workit({\"id\":\"Delphi Pro\",\"price\":999});"]}

Clearly this is not executable JavaScript.
Any ideas?

A: There is a way in Delphi DataSnap REST methods to bypass the custom JSON processing and return exactly the JSON you want. Here is a class function I use (in my Relax framework) to return plain data to a jqGrid:
class procedure TRlxjqGrid.SetPlainJsonResponse(jObj: TJSONObject);
begin
  GetInvocationMetadata().ResponseCode := 200;
  GetInvocationMetadata().ResponseContent := jObj.ToString;
end;

Info at http://blogs.embarcadero.com/mathewd/2011/01/18/invocation-metadata/.
Info at https://mathewdelong.wordpress.com/2011/01/18/invocation-metadata/.
BTW, you can assign nil to the result of the REST function.

A: You can write a TDSHTTPServiceComponent descendant and hook it up with your instance of TDSHTTPService. In the following example an instance of TJsonpDispatcher is created at runtime (to avoid registering it in the IDE):
type
  TJsonpDispatcher = class(TDSHTTPServiceComponent)
  public
    procedure DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse;
      const ARequest: string; var AHandled: Boolean); override;
  end;

  TServerContainer = class(TDataModule)
    DSServer: TDSServer;
    DSHTTPService: TDSHTTPService;
    DSServerClass: TDSServerClass;
    procedure DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass);
  protected
    JsonpDispatcher: TJsonpDispatcher;
    procedure Loaded; override;
  end;

implementation

procedure TServerContainer.DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass);
begin
  PersistentClass := ServerMethodsUnit.TServerMethods;
end;

procedure TServerContainer.Loaded;
begin
  inherited Loaded;
  JsonpDispatcher := TJsonpDispatcher.Create(Self);
  JsonpDispatcher.Service := DSHTTPService;
end;

procedure TJsonpDispatcher.DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest;
  AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean);
begin
  // e.g. http://localhost:8080/getdata?callback=workit
  if SameText(ARequest, '/getdata') then
  begin
    AHandled := True;
    AResponseInfo.ContentText := Format('%s(%s);', [ARequestInfo.Params.Values['callback'], '{"id": "Delphi Pro", "price":999}']);
  end;
end;

A: the origin policy problem can be solved easyly in DataSnap. You can Customize the response header in this way:
procedure TWebModule2.WebModuleBeforeDispatch(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  **Response.SetCustomHeader('access-control-allow-origin','*');**
  if FServerFunctionInvokerAction <> nil then
    FServerFunctionInvokerAction.Enabled := AllowServerFunctionInvoker;
end;

A: The answer from Nicolás Loaiza motivate me to find solution for TDSHTTPService, set customer response header in Trace event:
procedure TDataModule1.DSHTTPService1Trace(Sender:
    TObject; AContext: TDSHTTPContext; ARequest: TDSHTTPRequest; AResponse:
    TDSHTTPResponse);
begin
  if AResponse is TDSHTTPResponseIndy then
    (AResponse as TDSHTTPResponseIndy).ResponseInfo.CustomHeaders.AddValue('access-control-allow-origin', '*');
end;


text:
Q: ag-grid enterprise not displaying for Angular I used ag-grid community version for Angular without no problem, then I needed to use the "tree-grid" function of the enterprise version so I installed ag-grid-enterprise, however, I never got it to work. I got a trial key, so I don't get any errors in the console.
I followed the first example here: https://www.ag-grid.com/javascript-grid-tree-data/ but the table isn't showing, it looks like this:
Tree grid
I have tried install and re-install the ag-angular, ag-community and ag-enterprise, so that this is how it looks in the package.json file.

    "ag-grid-angular": "^23.0.0",
    "ag-grid-community": "^23.0.1",
    "ag-grid-enterprise": "^23.0.1",

Has anybody else experienced a similar problem when switching to enterprise version?

A: Make sure in your AG Grid component, you import the enterprise edition.
import 'ag-grid-enterprise';


text:
Q: Multiple Tailwind config files for one NextJS Project My question is, is it possible to have two configurations(tailwind.css) for two NextJS layouts?
Basically I want a frontend-tailwind.js and a backend-tailwind.js to generate two styles sheets backend.scss and frontend.scss in two Next layouts...
Thank you for your help.

A: I have created two layouts and add on each  I added a classic link stylesheet (example below)
<link rel="preload" href={process.env.NODE_ENV === 'development' ? `/css/tailwind-dev.css` : `/css/prod.min.css?${refreshCache}`} media="all" rel="stylesheet" type="text/css" />

And I use two Gulp tasks, one for building TailwindCSS dev (with all themes) and one for building the prod files (with purgecss, cleanCSS, concat...)...
PurgeCSS regex is here: https://tailwindcss.com/docs/optimizing-for-production