text:
Q: How to group list and split every n records? I would like to know how to group item and split every N record by using LINQ
# |ITEM  |QUANTITY
==================
1 |ITEM01| 10
2 |ITEM01| 10
3 |ITEM01| 10
.     .     .
.     .     .
22|ITEM01| 10
23|ITEM02| 50
24|ITEM02| 50

Suppose there's a list with 23 ITEM001 and 2 ITEM002
How to get
ITEM  |QUANTITY
=================
ITEM001 | 100
ITEM001 | 100
ITEM001 | 20
ITEM002 | 100

Group by ITEM, if grouped > 10, go to next
Is there any way to achieve it? Thanks for you help!
 Thanks for those nice guys help! Further question, now i would like to group the list like (grouped every 10 records, after grouping, if count does not reach 10, do not group), Sorry for my poor English :(
ITEM  |QUANTITY
=================
ITEM01 | 100
ITEM01 | 100
ITEM01 | 10
ITEM01 | 10
ITEM01 | 10
ITEM02 | 50
ITEM02 | 50

Thanks for your help again!

A: var query =
    items.GroupBy(item => item.Name)
         .SelectMany(g => g.Select((item, index) => new { item, index })
                           .GroupBy(x => x.index / 10)
                           .Select(batch => new Item {
                                 Name = batch.First().item.Name,
                                 Quantity = batch.Sum(x => x.item.Quantity)
                            })).OrderBy(item => item.Name);

*

*Group all items by name. That will give you two groups for your sample data.

*Split each group into batches by 10 items, and select new aggregated item from each batch (batch can contain less than 10 items, as thirds batch for ITEM001).

*Order results by item name.

This query can be simplified if you will use MoreLINQ (available from NuGet) Batch extension or write your own one:
var query =
    items.GroupBy(item => item.Name)
         .SelectMany(g => g.Batch(10)
                           .Select(batch => new Item {
                                 Name = batch.First().Name,
                                 Quantity = batch.Sum(item => item.Quantity)
                            })).OrderBy(item => item.Name);

Assume you have item class like this
public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }
}

Then this sample list of items (constructed with NBuilder):
var items = Builder<Item>.CreateListOfSize(32)
                         .TheFirst(23)
                             .With(i => i.Name = "ITEM01")
                             .And(i => i.Quantity = 10)
                         .TheNext(9)
                             .With(i => i.Name = "ITEM02")
                             .And(i => i.Quantity = 50)
                         .Build();

Will give result:
[
  { Name: "ITEM01", Quantity: 100 },
  { Name: "ITEM01", Quantity: 100 },
  { Name: "ITEM01", Quantity: 30  },
  { Name: "ITEM02", Quantity: 450 }
]

NOTE: @Thejaka solution will give you five items in this case - there will be two ITEM02 items with quantity 350 and 100.

A: Note: Below answer groups items by sum, not count. Nevertheless, I leave it here for future reference. Maybe someone will ever have similar problem.
You can achieve it with the following LINQ query:
List<Item> items = new List<Item>()
{
    new Item() { Name = "Item01", Quantity = 40 }, // 130
    new Item() { Name = "Item01", Quantity = 70 },
    new Item() { Name = "Item01", Quantity = 10 },
    new Item() { Name = "Item01", Quantity = 10 },
    new Item() { Name = "Item02", Quantity = 50 }, // 100
    new Item() { Name = "Item02", Quantity = 50 },
    new Item() { Name = "Item03", Quantity = 10 }  // 10
};

var result =
    // Group by Name, calculate total sum for each group
    items.GroupBy(i => i.Name, (k, v) => new Item()
    {
        Name = k,
        Quantity = v.Sum(i => i.Quantity)
    })
    // Split groups into 100 packages
    .SelectMany(i => Enumerable.Range(0, (int)Math.Ceiling(i.Quantity / 100.0))
                               .Select(n => new Item()
    {
        Name = i.Name,
        Quantity = i.Quantity > ((n + 1) * 100) ? 100 : i.Quantity - n * 100
    }))
    .ToList();

Then you have four elements in the list:
Item01 100
Item01 30
Item02 100
Item03 10


text:
Q: Login page verification in reactjs I want to translate an angularjs login page to reactjs. I did the code but I want to know if it's the right way to do it and if it's correct till what I have done. Also I want to add the dashboard page which can be accessed only authentication and user will be redirected to dashboard after login.
$scope.login=function(){
    $scope.newuser={
        'password':$scope.signinpassword,
        'email':$scope.emailid
    }
   return $http.post('/api/authenticate',$scope.newuser).then(function(response,status){
        if(response.data=='redirect'){
            $window.location.href="/dashboard";
        }else if(response.data=='verifyemail'){
            angular.element(document.querySelector('#verifyemailbtn')).click();
        }else if(response.data=='Invalid Password'){
            window.alert("Incorrect Password");
            $scope.error='Failed to authenticate'
        }
   });
}

my reactjs code that I translated so far
class Login extends Component {
constructor(props){
  super(props);
  this.state={
  emailid:'',
  password:''
  }
 }
performLogin = async (event) => {
    var body={
        "emailid":"this.state.emailid",
        "password":"this.state.password"
        }
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: body
    };
    const url = "api/login";
    try {
      const response = await fetch(url, options);
      const result = await response.json();
      console.log(`login successful`);
    } catch (error) {
      console.error("login credentials wrong");
    }
  };

render() {
    return (

             <input type="text"
             placeholder="emailid"
             onChange = {(event,newValue) => this.setState({emailid:newValue})}
             />

             <input
               type="password"
               placeholder="Enter your Password"
               onChange = {(event,newValue) => this.setState({password:newValue})}
              />

             <button type="submit" onClick={(event) => this.performLogin(event)}/>

    );
  }
}
export default Login;

A: your code approaching is ok but have some syntax issues.
1- your need to bind "this" for methods in constructor
2- remove double quotation in performLogin for this.state.emailid
3- you don't need many functions for each input you can just handle all input feilds just with one function like so.
i refactor your code :-)

class Login extends Component {
constructor(props){
  super(props);

  this.performLogin = this.performLogin.bind(this)
  this.handleChange = this.handleChange.bind(this)
  this.state={
  emailid:'',
  password:''
  }
 }

performLogin = async (event) => {
    const { enteredText } = this.state;
    var body={
        "emailid":this.state.emailid,
        "password":this.state.password
        }
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: body
    };
    const url = "api/login";
    try {
      const response = await fetch(url, options);
      const result = await response.json();
      $window.location.href="/dashboard";
    } catch (error) {
      console.error("login credentials wrong");
    }
  };

  handleChange(e) {
    this.setState({[e.target.name]:e.target.value})
  }

render() {
    return (

             <input type="text"
             placeholder="emailid"
             onChange = {handleChange}
             />

             <input
               type="password"
               placeholder="Enter your Password"
               onChange = {handleChange}
              />

             <button type="submit" onClick={this.performLogin}/>

    );
  }
}
export default Login;

for redirecting you can use lib like React-Router or just replace  console.log(login successful) with  $window.location.href="/dashboard"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Onclick Listeners in Android assume that i have three buttons all of whose listeners point to (this) . So if I press any of the button is it going to start from the beginning of the activity, irrespective of the button pressed?

A: No, it will go on override method onClick() of your Activity.
listeners point to (this)

you must have to implements onClickListener to your activity which will override onClick()
To verify which view had been clicked, you have to do something like
@Override
public void onClick(View v)
{
    if(v== controlName)
       // controlName is clicked
}

A: what you can do is use a switch case and get to know what's the button clicked.
try this:
class stuff extends Activity implements onClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
        Button button3 = (Button) findViewById(R.id.button3);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
             // do something
             break;
        case R.id.button2:
             // do something else
             break;
        case R.id.button3:
             // do yet another thing
             break;
        default:
            // do nothing
            break;
        }
}

A: Confusing question...
Anyway, here it goes an listener example .
public class MyClass extends Activity {
   private Button firstBtn;
   private Button secondBtn;
   private Button thirdBtn;

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    firstBtn  = (Button) findViewById(R.id.firstBtn);
    secondBtn = (Button) findViewById(R.id.secondBtn);
    thirdBtn  = (Button) findViewById(R.id.thirdBtn);

    firstBtn.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
        {
            Log.d("MyClass", "first button clicked!");
        }
    });

    secondBtn.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
        {
            Log.d("MyClass", "second button clicked!");
        }
    });

    thirdBtn.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
        {
            Log.d("MyClass", "third button clicked!");
        }
    });
   }

}
Hope it helps. Cheers


text:
Q: Integrating $\int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \frac{\log\left( x^2 + 2 x \sin(\theta) + 1 \right)}{x + 2 \sin(\theta)} d\theta$ Let $x>0$. I've encountered the following integral:
$$
I(x) \ = \ \int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \frac{\log\left( x^2 + 2 x \sin(\theta) + 1 \right)}{x + 2 \sin(\theta)} d\theta
$$
Is there a way to integrate this? I've been looking through Gradshteyn and Ryzhik, and I have found some similar integrals but nothing that looks exactly like this. Maybe through a contour integration?
If there is no way to integrate this, is it possible to derive asymptotics for the above $I(x)$ in the limit $x \to \infty$?

A: As I wrote in a comment, a CAS was able to find the antiderivative (the resulting formula is a few pages long !).
The only thing I was able to do is to expand the integrand as a Taylor series built at $t=0$ and then to integrate between the given bounds. Using the expansion to $O(t^{5})$ the result is
$$3840 x^5 \left(x^2+1\right)^4\,I(x)=2 \left(960 \pi  x^4+80 \pi ^3 x^2-\pi ^5 \left(x^2-12\right)\right)
   \left(x^2+1\right)^4 \log \left(x^2+1\right)+\pi ^3 x^2 \left(\pi ^2 \left(3
   x^8-42 x^6-97 x^4-82 x^2-24\right)-80 \left(3 x^2+2\right)
   \left(x^3+x\right)^2\right)$$
