text:
Q: Creating Rounded Edges for a Polygon in Python I came across this interesting question (How to make a tkinter canvas rectangle with rounded corners?) related to creating rounded rectangles in Tkinter and specifically, this answer by Francisco Gomes (modified a bit):
def roundPolygon(x, y, sharpness):

    # The sharpness here is just how close the sub-points
    # are going to be to the vertex. The more the sharpness,
    # the more the sub-points will be closer to the vertex.
    # (This is not normalized)
    if sharpness < 2:
        sharpness = 2

    ratioMultiplier = sharpness - 1
    ratioDividend = sharpness

    # Array to store the points
    points = []

    # Iterate over the x points
    for i in range(len(x)):
        # Set vertex
        points.append(x[i])
        points.append(y[i])

        # If it's not the last point
        if i != (len(x) - 1):
            # Insert submultiples points. The more the sharpness, the more these points will be
            # closer to the vertex.
            points.append((ratioMultiplier*x[i] + x[i + 1])/ratioDividend)
            points.append((ratioMultiplier*y[i] + y[i + 1])/ratioDividend)
            points.append((ratioMultiplier*x[i + 1] + x[i])/ratioDividend)
            points.append((ratioMultiplier*y[i + 1] + y[i])/ratioDividend)
        else:
            # Insert submultiples points.
            points.append((ratioMultiplier*x[i] + x[0])/ratioDividend)
            points.append((ratioMultiplier*y[i] + y[0])/ratioDividend)
            points.append((ratioMultiplier*x[0] + x[i])/ratioDividend)
            points.append((ratioMultiplier*y[0] + y[i])/ratioDividend)
            # Close the polygon
            points.append(x[0])
            points.append(y[0])

When I adapted this code to work with my graphics library, it worked well enough! but when I create a 'stretched-square' (a non-square rectangle), the roundness becomes stretched too:

So how can I change this code to remove the stretched roundness and keep it a constant radius?

A: Here is one approach that uses the built in tcl tk primitives canvas.create_line, and canvas.create_arc to build rectangles of various sizes, and proportions with round corners (arc of a circle).
The corners radii is expressed as a proportion of the shortest side of the rectangle (0.0 --> 0.5), and can be parametrized.
The function make_round_corners_rect returns a tuple containing all canvas item ids as fragments of the rectangle entity. All fragments are tagged with their companions' ids, so accessing the entire object is possible with only one fragment id.

#! python3

import math
import tkinter as tk
from tkinter import TclError

def make_round_corners_rect(canvas, x0, y0, x1, y1, ratio=0.2, npts=12):

    if x0 > x1:
        x0, x1 = x1, x0
    if y0 > y1:
        y0, y1 = y1, y0

    r = min(x1 - x0, y1 - y0) * ratio

    items = []

    topleft = x0, y0
    tld = x0, y0 + r
    tlr = x0 + r, y0
    item = canvas.create_arc(x0, y0, x0+2*r, y0+2*r, start=90, extent=90, fill='', outline='black', style=tk.ARC)
    items.append(item)

    top_right = x1, y0
    trl = x1 - r, y0
    trd = x1, y0 + r
    item = canvas.create_line(*tlr, *trl, fill='black')
    items.append(item)
    item = canvas.create_arc(x1-2*r, y0, x1, y0+2*r, start=0, extent=90, fill='', outline='black', style=tk.ARC)
    items.append(item)

    bot_right = x1, y1
    bru = x1, y1 - r
    brl = x1 - r, y1
    item = canvas.create_line(*trd, *bru, fill='black')
    items.append(item)
    item = canvas.create_arc(x1-2*r, y1-2*r, x1, y1, start=270, extent=90, fill='', outline='black', style=tk.ARC)
    items.append(item)

    bot_left = x0, y1
    blr = x0 + r, y1
    blu = x0, y1 - r
    item = canvas.create_line(*brl, *blr, fill='black')
    items.append(item)
    item = canvas.create_arc(x0, y1-2*r, x0+2*r, y1, start=180, extent=90, fill='', outline='black', style=tk.ARC)
    items.append(item)
    item = canvas.create_line(*blu, *tld, fill='black')
    items.append(item)

    items = tuple(items)
    print(items)

    for item_ in items:
        for _item in items:
            canvas.addtag_withtag(item_, _item)

    return items

if __name__ == '__main__':

    root = tk.Tk()
    canvas = tk.Canvas(root, width=500, height=500)
    canvas.pack(expand=True, fill=tk.BOTH)

    TL = 100, 100
    BR = 400, 200
    make_round_corners_rect(canvas, *TL, *BR)

    TL = 100, 300
    BR = 400, 400
    make_round_corners_rect(canvas, *TL, *BR, ratio = .3)

    TL = 300, 50
    BR = 350, 450
    that_rect = make_round_corners_rect(canvas, *TL, *BR, ratio=.4)
    for fragment in that_rect:
        canvas.itemconfig(fragment, width=4)
        try:
            canvas.itemconfig(fragment, outline='blue')
        except TclError:
            canvas.itemconfig(fragment, fill='blue')

    TL = 150, 50
    BR = 200, 450
    make_round_corners_rect(canvas, *TL, *BR, ratio=.07)

    TL = 30, 30
    BR = 470, 470
    that_rect = make_round_corners_rect(canvas, *TL, *BR, ratio=.3)
    for fragment in that_rect:
        canvas.itemconfig(fragment, dash=(3, 3))

    TL = 20, 20
    BR = 480, 480
    make_round_corners_rect(canvas, *TL, *BR, ratio=.1)

    root.mainloop()

The next step, (left to the reader as an exercise), is to encapsulate the round rectangles in a class.

Edit: how to fill a rounded corners rectangle:
It is a bit involved, and in the long run, probably requires an approach where all points are explicitly defined, and the shape is formed as a polygon, instead of the aggregation of tkinter primitives. In this edit, the rounded corners rectangle is filled with two overlapping rectangles, and four disks; it allows to create a filled/unfilled shape, but not to change that property after creation - although it would not require too much work to be able to do this too. (collecting the canvas ids, and turning them on/off on demand, in conjunction with the outline property); however, as mentioned earlier, this would make more sense to encapsulate all this behavior in a class that mimicks the behavior of tk.canvas.items.
def make_round_corners_rect(canvas, x0, y0, x1, y1, ratio=0.2, npts=12, filled=False, fillcolor=''):
    ...
    if filled:
        canvas.create_rectangle(x0+r, y0, x1-r, y1, fill=fillcolor, outline='')
        canvas.create_rectangle(x0, y0+r, x1, y1-r, fill=fillcolor, outline='')
        canvas.create_oval(x0, y0, x0+2*r, y0+2*r, fill=fillcolor, outline='')
        canvas.create_oval(x1-2*r, y0, x1, y0+2*r, fill=fillcolor, outline='')
        canvas.create_oval(x1-2*r, y1-2*r, x1, y1, fill=fillcolor, outline='')
        canvas.create_oval(x0, y1-2*r, x0+2*r, y1, fill=fillcolor, outline='')
    ...

if __name__ == '__main__':
    ...
    TL = 100, 300
    BR = 400, 400
    make_round_corners_rect(canvas, *TL, *BR, ratio=.3, filled=True, fillcolor='cyan')
    ...


text:
Q: Ajax form not rendering partial I'm trying to implement a follow/unfollow form to create/destroy a relationship between a user, and a company on a site. I'm having problems rendering a new partial on form submit, to change the relationship button from "follow" to "unfollow"
Currently, I render a different partial depending on whether or not a relationship already exists:
`<% unless current_user.id == @company.user_id  %>

    <% if current_user.following?(@company)  %>
      <%= render :partial => 'unfollow' %>
    <% else  %>
      <%= render :partial =>  'follow' %>
    <% end %>

<% end %>`

The follow partial looks like:
<%= form_for(current_user.relationships.build(followed_id: @company.id), remote: true) do |f| %>

<%= f.hidden_field :followed_id %>

  <%= f.submit "Follow",class: "btn-transparent btn-hollow btn-huge" %>
<% end %>

While the unfollow partial looks like:
<%= form_for(current_user.relationships.find_by(followed_id: @company.id), html: { method: :delete }, remote: true) do |f| %>
  <%= f.submit "Unfollow", class: "btn-transparent btn-hollow  btn-huge" %>
<% end %>

These use Create and Destroy methods in my Relationships_Controller:
class RelationshipsController < ApplicationController
  before_filter :authenticate_user!

  def create
    @company = Company.find(params[:relationship][:followed_id])
    current_user.follow!(@company)
    respond_to do |format|
      format.html { redirect_to @company }
      format.js {render layout: false}
    end
  end

  def destroy
    @company = Relationship.find(params[:id]).followed
    current_user.unfollow!(@company)
    respond_to do |format|
      format.html { redirect_to @company }
      format.js{render layout: false}
    end
  end
end

If I set remote: false, the form works as expected, creating and destroying relationships, and the button changes on page reload. When I try to use AJAX by setting remote: true, and use the code below for relationships/create.js.erb and relationships/destroy.js.erb
$("#relationship").html("<%= j render('companies/unfollow') %>");

$("#relationship").html("<%= j render('companies/follow') %>");

However, now when I reload my page - I can click on the button once to create/destroy a relationship object. If I click again, I get a 500 error. The new partial is never loaded.
Although I'm a bit of a noob, this error in seems to point me to this line in the jquery source in chrome dev tools:
xhr.send( ( options.hasContent && options.data ) || null );

I'm using Rails 4, Jquery-Turbolinks and Devise - if any of them bare any relevance to the problem.
Incredibly frustrated now, if anyone could help that would be greatly appreciated!
Update
The log output is below. The first DELETE says that it has rendered my partial, however it has not. The second DELETE is what is happening on clicking unfollow a second time - it rightly points out that the Relationship with that id number no longer exists, as it was deleted on the first action.
Started DELETE "/relationships/429" for 127.0.0.1 at 2014-10-28 14:34:59 +0000
Processing by RelationshipsController#destroy as JS
  Parameters: {"utf8"=>"✓", "commit"=>"Unfollow", "id"=>"429"}
  [1m[36mUser Load (1.0ms)[0m  [1mSELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1[0m
  [1m[35mRelationship Load (0.4ms)[0m  SELECT  "relationships".* FROM "relationships"  WHERE "relationships"."id" = $1 LIMIT 1  [["id", 429]]
  [1m[36mCompany Load (0.3ms)[0m  [1mSELECT  "companies".* FROM "companies"  WHERE "companies"."id" = $1 LIMIT 1[0m  [["id", 1]]
  [1m[35mRelationship Load (0.3ms)[0m  SELECT  "relationships".* FROM "relationships"  WHERE "relationships"."follower_id" = $1 AND "relationships"."followed_id" = 1 LIMIT 1  [["follower_id", 1]]
  [1m[36m (0.2ms)[0m  [1mBEGIN[0m
  [1m[35mSQL (3.6ms)[0m  DELETE FROM "relationships" WHERE "relationships"."id" = $1  [["id", 429]]
  [1m[36m (0.5ms)[0m  [1mCOMMIT[0m
  Rendered companies/_follow.html.erb (2.5ms)
  Rendered relationships/destroy.js.erb (5.3ms)
Completed 200 OK in 19ms (Views: 7.0ms | ActiveRecord: 6.3ms)

Started DELETE "/relationships/429" for 127.0.0.1 at 2014-10-28 14:35:04 +0000
Processing by RelationshipsController#destroy as JS
  Parameters: {"utf8"=>"✓", "commit"=>"Unfollow", "id"=>"429"}
  [1m[35mUser Load (0.9ms)[0m  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
  [1m[36mRelationship Load (0.3ms)[0m  [1mSELECT  "relationships".* FROM "relationships"  WHERE "relationships"."id" = $1 LIMIT 1[0m  [["id", 429]]
Completed 404 Not Found in 4ms

ActiveRecord::RecordNotFound - Couldn't find Relationship with 'id'=429:

A: You have a hash in the name of your ID.
Try changing

to

A: When use remote: true you must change:
format.js{render layout: false}

with
format.js

Otherwise: you never render relationships/create.js.erb and relationships/destroy.js.erb

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't parse the token along with special characters like (+) we get from URL params in Nodejs I'm getting automatically generated token along with url like mentioned below:
https://localhost:3000/?token=ebkfJu12VQpfwX3YwAMo7PZoGYJftaMisMcL6VeNSz8IUmaywH64U2k6l8KFCblWXZfPbd9oJSshcwo/6p6cPrMtifFOXfduJbKTeitJqpIwAsq4CpaagGHdZpluUlDSsVlS2KoYQBS/XqxTcSLq+iS4wUWNpKYH8z7w9Vzs7AYPOZEFixSIslP9amBZWtTSIOi/NZkNheYJPRLHun6gHGRZTBAgp8y/6jPvCyjS8HCgqscEqhNponeGoazJAVZuxE1syphiv4EBkjigLIbDl2IoN77shBWwEgojmvmo8UuhV8WhnziXQQrdJU1nirjgCIJ84jxn5d+fjqQC0xfSJQ==

Since this token contains +, hence at the time of parsing const params = new URLSearchParams(tokenString); + is replaced by spaces. How to get the token untouched?
The output I am expecting is
{
  token: 'ebkfJu12VQpfwX3YwAMo7PZoGYJftaMisMcL6VeNSz8IUmaywH64U2k6l8KFCblWXZfPbd9oJSshcwo/6p6cPrMtifFOXfduJbKTeitJqpIwAsq4CpaagGHdZpluUlDSsVlS2KoYQBS/XqxTcSLq+iS4wUWNpKYH8z7w9Vzs7AYPOZEFixSIslP9amBZWtTSIOi/NZkNheYJPRLHun6gHGRZTBAgp8y/6jPvCyjS8HCgqscEqhNponeGoazJAVZuxE1syphiv4EBkjigLIbDl2IoN77shBWwEgojmvmo8UuhV8WhnziXQQrdJU1nirjgCIJ84jxn5d+fjqQC0xfSJQ=='
}


text:
Q: jQuery animation glitch? Here is a fiddle of the problem. I have a span with display: inline-block that contains another span, which I am slowly hiding. At the end, the container span momentarily "jumps back" to its initial position.
Is this a bug, or the expected behaviour?

A: The problem is when the animated (calculated) width becomes lower than 1px, the browser (at least my chrome) won't render that fraction, and the #text element snaps back to its original width.
You can view this behaviour if you increase the animation time to something very big (e.g. 25s) and watch the css-values in the console.
If you try this:
$('#text').delay(1000).animate({
    width: 1,
    height: 1,
    opacity: 0
}, 5000, function () {
  $(this).hide();
});

You'll get nearly the same animation without the snapping.

A: Not sure what your are trying to do exactly, but try this:

  Text 1

  Much more text

and possibly add a width to the container
.container {
  border: solid 3px blue;
  width:200px;
}


text:
Q: Create a function to flip every n characters in a string. Output should have no commas in it, but my output does var input = 'a short example';
var output = flipEveryNChars(input, 5);

The result should be ohs axe trelpma, but my result is o,h,s, ,ax,e, ,t,re,l,p,m,a.  Why are there still commas after using .join?

//function definition
function flipEveryNChars(input, n) {
  // split string into separate characters
  var splitStr = input.split(''); // splits every character and reassigned to new var
  var resultStr = []; // push into new array and return result as a string
  var incrementN = n;
  // iterate through input string

  for (let i = 0; i < splitStr.length; i++) {
    resultStr.push(splitStr.slice(i, incrementN));; // slices through i to incremtN
    // console.log('each iteration:', resultStr)
    i += n - 1 // increment by original n - 1 since i++  every loop
    incrementN += n // increment by original n
  }

  //iterate through new array
  for (let j = 0; j < resultStr.length; j++) {
    resultStr[j].reverse(); // reverse to flip characters
  }
  return resultStr.join("");
}

var input = 'a short example';
var output = flipEveryNChars(input, 5);
console.log(output);


text:
Q: Creating the mean average of every nth object in a specific column of a dataframe I am trying to average every n-th object of a specific column in a dataframe using the following code. I understand that using the for-loop is computationally inefficient. This is why I would like to ask whether there is a more efficient way to create the average of every n-th row? My data looks a little bit like this.
set.seed(6218)
n <- 8760
s1 <- sample(30000:70000, n)
s2 <- sample(0:10000, n)
inDf <- cbind(s1, s2)

EDIT:
I call h_average like this:
h_average(inDf, 24, 1, 1)
This would mean that I average every first point of "every" 24 point subset. So the points 1, 25, 49, 73,... Also I only do this for the first column.
Thanks in advance,
BenR
#' h_average
#'
#' Computing the average of every first, second, third, ... hour of the day/week
#'
#' @param data merged data
#' @param tstep hour-step representing the number of hours for a day/week
#' @param h hour, which should be averaged. Should be between 1 - 24/1 - 168.
#' @param x column number
#' @return mean average of the specific hour
h_average <- function(data, tstep, h, x) {
  sum_1 <- 0
  sum_2 <- 0
  mean  <- 0

  for (i in seq(h, nrow(data), tstep)){
    if(data[i,x]){
      sum_1 <- sum_1 + 1
      sum_2 <- sum_2 + data[i,x]
    }
  }
  mean <- sum_2/sum_1
  return(mean)
}

A: Just use a combination of rowMeans and subsetting. So something like:
n = 5
rowMeans(data[seq(1, nrow(data), n),])

Alternatively, you could use apply
## rowMeans is better, but
## if you wanted to calculate the median (say)
## Just change mean to median below
apply(data[seq(1, nrow(data), n),], 1, mean)

A: If the question is how to reproduce h_average but without the loop then
1) colMeans  Try this:
# assume inDf and h_average as defined in the question

tstep <- 24
h <- x <- 1

h_average(inDf, tstep, h, x)
##       s1
## 49299.09

# same but without loop
colMeans(inDf[seq(h, nrow(inDf), tstep), x, drop = FALSE])
##       s1
## 49299.09

This also works if x is a vector of column numbers, e.g. x = 1:2.
1a) This variation works too:
colMeans(inDf[seq_len(tstep) == h, x, drop = FALSE])

2) aggregate Another possibility is this:
aggregate(DF[x], list(h = gl(tstep, 1, nrow(inDf))), mean)[h, ]

which has the advantage that both x and h may be vectors, e.g.
x <- 1:2
h <- 1:3

DF <- as.data.frame(inDF)
aggregate(DF[x], list(h = gl(tstep, 1, nrow(inDf))), mean)[h, ]
##   h       s1       s2
## 1 1 49299.09 4964.277
## 2 2 49661.34 5177.910
## 3 3 49876.77 4946.447

To get all h then use h <- 1:tstep or just omit [h, ].
Note: InDf as defined in the question is a matrix and not a data frame as its name seems to suggest.
Update Some improvements in (1) and added (1a) and (2).


text:
Q: Using image as button to upload file I've never done much css so I apologize if this is an obvious question but I've tried a million things and nothing's worked. I currently have an image that I'm trying to use as an upload button. The problem right now is that it's not marked as a file input so there are no files selected when I call my uploadFile() function which causes, obviously, a whole bunch of problems. A lot of the fixes I've found still end up with the default "upload" button that comes with the browser.
Edit: I've seen this post - Replace input type=file by an image - and maybe I'm stupid but I can't seem to get it to be on the top right side of the screen where I want it, and whenever I use that fix I end up with a big white bar at the top of the screen. Again I'm not great with css so I'm probably missing an easy fix.
Edit2: I basically want to do exactly what this guy did but with the button on the right side of the page. https://stackoverflow.com/a/40235746/9830411
Here's the html:

And the CSS:
#uploadButton1{
right: 3vw;
}

A: If you want to do something like this Replace input type=file by an image, and just want the button to be on the right, maybe you mean something like this:

  <input id="file-input" type="file" />

*Just add align="right" in div tag.


text:
Q: AttributeError: 'function' object has no attribute 'CANVAS_WIDTH' i am trying to make an breakout game, and i have an error that i dont know what to do with, below i've attached the main code and the borders code, if you please can have a look and say whats wrong it will be wonderful
this is the main file:
from pedalClass import Pedal
from ballClass import Ball
import bordersClass
from turtle import *
import random
import time
import turtle

canvas=getcanvas()
CANVAS_WIDTH = canvas.winfo_width()
CANVAS_HEIGHT = canvas.winfo_height()

turtle.penup()
turtle.setup(800,500)
turtle.ht()
turtle.bgpic('breakout.gif')
TIME_STEP = 30
SQUARE_SIZE=20

ball1=Ball(1, 0.5, 0, 0)
mypad=Pedal(0.5, 0, -230, 5, 1)

def borders(cells):
    global mypad
    width=get_screen_width()
    height=get_screen_height()
    x=mypad.xcor()
    y=mypad.ycor()

if (mypad.xcor() > width):
    mypad.set_dx(-mypad.get_dx())
if (cell.ycor() > height):
    cell.set_dy(-cell.get_dy())
if (mypad.xcor() < -width):
    mypad.set_dx(-mypad.get_dx())
if (cell.ycor() < -height):
    cell.set_dy(-cell.get_dy())

def move_pedal(event):
    global mypad
    global CANVAS_WIDTH
    global CANVAS_HEIGHT
    mypad.goto(event.x-canvas.winfo_width()/2, mypad.ycor())
    CANVAS_WIDTH = canvas.winfo_width()
    CANVAS_HEIGHT = canvas.winfo_height()

def move_left(event):
    global mypad
    mypad.goto(event.x-1, mypad.ycor())

def move_right(event):
    global mypad
    mypad.goto(event.x+1, mypad.ycor())

canvas.bind("<Motion>", move_pedal)
canvas.bind("<Left>", move_left)
canvas.bind("<Right>", move_right)
getscreen().listen()

Playing=True
while Playing:
    print(borders.CANVAS_WIDTH)
    ball1.move()
    mypad.borders()
    mypad.move_pedal()
time.sleep(3)

and this is the borders class:
from turtle import *
canvas=getcanvas() # the canvas is the area that the turtle is moving (the white background)
CANVAS_WIDTH = canvas.winfo_width() # here we get canvas(screen) width
CANVAS_HEIGHT = canvas.winfo_height() # here we get the canvas(screen)height
def get_screen_width():
    global CANVAS_WIDTH
    return int(CANVAS_WIDTH/2-10)

# This function returns the height of the screen
def get_screen_height():
    global CANVAS_HEIGHT
    return int(CANVAS_HEIGHT/2-5)

and this is the error:
Traceback (most recent call last):
  File "C:\Users\User\Desktop\MEET-YL1-master\breakout\BreakoutNew.py", line 70, in <module>
    print(borders.CANVAS_WIDTH)
AttributeError: 'function' object has no attribute 'CANVAS_WIDTH'
[Finished in 2.4s with exit code 1]
[shell_cmd: python -u "C:\Users\User\Desktop\MEET-YL1-master\breakout\BreakoutNew.py"]
[dir: C:\Users\User\Desktop\MEET-YL1-master\breakout]
[path: C:\ProgramData\Oracle\Java\javapath;C:\Python34;C:\Users\User\AppData\Local\Programs\Python\Python35-32;C:\Program Files\Skype\Phone\]

i dont know why i have an error, someone?

A: You've defined borders as a function.  You can't have properties for it.
def borders(cells):
    global mypad
    width=get_screen_width()
    height=get_screen_height()
    x=mypad.xcor()
    y=mypad.ycor()

Perhaps you mean borders(CANVAS_WIDTH)?


text:
Q: API Gateway Proxy Without URL Redirection
*

*I'm using AWS API Gateway at https://console.aws.amazon.com/apigateway/home

*I did all of the steps to set up a proxy for http://foo.com (example)

*I deployed it and the URL is http://bar.com (example)

*When I go to http://bar.com/hello, it redirects me to http://foo.com/hello

*I want it to stay at http://bar.com/hello, but deliver the contents from http://foo.com/hello like a normal proxy service

Note: My primary intent is to get around CORS issues with a service

A: It seems to me that whatever service you're using is forcing the redirect like @Steve's comment mentioned. They might be forcing HTTP_REFERER to be a certain domain.
Since I don't know what service you're calling this is just a guess.


text:
Q: Netbook as server? I'm thinking about this as a substitute for cheap little embedded systems like soekrises, used for lightweight server tasks.
The major advantages that I see over current tiny systems:

*

*built in monitor + keyboard

*built-in ups

*more commoditization

You also get the low power, low noise, smallness, etc advantages.  You lose the potential for multiple ethernet connections, but that's fine if you're not routing/firewalling or can use vlans or usb adapters.  I expect speed and reliability will improve over the next few years as flash drives continue to improve and get cheaper.
Is this a good/bad idea?  Has anyone else done this?

A: The advantage of a Soekris or similar solution is that it is purpose-built. The hardware is usually very stable and oriented at its exact role. Your netbook could not perform any of the tasks for which Soekrises are generally intended:

*

*Router

*Firewall

*Bridge

*Wifi AP

*PBX Server

*Light-use file server

The first three are not options because you only have a single NIC. The last three because you have no PCI expansion capabilities (for AP-capable wifi card, PRI/phone line termination, and RAID card, respectively). USB ethernet/wifi adapters are simply not feasible replacements for built-in capabilities.
A built-in monitor/keyboard is really not much of an advantage. Most embedded systems pump console ouptut out their serial port - you don't want to have to worry about a screen/keyboard/trackpad/etc in your rack or under the stack of hardware.
The built-in UPS is an interesting idea, but not compelling enough to overcome the other glaring deficiencies in a netbook.
Netbooks and laptops are best used for their original intent - portable end-user computing. Possibly there are a few minor niches where this might be useful (hobbyists who just need something running a particular OS permanently connected to their network), but I can't think of any within the scope of this forum (IT Pro/Sysadmin).

A: I suspect it may be usable in a few niches, but the few netbooks I have actually had an opportunity to play with don't look like they are a reliable/well-built device.  I am not sure it would be wise to put anything of importance on one.
I guess if you keep good backups, and keep a spare around in case of a failure, and you can tolerate a short outage if there is a failure you could use one.

A: I'm running Ubuntu 9.04 with UNR on an Acer AspireOne.  It works really nicely.  The AA1 isn't the fastest machine, but it's not bad.  It's hard to see downside in what you're suggesting.
I guess there is the question of longevity, but at the price, it's hard not to think it's worth a try.  No RAID.  If it's in a dusty area, you going to have to pull it apart to clean the fan once in a while.

A: This actually sounds like a reasonably good idea to me, at least for small tasks.  The fact of having the display and keyboard built in as well as integrated battery backup I think seals the deal.

A: Clustering a few netbooks (over wifi!) seems like a great idea... eh, I mean, hobby project anyway... let's get to it I say ^^
(Ahem, well yes, as you say, it got the major components; battery, flash drive and low noise and energy consumption. Wether the hardware itself is built to withstand 24/7 operation without ever entering sleep or being shut down is a different matter altogether)


text:
Q: How to seek to a certain frame_no in VideoCapture object (C++)? Is there a way to seek to a certain index in a VideoCapture object?  I want to start reading the stream at a specific position.

A: you have to use
cap.set(CV_CAP_PROP_POS_FRAMES, index);
I the following code do your aim
        #include <iostream> // for standard I/O
        #include <opencv2/core/core.hpp>        // Basic OpenCV structures (cv::Mat, Scalar)
        #include <opencv2/imgproc/imgproc.hpp>  // Gaussian Blur
        #include <opencv2/highgui/highgui.hpp>  // OpenCV window I/O

        using namespace std;
        using namespace cv;

        int main()
        {
            string sourceVideoPath;
            sourceVideoPath = "C:\\opencvVid\\video.mp4";
            VideoCapture cap(sourceVideoPath);
            Mat frame;
            char c;
            cout << "Stream frame numbre : " << cap.get(CV_CAP_PROP_FRAME_COUNT)<<endl;
            if (!cap.isOpened())
            {
                cout  << "Could not open reference " << sourceVideoPath << endl;
                return -1;
            }
            int seek_step = 750 ; // start at frame 750
            int frameNum = 0;
            cap.set(CV_CAP_PROP_POS_FRAMES, seek_step );
            while (1){
                cap >> frame;
                if (frame.empty())
                {
                    cout << " < < <  Channel stream ended!  > > > ";
                    break;
                }

                cv::putText(frame, "Frame "+to_string(frameNum+seek_step),
                           cvPoint(30,30), FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(0,0,255), 1, CV_AA);
                imshow("frameNum", frame );
                        c = (char)cvWaitKey(22);
                        if (c == 27) break;
            ++frameNum;
            }
            return 0;
        }


text:
Q: Documentation on "Analyzer errors" codes? As noted here, when you receive an error of the form
001272 : Analyzer errors were encountered (codes = <value>).

this means that the attempt to stage and publish a service failed.
The tool provides a set of codes in the error message, but the documentation I linked to only tells you to fire up an ArcGIS Desktop tool to find out the problem. Instead, I would prefer to use the code to look up what the error is; this would be especially helpful to me since the publish is happening automatically in Python via arcpy.
Is there a resource that tells us what the codes mean?
I am using 10.2 at the moment and will soon be upgrading to 10.3.

A: It appears that the documentation of the error codes can be found in the Technical guide for map services. Specifically, the documentation is in the Prepare window messages section. The codes in that list are padded with leading zeros, but the numbers themselves match up.


text:
Q: How to use the onClick Function in Next js I am a beginner and I am trying to learn Next js. I have a webpage which has a card and in the card i have an Arrow Right. I want a link to open when the Arrow right is clicked.
I have this code for the ArrowRight and I basically want to open a link, lets say google.com in a new tab on the click of this.
<ArrowRight
        className="heart"
        onClick={}
      />

A: you can simply wrap it with "a" tag
like this :

       <ArrowRight
        className="heart"
      />

or you can use Link component of nextjs
like this :
<Link href="https://google.com" rel="noopener noreferrer" target="_blank">
      <ArrowRight
        className="heart"
      />
 </Link>

A: I'm not doing Next.js. But I hope this will work
 export default function SampleComponent(){

        const redirectPage= (e) => {
            e.preventDefault()
            document.location.href = 'https://google.com/';
        }
        return(

                <ArrowRight
            className="heart"
            onClick={() => redirectPage()}
          />

        )
    }

A: You can do two things,
Option 1
Use Link tag,
import Link from "next/link";

<Link  href="https://www.google.com/" target="_blank">
       <ArrowRight
        className="heart"
      />
    </Link >

second One
You can use Programmatic navigation.
This has two variation. If you need to route within your App.
import { useRouter } from "next/router";

const YourComponent = props => {
  const router = useRouter();

  const routeWithinYourApp = () => {
    Router.push("INTERNAL URL");
  };

  return <ArrowRight className="heart" onClick={routeWithinYourApp} />;
};

If you use external web URL,
nothing special,
window.location = 'YOUR EXTERNAL LINK';

A: <ArrowRight
  className="heart"
  onClick={() => window.open("google.com", "_blank")}
/>


text:
Q: Open a Record from MSCRM Dashboard by Selenium Webdriver I am writing Script to open a Record from Dash Board of MSCRM 2011. Those Records are arranged in table as Checkbox inside a Frame. So on double click of Checkbox Record Page will open
Below is Exception which i am getting
java.util.NoSuchElementException
    at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
    at java.util.LinkedHashMap$KeyIterator.next(Unknown Source)
    at Ford_Account.main(Ford_Account.java:112)

Below is Webdriver Code
WebElement link = w1.findElement(By.xpath("html/body/div[5]/div[1]/div[2]/span/ul/li[2]/ul/li[1]/a[1]"));  //COntact click
link.click();

w1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try {
    windows= w1.getWindowHandles();
    iterator=windows.iterator();

    while((iterator.hasNext())){
        parent=iterator.next();
        child=iterator.next();
        w1.switchTo().window(child);
        System.out.println("Swicthed to child");
        Thread.sleep(1000);
    }
    w1.switchTo().frame("contentIFrame");

    Actions ac = new Actions(w1);
    WebElement element = (WebElement) ac.moveToElement(w1.findElement(By.id("checkBox_{EE9744AC-6737-E511-8459-E4115BDF9DFD}")));
    ac.doubleClick(element).perform();

I am Getting Exception on
child=iterator.next();

Below is HTML Structure

<!DOCTYPE html>

<colgroup>

<input id="checkBox_{21C2F87E-9E36-E511-8459-E4115BDF9DFD}" class="ms-crm-RowCheckBox" type="checkbox" style=" " title="ford Account123" tabindex="0">

Can anyone Suggest me how to open a record from dashboard of MSCRM 2011


text:
Q: Php метод GET Доброго времени.
Сделал простенький сайт, все страницы генерируются через index.php, согласно значению переменной page, переданной через $_GET['page']. Далее на одной из страниц, к примеру, ($_GET['page'] = cat_blobe), нужно через форму методом GET передать значение input. При нажатии сабмит все слетает, так как через GET отправляются только переменные формы, и page больше не существует.
Правильно ли я понимаю, что здесь решением того, чтобы остаться на этой же странице, есть передача текущего значения переменной page, поместив её в скрытый инпут?
<input type="hidden" name="page" value="cat_blobe">

Заранее спасибо.
A: Может, в форме action="index.php?page=cat_blobe" method="get"?  - работать не будет - браузер вытащит из index.php?page=cat_blobe только index.php и отправит только значения формы.
Есть много путей решения. Самые простые:

*

*Через JS - при нажатии на кнопку отправить сами собираете параметры и делайте редирект на страницу.

*Аction="index.php?page=cat_blobe" method="post" - данные из формы будут в POST массиве.

*Как вы и указали - через скрытое поле.

*Можно в куки положить.


text:
Q: Apache Ivy: Restrict Publishing to a Repository I'd like to have a setup where developers can resolve/retrieve dependencies from a URL Resolver (a remote, in-house server hosting our repo) but cannot publish to it (for security and code integrity reasons).
However, for their Ivy clients to "see" the remote repo so they can pull dependencies down off of it, I need to expose the URL in the resolve/retrieve patterns inside our Ant builds. This includes the username & password!
How do I give them "read" (resolution) access, but not "write" (publishing) access?!?!

A: Use a repository manager like Nexus, Archiva or Artifactory that has a security model for the repository access. It will allow you to create a read only user for the repository that you give to the developers.

A: Presumably the ant builds that are allowed to publish run on servers other than the developers' machines?
In which case, put the username and password into environment variables on those servers and read them using the environment option on the Property task.
Alternatively, read the username and password from a local file.
In any case, keep the credentials local to the machine which should have the permission to publish.


text:
Q: reordered and duplicated packets when using UDP over loopback interface We are seeing UDP packets being reordered and duplicated when being sent over lo. We can see this because we're sending MPEG transport streams, which have their own sequence number in their headers, though it can also be seen by sending the traffic as RTP and seeing packets come in reordered that way. This may be potentially related to this question, though we are not doing large writes, as we're using code that sends data over networks, so our packets fit in 1500 byte frames.
We've tried configuring RFS with the default suggested configurations (our lo has only one rx-queue), but this doesn't seem to make a difference. This seems to occur regardless of application, whether its our own UDP/RTP code or an application like srt-live-transmit (we didn't test FFMPEG but it probably behaves similarly).
This is on Redhat 8.3 (kernel 4.18.0-240.15.1.el8_3).

A: Try enabling RPS:
cat /sys/devices/virtual/workqueue/cpumask > /sys/class/net/lo/queues/rx-0/rps_cpus

Packet reordering is expected but RPS is a fix that should continue to work in the future:
https://lore.kernel.org/netdev/20221202133902.7888c0ce@kernel.org/


text:
Q: What is the keyboard shortcut to "replace next" in PyCharm? In PyCharm, what is the keyboard short-cut to replace the next occurrence of a word?
I know that Ctrl+R opens the dialogue to replace words, but is there a shortcut that actually does the replacing of the word, so I don't have to use the mouse to press the Replace button every time?

A: Buttons/options of the Replace dialog can be accessed using mnemonics, press the Alt key to see them, pressing AltP will have the same effect as clicking on the Replace button.


text:
Q: Wand python get pixel color with GIF I want get rgb color some pixel in gif
from wand.image import Image
with Image(blob=img, format='JPG') as picture:
    print picture[1][1].string
    # return srgb(0,0,0) is good

Problem:
from wand.image import Image
with Image(blob=img, format='GIF') as picture:
    print picture[1][1].string
    # return srgb(93%,93%,93%) why?

A: This is how color compliance works. Not all parts of the pixel in question can be represented as a 8-bit unsigned integer, so it's represented as a normalized percent -- between 0% and 100%.
Try the following...
from wand.image import Image
with Image(blob=img, format='GIF') as picture:
    picture.depth = 8
    print picture[1, 1].string
    #=> srgb(274,274,274)

A: This is my code for png (python3)
from wand.image import Image

with Image(filename='white_background_320x200_edited_alphaoff.png') as img:
    print(img[1][1])


text:
Q: Powershell - how to present choice of which AD OU to run against? I'm not a scripter and I'm trying to figure out how to allow the user a choice of what OU to run a script against.
I have the following basic script that enumerates through an OU and lists out some basic user object info to a CSV file:
$ADUserParams=@{
'Server' = 'ServerDC'
'Searchbase' = 'OU=ToBeDeleted,DC=domain,DC=com'
'Searchscope'= 'Subtree'
'Filter' = '*'
'Properties' = '*'
}

#This is where to change if different properties are required.

$SelectParams=@{
'Property' = 'SAMAccountname', 'CN', 'HomeDirectory'
}

get-aduser @ADUserParams | select-object @SelectParams | export-csv "c:\temp\tempoutput_users.csv" -Append -NoTypeInformation
Get-content "c:\temp\tempoutput_users.csv" | select -Skip 1 | Set-Content "C:\temp\UserOutput.csv"
Remove-Item "c:\temp\tempoutput_users.csv"

However, I would like to instead present the script runner a choice to be able to select which sub-OU inside the "ToBeDeleted" OU to run the rest of the script against.
For instance, if there is an OU called "September2016" and an OU called "October2016" both inside the "ToBeDeleted" OU, I would like the script to ask the person "Which OU would you like to run against?" and give them a numbered choice like:

*

*September2016

*October2016

and then they make a selection and the script runs against that particular sub-OU only and gets the user object info in that selected OU.
I looked up a few sites on giving "choices" but it seemed more like a Yes/No choice and I got lost.
Can anyone point me to the right direction to get this done?

A: Function Select-Array
{
    Param
    (
        $Array
    )
    $Count = 0
    Write-Host "Select Item"
    foreach ($Item in $Array)
    {
        Write-Host "$Count. $Item"
        $Count ++
    }
    $Selection = Read-Host
    return $Array[$Selection]
}

$OU = (Get-ADOrganizationalUnit -SearchBase 'OU=ToBeDeleted,DC=domain,DC=com'  -Filter * -SearchScope OneLevel).DistinguishedName

$ADUserParams=@{
'Server' = 'ServerDC'
'Searchbase' = $OU
'Searchscope'= 'Subtree'
'Filter' = '*'
'Properties' = '*'
}

$SelectParams=@{
'Property' = 'SAMAccountname', 'CN', 'HomeDirectory'
}

Get-ADUser @ADUserParams | select-object @SelectParams | export-csv "c:\temp\tempoutput_users.csv" -Append -NoTypeInformation
Get-Content "c:\temp\tempoutput_users.csv" | select -Skip 1 | Set-Content "C:\temp\UserOutput.csv"
Remove-Item "c:\temp\tempoutput_users.csv"


text:
Q: ReactJs: Prevent Rerender of wrapped component I'm trying to prevent a re-render when using custom hook for hours now -.-, need some help ;O|
(Dont know if I should call this custom hook or functional hoc though)
I have a MessageList component that display a SimpleMessage wrapped in WithAvatarHeader.
Here is my profiler result:

Every time I add a message to the list, all messages are rendered again.
This isn't happening when I only use SimpleMessage in MessageList
Is there a way to memo(WithAvatarHeader) ?
MessageList :
import React from "react";
import SimpleMessage from "./SimpleMessage";
import WithAvatarHeader from "./WithAvatarHeader";

const MessageList = props => {
  const Message = WithAvatarHeader(SimpleMessage);
  return (

      {props.messages.map(message => {
        return <Message message={message} key={message._id}/>;
      })}

  );
};

SimpleMessage:
import React, { memo } from "react";

const SimpleMessage = props => {
  return (

      {props.message}

  );
};

export default memo(SimpleMessage);

WithAvatarHeader:
import React from "react";

const WithAvatarHeader = WrappedComponent => props => {
  return <WrappedComponent {...props} />;
};

export default WithAvatarHeader;

Thanks for the help :-)

A: You should not declare component inside another component.
Once you move declaration outside:
const Message = WithAvatarHeader(SimpleMessage);
const MessageList = props => {
  return (

      {props.messages.map(message => {
        return <Message message={message} key={message._id}/>;
      })}

  );
};

you will be fine.
Reason is reconciliation process that decides what's to drop, what to create and what to update.
Besides your JSX says it still same element <Message> React checks component's constructor(it does not work with text representation from JSX). And it will referentially different(since you re-declare this constructor on next render). So React drops every <Message> and create them from scratch. Keeping declaration outside your MessageList means constructor is referentially the same so React will not re-create <Message> till key is the same.


text:
Q: xcodebuild gives an error for multiple implementation of AMSupportURLConnectionDelegate and AMSupportURLSession : "Which one is undefined." When I want to run any xcodebuild action it gives me the following error while the Xcode ide is working fine on Apple M1.
> xcodebuild -version
objc[72320]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x1dc35ab90) and /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x105ca42c8). One of the two will be used. Which one is undefined.
objc[72320]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x1dc35abe0) and /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x105ca4318). One of the two will be used. Which one is undefined.
Xcode 13.2.1
Build version 13C100

Both classes are implemented in /usr/lib/libauthinstall.dylib and also im another module, so I wanted check the /usr/lib/libauthinstall.dylib but it is not accessible
> open /usr/lib/libauthinstall.dylib
The file /usr/lib/libauthinstall.dylib does not exist.

A: I had the same issue again on M1. It seems the xcodebuild executable is Intel based. The error does not show if the xcodebuild process is started from a terminal running under Rosetta.
My Xcode was installed from the App Store.
Managed to fix it for terminal without Rosetta by removing Xcode and installing the 13.3 Xcode beta from: https://download.developer.apple.com/Developer_Tools/Xcode_13.3_beta/Xcode_13.3_beta.xip
Now the xcodebuild executable is compiled for Apple silicon and the issue is gone.

A: I resolved by adding arm64 to the excluded architectures.
Steps to resolve:

*

*Click your target

*Click Build Settings tab

*Make sure "all" tab is selected

*Expand debug / release / other stages under "Excluded Architectures"

*Add "arm64" next to "Any iOS Simulator SDK


text:
Q: Extract the last row of a pairs plot in R I have created this pairs plot of a 10X10 data frame. I am interested in extracting only the last row, as it shows the covariates (on x axis) against the response parameter of interest (on y axis) for each covariate. I have used basic R pairs plot, but if a solution exist for ggpairs I can easily modify the code below.
pairs.panels(data, smooth = TRUE, scale = FALSE, density = TRUE, ellipses = FALSE)

The pairs plot looks like this:

A: I wrote a package called psre (you can install it from CRAN) and it has a function called lsa() (which stands for Linear Scatterplot Array).  The function does what you want.  Here's how it works:
library(psre)
data(wvs)
lsa(sacsecval ~ resemaval + moral +
                pct_univ_degree + pct_female +
                pct_low_income,
    xlabels = c("Emancipative Vals", "Moral Perm",
                "% Univ Degree", "% Female", "% Low Income"),
    ylab = "Secular Values",
    data=wvs)

A: Use the arg horInd, which is documented in ?graphics::pairs.
library(psych)

pairs.panels(attitude, horInd = 7)

The original output:
pairs.panels(attitude)


text:
Q: Killing bash causes it to respawn itself I'm SSHed into my computer at home and I'm trying to format a drive.
lsof /dev/sdb2 shows:
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
bash    1366 mitch  cwd    DIR   8,18    24576    5 /media/mitch/1TBHDD

This is causing umount to not unmount that drive. I've tried killing the process with kill and kill -9 but each time, that /bin/bash process will come back under a new PID but still using /dev/sdb2
How do I kill this bash that just won't seem to die?
Some relevant outputs:
mitch@emerald /proc $ ps aux | grep bash
mitch     2339  0.0  0.0  23732  5048 pts/11   Ss   12:10   0:00 -bash
mitch     3711  0.2  0.0  23688  4780 pts/0    Ss+  14:01   0:00 /bin/bash
mitch     3781  0.0  0.0  11748   912 pts/11   S+   14:01   0:00 grep --colour=auto bash
mitch    14159  0.0  0.0  23628  4688 pts/9    Ss+  Jan04   0:00 /bin/bash

mitch@emerald /proc $ lsof /dev/sdb2
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
bash    3711 mitch  cwd    DIR   8,18    24576    5 /media/mitch/1TBHDD

A: @muru had me look at the ps tree for that PID
pstree -ps 3711
init(1)───mdm(1405)───mdm(1431)───cinnamon-sessio(1935)───nemo(2488)───bash(3711)

So you see that nemo (Mint's file manager) is using it. This is because of an addon, nemo-terminal installed, which puts a bash shell in nemo. I guess that the behavior of when it dies is to immediately respawn the bash shell.
Killing PID 2488 did the trick.


text:
Q: The method getLogger(String) is undefined for the type Logger - from log4j 1.x to log4j 2.x migration I am doing migration from Log4j 1.x to Log4j 2.x version
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

The above are the new import statements -
Logger.getLogger(ABC.class.getName()).setLevel(Level.DEBUG);
Logger.getLogger(XYZ.class.getName()).setLevel(Level.DEBUG);

Error which I see is

The method getLogger(String) is undefined for the type Logger

What can I try to resolve this?

A: The factory method is LogManager.getLogger in v2.
See https://logging.apache.org/log4j/2.x/manual/api.html
If you don't want to change any code, there is a bridge available between v1 and v2, see https://logging.apache.org/log4j/2.x/manual/migration.html


text:
Q: Importing anything from @angular/cdk in Cypress tests breaks the build with Angular 13 Since updating to Angular 13, my Cypress tests that are importing from @angular/cdk (mostly for using test harnesses on Angular material) fail to compile with the following error:
Error: Webpack Compilation Error
./node_modules/@angular/cdk/fesm2015/platform.mjs
Module not found: Error: Can't resolve '@angular/common' in 'C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\fesm2015'
resolve '@angular/common' in 'C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\fesm2015'
  Parsed request is a module
  using description file: C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\package.json (relative path: ./fesm2015)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\fesm2015\node_modules doesn't exist or is not a directory
      C:\dev\workspace\exp\cypress-test\node_modules\@angular\node_modules doesn't exist or is not a directory
      C:\dev\workspace\exp\cypress-test\node_modules\node_modules doesn't exist or is not a directory
      C:\dev\workspace\exp\node_modules doesn't exist or is not a directory
      C:\node_modules doesn't exist or is not a directory
      looking for modules in C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules
        using description file: C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
      looking for modules in C:\dev\workspace\exp\cypress-test\node_modules
        using description file: C:\dev\workspace\exp\cypress-test\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\package.json (relative path: .)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
      looking for modules in C:\dev\node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
      looking for modules in C:\dev\workspace\node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common is not a file
            .js
              Field 'browser' doesn't contain a valid alias configuration
          using description file: C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\package.json (relative path: ./node_modules/@angular/common)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.json doesn't exist
            .jsx
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.jsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.json doesn't exist
            .jsx
              Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.js doesn't exist
        .json
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.mjs doesn't exist
            .coffee
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.jsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.js doesn't exist
        .json
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.json doesn't exist
        .jsx
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.coffee doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.mjs doesn't exist
            .coffee
              Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.json doesn't exist
        .jsx
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.jsx doesn't exist
        .mjs
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.coffee doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.jsx doesn't exist
        .mjs
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.mjs doesn't exist
        .coffee
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.tsx doesn't exist
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.mjs doesn't exist
        .coffee
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.coffee doesn't exist
        .ts
          Field 'browser' doesn't contain a valid alias configuration
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.tsx doesn't exist
            as directory
              existing directory
                using path: C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index
                  using description file: C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\package.json (relative path: ./index)
                    no extension
                      Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.coffee doesn't exist
        .ts
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.ts doesn't exist
        .tsx
          Field 'browser' doesn't contain a valid alias configuration
            as directory
              C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common doesn't exist
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index doesn't exist
                    .js
                      Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.ts doesn't exist
        .tsx
          Field 'browser' doesn't contain a valid alias configuration
          C:\dev\node_modules\@angular\common.tsx doesn't exist
        as directory
          C:\dev\node_modules\@angular\common doesn't exist
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.js doesn't exist
                    .json
                      Field 'browser' doesn't contain a valid alias configuration
          C:\dev\workspace\node_modules\@angular\common.tsx doesn't exist
        as directory
          C:\dev\workspace\node_modules\@angular\common doesn't exist
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.json doesn't exist
                    .jsx
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.jsx doesn't exist
                    .mjs
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.mjs doesn't exist
                    .coffee
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.coffee doesn't exist
                    .ts
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.ts doesn't exist
                    .tsx
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.tsx doesn't exist
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\fesm2015\node_modules]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\node_modules]
[C:\dev\workspace\exp\cypress-test\node_modules\node_modules]
[C:\dev\workspace\exp\node_modules]
[C:\node_modules]
[C:\dev\node_modules\package.json]
[C:\dev\workspace\node_modules\package.json]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.js]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common]
[C:\dev\node_modules\@angular\common\package.json]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.json]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.js]
[C:\dev\workspace\node_modules\@angular\common\package.json]
[C:\dev\node_modules\@angular\common]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.jsx]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.json]
[C:\dev\workspace\node_modules\@angular\common]
[C:\dev\node_modules\@angular\common.js]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.mjs]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.jsx]
[C:\dev\workspace\node_modules\@angular\common.js]
[C:\dev\node_modules\@angular\common.json]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.coffee]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.mjs]
[C:\dev\workspace\node_modules\@angular\common.json]
[C:\dev\node_modules\@angular\common.jsx]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.ts]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.coffee]
[C:\dev\workspace\node_modules\@angular\common.jsx]
[C:\dev\node_modules\@angular\common.mjs]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common.tsx]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.ts]
[C:\dev\workspace\node_modules\@angular\common.mjs]
[C:\dev\node_modules\@angular\common.coffee]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\cdk\node_modules\@angular\common.tsx]
[C:\dev\workspace\node_modules\@angular\common.coffee]
[C:\dev\node_modules\@angular\common.ts]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index]
[C:\dev\workspace\node_modules\@angular\common.ts]
[C:\dev\node_modules\@angular\common.tsx]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.js]
[C:\dev\workspace\node_modules\@angular\common.tsx]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.json]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.jsx]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.mjs]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.coffee]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.ts]
[C:\dev\workspace\exp\cypress-test\node_modules\@angular\common\index.tsx]
 @ ./node_modules/@angular/cdk/fesm2015/platform.mjs 3:0-52 38:14-31
 @ ./cypress/integration/spec.ts

Any idea how to solve this? I assume it has something to do with the changes in the Angular Package Format..
See this repo for reproducing the issue: https://github.com/pongells/angular13-cypress

A: In the meanwhile, we found a workaround:
const webpackPreprocessor = require('@cypress/webpack-batteries-included-preprocessor')

module.exports = (on) => {
  on('file:preprocessor', webpackPreprocessor({
    typescript: require.resolve('typescript')
  }))
}

see: https://github.com/cypress-io/cypress/issues/19066


text:
Q: How can I feed input from a  element into a (MySQL) stored procedure? Problem
I would like a user to be able to select multiple options to search the database, (e.g. WHERE field IN (optionA, optionB, optionC)). The idea being that they select the options they would like in an HTML form, and then these options are passed to the stored procedure as parameters to be used in the WHERE clause.

Example
Let's assume we have experts who are singular experts - that is, they can each only be an expert in one technology. (I'm aware this is a rather silly example, and one would never usually want to structure a database this way! Just an example :) )

Steps taken to develop a solution so far
The first page displays a form allowing the user to select which technologies they are interested in.
<form action="showresult.php">
<select name="technologies[]" multiple>
    <option value="html">HTML</option>
    <option value="css">CSS</option>
    <option value="php">PHP</option>
    <option value="sql">SQL</option>
</select>
<input type="submit">
</form>

showresult.php should CALL a stored procedure, passing it the parameters of all selected technologies.
*(I'm not sure how to do this)*

The stored procedure itself will take the potentially multiple technologies as an IN parameter to the stored procedure to use in a WHERE IN clause.
DELIMITER //
CREATE PROCEDURE ExpertsInTechnologies(IN technologies VARCHAR(30))
BEGIN
    SELECT
        Name, Technology
    FROM
        SingularExperts
    WHERE
        Technology IN ( ... technologies ... );
END //
DELIMITER ;

Research so far

*

*I have been searching Stack Overflow and found several similar questions, however they all achieve slightly different things, apply to other flavours of SQL, and/or I struggle to understand them. This question describes a similar issue however the question (and answer provided) does not use prepared statements and is vulnerable to SQL injection.

*I updated the HTML so that the name technologies is technologies[] - so that it is passed as an array. This question tells me that to retrieve these values after they have been passed via GET, they can be accessed from $_GET['technologies'].


text:
Q: Syncing bookmarks between iCloud and Firefox I use Windows 7 and I've just got myself a lovely new iPhone. I've installed iCloud and it synchronizes my iPhone's calendar with Outlook, which is great, but I also prefer Firefox over Safari, but iCloud only apparently supports Safari or Internet Explorer (yuck).
Is there any way to sync bookmarks between Firefox/iCloud/iPhone?
Edit: A bit of research brings up a thing called Firefox Home - How does this fit in?

A: I use Xmarks, but this means that you'd have to have Safari or IE open (or at least the Xmarks client for them open) when you're on your desktop.
This way when you add/remove bookmarks from Firefox, Xmarks will bring it over to Safari, then Safari will bring it to iCloud.

A: It seems to me that your goal is to sync your bookmarks across multiple browsers, particularly Firefox on your PC and the built-in Safari browser on your iPhone.
If the use of iCloud isn't a hard requirement (and I don't know why it would be), then use XMarks instead.

*

*First, get an XMarks account.

*Second, install XMarks for Firefox.

*Third, install XMarks for iPhone.

[1] http://www.xmarks.com/
[2] https://addons.mozilla.org/en-US/firefox/addon/xmarks-sync/
[3] http://blog.xmarks.com/2010/08/xmarks-for-iphone-ipad-v127_8748.html


text:
Q: Trim end off of string in swift, getting error at runtime I'm making a calculator app in Swift, once my answer is obtained I want to display it in a UILabel. Only problem is I want to limit said answer to 8 characters. Here is my code:
let answerString = "\(answer)"
    println(answer)
    calculatorDisplay.text = answerString.substringToIndex(advance(answerString.startIndex, 8))

This does not return any compiler errors but at runtime I get:
fatal error: can not increment endIndex

Any and all help would be greatly appreciated.

A: There are two different advance() functions:
/// Return the result of advancing `start` by `n` positions. ...
func advance<T : ForwardIndexType>(start: T, n: T.Distance) -> T

/// Return the result of advancing start by `n` positions, or until it
/// equals `end`. ...
func advance<T : ForwardIndexType>(start: T, n: T.Distance, end: T) -> T

Using the second one you can ensure that the result is within the valid bounds of the string:
let truncatedText = answerString.substringToIndex(advance(answerString.startIndex, 8, answerString.endIndex))

Update for Swift 2/Xcode 7:
let truncatedText = answerString.substringToIndex(answerString.startIndex.advancedBy(8, limit: answerString.endIndex))

But a simpler solution is
let truncatedText = String(answerString.characters.prefix(8))

Update for Swift 3/Xcode 8 beta 6: As of Swift 3, "collections move
their index", the corresponding code is now
let to = answerString.index(answerString.startIndex,
                            offsetBy: 8,
                            limitedBy: answerString.endIndex)
let truncatedText = answerString.substring(to: to ?? answerString.endIndex)

The simpler solution
let truncatedText = String(answerString.characters.prefix(8))

still works.


text:
Q: PHP - Parsing String As Past Date Currently, I'm trying to parse out dates when messages were received into timestamps. I have the month and day but the year is not specified. The event always occurs at the most recent (human) reading of the time. It works great in most cases to do this:
$time = strtotime("Jan 2 8:38pm");

That returns a date for this year, which is correct. Unfortunately, I get problems when I try to do for example:
$time = strtotime("Dec 31 8:38pm");

That returns a date which hasn't happened yet, and wont happen for the whole rest of the year. Obviously, my message was not sent in the future. I need it to return December 31st of last year.
For weekdays, I had a solution by prepending 'last' before the weekday like so:
$time = strtotime("Last Saturday 8:38pm");

That always returned the time of the last Saturday. However, trying to do the same thing here doesn't work:
$time = strtotime("Last Dec 31 8:38pm");

This returns false. I know to decrement a date by 1 year, I can do this:
$time = strtotime("Dec 31 8:38pm -1 year");

And that works great for Dec 31. However, Jan 2 will now fail:
$time = strtotime("Jan 2 8:38pm -1 year");

One solution I thought of was to subtract off a year (86400 * 365) from the resulting value if it is past today's date. However, this result will fail if we passed over February of a leap year. In that case, we would end up with a time that was ahead by a day.
The best solution I came up with so far is this:
$time = strtotime($raw_time);
if ($time > time()) {
  $time = strtotime($raw_time." -1 year");
}

It seems kind of wasteful to make two calls to strtotime which I know is probably not a very efficient function. Is this the most elegant solution?
Is anyone aware of an option in strtotime which forces the dates to be in the past instead of in the future?
Is there another way to parse these dates that I should consider?
Efficiency is important for this because I am going to be parsing a lot of dates with it, but I would also like simple and readable code so I can understand it later.

A: Your approach is fine, as there is no date format to get what you want. Another approach could be using the DateTime class:
$datetime = new DateTime($raw_time);
if ($datetime > new DateTime()) {
    $datetime->modify('-1 year');
}

You could test which one of the two approaches is faster. My guess is that this is a micro-optimization that won't make a lot of difference.


text:
Q: Invalid input syntax for timestamp error with Postgres Copy command I am trying to load data in Postgres through COPY command in a SQL file
COPY <table name>  (<column1>, <column2>, <column3> etc etc) FROM stdin;

1    test1   test2   to_timestamp(1592818988000)

But I am getting this below error:

psql:/Users/sanupin/load.sql:1045: ERROR:  invalid input syntax for
type timestamp: "to_timestamp(1641278614000)" CONTEXT:  COPY
cstone_storage, line 1, column last_loaded:
"to_timestamp(1641278614000)"

Any idea what could be the problem? I know I have to convert the millisecond to second (div by 1000) on the epoch number, but not sure how else to proceed.

A: COPY does not evaluate expressions. It takes data only. The manual:

COPY moves data between PostgreSQL tables and standard file-system files.

(With the exception of an optional WHERE clause added with Postgres 12.)
To evaluate expressions, use INSERT.
I suggest to COPY to a temporary staging table - with a double precision column for the yet unconverted timestamp - and INSERT from there. See:

*

*COPY command: copy only specific columns from csv

*How to update selected rows with values from a CSV file in Postgres?


text:
Q: gnuplot setup VS Code Can't setup gnuplot in VS Code on Mac ('gnuplot.h' file not found).
Here are what I did:
1) installed gnuplot via brew;
2) also installed Gnuplot extension in VS Code;
3) opened VS Code Settings and searched for Gnuplot;
4) in the Gnuplot: Gnuplot Path specified the path;
5) restarted VS Code;
6) run program but still got an error 'gnuplot.h' file not found.