Using $x=10^k$ and the above formula, we can compare with the numerical integration. Below are some results for ten significant figures.
$$\left(
\begin{array}{ccc}
 k & \text{approximation} & \text{integration} & \color{blue} {\text{Maxim's asymptotics}}\\
 1 & 0.7285409898 & 0.7285572863 & \color{blue} {0.7284940770}\\
 2 & 0.1446859930 & 0.1446860624 & \color{blue} {0.1446860611}\\
 3 & 0.02170136876 & 0.02170136887 &\color{blue} { 0.02170136887}\\
 4 & 0.002893513786 & 0.002893513786 & \color{blue} {0.002893513786}\\
 5 & 0.0003616892206 & 0.0003616892206 & \color{blue} {0.0003616892206}\\
 6 & 0.00004340270647 & 0.00004340270647 & \color{blue} {0.00004340270647}
\end{array}
\right)$$ Using the result and expanding again as a Taylor series for infinitely large values of $x$
$$I(x)=\pi \frac {\log(x)} x+O\left(\frac{\log(x)}{x^3}\right)$$
Edit
For the evaluation fo the integral, it could be simpler to build a $[1,1]$ Padé approximant  at $t=0$. This will give for the integrand
$$\frac{a +b\, t}{1+c\, t}=\frac b c+\frac{a-\frac b c}{1+c\,t}$$ (easy to integrate) where
$$a=\frac{\log \left(x^2+1\right)}{x}$$
$$b=\frac{\left(x^2+2\right) \log \left(x^2+1\right)-2 x^2}{\left(x^2+1\right)
   \left(\left(x^2+1\right) \log \left(x^2+1\right)-x^2\right)}$$
$$c=\frac{2 \left(x^2+1\right)^2 \log \left(x^2+1\right)-x^2 \left(3 x^2+2\right)}{x
   \left(x^2+1\right) \left(\left(x^2+1\right) \log \left(x^2+1\right)-x^2\right)}$$
This would give
$$\left(
\begin{array}{ccc}
 k & \text{approximation} & \text{integration} \\
 1 & 0.7290369069 & 0.7285572863 \\
 2 & 0.1446872219 & 0.1446860624 \\
 3 & 0.02170137072 & 0.02170136887 \\
 4 & 0.002893513788 & 0.002893513786 \\
 5 & 0.0003616892207 & 0.0003616892206 \\
 6 & 0.00004340270647 & 0.00004340270647
\end{array}
\right)$$
Update
Concerning the initial Taylor expansion, the problem is a little simpler considering
$$\frac{\log (a+2 b \sin (t))}{b+2 \sin (t)}=\sum_{n=0}^4 c_i \, t^i + O\left(t^5\right)$$ where $a=x^2+1$ and $b=x$. This leads to
$$c_0=\frac{\log (a)}{b}\qquad c_1=\frac{2 \left(b^2-a \log (a)\right)}{a b^2}$$
$$c_2=\frac{4 a^2 \log (a)-2 b^2\left(2 a +b^2\right)}{a^2 b^3}$$
$$c_3=\frac{a^3 \left(b^2-24\right) \log (a)+24 a^2 b^2-(a-12) a b^4+8 b^6}{3 a^3 b^4}$$
$$c_4=\frac{-4 a^4 \left(b^2-12\right) \log (a)-48 a^3 b^2+4 (a-6) a^2 b^4+2 (a-8) a
   b^6-12 b^8}{3 a^4 b^5}$$
Now
$$\int_{-\frac \pi 4}^{\frac \pi 4} \frac{\log (a+2 b \sin (t))}{b+2 \sin (t)}\,dt\approx\frac{\pi}{2}   c_0+\frac{\pi ^3}{96}  c_2+\frac{\pi ^5 }{2560}c_4$$ Going to asymptotics
$$I(x)=\pi\frac{  \log (x)}{x}\left(1+\frac{\pi ^2 \left(80-\pi ^2\right)}{960\, x^2} +\cdots\right)$$
Update
After Maxim's answer, I added in blue the value obtained for the integral using jis/her asymptotics. Much better than mine.

A: If you make the standard substitution $\theta = 2 \arctan u$, the integrand becomes
$$\frac {\ln \frac {P(u)} {Q(u)}} {R(u)},$$
where $P, Q, R$ are quadratic polynomials. Factoring the polynomials and formally expanding the logarithm reduces the indefinite integral to a sum of integrals of the form
$$\int \frac {\ln u} {u + a} du =
\ln u \ln \left( 1 + \frac u a \right) +
 \operatorname{Li}_2 \left( - \frac u a \right).$$
With the natural choice of the factors, the antiderivative will be continuous in $u$ for large positive $x$, yielding a closed form for the definite integral.
To obtain the asymptotic, you can simply expand the integrand around $x = \infty$ and integrate term by term:
$$\frac {\ln (x^2 + 2 x \sin \theta + 1)} {x + 2 \sin \theta} = \\
\frac {2 \ln x} x - \frac {4 \ln x \sin t - 2 \sin t } {x^2} +
 \frac {8 \ln x \sin^2 t + \cos 2 t - 4 \sin^2 t} {x^3} + o(x^{-3}), \\
I(x) = \frac {\pi \ln x} x +
 \frac {2 (\pi - 2) \ln x - \pi + 3} {x^3} + o(x^{-3}).$$

A: For $x$ sufficiently large, and putting all in the form
$$2\int_{-\pi/4}^{\pi/4} \frac{\log(x)}{x}\cdot \frac{\textrm{d}\theta}{1+2\sin(\theta)/x}+\int_{-\pi/4}^{\pi/4} \frac{\log\left(1 + 1/x (2\sin(\theta) + 1/x) \right)}{x }\cdot \frac{\textrm{d}\theta}{1+2\sin(\theta)/x} $$
combined with the power series of $\log(1+x)$ and $\displaystyle \frac{1}{1+x}$, and integrating termwise, we arrive, for example, at the asymptotical behaviour
$$I(x)\approx\pi\frac{\log(x)}{x}+\frac{2(\pi-2)\log(x)+3-\pi}{x^3}+\frac{12(3\pi-8)\log(x)-21\pi+64}{6x^5}.$$


text:
Q: Should I configure a watcher for less files in a meteor project I'm setting up a meteor project in Webstorm and so I added less, and converted my .css file to .less.
Webstorm sees that this is a .less file and prompts me to add a watcher.
Given that this is a meteor project, is it necessary to add the watcher or does Meteor take care of this?

A: No need to use file watchers - if meteor less package is added, meteor takes care of compiling your .less files


text:
Q: How to move canvas objects each time I click the button? I'm trying to make a game and I have the blocks spawning randomly in the grid in the one fixed row (for example row 5 [horizontally]). Every time I click the button I want the blocks to move from row 5 to row 4(vertically). And then I want the new random blocks to generate on row 5 and so on. How can I do this? Right now it only spawning the new blocks under the first row (on the row 6, then 7 and so on).

//Accessing canvas
var canvas = document.getElementById('grid');
var ctx = canvas.getContext('2d');

var w = ctx.canvas.width;
var h = ctx.canvas.height;

// Drawing grid
var drawingGrid = function() {

  for (x = 0; x <= w; x += 60) {
    for (y = 0; y <= h; y += 60) {

      // Gray grid
      ctx.globalCompositeOperation = 'destination-over';
      ctx.strokeStyle = "#cccccc";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, h);
      ctx.moveTo(0, y);
      ctx.lineTo(w, y);

      if (x % 240 === 0) {
        // Black X-axis grid |
        ctx.globalCompositeOperation = "source-over";

        if (x === 0 || x === 480) {
          ctx.lineWidth = 5;
        } else {
          ctx.lineWidth = 1;
        }
        // Middle vertical line
        if (x === 240) {
          // 0-480
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, 480);
          ctx.strokeStyle = "#222831";
          ctx.stroke();

          // 480-560
          ctx.beginPath();
          ctx.moveTo(x, 480);
          ctx.lineTo(x, 540);
          ctx.strokeStyle = "#cccccc";
          ctx.globalCompositeOperation = 'destination-over';

        } else {
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, h);
          ctx.strokeStyle = "#222831";
        }

      } else if (y % 240 === 0 || y === 540) {
        // Black Y-axis grid _
        ctx.globalCompositeOperation = "source-over";
        ctx.strokeStyle = "#222831";

        if (y === 0 || y === 540) {
          ctx.lineWidth = 5;
        } else if (y === 480) {
          ctx.lineWidth = 2.5;
        } else {
          ctx.lineWidth = 1;
        }

        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(h, y);

      }
      ctx.stroke();
    }
  }

};

drawingGrid(480, 540, 'grid');

// Starting coordinates
var posX = 0;
var posY = 240;
// Move blocks on Y axis
function moveY(){
  posY +=60;
}
// Spawn random amount of blocks on the field
function gener(){
  posX = 60*Math.floor(8*Math.random());
}

  function spawnRandomObject() {

    // Game Object
      ctx.fillStyle = '#f2a365';
      ctx.globalCompositeOperation = "destination-over";
      ctx.beginPath();
      ctx.fillRect(posX, posY, 60, 60);
      ctx.stroke();
  }

// Blocks moving up
document.getElementById("button").addEventListener("click", function(){
  // Spawn random amount of objects
  for (var i=0; i<Math.floor((Math.random()*8)+1)*2; i++){
    gener();
    spawnRandomObject();

  }
moveY();
});
body{
  background-color: #ececec;
}

canvas{
  padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
}

.row{
  padding: 20px;
  margin: 0;
}
.firstrow{
  width:20%;
}

.mainrow{
  width:60%;
  display: block;
}

.thirdrow{
  width: 20%;
}

.header{
  background-color: #222831;
  color: #ececec;
  padding: 20px;
}

.container{
  margin-top: 20px;
  padding: 0px;
  display: flex;
  box-sizing: inherit;
}
.thirdrow{
  text-align: right;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Shmetris</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <link rel="stylesheet" href="styles.css">

Shmetris

Score: 0

            <button type="button" class="btn btn-dark" id="button">Refresh</button>

        <canvas id="grid" width="480" height="540" style="background: #ececec "></canvas>

A: I removed your moveY() function and added the moveRow() function. The game objects (the rects) are saved to a list objects. Their y position is increased on each button click. The old drawn positions are removed, the new positions are drawn. Then the randomly generated blocks are added in the 5th row.
Note that the clearRect() function inside the removeCell() also removes parts of the grid. This causes to redraw the grid every time. You can improve the code by splitting your grid creation in using a sub function which draws the grid on only one cell. Then you can redraw the grid only on those cells that are needed. This probably is a performance boost and makes the code more beautiful in my eyes, but it works like this too.
I also suggest to use length instead of 60 and calculate the thicker grid lines by the length, e.g. 8 * length instead of 480 and so on.

//Accessing canvas
var canvas = document.getElementById('grid');
var ctx = canvas.getContext('2d');

var w = ctx.canvas.width;
var h = ctx.canvas.height;

// Drawing grid
var drawingGrid = function() {

  for (x = 0; x <= w; x += 60) {
    for (y = 0; y <= h; y += 60) {

      // Gray grid
      ctx.globalCompositeOperation = 'destination-over';
      ctx.strokeStyle = "#cccccc";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, h);
      ctx.moveTo(0, y);
      ctx.lineTo(w, y);

      if (x % 240 === 0) {
        // Black X-axis grid |
        ctx.globalCompositeOperation = "source-over";

        if (x === 0 || x === 480) {
          ctx.lineWidth = 5;
        } else {
          ctx.lineWidth = 1;
        }
        // Middle vertical line
        if (x === 240) {
          // 0-480
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, 480);
          ctx.strokeStyle = "#222831";
          ctx.stroke();

          // 480-560
          ctx.beginPath();
          ctx.moveTo(x, 480);
          ctx.lineTo(x, 540);
          ctx.strokeStyle = "#cccccc";
          ctx.globalCompositeOperation = 'destination-over';

        } else {
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, h);
          ctx.strokeStyle = "#222831";
        }

      } else if (y % 240 === 0 || y === 540) {
        // Black Y-axis grid _
        ctx.globalCompositeOperation = "source-over";
        ctx.strokeStyle = "#222831";

        if (y === 0 || y === 540) {
          ctx.lineWidth = 5;
        } else if (y === 480) {
          ctx.lineWidth = 2.5;
        } else {
          ctx.lineWidth = 1;
        }

        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(h, y);

      }
      ctx.stroke();
    }
  }

};