Could you please advise how to set it up?
Thanks!


text:
Q: unit test with actual method in c# Hi I'm working on unit test for my project and I want to check a getmin method in an abstract class that is named Measurementool. That method return a minimum value of selectedarea  matrix from current matrix. my project has a rectangle area that is really N*N  matrix .
and I need minimum value inside of matrix. I write unit test for debug and test the getmin value but I don't see desired value for actual value. selectedarea matrix filled with zero and not set with expected value in test method. I think, it considers two matrix.  matrix with zero value is wrong  when new matrix created as follow:
MatrixHolder selectedArea =
           new MatrixHolder(new double[areaHeight * areaWidth], areaWidth);

unit test code:
[TestMethod()]
public void GetMinTest()
{
    AreaMeasurmentTool target = new Rectangle();
    double[,] MatrixResult = new double[,] {
    {10, 0, 20, 10, 10},
    {12, 2, 30, 15, 16},
    {19, 0, 43, 10, 17},
    {80, 0, 65, 18, 13},
    {70, 4, 10, 10, 10}};
    double []SelectedArea1 = new double[9]{2, 30, 15, 1, 43, 10, 2, 65, 18};
    MatrixHolder currentMatrix = new MatrixHolder(SelectedArea1, 3);
    double expected = 1;
    double actual;
    actual = target.GetMin(currentMatrix);
    Assert.AreEqual(expected, actual);
}

and class MeasurementTool:
public virtual double GetMin(MatrixHolder currentMatrix)
{
    if (currentMatrix == null)
    {
        throw new Exception("the image Matrix cannot be null.");
    }

    double minValue = 0;

    SetSelectArea(currentMatrix);
    minValue = CalculateMin();
    minValue = Math.Round(minValue, 2);

    return minValue;
}

private void SetSelectArea(MatrixHolder currentMatrix)
{
    PointHolder start = new PointHolder(0, 0);
    PointHolder end = new PointHolder(0, 0);

    SetBoundries(start, end);

    int areaHeight = (end.Y - start.Y);
    int areaWidth = (end.X - start.X);

    MatrixHolder selectedArea = new MatrixHolder(new double[areaHeight * areaWidth], areaWidth);
    for (int i = 0; i < areaHeight; i++)
    {
        int sourceIndex = start.X + (currentMatrix.Witdh * (i + start.Y));
        int targetIndex = areaWidth * i;
        Array.Copy(currentMatrix.Values, sourceIndex
            , selectedArea.Values, targetIndex
            , areaWidth);
    }

    SelectedAreas = selectedArea;
}


text:
Q: upgrade wizard "slugs" of TYPO3 9 failes with "something went wrong" after upgradig an installation from TYPo3 6.2 to 9.5 (via 7 and 8) the last upgrade wizard "Introduce URL parts ("slugs") to all existing pages" crashes. There is no real error message, simply "Something went wrong" in an alert box.
All slug fields in the pages are empty.
Any ideas how to fix it - or to get a better error message?
Thanks!