drawingGrid(480, 540, 'grid');

var length = 60;
// Starting coordinates
var posX = 0;
var posY = 4 * length;
var objects = []

function moveRows(){
  for(var i = 0; i < objects.length; i++){
    // remove old objects
    removeCell(objects[i][0], objects[i][1]);
    // move objects
    objects[i][1] += length;
  }

  drawingGrid();

  for(var i = 0; i < objects.length; i++){
    // redraw objects on new location
    drawCell(objects[i][0], objects[i][1]);
  }
}
// Spawn random amount of blocks on the field
function gener(){
  posX = length*Math.floor(8*Math.random());
}

  function spawnRandomObject() {

    // Game Object
    drawCell(posX, posY);
    objects.push([posX, posY]);
  }

function drawCell(x, y, color){
    ctx.fillStyle = "#f2a365";
    ctx.globalCompositeOperation = "destination-over";
    ctx.beginPath();
    ctx.fillRect(x, y, length, length);
    ctx.stroke();
}

function removeCell(x, y){
    ctx.clearRect(x, y, length, length);
}

// Blocks moving up
document.getElementById("button").addEventListener("click", function(){
  // Spawn random amount of objects
  moveRows();
  for (var i=0; i<Math.floor((Math.random()*8)+1)*2; i++){
    gener();
    spawnRandomObject();

  }
});
body{
  background-color: #ececec;
}

canvas{
  padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
}

.row{
  padding: 20px;
  margin: 0;
}
.firstrow{
  width:20%;
}

.mainrow{
  width:60%;
  display: block;
}

.thirdrow{
  width: 20%;
}

.header{
  background-color: #222831;
  color: #ececec;
  padding: 20px;
}

.container{
  margin-top: 20px;
  padding: 0px;
  display: flex;
  box-sizing: inherit;
}
.thirdrow{
  text-align: right;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Shmetris</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <link rel="stylesheet" href="styles.css">

Shmetris

Score: 0

            <button type="button" class="btn btn-dark" id="button">Refresh</button>

        <canvas id="grid" width="480" height="540" style="background: #ececec "></canvas>


text:
Q: Django Test Case Error 'WSGIRequest' object has no attribute 'session' I'm trying to write some tests for my django app and it's throwing up an error:
File "/Users/croberts/.virtualenvs/litem/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 101, in login
    if SESSION_KEY in request.session:
AttributeError: 'WSGIRequest' object has no attribute 'session'

Here's my code that I am trying to run:
class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

    def test_signup(self):
        request = self.request_factory.post("/signup/", {
            "email": "email@email.com",
            "password": "password",
            "password-confirm": "password",
            "firm": "big law firm"})
        response = signup_user(request)
        user = User.objects.get(email="email@email.com")
        self.assertEqual(user.username, "email@email.com")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.

Here's my middleware's:
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

and my installed apps:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'patents',
]

A: For anyone using Django 2.0 and up - the RequestFactory() doesn't have access to the Middleware:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

https://docs.djangoproject.com/en/2.2/topics/testing/advanced/#the-request-factory
Therefore, it needs to be added manually as follows:
from django.contrib.sessions.middleware import SessionMiddleware

class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

        middleware = SessionMiddleware()
        middleware.process_request(self.request_factory)
        self.request_factory.session.save()

    def test_signup(self):
        ...

A: In django 3.1, I got this error 'AttributeError: 'RequestFactory' object has no attribute 'COOKIES' after following @Alasdair's answer. I solved this by initializing the request first, below is the snippet.
def setUp(self):
    request = RequestFactory().get('/')
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()

Edit for version 4.0 the sessionmiddlewre requires a positional argument: 'get_response' so:
def setUp(self):
    request = RequestFactory().get('/')
    middleware = SessionMiddleware(request)
    middleware.process_request(request)
    request.session.save()

A: Try using the test client instead of the request factory. This has the advantage of testing your URL config as well.
class SimpleTest(TestCase):
    def test_signup(self):
        response = self.client.post("/signup/", {
            "email": "email@email.com",
            "password": "password",
            "password-confirm": "password",
            "firm": "big law firm"})
        user = User.objects.get(email="email@email.com")
        self.assertEqual(user.username, "email@email.com")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.


text:
Q: How can I pass request body for sklearn model, decision tree classifier in AWS Sagemaker while invoking endpoint? I am trying to invoke a multi-model endpoint in AWS Sagemaker and I am getting a ModelError -ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (500) from model with message "invalid literal for int() with base 10: 'Iris-virginica'". I have used Sklearn model with IRIS dataset and Decision Tree Algorithm to predict the output.
import boto3
import json

runtime_client = boto3.client('sagemaker')
content_type = "application/json"
request_body = {"Input": [[1.2,0.5, 1.7, 2.6, 2.7,1.0]]}
data = json.loads(json.dumps(request_body))
payload = json.dumps(data)
endpoint_name = "sklearn-endpoint"
print("payload ",type(payload))
response = runtime_client.invoke_endpoint(
    EndpointName=endpoint_name,
    ContentType=content_type,
    TargetModel="iris.tar.gz",
    Body=payload)


text:
Q: How to implement Search bar Autocomplete in cakephp I want to integrate the below autocomplete code into my CakePHP code. Mainly I want to pull the data from the database (Manufacturer + product for example: BMW X5) not from the array availableTags in the below code.
I am not an expert in CakePHP so how can I replace the array availableTags to CakePHP database function?
Products table columns: Id, product_name, version, manufacturer_id, category id
Manufacturers table columns : id, manufacturer
Search.html
 <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>jQuery UI Autocomplete - Default functionality</title>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

      <?php App::import('Controller','Products');App::import('Controller','Manufacturers');

<link rel="stylesheet" href="/resources/demos/style.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
      $( function() {
        var availableTags = [
          "ActionScript",
          "AppleScript",
          "Asp",
          "BASIC",
          "C",
          "C++",
          "Clojure",
          "COBOL",
          "ColdFusion",
          "Erlang",
          "Fortran",
          "Groovy",
          "Haskell",
          "Java",
          "JavaScript",
          "Lisp",
          "Perl",
          "PHP",
          "Python",
          "Ruby",
          "Scala",
          "Scheme"
        ];
        $( "#tags" ).autocomplete({
          source: availableTags
        });
      } );
      </script>
    </head>
    <body>

    <div class="ui-widget">
      <label for="tags">Tags: </label>
      <input id="tags">
    </div>

Products controller
public function suggestion() {
        $this->autoRender = false;

        $query = $this->params['url']['term'];

        $return_arr = array();
        $products = $this->Product->find('all', array('fields' => array('DISTINCT (Product.product_name) AS product_name'),'conditions' => array('Product.product_name LIKE' => $query.'%')));

        foreach($products as $product) {
            $return_arr[] = $product['Product']['product_name'];
        }

        echo json_encode($return_arr);

     }?>

Manufacturers Controller
public function suggestion() {
            $this->autoRender = false;

            $query = $this->params['url']['term'];

            $return_arr = array();
            $manufacturers = $this->Manufacturer->find('all', array('fields' => array('Manufacturer.manufacturer'),'conditions' => array('Manufacturer.manufacturer LIKE' => $query.'%')));

            foreach($manufacturers as $manufacturer) {
                $return_arr[] = $manufacturer['Manufacturer']['manufacturer'];
            }

            echo json_encode($return_arr);

        }?>

A: You can bind manufacturer table with products table then in products controller when you fetch products you can use virtual fields to combine values


text:
Q: Can't boot to Windows 10 with another broken Windows 10 drive installed I'm currently trying to recover the hard drive of the laptop of a family member. The drive apparently stopped working but still shows a lot of vital signs.
The broken drive still boots into Windows; even in Automatic Repair, but doesn't get all the way to either the login screen or repair stage, respectively, without getting a black screen. TestDisk identified the partitions correctly but only once, since plugging in the drive through my SATA to USB case.
I wanted to use my working Windows installation on my testbench to bring the drive back or at least get the files out, but attempting to boot on the working Windows drive doesn't work either unless the broken drive is taken out. The boot never ends and I'm left with a never-ending loading circle and a Windows logo.
As of now, this is the same as plugging the drive into the SATA to USB case. It now hangs Disk Management, DISKPART, and TestDisk simultaneously. After unplugging the drive, Disk Management does show the partitions of the broken drive, though, and so does the suspended TestDisk. So there's definitely still life in that drive.
Is there any way to boot Windows 10 up wherein either

*

*Windows doesn't recognize the broken drive unless I say so, or

*Windows recognizes the broken drive but does not attempt to read on it?

Is it also possible to have a portable Linux installation read the data and back it up? And if I can't use my testbench, is it possible to plug the drive in with a SATA to USB case without hanging everything?
I'm still quite hoping to get said drive back. It contains a lot of important files. Thank you all in advance.


text:
Q: Replacing "HTML tag with content" with "content" I need to replace
bar

with
bar

using JavaScript / jQuery.
Note: tag content must be inserted exactly in the same place, where tag was.

A: Using jQuery you can do it with replaceWith method:
$(".foo").replaceWith(function() {
    return $(this).contents();
});

DEMO: http://jsfiddle.net/wwAu4/

A: One plain JavaScript approach is the following:
function textUnwrap(el) {
    if (!el) {
        return false;
    }
    else {
        var text = el.textContent || el.innerText,
            textnode = document.createTextNode(text);
        el.parentNode.insertBefore(textnode, el.nextSibling);
        el.parentNode.removeChild(el);
    }
}

var spans = document.getElementsByTagName('span');

for (var i=0, len=spans.length; i<len; i++){
    if (spans[i].className.indexOf('foo') !== -1) {
        textUnwrap(spans[i]);
    }
}