A: Sometimes there is broken Page Data. Did or do You have ext:workspaces activated some time ago? I would Check there for broken Datasets and delete them If not needed. If I remember right, i ran the Update Wizard through cli and got the uid of the First not working Page there.

A: If you don't find the cause, you can also use extensions like 'ig_slug' to generate all slugs later.


text:
Q: Binding happens at different Phases for different components I have two viewParameters and two inputTexts bound to a bean property.
When I load that page (by entering the URL in the browser) the setters for the viewParameters get called twice each during the RESTORE_VIEW phase.
The setters for the inputTexts get called once in the RENDER_RESPONSE
Why do the setter for viewParameters get called twice?
Why do the setters for different UI components get called in completely different phases?
Body of the xhtml:
<h:body>
    <h:form
      id="modelSearch">

<f:metadata>
   <f:viewParam name="one" binding="#{modelSearchBean.requestOne}" > </f:viewParam>
   <f:viewParam name="two" binding="#{modelSearchBean.requestTwo}" />
</f:metadata>

      <p:messages display="text" />

                  <p:outputLabel
                    for="one"
                    value="one" />
                  <p:inputText
                    id="one"
                    binding="#{modelSearchBean.one}"
                    >
                  </p:inputText>

                  <p:outputLabel
                    for="two"
                    value="two" />
                  <p:inputText
                    id="two"
                    binding="#{modelSearchBean.two}"
                    >
                  </p:inputText>
    </h:form>
</h:body>

The bean:
@Component("modelSearchBean")
@Scope("request")
public class ModelSearchBean {

    private UIInput requestOne;
    private UIInput requestTwo;
    private UIInput one;
    private UIInput two;

    public UIInput getRequestOne() {
        return requestOne;
    }

    public void setRequestOne(UIInput requestOne) {
        this.requestOne = requestOne;
        System.out.println("requestOne");
    }

    public UIInput getRequestTwo() {
        return requestTwo;
    }

    public void setRequestTwo(UIInput requestTwo) {
        this.requestTwo = requestTwo;
        System.out.println("requestTwo");
    }

    public UIInput getOne() {
        return one;
    }

    public void setOne(UIInput one) {
        this.one = one;
        System.out.println("One");
    }

    public UIInput getTwo() {
        return two;
    }

    public void setTwo(UIInput two) {
        this.two = two;
        System.out.println("two");
    }
}

Output (the Phase information comes from a PhaseListener):
>>>>>> STARTING PHASE: RESTORE_VIEW 1
requestOne
requestTwo
requestOne
requestTwo
<<<<<< ENDING PHASE: RESTORE_VIEW 1
>>>>>> STARTING PHASE: APPLY_REQUEST_VALUES 2
<<<<<< ENDING PHASE: APPLY_REQUEST_VALUES 2
>>>>>> STARTING PHASE: PROCESS_VALIDATIONS 3
<<<<<< ENDING PHASE: PROCESS_VALIDATIONS 3
>>>>>> STARTING PHASE: UPDATE_MODEL_VALUES 4
<<<<<< ENDING PHASE: UPDATE_MODEL_VALUES 4
>>>>>> STARTING PHASE: INVOKE_APPLICATION 5
<<<<<< ENDING PHASE: INVOKE_APPLICATION 5
>>>>>> STARTING PHASE: RENDER_RESPONSE 6
One
two
<<<<<< ENDING PHASE: RENDER_RESPONSE 6