JS Fiddle demo.
Edited the function in order to cache the el.parentNode (since I'm using it twice):
function textUnwrap(el) {
    if (!el) {
        return false;
    }
    else {
        var text = el.textContent || el.innerText,
            textnode = document.createTextNode(text),
            parent = el.parentNode;
        parent.insertBefore(textnode, el.nextSibling);
        parent.removeChild(el);
    }
}

JS Fiddle demo.
Also, again an update to the function, to use replaceChild() rather than insertBefore() and removeChild():
function textUnwrap(el) {
    if (!el) {
        return false;
    }
    else {
        var text = el.textContent || el.innerText,
            textnode = document.createTextNode(text),
            parent = el.parentNode;
        parent.replaceChild(textnode, el);
    }
}

JS Fiddle demo.

A:  var $foo = $(".foo").first();
 $foo.replaceWith($foo.contents());

A: Seems to me like you've not really tried anything, but this should get you started:
var theElement = document.getElementById('foobar');// or: $('#foobar')[0]
theElement.parentNode.innerHTML = theElement.parentNode.innerHTML.replace(theElement.outerHTML, theElement.innerText);//<- done
//or:
theElement.parent.html(theElement.parent.html().replace(theElement[0].outerHTML,theElement.contents());

The latter being jQuery only. There probably is a cleaner jQ way, but I still prefer pure JS, so my focus is on the tool-kit-free approach
BTW: if you use jQuery, you use JavaScript (jQuery IS JavaScript)


text:
Q: Moving to Linux The family PC is riding off into the sun.
I want to replace it with a Linux solution. I'm looking at Ubuntu and openSUSE. I want to end up with a solution where anyone in my family can access their files securely from a remote location (laptop, desktop, iOS device, Android device, ....). We also use Google for docs, calendar, sites, drive, basically everything so I need compatibility there also.
I'm willing to invest the time to move from Windows and really learn a new OS so I want to know if ...
 1. Ubuntu will meet my families growing needs?
 2. If so, should the solution I'm looking for be housed in one machine or should I build multiple?

A:
Ubuntu will meet my families growing needs?

Yes!

anyone in my family can access their files securely from a remote location (laptop, desktop, iOS device, Android device, ....).

I recommend Ubuntu One for that. It's a cloud storage service that tightly integrates with Ubuntu and you can access your files from any device running Windows, Mac OS X, Ubuntu, iOS or Android.

We also use Google for docs, calendar, sites, drive, basically everything so I need compatibility there also.

There is an amazing feature in Ubuntu called Unity Web Apps. It allows supported web applications to act as installed ones. Just open a supported webapp in Firefox (Or Chromium. Other web browsers don't work) and you will be prompted to install it with Unity Web Apps. Google Docs and Google Calender are supported!
Ubuntu's mail client, Evolution, supports GMail. But GMail also supports Unity Web Apps.
You can use Sites in Firefox.
About Drive: Unfortunately, Google is lazy and haven't released a Linux version of the Google Drive client yet. Google has said there will be one, but it hasn't been released yet. You can still use it in Firefox however.
There is a petition for Google going on to create a Linux version of the Google Drive client.

should the solution I'm looking for be housed in one machine or should I build multiple?

One machine is enough!

A: So, if I understand is correctly, you would like a computer where everything is in the cloud? Well Ubuntu has a service called Ubuntu One that is like Dropbox and is also available for Windows Mac Android IOS. And if you have all you files in the cloud then you don't need multiple machines.
I hope that this helps.


text:
Q: TypeError: only size-1 arrays can be converted to Python scalars when trying to fit SVR Model I'm trying to optimize SVR parameter using particle swarm optimization (PSO) in Python. to reach that, i'm using PySwarms's documentation. my dataset has 12 columns. here is my code:
import pandas as pd
import numpy as np
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
from pyswarms.single.global_best import GlobalBestPSO

# Load the input and output data from a CSV file
# data = pd.read_csv('data.csv')

# Separate the input and output data

X=d3.iloc[:,:11]
y=d3.iloc[:,-1]

# Define the fitness function to optimize the SVR model
def svr_fitness_function(params):
    # Extract the SVR hyperparameters from the input vector
    C = params[0]
    gamma = params[1]
    epsilon = params[2]

    # Create a new SVR model with the given hyperparameters
    model = SVR(C=C, gamma=gamma.all(), epsilon=epsilon)

    # Train the model on the input and output data
    model.fit(X, y)

    # Use the trained model to make predictions on the input data
    y_pred = model.predict(X)

    # Calculate the mean squared error of the predictions
    mse = mean_squared_error(y, y_pred)

    # Return the negative of the mean squared error as the fitness value
    return -mse

# Set up the PSO optimizer
n_particles = 20
max_iter = 100
bounds = (np.array([0.1, 0.1, 0.1]), np.array([10, 10, 1]))
optimizer = GlobalBestPSO(n_particles=n_particles, dimensions=3, options={'c1': 0.5, 'c2': 0.3, 'w': 0.9})

# Run the PSO optimizer to find the optimal SVR hyperparameters
best_cost, best_params = optimizer.optimize(svr_fitness_function, iters=max_iter)

# Print the optimal SVR hyperparameters and the corresponding mean squared error
print('Optimal SVR hyperparameters:', best_params)
print('Corresponding mean squared error:', -best_cost)

I'm expecting this code returns optimized parameters but when is trying to fit model there is this error:
TypeError: only size-1 arrays can be converted to Python scalars
i'm chaneged y to:
y = d3.iloc[:, -1].values.reshape(-1).astype(float)
but still not working.
is anybody can solve this?


text:
Q: How to predict and extract R Squared with .lm.fit? As the title suggest, I have seen some user mentioned that .lm.fit() functions has an advantage of more speed than a regular lm(), but when i look deeper at .lm.fit() in help, it is supposed to be a fitter functions, it returns a set of list instead of a model, which makes me to think is it still possible to extract components like R squared, Adj R Squared, and lastly do a predict() out of it?
Below is sample data and executions:
test_dat <- data.frame(y = rnorm(780, 20, 10))
for(b in 1:300){
  name_var <- paste0("x",b)
  test_dat[[name_var]] <- rnorm(780, 0.01 * b, 5)
}

tic()
obj_lm <- lm(y ~ ., data = test_dat)
print(class(obj_lm))
print(summary(obj_lm)$r.squared)
print(summary(obj_lm)$adj.r.squared)
predict(obj_lm)
toc() #approximately 0.4 seconds

tic()
datm <- as.matrix(test_dat)
obj_lm_fit <- .lm.fit(cbind(1,datm[,-1]), datm[,1])
print(class(obj_lm_fit))
toc() #approximately 0.2 seconds

A: Functions predict and resid are generic and since .lm.fit returns an object of class "list", all you have to do is to write methods implementing the definitions of what you want. Below are methods to compute fitted values, residuals and R^2.
set.seed(2023)    # make the results reproducible
test_dat <- data.frame(y = rnorm(780, 20, 10))
for(b in 1:300){
  name_var <- paste0("x",b)
  test_dat[[name_var]] <- rnorm(780, 0.01 * b, 5)
}

obj_lm <- lm(y ~ ., data = test_dat)

datm <- as.matrix(test_dat)
obj_lm_fit <- .lm.fit(cbind(1,datm[,-1]), datm[,1])

#------------------------------------------------------------------------
# the methods for objects of class "list"
#
fitted.list <- function(object, X) {
  X %*% coef(object)
}
resid.list <- residuals.list <- function(object, X, y) {
  y_fitted <- fitted(object, X)
  y - y_fitted
}
rsquared <- function(x, ...) UseMethod("rsquared")
rsquared.default <- function(x, ...) {
  summary(x)$r.squared
}
rsquared.list <- function(object, X, y) {
  e <- resid.list(object, X, y)
  1 - sum(e^2)/sum( (y - mean(y))^2 )
}

rsquared(obj_lm_fit, cbind(1,datm[,-1]), datm[,1])
#> [1] 0.3948863
rsquared(obj_lm)
#> [1] 0.3948863

Created on 2023-01-03 with reprex v2.0.2

Edit 1
Added method to also calculate adj.R2
adj_rsquared_list <- function(object, X, y){
  r2 <- rsquared.list(object, X, y)
  k <- ncol(X) - 1
  n <- nrow(X)
  rate_of_error <- (1 - r2) * (n - 1) / (n - k - 1)
  adj_r2 <- 1 - rate_of_error
  return(adj_r2)
}

adj_rsquared_list(obj_lm_fit, cbind(1,datm[,-1]), datm[,1])
#> [1] 0.01590061

Edit 2
After the edit by Jovan, I have changed fitted.list above to use coef(), a function that extracts the first arguments list member "coefficients", if it exists, and rewrote the default and list methods of rsquared to accept a adj argument. The code to compute the adjusted R^2 is a copy&paste of Jovan's code.
rsquared <- function(x, ...) UseMethod("rsquared")
rsquared.default <- function(x, adj = FALSE, ...) {
  if(adj) {
    summary(x)$adj.r.squared
  } else summary(x)$r.squared
}
rsquared.list <- function(object, X, y, adj = FALSE) {
  e <- resid.list(object, X, y)
  r2 <- 1 - sum(e^2)/sum( (y - mean(y))^2 )
  if(adj) {
    k <- ncol(X) - 1
    n <- nrow(X)
    rate_of_error <- (1 - r2) * (n - 1) / (n - k - 1)
    adj_r2 <- 1 - rate_of_error
    adj_r2
  } else r2
}

# same as above
rsquared(obj_lm_fit, cbind(1,datm[,-1]), datm[,1])
#> [1] 0.3948863
rsquared(obj_lm)
#> [1] 0.3948863

# new, `adj = TRUE`
rsquared(obj_lm_fit, cbind(1,datm[,-1]), datm[,1], adj = TRUE)
#> [1] 0.01590061
rsquared(obj_lm, adj = TRUE)
#> [1] 0.01590061

Created on 2023-01-03 with reprex v2.0.2


text:
Q: Find the transformation associated with the random variable X with the following PMF: Here is the question:

This is my work thus far.

A: Use the Taylor series for the exponential function $e^x$:
$$\sum_{k=0}^\infty \frac{\lambda^ke^{sk}}{k!}=\sum_{k=0}^\infty \frac{\left(\lambda e^{s}\right)^k}{k!}=e^{\lambda e^s}.
$$


text:
Q: Should missing definition of object / function with non-reserved identifier lead to diagnostics? Sample code:
void accept(int x);

int main(void)
{
        accept(0);
        return 0;
}

Invocations:
$ gcc t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>

$ clang t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>

$ cl t719.c /std:c11 /Za
t719.obj : error LNK2019: unresolved external symbol accept referenced in function main

$ icc t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>

Consider that the user forgot to define accept. We see that no diagnostics may be produced. Is diagnostics required?
UPD: Another example:
extern int y0;

int main(void)
{
        return y0;
}

# linux (begin)
$ gcc t719.c -std=c11 -pedantic -Wall -Wextra
undefined reference to `y0'

$ clang t719.c -std=c11 -pedantic -Wall -Wextra
undefined reference to `y0'

$ icc t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>
# program returned: 243
# linux (end)

# windows (begin)
# gcc in cygwin
$ gcc t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>
# program returned: 255

# clang in cygwin
$ clang t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>
# program returned: 255

$ cl t719.c /std:c11 /Za
unresolved external symbol _y0 referenced in function _main

$ LLVM/12.0.0/bin/clang t719.c -std=c11 -pedantic -Wall -Wextra
<nothing>
# program returned: 72

$ icl -Qstd=c11 t719.c
<nothing>
# program returned: 65
# windows (end)

A: C 2018 §6.9 ¶5 says:

… If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier;…

Since a "shall" is violated, but it is not in a constraint paragraph, C 2018 §4 ¶2 makes this undefined behavior:

If a "shall" or "shall not" requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined…

The clause on diagnostics, §5.1.1.3, does not require a diagnostic for this:

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined. Diagnostic messages need not be produced in other circumstances.


text:
Q: NetLogo input slider problem, slider disappearing after reset I want the max value of my input slider to be equal to the number of turtles in my environment. I've done this by inserting "count turtles" in the maximum input box in the slider settings. However, the problem I am facing is that when I (significantly) decrease the number of turtles and setup/reset the slider sort of glitches, stays on the old value (which is larger than the new max value which causes the red knob to disappear) and cannot be changed anymore. A workaround could be to drag the slider completely to the left before resetting the model but this does seem somewhat silly imo. Does anyone know how to fix this? Thanks in advance.

A: In my minimal working example, I could reset the slider value to turtle count, e.g. during setup. I think you could use if slider_value > count turtles [set slider_value count turtles] also in the end of the go procedure, in case the number of turtles decreases in your model and you want to keep the slider value updated.
globals [
  ; n_turtles - given by slider
  ; slider_value - given by slider
]

to setup
  clear-all
  crt n_turtles

  if slider_value > count turtles
  [
    set slider_value count turtles
  ]
end


text:
Q: Load an image file to core data I'm a new developer with objective c.
I have images stored in a folder on my computer and I want to insert it to my coredata, can someone please tell me how can I do so, cause I can't find the right way for this.
By the way its my first question so get mad on me :)
Thank you

A: You need an Entity:(b.e.: Photos), this entity need an attribute, with type is Binary Data. (b.e imageData.
Here the example to save and to show:
   // Save the image.

UIImage *imageToSave;

NSManagedObject *newPhoto = [NSEntityDescription entityForName:@"Photo" inManagedObjectContext:yourManagedObjectContext];
NSData *imageData =  UIImageJPEGRepresentation(imageEdited, 0.7);
[newPhoto setValue:imageData forKey:@"imageData"];
[yourManagedObjectContext save:&error];

// Sow the image
UIImage *image = [UIImage imageWithData:[newPhoto valueForKey:@"imageData"]];


text:
Q: Python mechanize redirection destination leads to new redirects I'm new to mechanize and now need to scrape a webpage that requires authentication to view the content. I am able to log in with mechanize separately (with browser.open(login link)), but the login seems to exert no effect when I try browser.open(content link) right after the login. I also tried to start with browser.open(content link) and hope it redirects to the login link, but when I run browser.response().read(), it always give me a destination URL (say www.url,com/url1), and when I try to browser.open(this destination link), it gives a new destination URL (something like www.url,com/xyz-url1), which seems like an endless loop.
Therefore, I am wondering if there is any way to fix this. I have tried browser.set_handle_redirect(mechanize.HTTPRedirectHandler) after browser.open and browser.follow_meta_refresh but neither works. It would also help if I can stay logged in while I scrape the original content page as well, but I do not know how. I only scraped with BeautifulSoup before so am really unfamiliar with mechanize. Thanks in advance.


text:
Q: Angular momentum conservation laws and GHZ article (Greenberger et al 1990) Can anyone recommend a good book or an online source on angular momentum conservation laws in decay processes?
I'm writing a master's thesis concerning Bell inequalities and currently working on GHZ theorem. In the paper by Greenberger et al http://www.physik.uni-bielefeld.de/~yorks/qm12/ghsz.pdf , on page 1134 there's a decay of a spin 1 particle into two spin 1 particles and a subsequent decay into four spin 1/2 particles.
Spin conservation in the basic Bohm version of EPR is understandable but I cannot grasp how it goes in this case and what the practical decay process might be. As of yet, I haven't investigated experimental realizations of GHZ in detail.

A: Imagine a pair of spin one particles going off in opposite directions one with $S_z$ of $+ \hbar$ and the other with $S_z$ of $- \hbar$. And in a superposition of the form $\frac{\vert +1\rangle\vert -1\rangle-\vert -1\rangle\vert +1\rangle}{\sqrt{2}}$. When each spin 1 decays into a pair of spin 1/2 you get
 $$\frac{
\vert\frac{1}{2}\rangle\vert\frac{1}{2}\rangle
\vert\frac{-1}{2}\rangle\vert\frac{-1}{2}\rangle
-
\vert\frac{-1}{2}\rangle\vert\frac{-1}{2}\rangle
\vert\frac{1}{2}\rangle\vert\frac{1}{2}\rangle
}{\sqrt{2}}$$
And the second decay shouldn't be all that mysterious.


text:
Q: How can you configure nginx to prevent it blocking on a slow uwsgi backend service? Lets say I have a simple nginx config that talks to a uwsgi backend:
server {
    listen 9900 default_server;
    listen [::]:9900 default_server;
    location / {
            include         uwsgi_params;
            uwsgi_pass      unix:/tmp/service-foo.sock;
    }
}

This service has a certain subset of urls (/renderer/...) that are always enormously slow, and under heavy load the entire site goes down.
What I want is to replace this with two copies of the backend, like this:
server {
    listen 9900 default_server;
    listen [::]:9900 default_server;

    location / {
            include         uwsgi_params;
            uwsgi_pass      unix:/tmp/service-foo.sock;
    }
    location ~ ^/renderer/[0-9]+/ {
            include         uwsgi_params;
            uwsgi_pass      unix:/tmp/service-renderer.sock;
            uwsgi_read_timeout      30s;
            uwsgi_send_timeout      30s;
            uwsgi_request_buffering on;
    }
}

...my naive expectation was that this would fix the problem by allowing the /renderer/... requests to be served slowly one at a time while the rest of the site remained responsive.
However, it didn't work.
It seems like nginx is serving requests into both locations from the same process and eventually the server justs sits there blocking with all the requests sitting in the second uwsgi instance, and the first uwsgi instance doing nothing at all.
I read up about the nginx thread_pool directive which looks almost exactly like what I want (ie. a specific reserved thread pool for the renderer location), but this doesn't seem to be supported by uwsgi, it's just for file io.
Is there any way of doing what I want at the nginx level?


text:
Q: C# 3.5 partial class String IsNullOrWhiteSpace I'm trying to create extra functionality to the String class (IsNullOrWhitespace as in .NET4 )
But I'm having an problem with referencing:

Error 1   'String' is an ambiguous reference between 'string' and 'geolis_export.Classes.String'

I don't want to create an extension method. Because this will crash if string x = null;
Usage:
private void tbCabineNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !e.Text.All(Char.IsNumber) || String.IsNullOrWhiteSpace(e.Text);
}

String partial:
public partial class String
{
    public static bool IsNullOrWhiteSpace(string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

Is it not possible to create extras for the String class?
I have tried to put the partial in the System namespace, but this gives other errors.
Renaming String to String2 fixes the problem also. But this is not what I want, because then there is no reference with the original String class.

A: An extension method has to be defined as a static method inside a static class. Also notice the this keyword on the parameter.
public static class MyExtensions
{
    public static bool IsNullorWhitespace(this string input)
    {
         // perform logic
    }
}

What you have done by omitting the static on the class is define a competing class within your assembly, hence the ambiguous message from the compiler.

A: It is not possible like this, because the string class in the .NET framework is not partial.
Instead, use a real extension method like this:
public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

The usage would then be like this:
string s = "test";
if(s.IsNullOrWhiteSpace())
    // s is null or whitespace

As with all extension methods, the call will not result in a null reference exception if the string is null:
string s = null;
if(s.IsNullOrWhiteSpace()) // no exception here
    // s is null or whitespace

The reason for this behavior is that the compiler will translate this code into IL code that is equivalent to the IL code of the following:
string s = null;
if(StringExtensions.IsNullOrWhiteSpace(s))
    // s is null or whitespace

A: The string class is not declared as partial, you will have to write an extension method instead.

A: public static class MyExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value == null) return false;
        return string.IsNullOrEmpty(value.Trim());
    }
}

A: That isn't how you create an extension method. The class isn't a partial, it needs to be a static class and it can be named anything (MyExtensionMethods). You also need to mark your parameter with "this" on an extension method.
Try this instead
public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

A: In order to create an extension method, you need to use the following syntax. (Note the use of the keyword this):
public static bool IsNullOrWhiteSpace(this string value)

A: Trimming the string results in an avoidable string allocation (which can hurt performance). Better to check each character in turn and not allocate anything:
        public static bool IsNullOrWhiteSpace(this string value)
        {
#if NET35
            if (value == null)
                return true;

            foreach (var c in value)
            {
                if (!char.IsWhiteSpace(c))
                {
                    return false;
                }
            }

            return true;
#else
            return string.IsNullOrWhiteSpace(value);
#endif
        }

The #if NET35 code means that the fallback implementation exists only when targeting .NET 3.5. You can adjust that comparison to meet your project's target frameworks as needed. Otherwise, the default string.IsNullOrWhiteSpace method is used, and this util method would likely be inlined.


text:
Q: Word Prediction algorithm I'm sure there is a post on this, but I couldn't find one asking this exact question. Consider the following:

*

*We have a word dictionary available

*We are fed many paragraphs of words, and I wish to be able to predict the next word in a sentence given this input.

Say we have a few sentences such as "Hello my name is Tom", "His name is jerry", "He goes where there is no water". We check a hash table if a word exists. If it does not, we assign it a unique id and put it in the hash table. This way, instead of storing a "chain" of words as a bunch of strings, we can just have a list of uniqueID's.
Above, we would have for instance (0, 1, 2, 3, 4), (5, 2, 3, 6), and (7, 8, 9, 10, 3, 11, 12). Note that 3 is "is" and we added new unique id's as we discovered new words. So say we are given a sentence "her name is", this would be (13, 2, 3). We want to know, given this context, what the next word should be. This is the algorithm I thought of, but I dont think its efficient:

*

*We have a list of N chains (observed sentences) where a chain may be ex. 3,6,2,7,8.

*Each chain is on average size M, where M is the average sentence length

*We are given a new chain of size S, ex. 13, 2, 3, and we wish to know what is the most probable next word?

Algorithm:

*

*First scan the entire list of chains for those who contain the full S input(13,2,3, in this example). Since we have to scan N chains, each of length M, and compare S letters at a time, its O(N*M*S).

*If there are no chains in our scan which have the full S, next scan by removing the least significant word (ie. the first one, so remove 13). Now, scan for (2,3) as in 1 in worst case O(N*M*S) which is really S-1.

*Continue scanning this way until we get results > 0 (if ever).

*Tally the next words in all of the remaining chains we have gathered. We can use a hash table which counts every time we add, and keeps track of the most added word. O(N) worst case build, O(1) to find max word.

*The max word found is the the most likely, so return it.

Each scan takes O(M*N*S) worst case. This is because there are N chains, each chain has M numbers, and we must check S numbers for overlaying a match. We scan S times worst case (13,2,3,then 2,3, then 3 for 3 scans = S). Thus, the total complexity is O(S^2 * M * N).
So if we have 100,000 chains and an average sentence length of 10 words, we're looking at 1,000,000*S^2 to get the optimal word. Clearly, N >> M, since sentence length does not scale with number of observed sentences in general, so M can be a constant. We can then reduce the complexity to O(S^2 * N). O(S^2 * M * N) may be more helpful for analysis though, since M can be a sizeable "constant".
This could be the complete wrong approach to take for this type of problem, but I wanted to share my thoughts instead of just blatantly asking for assitance. The reason im scanning the way I do is because I only want to scan as much as I have to. If nothing has the full S, just keep pruning S until some chains match. If they never match, we have no idea what to predict as the next word! Any suggestions on a less time/space complex solution? Thanks!

A: Yeh Whye Teh also has some recent interesting work that addresses this problem. The "Sequence Memoizer" extends the traditional prediction-by-partial-matching scheme to take into account arbitrarily long histories.
Here is a link the original paper: http://www.stats.ox.ac.uk/~teh/research/compling/WooGasArc2011a.pdf
It is also worth reading some of the background work, which can be found in the paper "A Bayesian Interpretation of Interpolated Kneser-Ney"

A: This is the problem of language modeling. For a baseline approach, The only thing you need is a hash table mapping fixed-length chains of words, say of length k, to the most probable following word.(*)
At training time, you break the input into (k+1)-grams using a sliding window. So if you encounter
The wrath sing, goddess, of Peleus' son, Achilles

you generate, for k=2,
START START the
START the wrath
the wrath sing
wrath sing goddess
goddess of peleus
of peleus son
peleus son achilles

This can be done in linear time. For each 3-gram, tally (in a hash table) how often the third word follows the first two.
Finally, loop through the hash table and for each key (2-gram) keep only the most commonly occurring third word. Linear time.
At prediction time, look only at the k (2) last words and predict the next word. This takes only constant time since it's just a hash table lookup.
If you're wondering why you should keep only short subchains instead of full chains, then look into the theory of Markov windows. If your model were to remember all the chains of words that it has seen in its input, then it would badly overfit its training data and only reproduce its input at prediction time. How badly depends on the training set (more data is better), but for k>4 you'd really need smoothing in your model.
(*) Or to a probability distribution, but this is not needed for your simple example use case.


text:
Q: Output nested set for Google Visualisation I am using Baum for Laravel to retrieve a nested set, but I can't begin to think how to get it into the format that my Google organisation chart needs it.
The outputted JSON:
{
   "1":{
      "id":1,
      "parent_id":null,
      "lft":1,
      "rgt":10,
      "depth":0,
      "name":"Jing's Team",
      "created_at":"-0001-11-30 00:00:00",
      "updated_at":"2016-01-24 18:32:22",
      "children":[
         {
            "id":2,
            "parent_id":1,
            "lft":2,
            "rgt":3,
            "depth":1,
            "name":"Ann's Team",
            "created_at":"-0001-11-30 00:00:00",
            "updated_at":"2016-01-24 18:32:22",
            "children":[

            ]
         },
         {
            "id":3,
            "parent_id":1,
            "lft":4,
            "rgt":9,
            "depth":1,
            "name":"Mike's Team",
            "created_at":"-0001-11-30 00:00:00",
            "updated_at":"2016-01-24 18:32:22",
            "children":[
               {
                  "id":4,
                  "parent_id":3,
                  "lft":5,
                  "rgt":8,
                  "depth":2,
                  "name":"Laidy's Team",
                  "created_at":"-0001-11-30 00:00:00",
                  "updated_at":"2016-01-24 18:32:22",
                  "children":[
                     {
                        "id":5,
                        "parent_id":4,
                        "lft":6,
                        "rgt":7,
                        "depth":3,
                        "name":"Steve's Team",
                        "created_at":"-0001-11-30 00:00:00",
                        "updated_at":"2016-01-24 18:32:22",
                        "children":[

                        ]
                     }
                  ]
               }
            ]
         }
      ]
   }
}

Which is generated with:
    Team::rebuild(true);
    $nodes = Team::where('id', Auth::user()->team_id)->first();
    $nodes = $nodes->getDescendantsAndSelf()->toHierarchy();

    return view('team.index', ['nodes' => $nodes]);

The way that Google organisation takes it:
data.addRows([
    [{v:'Mike', f:'Mike
President
'},
        '', 'The President'],
    [{v:'Jim', f:'Jim
Vice President
'},
        'Mike', 'VP'],
    ['Sam', 'Mike', ''],
    ['Bob', 'Jim', 'Bob Sponge'],
    ['Phil', 'Jim', 'Bob Sponge'],
    ['Carol', 'Bob', '']
]);

['NAME', 'PARENT_NAME', 'HOVER OVER TITLE']
How can parse the JSON to get it into the format that Google needs it?

So far I have:
public function index()
{
    Team::rebuild(true);
    $nodes = Team::where('id', Auth::user()->team_id)->first();
    $nodes = $nodes->getDescendantsAndSelf()->toHierarchy();

    $data = [];
    foreach($nodes as $node) {
        $data[] = [$node->name, '', ''];
        $data = $this->parseChildNode($node, $data);
    }

    return view('team.index', ['nodes' => json_encode($data)]);
}
protected $i = 0;
protected function parseChildNode($node, $data)
{
    if ($node->children()->count() > 0) {
        foreach ($node->children as $child) {
            $data[] = [$child->name, $data[$this->i][0], ''];
            $data = $this->parseChildNode($child, $data);
        }
        $this->i++;
        return $data;
    }
    return $data;
}

But it only goes down two levels and no further :(

I am now getting (everything is under "Jing's Team" which is incorrect):
[["Jing's Team","",""],["Ann's Team","Jing's Team",""],["Mike's Team","Jing's Team",""],["Laidy's Team","Jing's Team",""],["Steve's Team","Jing's Team",""]]

With the above altered code.

A: The following code seems to works with your use case, biggest issue was $data[$this->i][0]
public function index()
{
    Team::rebuild(true);
    $node = Team::where('id', Auth::user()->team_id)->first();
    $nodes = $nodes->getDescendantsAndSelf()->toHierarchy();

    $data = [];
    foreach($nodes as $node) {
        $data[] = [$node->name, '', ''];
        $data = $this->parseNodesChildren($node, $data);
    }

    return view('team.index', ['nodes' => json_encode($data)]);
}
protected function parseNodesChildren($node, &$data)
{
    if ($node->children->count() > 0) {
        foreach ($node->children as $child) {
            $data[] = [$child->name, $node->name, ''];
            $this->parseNodesChildren($child, $data);
        }
    }
}


text:
Q: Difference between "touching", "about" and "concerning" as a preposition The Macmillan Dictionary regard touching as a formal preposition, and other dictionaries nearly related the prepositions concerning, about, touching as synonyms. So is it fine to use all of three prepositions in written exams, as in:

*

*They had discussed touching the beauty of that place.

*They had discussed about the beauty of that place.

*They had discussed concerning the beauty of that place.

I don't have an idea which one is more preferable in written exams or other formal speaking occasions?
And the following usage of touching as a preposition lead me towards the confusion, as it looks like present progressive tense:

*

*It is touching them.

In this case, shouldn't it be like this:

*

*It is about them.

A: The use of touching in a context where it means something similar to about or concerning is, as @jason-bassford pointed out in a comment "above" [currently], usually in the form of touching on, and implies that [the topic] is dealt with in passing rather than being the central theme of the piece in question.
Using about or concerning implies that the subject is the central concern [sic] of the work, and the latter can imply concern in the sense of worry: for example I sent you a letter concerning [X] would suggest you should be concerned about [X].
Examples:

*

*Henry IV, part one is about Prince Henry, or Hal.

*Henry IV, part one touches on the perils of being a leader isolated from their people, and the dangers of being seduced by corrupt hangers-on [such as Falstaff].

*I can't think of a good example for concerns here, sorry.

A:
They had discussed touching the beauty of that place.

They discussed having physical or figurative contact with the beauty of the place.  (I would interpret this as some sort of visit.)

They had discussed the touching beauty of that place.

They talked about the emotional response elicited by the beauty of the place.

They had discussions touching on the beauty of that place.

They had discussions which, among other things, involved discussing the place's beauty.

A: None of the examples given are correct, because "discuss" is a transitive verb, so simply takes an object with no preposition. The object is the topic of discussion.

They had discussed the beauty of that place.

A: touching TFD
adj

evoking or eliciting tender feelings: your sympathy is touching.

prep (OED registers use of this as a preposition as somewhat archaic.

on the subject of; relating to

Thus in AmE avoiding prepositional use:
They (had) discussed the touching beauty of (that) the place.
or
In their discussion, they had touched on the beauty of that place. (@jasonbassford)

A: Notice how the example usage in Macmillan is not a complete sentence, and is preceded by a noun:

questions touching party politics or religion

whereas your example uses a verb before the word touching:

They had discussed touching the beauty of that place.

Therefore, a better example usage would be:

They had a discussion touching the beauty of that place.

Although, as another answer mentions, this isn't a common usage in contemporary English, and it is prone to sound a little awkward even when used grammatically.
One more common, contemporary phrasal verb is touch on. Macmillan says:

touch on something to mention something when you are talking or writing

So, one could say:

Their discussion touched on the beauty of that place.


text:
Q: Letsencrypt SSL Certifcate with Same Public Key? As Letsencrypt SSL certificates renew every 90 days, I would like to keep same public key even after renewal. Is it possible, if yes, how?

A: Found the solution here - https://community.letsencrypt.org/t/prevent-public-key-changin-when-renewing-ssl-certs/25489/6
As of now we can use clients other than cert-bot to renew certificates by keeping same public key.


text:
Q: How Do I not call socket.disconnect() when in queue When the wifi get disconnected for 10 seconds and gets reconnect, it calls the disconnect then
"connect" at the same time (instantaneously). I was wondering how I can make the 'disconnect' not be called when the wifi disconnects then reconnects quicky.
The disconnect should only be called when the wifi is disconnected  for a long time or the user force quits
io.on('connection', (socket: any) => {
    console.log(new Date(), 'Socket connected', socket.id);
})

socket.on('disconnect', () => {
      console.log('DISCONNECT');})


text:
Q: Update a object field in an array In mondodb I want to update a field of an object within an array. The example database looks like this:
{
    "_id" : ObjectId("5ad237559d30d918c89c7f46"),
    "myArray" : [
        {
            "name" : "a",
            "name2" : "a",
            "value" : 900000 //<--- instead of this...
        },
        {
            "name" : "b",
            "name2" : "b",
            "value" : 0
        }
    ]
},
{
    "_id" : ObjectId("5ad238049d30d918c89c7f47"),
    "myArray" : [
        {
            "name" : "b",
            "name2" : "b",
            "value" : 0
        },
        {
            "name" : "c",
            "name2" : "a",
            "value" : 0 //... I want to update this
        }
    ]
}

I want to update the last value field by querying name:c AND name2:a. I tried it with the following instruction, but it sets the value of the first object (name:a name2:a). Does the problem lie near the $ char?
db.test.updateOne({$and:[{"myArray.name" : "c"}, {"myArray.name2" : "a"}]},
                 {$set:{"myArray.$.value" : 900000}})

A: You can use arrayFilters.
db.test.updateOne({}, {$set:{"myArray.$[element].value" : 900000}}   {
 multi: true,
 arrayFilters: [ {$and:[{"element.name" : "c"}, {"element.name2" : "a"}]}        ]
},
)

Sorry, I have no mongodb right there to test it, the query will probably need to be tuned a little

A: You need to do an $elemMatch to match the specific item in the array and then you can use the positional operator:
db.test.updateOne(
    { "myArray": { $elemMatch: { "name": "c", "name2"; "a" } } },
    { $set: { "myArray.$.value": 900000 } }
);


text:
Q: PHP Cookie not working on redirect I have rather frustration problem. I am trying to store a form variable into a cookie.
<form id = "vraagStellen" action = "shoutbox.php" method = "post" class = "col-lg-4 col-md-6 col-sm-12" role="form">

        Gamertag:
        <input type = "text" id = "gamertag" name = "gamertag" class = "form-control" maxlength="30" value="<?php if(isset($_COOKIE['gamertag'])){echo $_COOKIE['gamertag'];} else {echo "";} ?>" placeholder="<?php if(isset($_COOKIE['gamertag'])){echo $_COOKIE['gamertag'];} else {echo "Hier typen";} ?>" required>

        Bericht:
        <textarea id = "bericht" onkeyup = "count()" name = "bericht" class = "form-control" maxlength="100" cols = "40" rows = "2" placeholder = "Hier typen" required></textarea>

        <input type="submit" name = "verzend" value = "Verzenden" id = "verzenden">
        <input type="reset" name = "reset" value = "Leegmaken" id = "reset">

</form>

And php:
if (isset($_POST['gamertag']) && isset($_POST['bericht']) && !empty($_POST['gamertag']) && !empty($_POST['bericht'])){

$afbeelding_before = $_POST['gamertag'];
$vraag_before = $_POST['bericht'];

$cookie_var = $_POST['gamertag'];

$afbeelding = mysql_real_escape_string($afbeelding_before);
$vraag = mysql_real_escape_string($vraag_before);

setcookie("gamertag", $cookie_var, time() + (86400 * 30), "/",$_SERVER['SERVER_NAME']);

//echo $afbeelding . $vraag;

$sql3="INSERT INTO `shoutbox` (`id`, `gamertag`, `bericht`, `date`) VALUES (NULL, '$afbeelding', '$vraag', CURRENT_TIMESTAMP)";
mysql_query($sql3,$con);

echo "post gamertag ".$_POST['gamertag']."
";
echo "cookie ". $_COOKIE['gamertag']."
";

header('Location: http://link.nl#shoutbox');

}

else{
    echo 'Er ging iets fout...';
}

The cookie is not displaying in the form input called "gamertag" when redirected from the PHP code. But when I erase the #shoutbox from the link, it will display the cookie correctly. Navigating through different pages isn't a problem eighter. Only when redirecting from the PHP code it is not displayed.
I hope someone can help me!
Thanks!

A: Make sure that value in $_SERVER['SERVER_NAME'] is exactly link.nl and not www.link.nl. For browsers these are two different values so they create two different cookies.

A: Maybe you using invalid session id  or PHPSESSID. Could you check PHPSESSID?


text:
Q: User agent for mobile application htaccess file I have done a jquery mobile application. Now i want to run the url in mobile device only and desktop device are shoeing false.
After a long time i am trying the htaccess file in application folder where the index.html is there.
mY htaccess file is
RewriteCond %{REQUEST_URI} !^/http://originalsite.com/.*$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ /http://www.othersite.com/ [L,R=302]

NOW I can not get the effect in my site.
Is there something i missed here ?

A: Try with those lines:
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ http://www.othersite.com [L,R=302]


text:
Q: Controlling wave amplitude by arduino I built waveform generator using AD9833. It can produce sine and triangular wave with amplitude about 1.6 V and square wave with amplitude of 4.5 V. I'm searching for some circuit which can control amplitude of output wave and this amplitude can be set by arduino so something like PWM should be used.
In conclusion I am searching for a circuit which has:
First input - square, triangle or sine signal, frequency 1Hz to 1MHz. Signal is produced by AD9833. Its impedance should be 200 Ohms. Amplitude is 1.6 V for sine and triangle and 4.5 V for square.
Second input - signal from arduino about set amplitude
Wanted output - input signal with modified amplitude between 0 - 12 V. This output amplitude should be set by arduino.
I would like to hear some ideas which circuit should I use. I'm still a beginner and I need your help. Thanks for reply. I look forward to your ideas for solving my problem.

A: Classic answer : Multiplying DAC or MDAC, e.g. AD7528 (with two channels).
Apply audio input to the reference voltage pin. The output is a current, feeding an opamp in inverting configuration as an I-V converter.
Controlling the DAC's digital inputs then controls the gain of the analog input signal.
More here


text:
Q: What happens if a file with server-side code is deleted while being executed? If I write the following script (not just in php but any server-side language really):
<?php
  while (true)
  {
      sleep(4)
  }
?>

and I then run the file with the linux terminal like so: php file.php
QUESTION: What would happen if I delete the file itself? Was the process first stored in ram, and now is executing regardless of the existence or non-existence of file.php, would the process stop abruptly, or would something entirely different happen?

A: If it's already running, then it's already been loaded into memory, parsed and compiled, so it's running in memory.... deleting the file won't change that.... this is how compiled languages work, and contrary to many people's opinions, PHP is a compiled language.... it's compiled at execution time, and compiled to bytecode rather than to native machine code; but is still compiled nontheless

A: I am not sure about Windows, but in Unix based systems the following applies:
If a program (like php) opened a file descriptor (e.g. by opening the file and executing/interpreting the content) the file will remain in existence until the file descriptor is closed. However, the kernel will prevent programs from obtaining new file descriptors after it was removed, and then delete it "for real" when the last descriptor is closed.
In the case of PHP it is most likely like Mark said in his answer. PHP will consume the entire file in one go, and then run from memory. But given the above it will sill work fine even if the file is removed while the process is busy reading it.
For more info see the following man pages: unlink(2) and open(2)


text:
Q: wordpress exclude last post SHORTER question
I am using this to get recent posts
$args = array(  'posts_per_page' => 20,  'category' => $category );
$postslist = get_posts( $args );

but how would I exclude the last post? because for the newest post I want to do something different, for example to include an excerpt.
And i can call that separately..
I did some search and apparently there is offset, but I'm not sure if it will interfere with pagination when i get to that.
LONGER explanation
(In reality, I could do something like $i = 0 and increment it in foreach loop, and if it is $i==0 i can display an excerpt.. but things are getting somehow complicated since I would like to display them with bootstrap columns, so currently i have this code which puts every post inside col-md-3 but if it already has 4 columns in current row then do that in the next row..
    $args = array(  'posts_per_page' => 20,  'category' => $category );
    $postslist = get_posts( $args );

    $i = 0;
    foreach ( $postslist as $post ) :
    $i++;
    setup_postdata( $post ); ?>

    <?php if($i<4) : ?>

  the_title() and other stuff

    <?php else :
    $i = 0; ?>

 the_title() and other stuff

A: According to the docs, get_posts has an offset option.
Just use this like:
$args = array('posts_per_page' => 20, 'category' => $category, 'offset' => 1);
$postslist = get_posts($args);

This will return the 20 latest posts excluding the very last one.


text:
Q: Mongo DB Update - Not Deleting the Empty fields We are having Node Express API and the backend data store is Mongo DB. We use Mongoose package for interacting with the Mongo DB. The Mongoose Schema is as below:
const employeeSchema = new Schema<IEmployee, EmployeeModel>(
    {
        _id: { type: String, default: uuidv4() },
        providerIdentifier: { type: String, maxlength: 255 },
        firstName: { type: String, maxlength: 100 },
        lastName: { type: String, maxlength: 100 },
        hobbies: { type: String, maxlength: 1000 },
        employeeId: { type: String, maxLength: 4, immutable: true },
        department: { type: String, maxlength: 100 },
        phoneNumbers: [phoneNumberSchema],
        emails: [emailSchema],
    }
);

const emailSchema = new Schema<IEmail>(
    {
        emailAddress: { type: String, trim: true, maxlength: 255 },
        emailType: { type: String, trim: true },
    },
    { _id: false },
);

const phoneNumberSchema = new Schema<IPhoneNumbers>(
    {
        phoneNumber: { type: String, trim: true, maxlength: 50 },
        phoneType: { type: String, trim: true },
    },
    { _id: false },
);

In the mongo db for the employee document, we do have an extra field - isExecutive. This field is derived through a Mongo Trigger and is not exposed in the API and hence we are not maintaining it in the Mongoose Schema.
For updating a document, we are using findByIdAndUpdate command and pass the employee object obtained from the API request. We are facing an issue when trying to update. If an employee has hobbies data populated while creating the document in Mongo collection, if the hobbies field is not sent in the API, it should actually delete the field from the Mongo Document, but it is getting protected and is not removed. Same is the case with email and phone collections. If we do not send these collections, the data in the Mongo Data store is being protected. We could see that the findOneAndReplace is an option which will replace all the contents of the document. But, in that case, we will loose the isExecutive flag which is calculated internally and not exposed in the API.
Is there any way we can achieve this?


text:
Q: jQuery change css based on class of another element I have this code, it does check for a class and changes the CSS based on whether or not that class is present. However, it then keeps the CSS that way, with 37px top margin. How would I make it check again if the Class has been removed and change the CSS back?
function checkForStickyClass()
{
    if ($('.sticky-wrapper').hasClass('is-sticky'))
        $('#mobile-menu-wrap').css('top','37px');

    else
        setTimeout(checkForStickyClass, 100);
}

$(checkForStickyClass);

I tried to modify like
function checkForStickyClass()
{
    if ($('.sticky-wrapper').hasClass('is-sticky'))
        $('#mobile-menu-wrap').css('top','37px');

    else if
        (!$('.sticky-wrapper').hasClass('is-sticky'))
        $('#mobile-menu-wrap').css('top','0');
    else
        setTimeout(checkForStickyClass, 100);
}

$(checkForStickyClass);

Now this doesnt work because it keeps it at 0px at all times. Obviously I have some logic error here. Please help

A: You need to set that Timeout every time, so no else in front of setTimeout.
What is changing your class? Can you use that code to also change the style of #mobile-menu-wrap?

A: I got it! here's the working code, thx to Alex
function checkForStickyClass()
{
    setTimeout(checkForStickyClass, 100);
    if (jQuery('.sticky-wrapper').hasClass('is-sticky'))
        jQuery('#mobile-menu-wrap').css('top','37px');

    else if (!jQuery('.sticky-wrapper').hasClass('is-sticky'))
        jQuery('#mobile-menu-wrap').css('top','0px');
}

jQuery(checkForStickyClass);


text:
Q: Why using lifecycleScope in Fragment causes memory leak when used in ViewPager2? I have a screen with a view pager inside which I am using multiple fragment instances of same fragment class which are using Paging 3 to load data from server.
Inside onViewCreated I have this function,
onViewCreated() {
   fun updateList()
}

fun updateList() {
       lifecycleScope.launch {
            viewModel.orders.collectLatest {
                adapter?.submitData(it)
            }
        }
}

The above function was giving me a memory leak, couldn't find a solution and gave this a try and it worked. Still not able to find why it worked or whether this is the rightway to do it.
viewLifecycleOwner.lifecycleScope.launch {
            viewModel.orders.collectLatest {
                adapter?.submitData(it)
            }
}

Leak Logcat trace:
D/LeakCanary:
D/LeakCanary: ┬───
D/LeakCanary: │ GC Root: Input or output parameters in native code
D/LeakCanary: │
D/LeakCanary: ├─ dalvik.system.PathClassLoader instance
D/LeakCanary: │    Leaking: NO (InternalLeakCanary↓ is not leaking and A ClassLoader is never leaking)
D/LeakCanary: │    ↓ ClassLoader.runtimeInternalObjects
D/LeakCanary: ├─ java.lang.Object[] array
D/LeakCanary: │    Leaking: NO (InternalLeakCanary↓ is not leaking)
D/LeakCanary: │    ↓ Object[950]
D/LeakCanary: ├─ leakcanary.internal.InternalLeakCanary class
D/LeakCanary: │    Leaking: NO (HomeActivity↓ is not leaking and a class is never leaking)
D/LeakCanary: │    ↓ static InternalLeakCanary.resumedActivity
D/LeakCanary: ├─ com.awantunai.app.home.HomeActivity instance
D/LeakCanary: │    Leaking: NO (Activity#mDestroyed is false)
D/LeakCanary: │    mApplication instance of com.awantunai.app.base.AwanApplication
D/LeakCanary: │    mBase instance of androidx.appcompat.view.ContextThemeWrapper
D/LeakCanary: │    ↓ ComponentActivity.mActivityResultRegistry
D/LeakCanary: │                        ~~~~~~~~~~~~~~~~~~~~~~~
D/LeakCanary: ├─ androidx.activity.ComponentActivity$2 instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 348,5 kB in 8676 objects
D/LeakCanary: │    Anonymous subclass of androidx.activity.result.ActivityResultRegistry
D/LeakCanary: │    this$0 instance of com.awantunai.app.home.HomeActivity with mDestroyed = false
D/LeakCanary: │    ↓ ActivityResultRegistry.mKeyToLifecycleContainers
D/LeakCanary: │                             ~~~~~~~~~~~~~~~~~~~~~~~~~
D/LeakCanary: ├─ java.util.HashMap instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 504 B in 18 objects
D/LeakCanary: │    ↓ HashMap["fragment_978a66c7-ff9d-435c-a477-d49cb3df918d_rq#0"]
D/LeakCanary: │             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D/LeakCanary: ├─ androidx.activity.result.ActivityResultRegistry$LifecycleContainer instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 76 B in 3 objects
D/LeakCanary: │    ↓ ActivityResultRegistry$LifecycleContainer.mLifecycle
D/LeakCanary: │                                                ~~~~~~~~~~
D/LeakCanary: ├─ androidx.lifecycle.LifecycleRegistry instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 84,5 kB in 2074 objects
D/LeakCanary: │    ↓ Lifecycle.mInternalScopeRef
D/LeakCanary: │                ~~~~~~~~~~~~~~~~~
D/LeakCanary: ├─ java.util.concurrent.atomic.AtomicReference instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 12 B in 1 objects
D/LeakCanary: │    ↓ AtomicReference.value
D/LeakCanary: │                      ~~~~~
D/LeakCanary: ├─ androidx.lifecycle.LifecycleCoroutineScopeImpl instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,7 kB in 2042 objects
D/LeakCanary: │    ↓ LifecycleCoroutineScopeImpl.coroutineContext
D/LeakCanary: │                                  ~~~~~~~~~~~~~~~~
D/LeakCanary: ├─ kotlin.coroutines.CombinedContext instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,7 kB in 2041 objects
D/LeakCanary: │    ↓ CombinedContext.left
D/LeakCanary: │                      ~~~~
D/LeakCanary: ├─ kotlinx.coroutines.SupervisorJobImpl instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,7 kB in 2040 objects
D/LeakCanary: │    ↓ JobSupport._state
D/LeakCanary: │                 ~~~~~~
D/LeakCanary: ├─ kotlinx.coroutines.ChildHandleNode instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,7 kB in 2039 objects
D/LeakCanary: │    ↓ ChildHandleNode.childJob
D/LeakCanary: │                      ~~~~~~~~
D/LeakCanary: ├─ kotlinx.coroutines.StandaloneCoroutine instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,6 kB in 2038 objects
D/LeakCanary: │    ↓ JobSupport._state
D/LeakCanary: │                 ~~~~~~
D/LeakCanary: ├─ kotlinx.coroutines.ChildHandleNode instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,6 kB in 2036 objects
D/LeakCanary: │    ↓ ChildHandleNode.childJob
D/LeakCanary: │                      ~~~~~~~~
D/LeakCanary: ├─ kotlinx.coroutines.internal.ScopeCoroutine instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 83,6 kB in 2035 objects
D/LeakCanary: │    ↓ ScopeCoroutine.uCont
D/LeakCanary: │                     ~~~~~
D/LeakCanary: ├─ com.awantunai.app.home.cart.v3.OrderListFragment$updateAdapter$1 instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 61,6 kB in 1246 objects
D/LeakCanary: │    Anonymous subclass of kotlin.coroutines.jvm.internal.SuspendLambda
D/LeakCanary: │    ↓ OrderListFragment$updateAdapter$1.$adapter
D/LeakCanary: │                                        ~~~~~~~~
D/LeakCanary: ├─ com.awantunai.app.home.cart.v3.OrderAdapter instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 61,6 kB in 1244 objects
D/LeakCanary: │    ↓ RecyclerView$Adapter.mObservable
D/LeakCanary: │                           ~~~~~~~~~~~
D/LeakCanary: ├─ androidx.recyclerview.widget.RecyclerView$AdapterDataObservable instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 61,0 kB in 1218 objects
D/LeakCanary: │    ↓ Observable.mObservers
D/LeakCanary: │                 ~~~~~~~~~~
D/LeakCanary: ├─ java.util.ArrayList instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 60,9 kB in 1217 objects
D/LeakCanary: │    ↓ ArrayList[0]
D/LeakCanary: │               ~~~
D/LeakCanary: ├─ androidx.recyclerview.widget.RecyclerView$RecyclerViewDataObserver instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 60,9 kB in 1215 objects
D/LeakCanary: │    ↓ RecyclerView$RecyclerViewDataObserver.this$0
D/LeakCanary: │                                            ~~~~~~
D/LeakCanary: ├─ androidx.recyclerview.widget.RecyclerView instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 60,9 kB in 1214 objects
D/LeakCanary: │    View not part of a window view hierarchy
D/LeakCanary: │    View.mAttachInfo is null (view detached)
D/LeakCanary: │    View.mID = R.id.rv_orders
D/LeakCanary: │    View.mWindowAttachCount = 1
D/LeakCanary: │    mContext instance of com.awantunai.app.home.HomeActivity with mDestroyed = false
D/LeakCanary: │    ↓ View.mParent
D/LeakCanary: │           ~~~~~~~
D/LeakCanary: ├─ androidx.swiperefreshlayout.widget.SwipeRefreshLayout instance
D/LeakCanary: │    Leaking: UNKNOWN
D/LeakCanary: │    Retaining 57,2 kB in 1113 objects
D/LeakCanary: │    View not part of a window view hierarchy
D/LeakCanary: │    View.mAttachInfo is null (view detached)
D/LeakCanary: │    View.mID = R.id.swipe_to_refresh
D/LeakCanary: │    View.mWindowAttachCount = 1
D/LeakCanary: │    mContext instance of com.awantunai.app.home.HomeActivity with mDestroyed = false
D/LeakCanary: │    ↓ View.mParent
D/LeakCanary: │           ~~~~~~~
D/LeakCanary: ╰→ androidx.coordinatorlayout.widget.CoordinatorLayout instance
D/LeakCanary:      Leaking: YES (ObjectWatcher was watching this because com.awantunai.app.home.cart.v3.OrderListFragment received
D/LeakCanary:      Fragment#onDestroyView() callback (references to its views should be cleared to prevent leaks))
D/LeakCanary:      Retaining 52,8 kB in 1015 objects
D/LeakCanary:      key = 80c7cbe8-db9d-49d9-8607-03f6b9e662bc
D/LeakCanary:      watchDurationMillis = 5964
D/LeakCanary:      retainedDurationMillis = 949
D/LeakCanary:      View not part of a window view hierarchy
D/LeakCanary:      View.mAttachInfo is null (view detached)
D/LeakCanary:      View.mID = R.id.parentLayout
D/LeakCanary:      View.mWindowAttachCount = 1
D/LeakCanary:      mContext instance of com.awantunai.app.home.HomeActivity with mDestroyed = false
D/LeakCanary:
D/LeakCanary: METADATA
D/LeakCanary:
D/LeakCanary: Build.VERSION.SDK_INT: 32
D/LeakCanary: Build.MANUFACTURER: Google
D/LeakCanary: LeakCanary version: 2.8.1
D/LeakCanary: App process name: com.awantunai.app.alpha
D/LeakCanary: Stats: LruCache[maxSize=3000,hits=134631,misses=245082,hitRate=35%]
D/LeakCanary: RandomAccess[bytes=14017705,reads=245082,travel=175631031479,range=69026744,size=98758092]
D/LeakCanary: Analysis duration: 25897 ms

A: Did some research and realized that viewLifeCycleOwner.lifecycleScope is bound to lifecycle starting from onCreateView to onDestroyView.
On the other hand, if we use just use this.lifecycleScope, this scope will be bound starting from onAttach to onDetach.
In the above expression, let's say the view got destroyed when i moved to the other fragment and after this before calling onDetach i get response in
viewModel.orders.collectLatest {
adapter?.submitData(it)
}

This will access recyclerview when fragment's view is destroyed because its holding reference to adapter and cause a memory leak
Here is some reference:
https://cs-ibrahimyilmaz.medium.com/viewlifecycleowner-vs-this-a8259800367b


text:
Q: Show all compile errors in FlexBuilder? Is it possible to make FlexBuilder show all compile errors in all files? FlexBuilder does not show errors in Action Script files, that are not referenced. Also very often I fix a problem just to see new problems pop up after compiling the whole project although these errors existed long before.
IntelliJ is showing all compile errors it can find and I would like to have FlexBuilder behaving the same way since IntelliJ is not mature enough to handle our complex set up. Is there a compiler switch to enable this?

A: The compiler can (and will) show errors only in code that you tell it to compile, and like you said, whatever is not referenced in the code you compile, will not be compiled, and thus, checked by the compiler.
So if you want to have the compiler check some part of your code, you need to tell it to compile it. I'm not sure how your projects are set up, but I'm assuming that you're compiling a bunch of smaller projects that are all using different parts of a shared codebase (or something similar.) In this case, you could either:

*

*set up some sort of "master" project that references all of your code, compiling which would then check for errors everywhere (maybe you have this already, in which case the solution is simply to compile this regularly)

*set up a job/target for compiling the AsDoc documentation for all of your code -- you could then run this regularly and at the same time you'd be keeping your API docs up to date

A: The following MXMLC compiler arguments might be useful:
-includes className [...]
Links one or more classes into the output SWF, regardless of whether they are required at compile time.
-include-libraries swcPath [...]
Links the entire contents of one or more SWC libraries into the output SWF, regardless of whether its classes are required at compile time.


text:
Q: Resolving localhost in email template in WSO2 IS About reset password email template, in WSO2 IS, is there any params to render server IP?
For example, something like {first-name} tag.

A: AFAIK, currently WSO2 IS doesn't support Server IP parameter in email templates.
If you are trying to generate recovery links with server IPs, I suggest it's better if you can use domain names.
Regards,
Lasitha.