text:
Q: How to count the rows of a filtered table in power bi in a calculated column I want to numerate the occurances of a specific column in my table.  The best way I have thought to do this is to count the rows of a filtered table.  So, my WorkOrders table looks like this:
WO#  Date       CompCode  Serial#
001  1/1/2021   100       A
001  1/1/2021   101       A
002  1/2/2021   100       B
003  2/1/2021   100       A
004  2/2/2021   100       B
005  2/15/2021  101       A
006  3/1/2021   102       A
006  3/1/2021   100       A

I want to create a new column that numerates the occurance on the CompCode by Serial#.  There is no gaurantee that the data is sorted by date.  So, I tried to count the rows of a filtered table using this formula:
COMP_OCCURANCE =
CALCULATE(
    COUNTROWS(WorkOrders),
    Serial# = Serial#,
    Date <= Date,
    CompCode = CompCode
)

I assumed that would work but it does not.  The desired result would look like this:
WO#  Date       CompCode  Serial#  COMP_OCCURANCE
001  1/1/2021   100       A        1
001  1/1/2021   101       A        1
002  1/2/2021   100       B        1
003  2/1/2021   100       A        2
004  2/2/2021   100       B        2
005  2/15/2021  101       A        2
006  3/1/2021   102       A        1
006  3/1/2021   100       A        3

Thanks in advance for the help.

A: Try this:
COMP_OCCURANCE =
VAR CurrentSerial = WorkOrders[Serial #]
VAR CurrentDate = WorkOrders[Date]
VAR CurrentCode = WorkOrders[CompCode]
VAR Result =
    CALCULATE (
        COUNTROWS ( WorkOrders ),
        WorkOrders[Serial #] = CurrentSerial,
        WorkOrders[CompCode] = CurrentCode,
        WorkOrders[Date] <= CurrentDate,
        REMOVEFILTERS ( WorkOrders )
    )
RETURN
    Result

Screenshot - https://ibb.co/Bj5xrFS

A: For this type of calculation, you must need to rely on a column for sorting/ordering your data. As you cannot use Date in this case, I think you can go for column "WO#" this case. If this is acceptable, you can try this below measure for your expected output-
COMP_OCCURANCE =
CALCULATE(
    COUNT(your_table_name[WO#]),
    FILTER(
        ALL(your_table_name),
        your_table_name[WO#] <= MIN(your_table_name[WO#])
            && your_table_name[CompCode] = MIN(your_table_name[CompCode])
            && your_table_name[Serial#] = MIN(your_table_name[Serial#])
    )
)

Output-


text:
Q: I receive conversion varchar to float error when insert **set rowcount=1** in first line of code I receive an error

Coversion of varchar to float

when I write
set rowcount = 1

on first line of my code.
My script is:
select
    vh.VchNum, ct.Val, r.RoutSheetNo, vi.FinalQty,
rh.RequestNo, vh.VchDate,
p.PartCode, d.Title, co.val
from
    inv.InvVchHdr vh
join
    acc.DL d on d.AccNum = vh.DLREF
join
    inv.InvVchItm vi on vi.VchHdrRef = vh.VchHdrID
join
     inv.InvVchItmCtrl ct on ct.VchItmRef = vi.VchItmID
join
     QCS.QcsCertificateOfAnalysis q on q.Number = ct.Val
join
     USR.kalaf_info_p kp on kp.Id = q.QcsCertificateOfAnalysisId
join
     USR.coil_trace co on co.id = kp.coil_id
join
     inv.Part p on p.Serial = vi.PartRef
join
     inv.InvRqstItm rq on rq.RqstItmID = vi.RefNum
join
     inv.InvRqstHdr rh on rh.RqstHdrID = rq.HdrRef
join
     PRD.vwPrdOrderItemPlan pl on rh.OrdPlnBase = pl.OrdPlnId
join
     prd.prdroutsheet r on r.OrdPlnRef = pl.OrdPlnId
where
     pl.pPartRef not in (select pipe_code from usr.pipe_kalaf)
     and pl.pPartRef not in (select Serial from inv.Part where PartName like '%لاف%')
     and vi.VchType = 57

union

    select vh.VchNum,ct.Val,pl.OrdPlnNo
    ,vi.FinalQty,
    rh.RequestNo,vh.VchDate,
    p.PartCode,d.Title,co.val  from
    inv.InvVchHdr vh
    join acc.DL d
    on d.AccNum=vh.DLREF
    join
    inv.InvVchItm vi
    on vi.VchHdrRef=vh.VchHdrID
    join inv.InvVchItmCtrl ct
    on ct.VchItmRef=vi.VchItmID
    join QCS.QcsCertificateOfAnalysis q
    on q.Number=ct.Val
    join USR.kalaf_info_p kp
    on kp.Id=q.QcsCertificateOfAnalysisId
    join USR.coil_trace co
    on co.id=kp.coil_id
    join
    inv.Part p
    on p.Serial=vi.PartRef
    join inv.InvRqstItm rq
    on rq.RqstItmID=vi.RefNum
    join inv.InvRqstHdr rh
    on rh.RqstHdrID=rq.HdrRef
    join PRD.vwPrdOrderItemPlan pl
    on rh.OrdPlnBase=pl.OrdPlnId
    where pl.pPartRef in (select pipe_code from usr.pipe_kalaf) and vi.VchType=57

    SET ROWCOUNT 0

i use sql server 2000 and when I remove setrowcount statement, problem resolve.
please help me

A: Remove the =(equal) sign
from
set rowcount = 1

To
SET ROWCOUNT 1


text:
Q: instantiated from here error with a predicate template function I tried researching this question already, but it seems as though every question dealing with my error has to do with classes and their default constructors whereas my code contains no classes. It's a simple size() function that returns the number of elements in a given array. (I'm aware there is a built in size() function, that's not the point).
I at first thought that it was upset with my naming my function size() when a size() function already existed so I changed mine to sise() but I still recieve the same error and have no idea how to solve it.
Code:
template<class T > int sise(T array[], int count){
  if(array[count+1]== NULL){
    return count+1;
  }
  else{
    return sise(array,count+1);
  }
}

template <class T> int sise(T array[]){
  return sise(array , 0);
  }

int main(){
  int array[] = {1 , 7 , 5, 4, 6 ,2 , 3};
  int len = sise<int>(array);
  std::cout << len << std::endl;
  //print<int>(array);
  //  shakersort<int>(array);
  // print<int>(array);

  return 0;
}

Don't worry about the commented out function calls in main(), as each respective's calls functions have been commented out but the same error of
Shakersort.cpp: In function 'int sise(T*, int) [with T = int]':
Shakersort.cpp:60:24:   instantiated from 'int sise(T*) [with T = int]'
Shakersort.cpp:77:28:   instantiated from here
Shakersort.cpp:51:3: warning: NULL used in arithmetic [-Wpointer-arith]

is given. What is going on?

A: The compiler is warning about NULL being compared to an int from the looks of it. Not strictly an error (nor is it made an error) but a likely indication of false assumptions being made. One such assumption seems to be that arrays are magically null-terminated: they are not. That is something very specific to string literals and even then the null-terminator is not NULL but rather '\0'. You'll either need to pass the size of the array along or you'll need to deduce it using a template, e.g.:
template <typename T, int Size>
int sise(T (&array)[Size], int count) {
    ...
}


text:
Q: Detect touch of UIImage added as subview of UIScrollView I have UIScrollView with many UIImageViews.I need to drag and drop image from UIScrollView to another view. Outside the scrollView touch is worked. But inside scroll view touch is not worked. I used touchesBegan,touchesMoved etc method. Please help me.
-(IBAction)selectBut:(id)sender
{

 scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(x,y,w,h)];

 scrollView.userInteractionEnabled = YES;

 int y = 0;

 for (int i = 0; i < [myArray count]; i++) {

UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, y, 75, 30)];

 image.userInteractionEnabled = YES;

  y=y+35;

 [scrollView addSubview:image];

}

[self.view addSubview:scrollView];

[scrollView setContentSize:CGSizeMake(150, 300)]

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

   UITouch *touch = [touches anyObject];

    if ([touch tapCount] == 1) {

        NSLog(@"One touch !!");
    }

}

A: you need to customize the UIImageView with your own view inherited from UIImageView. Provide touch methods in that customized subclass and add it on your UIScrollView..
Subviews of UIScrollview will never call touchesBegan method directly. You need to customized with subview to get touchesBegan properties of that added subview/customized view.
I mean to say take subclass of ImageView like
CustomImageView *imageView = [[CustomImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[imageView setUserInteractionEnabled:YES];
[scrollView addSubview:imageView];
[imageView release];

CustomImageView class is should be inherited from UIImageView like
 @interface CustomImageView : UIImageView
  {
  }

in # .m File
  #import "CustomImageView.h"

@implementation CustomImageView

    - (id)initWithFrame:(CGRect)frame
   {
self = [super initWithFrame:frame];
if (self) {

}
return self;
}

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
      NSLog(@"%s", __FUNCTION__);

     }

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    }

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

      if ([touch tapCount] == 2) {
    drawImageView.image = nil;
    return;
    }

     }

A: Add a Tap gesture recognizer to the scroll view for enabling touch inside scroll view:
UITapGestureRecognizer *singlTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodName:)];
singlTap.cancelsTouchesInView = NO; //Default value for cancelsTouchesInView is YES, which will prevent buttons to be clicked
[scrollViewName addGestureRecognizer:singlTap];

then write your code in specified method.
-(void)methodName:(UITapGestureRecognizer *)gesture
{
     //your code here
}

A: I don't know if this help you. But try to set the exclusiveTouch property of the UIImageView to YES.

A: Did you add your scrollview as an IBOutlet? If its from xib and as you say touches are available outside the scroll and not within, I guess you might have accidentally unchecked userInteractionEnabled for the scrollview which inhibits touch events. And you have added UIImageViews as subviews to UIScrollView. For UIImageView you have to first set userInteractionEnabled to YES and then add any gestures if necessary to get events or use the touchesBegan, touchesMoved methods. Unless you set interaction enabled you wont receive touch events on UIImageView. If the parent view I mean the UIScrollView's interaction is disabled you wont get touches on UIImageView too. Hope this helps :)


text:
Q: Query unique values inside django forloop I have a query where I should avoid double entry of the same question. In fact, I would like to get only unique values but, I am using the distinct() django function which isn't working.
I have these models:
class QuestionTopic(models.Model):
    name = models.CharField(max_length=255)
    question_subject = models.ForeignKey(
        QuestionSubject, on_delete=models.CASCADE)
    exam_questions_num = models.IntegerField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('created_at',)

class Question(models.Model):
    id = models.CharField(max_length=7,
                          unique=True,
                          primary_key=True,
                          editable=False)
    question_subject = models.ForeignKey(
        QuestionSubject, on_delete=models.CASCADE)
    text = tinymce_models.HTMLField()
    mark = models.IntegerField(default=1)
    is_published = models.BooleanField(default=True)
    question_bank_id = models.CharField(max_length=255, blank=True, null=True)
    question_topic = models.ForeignKey(
        QuestionTopic, on_delete=models.CASCADE, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

and the query is:
        subject = QuestionSubject.objects.get(id=request.POST.get('subject'))
        question_topics = QuestionTopic.objects.filter(
            question_subject=subject)
        questions_list = []
        for topic in question_topics:
            for q in range(topic.exam_questions_num):
                question = Question.objects.filter(
                    question_subject=subject, question_topic=topic).values_list(
                    'id', flat=True).order_by('?').distinct().first()
                questions_list.append(question)

What I would like to achieve is to have all different questions for each different topic inside questions_list. Which I am not achieving at the moment being the distinct used inside a loop.

A: Just make questions_list a set:
questions_list = set()

Sets don't allow a value more than once.

A: You can work with a single query with:
subject = QuestionSubject.objects.get(id=request.POST.get('subject'))
question_topics = QuestionTopic.objects.filter(question_subject=subject)
questions_list = [
    question
    for topic in question_topics
    for question in Question.objects.filter(
        question_subject=subject, question_topic=topic
    ).order_by('?')[: topic.exam_questions_num]
]
This will make O(n) queries with n the number of topics.
If the number of questions is not that large, you can do this with two queries with:
from random import sample

subject = QuestionSubject.objects.get(id=request.POST.get('subject'))
question_topics = QuestionTopic.objects.filter(
    question_subject=subject
).prefetch_related('question_set')
questions_list = [
    question
    for topic in question_topics
    for question in sample(topic.question_set.all(), topic.exam_question_num)
]


text:
Q: What is the largest planar clique in n-dimensions? In other words, what is the largest clique that can be drawn without any crossing edges in $\mathbb{R}^n$?
It's trivial in $\mathbb{R}$: 2.
In $\mathbb{R}^2$: 4, as we know that $K_5$ is non-planar
But what if we take it further to $\mathbb{R}^3$ and beyond? I can imagine at least a planar clique of size 6 in $\mathbb{R}^3$ by adding a vertex "above" and "below" the planar form of $K_4$ and adding edges appropriately. But is that the limit? Is there a general law for $\mathbb{R}^n$?

A: You can draw a clique of any size in $\mathbb R^3$. To construct the points inductively, all you have to do is place the $n^{\text{th}}$ point off any of the $\binom{n-1}{3}$ planes spanned by any three of the previous points; if you do, then no crossings occur.


text:
Q: vueJs equivalent of jQuery slideDown/slideUp or slideToggle I'm experimenting with vue for the first time.
I've replaced a jquery show/hide that was using .slideDown() / .slideUp() with v-show - however I much prefer the animation of jQuery's slideup/down. Is there an easy way to do this with vue?
Simplified code here:

        Site Name

      <button class="classes here"  @click="isShowing ^= true">
        hamburger svg here
      </button>

Please advise.

A: You can install modules for this, or you can write a custom component. I suggest the second option.
<template>

        <button @click="isShowing">
            hamburger svg here
        </button>

        <transition name="main-nav"
                    @enter="transitionStep1"
                    @after-enter="transitionStep2"
                    @before-leave="transitionStep3"
                    @after-leave="transitionStep4">

Some text

        </transition>

</template>


text:
Q: GraphQL __InputValue and "using the GraphQL language" The now-current edition of the GraphQL specification says this about defaultValue on __InputValue:

defaultValue may return a String encoding (using the GraphQL language) of the default value used by this input value in the condition a value is not provided at runtime. If this input value has no default value, returns null.

What is "the GraphQL language" in the parenthetical expression? Operationally, it seems as though this equates to "what JSON would use, except that enums are treated as strings, since JSON does not have enums", but I am uncertain if I am correctly interpreting what I am seeing.

A: The GraphQL specification defines how the language encodes supported values in 2.9, "Input Values": http://facebook.github.io/graphql/#Value (Referred to as Value in the rest of the spec)
This is the same syntax used to define default values in operation definitions. In that case, the language is used inside a GraphQL query document, but in the introspection case the snippet of language itself is returned as a string.


text:
Q: Forcing right alignment with floated elements not possible when word wrapping

first

second

third

and the fourth is longer than the others

https://jsfiddle.net/xLq1hfby/
I want the
s to align to the right like this:
                  [first] [second] [third]
[and the fourth is longer than the others]

However, since the last element causes a word wrap, it just looks like this:
[first] [second] [third]
[and the fourth is longer than the others]

When the last
 is removed, they align like I want them to, like this:
                  [first] [second] [third]

How can I get them to align to the right even when word wrapping?
Please keep in mind:

*

*I can't use display:inline-block on the
s because I need vertical margins.

*I can't use float:right on the
s because this reverses their order.

A: You can use flexbox with the following settings (note: no float, 'justify-content: flex-end;' aligns the items to the right.):
ul {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  list-style-type:none;
  margin:0;
  padding:0;
}

li {
  margin-right: auto;
  background:red;
  color:#fff;
  margin:4px;
}

Here is a fork of your fiddle: https://jsfiddle.net/0o93dvrp/

A: In case you want a none-flexbox version (inline block + text align right trick)
https://jsfiddle.net/sxLk5mt2/
/* toggle the following line: */
/* #longest {display:none;} */

#wrap {
  background:yellow;
  width:300px;
}

ul {
  float:right;
  list-style-type:none;
  margin:0;
  padding:0;
  text-align: right;
}

li {
  background:red;
  color:#fff;
  /* float:left; */
  display: inline-block;
  margin:4px;
}


text:
Q: Downloading Excel file with using Selenium and C# I want to download an Excel file on the web site, but I think i did something wrong. I have HTML code:
<label class="pager">
<input onclick="excelForm.submit()" type="image" value="Excel" src="/YeniSistem/images/Excel_Document_Icon.png">
</label>

What I want to do this with using Selenium I want to click that input with using C#. I have tried in many ways, like:
driver.FindElement(By.XPath(".//html/body/div/div/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/div/div/label[2]/input")).Click();

and:
 driver.FindElements(By.XPath(".//div[@id='contentContainer']/div/table/tbody/tr[2]/td/table/tbody/tr[2]")).Click();

and:
driver.FindElements(By.XPath(".//input[contains(@value , 'Excel')]")).Click();

Also I tried previous codes without . in frond of XPath. Please help me to resolve this.

A: From your code, I understand that you are trying to download an excel file instead of XPath you can use the following code:
WebClient client = new WebClient();
client.DownloadFile("link here",@"file_path.xlsx");


text:
Q: Login to ssh session and afterwards automatically look for and access existing screen session? I would like to connect to a server using ssh and after logging in I would like to automatically execute
screen -R

My script looks as follows:
sshpass -p password ssh -t name@server.cheese 'screen -R; bash -l'

It is important that I would like to be able to control from the outside which commands are executed after login. Else I could most likely just add stuff the ".bashrc" or some equal file.

A: ssh -tt user@server 'screen -ls 2>/dev/null | grep -i detached && screen -r || echo "No screen detached sessions found"'

This would work provided you have one screen detached.

A: check your ssh config? for example:
grep PermitTTY /etc/ssh/config
grep PermitTTY ~/.ssh/config

If they are not set to YES, maybe that's your problem?
PS: any reason to not use tmux instead of screen? Just curious.


text:
Q: Acceder una sola tabla con web scraping y python estoy intentando scrapear una web de estadisticas con python para la creacion de gráficas, principalmente, pero no puedo acceder a una sola tabla. La página es la siguiente: https://www.basketball-reference.com/leagues/NBA_2019.html#all_team-stats-base
Solo quiero acceder a  una tabla, que es la quinta, la titulada como "Team Per Game Stats", pero me es imposible, he probado a acceder mediante la id de la pagina pero nada. El código que tengo es el siguiente:
from bs4 import BeautifulSoup
import urllib.request

URL = 'https://www.basketball-reference.com/leagues/NBA_2019.html'
pagina = urllib.request.urlopen(URL)

#response = requests.get(URL)
soup = BeautifulSoup(pagina, 'html.parser')
tabla = soup.find('table', attrs={'id':'team-stats-per_game'})

print(tabla)

#Devuelve None

¿Alguien podría ayudarme?
Gracias

A: La página en cuestión hace algo curioso, la tabla que buscas aparece comentada en el HTML original (view-source:https://www.basketball-reference.com/leagues/NBA_2019.html), entiendo que lo que hace es descomentarla por javascript, de todas formas puedes acceder a ella, jugando un poco con las cadenas:
from bs4 import BeautifulSoup
import urllib.request

URL = 'https://www.basketball-reference.com/leagues/NBA_2019.html'
pagina = urllib.request.urlopen(URL)

soup = BeautifulSoup(pagina, 'html.parser')

# Buscamos el contenedor de la tabla
conteneder_tabla = tabla = soup.find('div', {'id': 'all_team-stats-per_game'})

str_tabla = str(conteneder_tabla)
# nos quedamos ocn el "outputHTML" de la tabla
str_tabla = str_tabla[str_tabla.index('<table') : (str_tabla.rindex('</table>') + 8)]

soup = BeautifulSoup(str_tabla, 'html.parser')

tabla = soup.find('table', attrs={'id':'team-stats-per_game'})

print(tabla)