text:
Q: How does python3 diamond inheritance works for data fields? How to initialize the inherited fields with super()._init__? I was checking this problem to understand multiple inheritance and I got stuck.
How can I set the fields of the inherited objects from the last class?
class Vehicle():
  def __init__(self, name:str, seats:int):
    self.name = name
    self.seats = seats

  def print_vehicle(self):
    print(f'Vehicle {self.name} has {self.seats} seats')

class Boat(Vehicle):
  def __init__(self, name:str, seats:int, engine_type:str):
    super().__init__(name, seats)
    self.engine_type = engine_type

  def print_vehicle(self):
    print(f'Boat {self.name} has {self.seats} seats and engine {self.engine_type}')

class Car(Vehicle):
  def __init__(self, name:str, seats:int, fuel:str):
    super().__init__(name, seats)
    self.fuel = fuel

  def print_vehicle(self):
    print(f'Car {self.name} has fuel {self.fuel}')

class AnphibiousCar(Boat, Car):
  def __init__(self, name, seats, engine_type, fuel):
    super(AnphibiousCar, self).__init__(name, seats, engine_type) # ???

  def print_vehicle(self):
    print(f'Anphibious car {self.name} has {self.seats} seats and {self.engine_type} - {self.fuel} engine')

ac = AnphibiousCar('name', 4, 'piston', 'gas')
ac.print_vehicle()

A: The point is that each class should focus only on the stuff which is its direct responsibility; the rest should be delegated to superclasses (and note that, when you deal with such a cooperative inheritance with super(), your methods that call super() should not need to know what exactly are the actual superclasses, in particular the nearest one - as this can change, depending on the actual class of self).
So let's reimplement your classes (with a bunch of explanations in the comments):
class Vehicle:

    # Added the `*,` marker to make `name` and `seats` *keyword-only*
    # arguments (i.e., arguments that are identified only by their
    # *names*, never by their positions in a call's arguments list).
    def __init__(self, *, name: str, seats: int):
        self.name = name
        self.seats = seats

    # We abstract out class-specific features into separate methods,
    # keeping in the `print_vehicle()` method only the common stuff,
    # so that in subclasses we'll need to customize only those methods
    # (`list_features()`, `get_type_label()`), *not* `print_vehicle()`.
    def print_vehicle(self):
        vehicle_type_label = self.get_type_label()
        features = ', '.join(self.list_features())
        print(f'{vehicle_type_label} {self.name}: {features}.')

    # Side note: the `list[str]` type annotation requires Python 3.9
    # or newer (for compatibility with older versions you need to
    # replace it with `List[str]`, using `from typing import List`).
    def list_features(self) -> list[str]:
        return [f'has {self.seats} seats']

    # This implementation is, in fact, quite generic (so that
    # in most subclasses we will *not* need to customize it).
    def get_type_label(self) -> str:
        return self.__class__.__name__

class Boat(Vehicle):

    # Only `Boat`-specific arguments (as keyword-only ones, as above...)
    # are declared here explicitly. Any other are treated as a "black
    # box", just being passed into superclasses...
    def __init__(self, *, engine_type: str, **kwargs):
        super().__init__(**kwargs)
        self.engine_type = engine_type

    # Also here we focus only on this-class-specific stuff, handling
    # other stuff as "agnostically" as possible...
    def list_features(self) -> list[str]:
        return super().list_features() + [f'has {self.engine_type} engine']

class Car(Vehicle):

    # And analogously...
    def __init__(self, *, fuel: str, **kwargs):
        super().__init__(**kwargs)
        self.fuel = fuel

    def list_features(self) -> list[str]:
        return super().list_features() + [f'needs {self.fuel} fuel']

class AmphibiousCar(Boat, Car):

    # Note: here we get our `__init__()` and `list_features()`
    # for free (!), as the superclasses provide all we need
    # when it comes to those two methods.

    # The only thing we may want to customize is:
    def get_type_label(self) -> str:
        return 'Amphibious car'

ac = AmphibiousCar(
    name='Julia-III',
    seats=4,
    engine_type='piston',
    fuel='gas')

# "Amphibious car Julia-III: has 4 seats, needs gas fuel, has piston engine."
ac.print_vehicle()

As a further reading, I'd recommend: https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

A: You have some errors:

*

*super(AnphibiousCar, self).__init__(name, seats, engine_type) could become
Boat.__init__(self, name, seats, engine_type) so calling the class you could
give information about how to initialize it.

*there is a missing parameter in Boat where you should give a fuel argument
to the superclass Vehicle, like super().__init__(name, seats, "oil")
As you can note if you use super you don't need to pass self, if you use
the class name you are using it.
My point of view is that, yes, is good to understand, but don't loose to much
time as this kind of multiple inheritance is only theoretical and practically
not used in real coding. This in fact can cause a lot of confusion and add
boilerplate... "new" languages like, for example, Rust do not even provide
inheritance.
Just to say: "Yes, study it, but keep it simple" ^_^


text:
Q: Rotate svg pattern around it's center when using objectBoundingBox I need to rotate pattern used as background for svg element (part of wheelnav.js menu) around it's center. I know I can use patternTransform = rotate(angle, centerX, centerY), but the pattern uses objectBoundingBox as patternUnits and I don't know how to get width and height of the element.
Is there any way to get its dimensions? Or rotate around center without knowing width and height?
Edit:
Here is the code I use:
var bounRect = document.getElementById("wheelnav-piemenu" + 3 + "-slice-" + 0).getBoundingClientRect()
var patt = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');
patt.setAttribute('id', 'img' + itemId);
patt.setAttribute('patternUnits', 'objectBoundingBox');
patt.setAttribute('width', '1');
patt.setAttribute('height', '1');
patt.setAttribute('x', '0');
patt.setAttribute('y', '0');
patt.setAttribute('patternTransform',"rotate(" + itemId*-36 + ", 0.5, 0.5)")

var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'assets/images/Logo-cropper.png');
image.setAttribute('width', bounRect.width*1.12);
image.setAttribute('height', bounRect.height*1.12);
image.setAttribute('x', -bounRect.height*0.06);
image.setAttribute('y', -bounRect.height*0.04);

var defs = document.getElementsByTagName('defs')[0];
patt.appendChild(image);
defs.appendChild(patt);

However it doesn't rotate around its center.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stream Corrupted Exception When calling Jasper Report I have used a fileDownloadActionListener for opening a jasper report from an ADF form. First time, it's opening correctly. But the second time onwards it gives an error message on the application saying, "The file was not downloaded or was not downloaded correctly."
This is my code:
    public void reportAction(FacesContext ctx,OutputStream output) throws FileNotFoundException,NamingException,
                                     SQLException, IOException, JRException,
                                     ClassNotFoundException,
                                     InstantiationException,
                                     IllegalAccessException,StreamCorruptedException {
    File input = null;
    Connection conn = null;
    String branchId = getBranchId().getValue().toString();
    Map reportParameters = new HashMap();
    reportParameters.put("branchId", branchId);
    bindings = this.getBindings();
    ctx = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
    ServletOutputStream servletOutputStream;
    servletOutputStream = response.getOutputStream();
    String reportPath = ctx.getExternalContext().getInitParameter("reportpath");
    input = new File(reportPath+"testJob.jasper");
    byte[]  bytes= null;
    if(bindings!=null){
            OperationBinding ob = bindings.getOperationBinding("getCurrentConnection");
            ob.execute();
            conn = (Connection)ob.getResult();
    System.out.println("Report Path===========>"+input.getPath().toString());
    if(input.getPath()!=null&&reportParameters!=null&&conn!=null){
        JRPdfExporter pdfExporter = new JRPdfExporter();
        bytes = JasperRunManager.runReportToPdf(input.getPath(), reportParameters,  conn);
        JasperPrint print = JasperFillManager.fillReport(input.getPath(),reportParameters,conn);
        pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
        pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, input.getPath());
        pdfExporter.exportReport();
        response.addHeader("Content-disposition", "attachment;filename=testJob1.pdf");
        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);
        File file = new File(input.getPath());
        output = response.getOutputStream();
        servletOutputStream.write(bytes, 0, bytes.length);
        FileInputStream fis = new FileInputStream(file);
         BufferedInputStream bui = new BufferedInputStream(fis);
         int readBytes = 0;
            while ((readBytes = bui.read()) != -1)
              output.write(readBytes);
        bui.close();
        fis.close();
        servletOutputStream.flush();
        servletOutputStream.close();
        ctx.responseComplete();
    }
}
else{
    ctx.addMessage(null,new FacesMessage("No bindings configured for this page"));
}
}


text:
Q: Assign id to div dynamically created from a JSON file I want to assign dynamic id attributes to the div(s) which are being appended through JavaScript. For example:
function x() {
    for (current_list = 0; current_list < data.length; current_list++) {
        $("#current").append(
            "
" +
            "" + data[current_list].name + "" +
            "
");
    }
}

Two cards will be appended, so I want to assign them an id which can increase if there are more numbers of arrays present in the JSON.

A: you probably looking for this.
function x() {
  var container=$("#current");
  for(var i=1;i<10;i++)
  {
    var id="card"+i;
    var divHtml="
" +
      ""+data[current_list].name+"" +
    "
"
    container.append(divHtml);
   }
}

A: As Rory said, here a solution using DOM traversal.
You would have to call this after appending your "cards".
$(".card").each(function(value, index){
   $(value).attr("id", "card" + index);
});

A: if you call x() function one time you can use
function x() {
  for (current_list = 0; current_list < data.length; current_list++) {
    $("#current").append('
' + data[current_list].name + '
');
  }
}

and if you call it many time you can use this function after every call
$(".card").each(function(value, index){
  $(value).attr("id", "card-" + index);
});


text:
Q: Paginación de la API de Instagram con React Tengo un inconveniente al hacer el paginado de la API de instagram.
El problema es que al llegar a la tercera o cuarta página el renderizado empieza a fallar y devuelve páginas anteriores y en un momento ya se vuelve loco y tarda mucho en renderizar.
El paginado lo hago cambiando el estado cuando se hace click en los botones, y paso la url que me envía la paging.
Dejo el código abajo:
function Peticion () {

let FeedInstagram = `https://graph.instagram.com/me/media?
   fields=thumbnail_url,media_url,children,
   children_url,timestamp,media_type,caption,permalink&limit=
   10&access_token=${token}`

const [url, setUrl] = useState(FeedInstagram);
const [post, setPost] = useState([]);
const [loading, setLoading] = useState(false);

useEffect(() => {
        const Post = async () => {
            setLoading(true);
            let res = await axios.get(url),
                data = await res.data,
                pagina = await data.paging,
                json = await data.data,
                next = pagina.next,
                prev = pagina.previous;
            setPost(json);
            setLoading(false)
            window.addEventListener('click',(e)=>{
                (prev===undefined
                    ?anterior.current.classList.add('inactive')
                    :(anterior.current.classList.remove('inactive'),
                    e.target.matches('.previous')&&setUrl(prev)))
                (next===undefined
                    ?siguiente.current.classList.add('inactive')
                    :(siguiente.current.classList.remove('inactive'),
                    e.target.matches('.next')&&setUrl(next)))
            })
            }
            Post()
        }, [url]);
return (
    <>

            <Data post={post} loading={loading} />

            <button className='previous botones'>Anterior</button>
            <button className='next botones'>Siguiente</button>

    </>
  )
 }

export default Peticion;

A: Simplemente crea un estado de la página por ejemplo const [pagina, setPagina] = useState(null) y ya puedes usarlo fuera del useEffect. Dentro del useEffect solo seteas el estado cuando obtienes la respuesta de la API: setPagina(pagina)
gracias Andres Gardiol, esta fue la solucion a mi problema


text:
Q: Eclipse Content Assist Showing Same Options Everywhere I am using the latest version of Eclipse (4.3) and every time I go to use the dot operator it shows the same options every single time. Here is what it shows.

As you can see it only displays things such as "create new object" which does not make any sense for an import. Can anyone explain why this is happening and show me how to get it back to normal?

A: You can check and activate the available autocompletion suggestion providers via Window > Preferences, Java > Editor > Content Assist > Advanced.


text:
Q: Put optional input files for rule all in Snakemake In my Snakemake project, I have a config.yaml file which allows users to run certain steps of the pipeline or not, for example:
DEG :
   exec : True

And so, in the Snakefile, I include the rules associate with the DEG:
if config["DEG"]["exec"]:
   include: "rules/classic_mapping.smk"
   include: "rules/counts.smk"
   include: "rules/run_DESeq2.smk"

The problem is, now I would like to dynamically specify the output files in the "all" rule, so that Snakemake knows which files to generate based on the parameters entered by the user. For example I had in mind to proceed as follows:
rule all:
   input:
       if config["DEG"]["exec"]:
          "DEG/DEG.txt"
       if config["DTU"]["exec"]:
          "DTU/DTU.txt"

but it doesn't work:
    SyntaxError in line 58 of Unexpected keyword if in rule definition (Snakefile, line 58)
I would need an outside point of view to find an alternative because Snakemake should not work on this way
Thank's by advance

A: You can use snakemake's ability to take functions as input and put the if loop in a function. A sample implementation could be as follows
def get_input(wildcards):
    input_list = []
    if config["DEG"]["exec"]:
          input_list.append("DEG/DEG.txt")
    if config["DTU"]["exec"]:
          input_list.append("DTU/DTU.txt")
    return input_list

rule all:
    input:
        get_input

You can customize the get_input function to include additional conditions if required. This is documented further here.
Another alternate way of doing this which is far less readable and not recommended but can work incase an addtional function is to be avoided is as follows
rule all:
    input:
        lambda wildcards: "DEG/DEG.txt" if config["DEG"]["exec"] else [],
        lambda wildcards: "DTU/DTU.txt" if config["DTU"]["exec"] else [],

A: Inputs are just lists of files. You can define them outside the rule definition:
deg_files = []
if config["DEG"]["exec"]:
    deg_files.append("DEG/DEG.txt")

dtu_files = []
if config["DTU"]["exec"]:
    dtu_files.append("DTU/DTU.txt")

rule all:
    input:
        deg_files,
        dtu_files,


text:
Q: How do you find a corresponding recurrence relation for some random algorithm?     void doSomething(int *a, int left, int right) {
       if (left == right) {
          for (int j = 0; j < right; ++j)
             cout << a[j];
          cout << endl;
          return;
    }
       for (int i=left; i<right; ++i) {
          std::swap(a[left],a[i]);
          doSomething(a,left+1,right);
          std::swap(a[left],a[i]);
    }

}

With base case T(1) = right, swap runs in O(1) time, and n = right-left+1 for T(n).
Can someone please walk me through the steps one would take to find the recurrence relation for this algorithm (or any algorithm for that matter)?  In particular, I'm confused with the terminology of left and right, or how n = right-left+1 and T(1) = right effect how we determine what a final solution should look like.

A: A general method for analyzing the running time of any algorithm is to walk through the algorithm step by step, counting the number of statements executed and express this count as a function of the "size" of the input.
For example, suppose we defined a predicate, isSorted, which would take as input an array $a$ and the size, $n$, of the array and would return true if and only if the array was sorted in increasing order. It might look like this
bool isSorted(int *a, int n) {
   if (n == 1)
      return true;       // a 1-element array is always sorted
   for (int i = 0; i < n-1; i++) {
      if (a[i] > a[i+1]) // found two adjacent elements out of order
         return false;
   }
   return true;         // everything's in sorted order
}

Clearly, the size of the input here will simply be $n$, the size of the array. How many steps will be performed in the worst case, for input $n$?

*

*The first if statement counts as 1 step

*The for loop will execute $n-1$ times in the worst case (assuming the internal test doesn't kick us out), for a total time of $n-1$ for the loop test and the increment of the index.

*Inside the loop, there's another if statement which will be executed once per iteration for a total of $n-1$ time, at worst.

*The last return will be executed once.

So, in the worst case, we'll have done $1+(n-1)+(n-1)+1$ computations, for a total run time $T(n)\le 1+(n-1)+(n-1)+1=2n$ and so we have the timing function $T(n)=O(n)$.
For non-recursive algorithms, the process is, in theory, simple:

*

*Find a parameter, $n$, that expresses the "size" of the input. Walk through the algorithm, assuming

*Every statement executed will take time 1,

*Every if statement will take its longest branch,

*Every loop will iterate the maximum number of times allowable.

Then express the run time of your algorithm as a function of the sum of statements executed, using (2) through (4) above.

For recursive algorithms, you do the same thing, only this time you add the time taken by each recursive call, expressed as a function of the time it takes on its input.
For example, let's rewrite, isSorted as a recursive algorithm:
bool isSorted(int *a, int n) {
   if (n == 1)
      return true;
   if (a[n-2] > a[n-1])         // are the last two elements out of order?
      return false;
   else
      return isSorted(a, n-1); // is the initial part of the array sorted?
}

In this case we still walk through the algorithm, counting: 1 step for the first if plus 1 step for the second if, plus the time isSorted will take on an input of size $n-1$, which will be $T(n-1)$, giving a recurrence relation
$$
T(n) \le 1 + 1 + T(n-1) = T(n-1) +O(1)
$$
Which has solution $T(n)=O(n)$, just as with the non-recursive version, as it happens.

With this done, lets analyze your algorithm. We'll compute the run time as a function of right - left. That will be the size, $n$, so we'll try to find a recurrence relation that expresses the run time, $T(n)$, as a function of $n$.
If $n>0$, the function will take 1 step for the if test and then pass to the second loop. This loop will iterate $n$ times, doing two swaps and calling itself recursively with arguments that we'd express as $n-1, n-2, \dots 1, 0$. In other words, we'll have
$$
T(n) \le T(n-1) + T(n-2) + \cdots + T(1) + T(0) + kn
$$
where the last term takes account of the loop overhead and the two swaps. We have reached our goal: the timing function for the algorithm satisfies the recurrence
$$
T(n) = T(n-1) + \cdots + T(0) + O(n)
$$
and of course, when $n=0$, i.e., when left = right we just print the contents of the array, which we can do in a (possibly large) constant amount of time.
Any questions? Just ask.

A: . Consider the following recursive algorithm.
Algorithm RiddleA[0..n − 1]
// Input: An array of n real numbers
if (n = 1) return A[0]
else
temp ← Riddle(A[0, n − 2])
if temp ≤ A[n − 1] return temp
else return A[n − 1]
(b) Set up a recurrence relation for the algorithms basic operation count and solve it
can anyone help out with this


text:
Q: ASP .NET User Control Properties not getting displayed in property window I created a user control with a few properties. In my demo project, the properties that have been exposed using getter and setter methods are being correctly displayed in the property window.

This is how I expected it to work.
When I copied the files related to the user control to my main solution, I no longer see the properties in the properties window. The control now displays as an HTML Element instead of the actual name of the control.


text:
Q: Conversion from String to datetime (yyyy-mm-dd hh:mm:ss) in Pyspark The column in dataframe look like:-
Input--> 20191106 ---Output---> 2019-11-06 00:00:00
Input--> 20180815--Output---> 2018-08-15 00:00:00

Code:
from pyspark.sql.functions import from_unixtime, unix_timestamp
df.withColumn("newcol", from_unixtime(unix_timestamp(df("coldt"), "YYYY--MM-DD HH:MM:SS")))

Error:
File "C:/Users/nance.py", line 14, in <module>
    df.withColumn("newcol", from_unixtime(unix_timestamp(df("coldt"), "YYYY--MM-DD HH:MM:SS")))
TypeError: 'DataFrame' object is not callable

Please help.

A: just use to_timestamp function.
Working example:
import pyspark.sql.functions as F
df = spark.createDataFrame([['20191106'],['20180815']])
df = df.withColumn('dates',F.to_timestamp('_1','yyyyMMdd'))
display(df)


text:
Q: wordpress plugin page error i get an error on plugin page:
An unexpected error occurred. Something may be wrong with WordPress.org or this server's configuration. If you continue to have problems, please try the support forums.
Thanks in advance.

A: This is an error in WordPress core displayed when the WordPress core can't reach the WordPress.org update servers. Usually, it will go away on its own - minor issue with reaching WordPress.org, or, if it persists, it could point to some configuration error on your server preventing WordPress in reaching to WordPress.org servers for update checks.


text:
Q: How can I correct a "Java heap space - Out of Memory" error I'm currently running my system against a rather large dataset and am getting the error. 'Out of memory. Java Heap Space'.
Is there anyway to get around this or is it just a case of the dataset is too large and can't be used?

A: In general, you can either

*

*give it more memory e.g. increase the maximum heap size, but don't give it more than about 90% of main memory.  BTW the default is 25% of main memory up to 32GB.

*optimise the code so that it uses less memory, e.g. use a memory profiler. You can use a more efficient data structure or load portions of data into memory at a time.

*break up the data so it own works on a portion at a time.

A: If it's not the dataset that's eating up memory, it could be that you are not freeing up objects once they are inactive.
This is typically due to keeping references to very large objects or to lots objects laying around long after they are no longer needed. This is most likely references that are static variables, but it can also be references to large temporary variables (e.g., largeStringBuilderobjects) within methods that are still active.


text:
Q: Flutter - Reuse previously painted canvas in a CustomPainter I have a CustomPainter that I want to render some items every few milliseconds. But I only want to render the items that have changed since the last draw. I plan on manually clearing the area that will be changing and redrawing just in the area. The problem is that the canvas in Flutter seems to be completely new every time paint() is called. I understand that I can keep track of the entire state and redraw everything every time, but for performance reasons and the specific use case that is not preferable. Below is sample code that could represent the issue:
I understand that everything will need to be redrawn when the canvas size changes.
import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

class CanvasWidget extends StatefulWidget {
  CanvasWidget({Key key}) : super(key: key);

  @override
  _CanvasWidgetState createState() => _CanvasWidgetState();
}

class _CanvasWidgetState extends State<CanvasWidget> {
  final _repaint = ValueNotifier<int>(0);
  TestingPainter _wavePainter;

  @override
  void initState() {
    _wavePainter = TestingPainter(repaint: _repaint);
    Timer.periodic( Duration(milliseconds: 50), (Timer timer) {
      _repaint.value++;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
       painter: _wavePainter,
    );
  }
}

class TestingPainter extends CustomPainter {
  static const double _numberPixelsToDraw = 3;
  final _rng = Random();

  double _currentX = 0;
  double _currentY = 0;

  TestingPainter({Listenable repaint}): super(repaint: repaint);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint();
    paint.color = Colors.transparent;
    if(_currentX + _numberPixelsToDraw > size.width)
    {
      _currentX = 0;
    }

    // Clear previously drawn points
    var clearArea = Rect.fromLTWH(_currentX, 0, _numberPixelsToDraw, size.height);
    canvas.drawRect(clearArea, paint);

    Path path = Path();
    path.moveTo(_currentX, _currentY);
    for(int i = 0; i < _numberPixelsToDraw; i++)
    {
      _currentX++;
      _currentY = _rng.nextInt(size.height.toInt()).toDouble();
      path.lineTo(_currentX, _currentY);
    }

    // Draw new points in red
    paint.color = Colors.red;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

A: The only solution currently available is to capture the progress as image and then draw the image instead of executing the whole canvas code.
for drawing the image you can use canvas.drawImage as mentioned by pskink in the above comment.
but the solution i would recommend is to wrap the CustomPaint with RenderRepaint to convert that widget to image. for detials refer to
Creating raw image from Widget or Canvas and (https://medium.com/flutter-community/export-your-widget-to-image-with-flutter-dc7ecfa6bafb for brief implementation), and have a condition to check if you are building for the first time or not.
class _CanvasWidgetState extends State<CanvasWidget> {
  /// Just to track if its the first frame or not.
  var _flag = false;

  /// Will be used for generating png image.
  final _globalKey = new GlobalKey();

  /// Stores the image bytes
  Uint8List _imageBytes;

  /// No need for this actually;
  /// final _repaint = ValueNotifier<int>(0);
  TestingPainter _wavePainter;

  Future<Uint8List> _capturePng() async {
    try {
      final boundary = _globalKey
         .currentContext.findRenderObject();
      ui.Image image = await boundary.toImage();
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      var pngBytes = byteData.buffer.asUint8List();
      var bs64 = base64Encode(pngBytes);
      print(pngBytes);
      print(bs64);
      setState(() {});
      return pngBytes;
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    _wavePainter = TestingPainter();
    Timer.periodic( Duration(milliseconds: 50), (Timer timer) {
      if (!flag) flag = true;

      /// Save your image before each redraw.
      _imageBytes = _capturePng();

      /// You don't need a listener if you are using a stful widget.
      /// It will do just fine.
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: _globalkey,
      child: Container(
        /// Use this if this is not the first frame.
        decoration: _flag ? BoxDecoration(
          image: DecorationImage(
            image: MemoryImage(_imageBytes)
          )
        ) : null,
        child: CustomPainter(
          painter: _wavePainter
        )
      )
    );
  }
}

This way the image will not be a part of your custom painter and let me tell you, i tried drawing image using canvas but it was not that efficient, the MemoryImage provided by flutter renders image in a much better way.

A: Redrawing the whole canvas, even on every frame, is completely efficient. Trying to reuse the previous frame will often not be more efficient.
Looking at the code you posted, there are certain areas with rooms for improvement, but trying to preserve parts of the canvas should not be one of them.
The real performance issue you are having, is from repeatedly changing a ValueNotifier from a Timer.periodic event, every 50 ms. A much better way to handle redrawing on every frame, is to use AnimatedBuilder with a vsync, so the paint method of the CustomPainter will be called on every frame. This is similar to Window.requestAnimationFrame in the web browser world, if you are familiar with that. Here vsync stands for "vertical sync", if you are familiar with how computer graphics work. Essentially, your paint method will be called 60 times per second, on a device with 60 Hz screen, and it'll paint 120 times per second on a 120 Hz screen. This is the correct and scalable way to achieve buttery smooth animation across different kind of devices.
There are other areas worth optimizing, before thinking about preserving parts of the canvas. For example, just briefly looking at your code, you have this line:
_currentY = _rng.nextInt(size.height.toInt()).toDouble();

Here I assume you want to have a random decimal between 0 and size.height, if so, you can simply write _rng.nextDouble() * size.height, instead of casting a double to int and back again, and (probably unintentionally) rounding it during that process. But the performance gain from stuff like these is negligible.
Think about it, if a 3D video game can run smoothly on a phone, with each frame being dramatically different from the previous one, your animation should run smoothly, without having to worry about manually clearing parts of the canvas. Trying to manually optimize the canvas will probably lead to performance loss instead.
So, what you really should be focusing, is to use AnimatedBuilder instead of Timer to trigger the canvas redraw in your project, as a starting point.
For example, here's a small demo I made using AnimatedBuilder and CustomPaint:

Full source code:
import 'dart:math';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  List<SnowFlake> snowflakes = List.generate(100, (index) => SnowFlake());
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    )..repeat();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.blue, Colors.lightBlue, Colors.white],
            stops: [0, 0.7, 0.95],
          ),
        ),
        child: AnimatedBuilder(
          animation: _controller,
          builder: (_, __) {
            snowflakes.forEach((snow) => snow.fall());
            return CustomPaint(
              painter: MyPainter(snowflakes),
            );
          },
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  final List<SnowFlake> snowflakes;

  MyPainter(this.snowflakes);

  @override
  void paint(Canvas canvas, Size size) {
    final w = size.width;
    final h = size.height;
    final c = size.center(Offset.zero);

    final whitePaint = Paint()..color = Colors.white;

    canvas.drawCircle(c - Offset(0, -h * 0.165), w / 6, whitePaint);
    canvas.drawOval(
        Rect.fromCenter(
          center: c - Offset(0, -h * 0.35),
          width: w * 0.5,
          height: w * 0.6,
        ),
        whitePaint);

    snowflakes.forEach((snow) =>
        canvas.drawCircle(Offset(snow.x, snow.y), snow.radius, whitePaint));
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

class SnowFlake {
  double x = Random().nextDouble() * 400;
  double y = Random().nextDouble() * 800;
  double radius = Random().nextDouble() * 2 + 2;
  double velocity = Random().nextDouble() * 4 + 2;

  SnowFlake();

  fall() {
    y += velocity;
    if (y > 800) {
      x = Random().nextDouble() * 400;
      y = 10;
      radius = Random().nextDouble() * 2 + 2;
      velocity = Random().nextDouble() * 4 + 2;
    }
  }
}

Here I'm generating 100 snowflakes, redrawing the whole screen every frame. You can easily change the number of snowflakes to 1000 or higher, and it would still run very smoothly. Here I'm also not using the device screen size as much as I should be, as you can see, there are some hardcoded values like 400 or 800. Anyway, hopefully this demo would give you some faith in Flutter's graphics engine. :)
Here is another (smaller) example, showing you everything you need to get going with Canvas and Animations in Flutter. It might be easier to follow:
import 'package:flutter/material.dart';

void main() {
  runApp(DemoWidget());
}

class DemoWidget extends StatefulWidget {
  @override
  _DemoWidgetState createState() => _DemoWidgetState();
}

class _DemoWidgetState extends State<DemoWidget>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    )..repeat(reverse: true);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (_, __) => CustomPaint(
        painter: MyPainter(_controller.value),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  final double value;

  MyPainter(this.value);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawCircle(
      Offset(size.width / 2, size.height / 2),
      value * size.shortestSide,
      Paint()..color = Colors.blue,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}


text:
Q: Laravel routes ending with '.php' not working Using Laravel, I want to create a route to replace functionality of a legacy URL that used to be a PHP file, but whenever I create a route that ends with .php it does not recognize the route and I get a 404.
Route::get('test.php', function(){return "test";}); // Gets a 404  error.
However other routes with extensions seem to work.
Route::get('test.txt', function(){return "test";}); // works fine

A: see mod_rewrite as its a part of apache mod_rewrite handling this, not the laravel framework alone. see into public/.htaccess file .
I don't see any reason to do this. But as you want to know i am telling. I don't recommend this as its avoiding some purposes of the framework.
At first what you need to do is edit your .htaccess file rewrite rules to enable php extension. i can't say much as i don't see those files here.
Second thing is that all requests will be by default redirected to index.php . see one of my laravel project public/ folder .htaccess file. you need to look into yours and modify that, there is lot of ways you can modify according to your needs. there could be other .htaccess files
for extension changing part look here
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^ index.php [L] part for changing index.php
my .htaccess file as it is not modified
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

A: In laravel your routes do not need a .php extension.
check out the documentation.
Also when you return views you do not need the .php extension.


text:
Q: Button Handle MouseLeftButtonDown but still want the event to bubble I have a listbox with a DataTemplate for the items.
Inside my template, I have a label and 3 buttons.
My problem is that when i click the buttons, the listboxitem never become selected since the button handles the event.
Is there a way I could make the event still bubble up the tree so my listboxitem become selected and still fire the click on the button?

A: Put this in your ListBox.Resources
<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>

And this in the Code Behind
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

You could use the following code as well which doesn't use code-behind, however it only keeps the ListBoxItem selected for as long as it has KeyBoard focus. Once focus leaves, the item becomes unselected
<Style TargetType="ListBoxItem">
  <Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="True">
      <Setter Property="IsSelected" Value="True" />
    </Trigger>
  </Style.Triggers>
</Style>


text:
Q: Blazor Wasm Performance issue opening excel with npoi / closedXML On a project WebAssembly i'm currently struggling with performance issues while reading XLSX file with NPOI or ClosedXML
The goal is to have a front end validation of the XLSX file before sending it to the back.
async Task ImportExcelFile(InputFileChangeEventArgs e)
{
    dataTable = new DataTable();

    MemoryStream memoryStream = new();

    await e.File.OpenReadStream().CopyToAsync(memoryStream);

    memoryStream.Position = 0;

    XSSFWorkbook xsswb = new(memoryStream);
    ISheet sheet = xsswb.GetSheetAt(0);
    IRow hr = sheet.GetRow(0);
    var rows = new List<string>();

    int cc = hr.LastCellNum;

    for (var j = 0; j < cc; j++)
    {
        ICell cell = hr.GetCell(j);
        dataTable.Columns.Add(cell.ToString());
    }

    for (var j = (sheet.FirstRowNum + 1); j <= sheet.LastRowNum; j++)
    {
        var r = sheet.GetRow(j);
        for (var i = r.FirstCellNum; i < cc; i++)
        {
            rows.Add(r.GetCell(i)?.ToString());
        }

        if (rows.Count > 0)
        {
            dataTable.Rows.Add(rows.ToArray());
        }
        rows.Clear();
    }
}

Uploading an 1K rows  takes like 6/7 seconds to run  this line (110 KO)
Uploading an 13K rows takes between 30/40 seconds to run this line (1 MB)
    XSSFWorkbook xsswb = new(memoryStream);

I'm not sure with that to keep validation on front or to just send the stream to the back end and validate it here.
Is that normal it take so much time once ran on navigator side ?


text:
Q: Can Emacs' org-mode recognize tags within (instead of just at the endof ) a headline I am learning how to use Emacs and org-mode, and am wondering whether Emacs can support tags within rather than just at the end of headlines (whether natively or through a package or configuration in ~/.emacs).
Put differently, Emacs natively supports tags in this form:
* This is a headline.     :tag1:tag2:
Is there a way to get Emacs to recognize tags in the format below in addition?
* This is a headline with :tag1: and :tag2:.
I've been searching for answers for several hours, and haven't found this question anywhere else; I'd be grateful for any advice!

A: The real answer to this question is in @lawlist's comment above, that (to quote @lawlist) it "is not possible [to get org-mode to recognize tags within a line of text instead of at the end of the line] without substantially modifying several aspects of org-mode yourself."
For this reason, if @lawlist writes the comment up as an answer, I'll accept it. I'm also writing up this additional answer, though, for anyone like me who comes along and, learning this, wants a way to take some text and automatically generate org-mode tags for it. Following the discussion in the comments above, I've written a function in elisp below, which allows a user to highlight some text and automatically find any tags within the text (here, in the form {{tag}}) and concatenate them in org-mode tag format at the end of the first line.
(defvar tag-regexp-for-generating-org-mode-tag-list-from-text "{{\\(.*?\\)}}"
"A regular expression, in double-quotes, used for finding 'tags' within lines of text (these can then be translated into org-mode syntax tags.

For example, in the string \"This text contains the 'tags' {{tag1}} and {{tag2}}\", the default regular expression

\"{{\\(.*?\\)}}\"

would find \"tag1\" and \"tag2\", which could then be transformed into org-mode syntax tags, \":tag1:tag2:\"")

;; Following https://emacs.stackexchange.com/a/12335, use just the selected region.
(defun generate-org-mode-tag-list-from-selected-text (beginning-of-selected-region end-of-selected-region)
    "Take a highlighted section of text, find all strings within that text that match the search parameters defined in the variable tag-regexp-for-generating-org-mode-tag-list-from-text (by default, strings of the form {{tag1}} {{tag2}}), and concatenate them into a set of org-mode tags (:tag1:tag2:)

When text is highlighted, the argumentes beginning-of-selected-region and end-of-selected-region will be automatically populated.
"
    (interactive "r") ;; 'r' mode will auto-populate 'beginning-of-selected-region' and 'end-of-selected-region' above with the values of region-beginning and region-end.
    (if (use-region-p) ;; If a region is actively highlighted
        (progn ;; Start a multi-line sequence of commands
            ;; Following https://learnxinyminutes.com/docs/elisp/, go to the beginning-of-selected-region (here, of the selected region), and do a find-and-replace.
            (setq list-of-tag-strings (list)) ;; Create a blank list, which we'll fill in below.

            (goto-char beginning-of-selected-region) ;; Go to the beginning of the selected region (we'll then search forward from there.

            ;; A regex of "{{\\(.*?\\)}}" below looks for tags in {{this}} form. You can specify any other regex here instead.
            (while (re-search-forward tag-regexp-for-generating-org-mode-tag-list-from-text end-of-selected-region 't) ;; Search forward, but only up to the end-point of the selected region (otherwise, end-of-selected-region could be replaced with nil here).
                (add-to-list 'list-of-tag-strings ;; Add to the list called list-of-tag-strings
                    (replace-regexp-in-string "[[:space:]|:|-]+" "_" (match-string 1)) ;; Since org-mode tags cannot have spaces or colons (or dashes?) within them, replace any of those in the first capture group from the regular expression above ('match-string 1' returns whatever was in the parentheses in the regular expression above) with an underscore.
                    t) ;; Append (first checking for duplicate items) the first capture group from the regular expression above (i.e., what's inside the parentheses in the regular expression) to a list. The t tells the function to append (rather than prepend) to the list.
            ) ;; End of while statement

            ;; Go to the end of the first line of the selected region.
            (goto-char beginning-of-selected-region)
            (end-of-line)

            (if (> (length list-of-tag-strings) 0) ;; If the length of the list of found tags is greater than 0:
                (insert "  " ":" (mapconcat 'identity list-of-tag-strings ":") ":")) ;; Insert two spaces, a ':', the items from the list each separated by a ':', and a final ':'.

            (message "Tags gathered from the selected region (which comprises character markers %d to %d) and printed on the first line of the region." beginning-of-selected-region end-of-selected-region))

        ;; 'Else' part of the statement:
        (message "No region is selected for gathering tags. To run the function, you need to highlight a region first.")
    ))

You can then highlight text like this, and run the function with M-x generate-tag-list-from-selected-text:
This is a test {{with}} some {{tags}} in it.
This is another test with an {{additional           tag}} and {{one:more}}.

This text will then become
This is a test {{with}} some {{tags}} in it.  :with:tags:additional_tag:one_more:
This is another test with an {{additional           tag}} and {{one:more}}.

Since this is the first function I've written in elisp, I used two sources for understanding the basics of elisp syntax, specifically regarding a) using just a selected area of text and b) running find-and-replace operations on that text. Given that the function uses the generic structure of the code vs. its specific content, I'm thinking that I'm within my rights to open up the function with a CC0 dedication (I do this because of StackOverflow's ongoing discussion about licensing of code on this site).


text:
Q: Using PDF file in Keras OCR or PyTesseract - Python, is it possible? I am using Keras OCR and PyTesseract and was wondering if it is possible to use PDF files as the image input.
If not, does anyone have a suggestion as to how to convert a very massive PDF file into PNG or another acceptable format?
Thank you!

A: No, as far as I know PyTesseract works only with images. You'll need to convert your pdf to images first.
By "very massive PDF" I'm assuming you mean a pdf with lots of pages. This is not an issue. You can use pdf2image library (see the docs here). The method convert_from_path has an output_folder argument that lets you specify the folder where all your generated images will be saved:

Output directory for the generated files, should be seen more as a
"working directory" than an output folder. The converted images will
be written there to save system memory.

You can later use them one by one instead of your pdf to work with PyTesseract. If you don't assign the returned list of images from convert_from_path you don't risk filling up your memory.
Otherwise, if you are willing to keep everything in memory you can use the returned pages directly, like so:
pages = convert_from_path(pdf_path)

A: for example, my code :
Python : 3.9
Macos: BigSur
from PIL import Image
from fonctions_images import *
from pdf2image import convert_from_path
path='/Users/yves/documents_1/'
fichier =path+'TOUTOU.pdf'
images = convert_from_path(fichier,500, transparent=True,grayscale=True,poppler_path='/usr/local/Cellar/poppler/21.12.0/bin')

for v in range(0,len(images)):
    image=images[v]
    image.save(path+"image.png", format="png")
    test=path+"image.png"
    img = cv2.imread(test) # to store image in memory
    img = del_lines(path,img) # to supprime the lines
    img = cv2.imread(path+"img_final_bin_1.png")
    pytesseract.pytesseract.tesseract_cmd = "/usr/local/bin/tesseract"

    d=pytesseract.image_to_data(img[3820:4050,2340:4000], lang='fra',config=custom_config,output_type='data.frame')


text:
Q: Identifying a Winning Mahjong Hand I'm working on trying to identify a winning hand in mahjong, does anyone have any tips or a working formula?
The game of mahjong is like gin rummy with 13 cards, sets of 4,3 or flushes of 3. A winning hand includes the stolen or given card, which totals 14 cards.  A winning hand is sets of:

*

*3 sets of 4 plus 1 pair

*4 sets of 3 plus 1 pair.

*2 sets of 4 plus 2 sets of 3, no pair.

*Flushes are in sets of 3, but all one suite is a bonus.

*All pairs is also an option.

There are also points associated with this.
Any guidance or help would be much appreciated.
To follow up, and add info, this may help others, and gould help us to answer our own question,
I am aiming at Hong Kong Mahjong Rules.
When I work through an algorithm, the one I am investigating is the removal of streets, and if fail, remove the set.
works when I have a b3333 b4 b5 b666
check b345 - remove
check b345 fail, b333 is a set, remove
check b678, fail, b666 is a set.
none left, Win

but when I have a b222 b33 b44 b5. I need to skip and restart.
check b234 ok, remove
check b234 ok, remove
check b234 fail, single b2 (Failed hand)
restart, skip 1.
check b345 ok, remove
end, return to start
check b234 ok remove
check b234 fail, b22 is pair.
none left win.

but this method is troublesome, because there could be a double state to retry.
b222 b33 b44 b555 b66 b77
check b234 ok, remove
check b234 ok, remove
check b234 fail, resart, skip 1.
check b345 ok, remove
check b345 ok, remove
check b567 ok, remove
check b678 fail, no 7, skip one rety

any ideas?

A: I have implemented a successful mahjong game in Android.  The algorithm I used was as follows:
1) Count the occurrence of each tile into an array of 34
2) Remove every possible pair
3) Recursively check the remaining tiles for triplets
Hope that helps


text:
Q: Integral $\int_{-\infty}^\infty e^{-\frac{1}{2}x^2}dx$ How to compute integral $\int_{-\infty}^\infty e^{-\frac{1}{2}x^2}dx$? I try to change it to polar coordinates but I have only one variable.
Thanks in advance!

A: Let $I$ be the integral in question and note that
$$
I^2=\int_{-\infty}^\infty\int_{-\infty}^\infty e^{-\frac{1}{2}(x^2+y^2)}\,dx\,dy
=\int_{0}^{2\pi}\int_{0}^\infty e^{-\frac{1}{2}r^2}r\,dr\,d\theta
$$
by changing to polar coordinates. The last integral is easy to compute.


text:
Q: C# Adding node in XML error: "This operation would create an incorrectly structured document." XML-1
<CurrentStatus>
    <Time Stamp= "12:30">
        <price>100</price>
        <amount>1</amount>
    </Time>

    <Time Stamp= "14:50">
        <price>10</price>
        <amount>5</amount>
    </Time>

    <Time Stamp= "16:30">
        <price>10</price>
        <amount>5</amount>
    </Time>
</CurrentStatus>

XML-2
<CurrentStatus>
    <Time Stamp= "17:22">
        <price>40</price>
        <amount>120</amount>
    </Time>
</CurrentStatus>

I am first reading the XML-1 and then trying to insert the Time node from XML-2 into it (XML-1):
//Read first XML
XDocument xDoc1 = XDocument.Load(@"D:\myfile1.xml");

//Read second XML
XDocument xDoc2 = XDocument.Load(@"D:\myfile2.xml");
XElement currentTimeNode = xDoc2.Descendants("Time").ToList()[0]; //first decendent
//Append data
xDoc1.AddFirst(currentTimeNode); //This line throws ERROR

PROBLEM: I want to add the node as the first child node (add the complete block of Time node). The line xDoc1.AddFirst(currentTimeNode); throws the following error:

This operation would create an incorrectly structured document.

A: You are trying to add currentTimeNode as a child of xDoc1 -- but xDoc1 is the XML document itself, which means you are trying to add currentTimeNode as a second XML root element.  However, a well-formed XML document must have exactly one root element, and so xDoc1.AddFirst(currentTimeNode) throws the exception you are seeing since it already has a root element <CurrentStatus>.
Instead you should add currentTimeNode to the pre-existing Root of xDoc1:
xDoc1.Root.AddFirst(currentTimeNode);

Or, if there is a chance that xDoc1.Root is null (because you are constructing it from scratch in memory rather than loading from a pre-existing file), you could allocate it conditionally:
if (xDoc1.Root == null)
    xDoc1.Add(new XElement("CurrentStatus"));
xDoc1.Root.AddFirst(currentTimeNode);

Incidentally, it may be simpler and more performant to replace ToList()[0] with First() because First() will not attempt to enumerate and materialize the entire query once the first element is returned:
var currentTimeNode = xDoc2.Descendants("Time").First(); //first decendent

Sample fiddle here.

A: FWIW - for VB'ers that might come across this it would be.
    Dim xe1 As XElement
    Dim xe2 As XElement

    xe1 = <CurrentStatus>
              <Time Stamp="12:30">
                  <price>100</price>
                  <amount>1</amount>
              </Time>

              <Time Stamp="14:50">
                  <price>10</price>
                  <amount>5</amount>
              </Time>

              <Time Stamp="16:30">
                  <price>10</price>
                  <amount>5</amount>
              </Time>
          </CurrentStatus>

    xe2 = <CurrentStatus>
              <Time Stamp="17:22">
                  <price>40</price>
                  <amount>120</amount>
              </Time>
          </CurrentStatus>

    xe1.Add(xe2.<Time>) 'add to end
    ' OR
    ' xe1.AddFirst(xe2.<Time>) 'first


text:
Q: allow alphanum space alongwith dot special character in validation  ->add('proposer_name', 'custom', [
                    'rule' => array('custom', '/^[a-z0-9 ]*$/i'),
                    'message' => __('Only alphanumeric characters are allowed')
                ])

This is the method I am using in server side validation for name. Also I want to write eg. Mr. ABC DEF in name field. But it is not allowing . in field.  How should be my regex please help.  I working in cakephp 3.x.

A: Just add the dot inside your character class (square brackets []). It has no special meaning inside.
 ->add('proposer_name', 'custom', [
                    'rule' => array('custom', '/^[a-z0-9 .]*$/i'),
                    'message' => __('Only alphanumeric characters are allowed')
                ])


text:
Q: Does open set in $R_d \times R $ containing $R\times 0$ contain any subset $I \times (-\varepsilon, \varepsilon)$, with infinite $I$? Let $R_d$ be the set of reals with discrete topology, $R$ be the set of reals with natural topology and let $X=R_d \times R$ with product topology. Assume that $R_d \times \{0\} \subset V \subset X$  and $V$ is open. Do there exist an infinite set $I \subset R$ and a number $\varepsilon >0$ such that $I \times (-\varepsilon, \varepsilon) \subset V$ ?
Thanks

A: Directly from the definition of product topology we know that for each $x\in\mathbb  R$ there is a rational $\varepsilon_x>0$ such that $\{x\}\times(-\varepsilon_x,\varepsilon_x)\subseteq V$.
Now, for each $q\in\mathbb Q$ denote $A_q=\{x\in\mathbb R; \{x\}\times(-q,q)\subseteq V\}$. We have $\mathbb R=\bigcup_{q\in\mathbb Q} A_q$.
If every set $A_q$ would be finite, this would imply that $\mathbb R$ is countable, a contradiction.
(You could do basically the same thing working with the numbers of the form $\frac1n$, $n\in\mathbb N$, instead of rationals.)
You can also note that we would obtain the same contradiction by assuming that all $A_q$'s are countable, hence this shows that there is an $\varepsilon>0$ and an uncountable set $I$ with the property you're asking about.


text:
Q: using checkbox to enable textbox i have an application here in winforms that am trying to make. This is how i want it to happen: whenever the user clicks on register visitor button the registration form should be opening. works fine. here is the function that is called in that case:
private void Register_Visitor_Load(object sender, EventArgs e)

On this form i have a textfield placed which i want to disable when the form loads. i wrote a line which disables the textbox on form load:
textbox1.enabled = false;

i placed the above line in the load function which is working fine. now i want to enable my textbox1 based on the checkbox checked. for this i wrote the code:
CheckState state = checkBox1.CheckState;
            switch (state)
            {
                case CheckState.Checked:
                    {
                        textBox1.Enabled = true;
                        break;
                    }
                case CheckState.Indeterminate:
                case CheckState.Unchecked:
                    {
                        break;
                    }

now when i place the code above in the page load function nothing happens which is surely going to happen as that function is only called on form load. what am not getting is where to place the checkbox code so that my textbox is enable on runtime. other function are in response to button but what i want here it to instantly enable the textfield on runtime when the user checks the checkbox. kindly explain me how am i going to accomplish this!

A: You can use CheckStateChanged event; so whatever reason the checkBox1 is checked/unchecked/grayed you'll have the textBox1 properly enabled/disabled
private void checkBox1_CheckStateChanged(object sender, EventArgs e) {
  textBox1.Enabled = (checkBox1.CheckState == CheckState.Checked);
}

A: you are placing code at wrong event.
Instead of placing in pageload place that code on chekchange event of checkbox.
That will help you.
private void chkDisable_CheckedChanged(object sender, EventArgs e)
{
        if (((CheckBox)sender).Checked)
        {
            textBox1.Enable=true;
        }
        else
        {
            textBox1.Enable=false;
        }
}

A: Place the above code inside the function which handles the event for check box.
In your case it is checkchanged status.

A: You can try this:
 private void checkBox1_Click(object sender, EventArgs e)
 {

        if (checkBox1.Checked)
        {
            textBox1.Enabled = false;
        }
        else
        {
            textBox1.Enabled = true;
        }
 }

A: I did a hybrid of some of the above answers and it worked perfectly. I wanted the state of a button to be disabled upon loading the form, but then enabled if the user checks a box, here's the code:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
       button1.Enabled = (checkBox1.CheckState == CheckState.Checked);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (checkBox1.Checked)
        {
            button1.Enabled = true;
        }
        else
        {
            button1.Enabled = false;
        }

    }


text:
Q: How to add a non-printable image in xsl / apache-fop I'm trying to generate an xsl to be printed in a pre-printed sheet which works fine.
Now i want to give the user a better previsualization (in the pdf screen version) adding a background image which emulates the "pre-printed" stuf on the sheet to give the user a "context" of what is he printing.
The question is: Is there any way I can set a background image in xsl (using apache fop) visible only in pdf but not in the printed version of it?
Thank you all for reading or givin any advice.

A: Although as the comments state, you can't have content in the PDF that does not come out in a physical printed copy, here is one possible work around for you. Depending on how your users are ultimately going to be using FOP for PDF rendering and how your a driving the work flow, it's possible to pass a parameter into an xslt file before the transofrmation phase is run, so potentially, you could do a dual rendering of the same PDF, one that is presented to the user where the background image is enabled, and one that gets printed, you could just set a variable similar to how they do in this Example, and call it something like $isPreview, and just use a simple if or choose statement to check for 'Y' or 'N'.
Since you are sending to a printer, you may even want to take advantage of FOP's ability to generate to Postscript rather than PDF, I've used this feature quite extensively for print documents using FOP while also producing a PDF copy for electronic delivery via email or hosted services, and I've yet to find any discrepancy between the PDF rendering and what is printed after sending a rendered postscript file, so it should work well for you as well.
As I said, this is not truly a solution to your problem as you've presented it, but as a work around, it could get you the desired results if your clever about how you implement it.

A: I don;t think the statement that it is not possible is true, I am just not sure how to create such a PDF with FOP. Certainly you can add an image field. One would use a button field and place the image in the button. Then you would set the properties of that button to not print (printable false).
PDF support images in fields: https://answers.acrobatusers.com/adding-image-field-form-q41825.aspx
RenderX supports PDF Form fields but I do not see where they support an image inside the button, only text: http://www.renderx.com/reference.html#PDF%20Forms. But they do support setting a field to "printable".


text:
Q: Animating UIView while pushing a UINavigationController following situation.
i have an app that uses a UINavigationController for navigating.
For a push of a special Navigation Controller i want a custom Animation, a zoom out.
What i have is looking good so far, the only problem is, that the "old" Viewcontroller disappears before the animation starts, so the new viewcontroller zooms out of "nothing" instead of viewing the old viewcontroller in the background.
For better viewing i created a simple sample app: download

Does anybody know, how to animate the new viewcontroller (image3) that the old view controller(image1) stays in the background while animating (image 2)?
/* THIS CANNOT BE CHANGED */
    AnimatedViewController *animatedViewController = [[AnimatedViewController alloc] initWithNibName:@"AnimatedViewController" bundle:nil];

    /* THIS CAN BE CHANGED */
    animatedViewController.view.transform = CGAffineTransformMakeScale(0.01, 0.01);
    [UIView beginAnimations:@"animationExpand" context:NULL];
    [UIView setAnimationDuration:0.6f];
    animatedViewController.view.transform=CGAffineTransformMakeScale(1, 1);
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];

    /* THIS CANNOT BE CHANGED */
    [self.navigationController pushViewController:animatedViewController animated:NO];

Additional information: my app isn't that simple. i use three20 framework for my app but the pushing and creating of the view controllers is simply what three20 does. i only can hook into the part between (THIS CAN BE CHANGED in my code). i cannot change the code before and after this (except with a lot of researching).

A: I whipped this up very quickly. The idea is to call pushViewController after the scale animation is completed.
-(IBAction)animateButtonClicked:(id)sender {
    animatedViewController = [[AnimatedViewController alloc] initWithNibName:@"AnimatedViewController" bundle:nil];
    animatedViewController.view.transform = CGAffineTransformMakeScale(0.01, 0.01);

    [UIView animateWithDuration:0.6
                     animations:^{
                         [self.view addSubview:animatedViewController.view];
                         animatedViewController.view.transform=CGAffineTransformMakeScale(1, 1);
                     }
                     completion:^(BOOL finished){
                         [animatedViewController.view removeFromSuperview];
                         [self.navigationController pushViewController:animatedViewController animated:NO];
                     }];

}

A: Ok, one way to do this (a bit ugly) is to do the animation and upon the completion of the animation, do the pushViewController. When you do the animation, you need to animate up what the about-to-be-presented view controller's screen would look like. Since the animation ends with the new view, when the new view comes to the screen, nothing should change because its the same as the just animated view.


text:
Q: How to create a Stepper in a layout?
I want to create the stepper as shown in above image. Below is the code what I have tried. text below the circles should be at the center of circle. color of each line should be changed as next activity is navigated. and also color of each circle should be also changed when navigated to next activity.
  <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_title"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="horizontal"
            android:visibility="visible">

            <View
                android:id="@+id/circle_one"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:background="@drawable/ic_gray_hollow_circle" />

            <View
                android:id="@+id/line_one"
                android:layout_width="76dp"
                android:layout_height="15dp"
                android:layout_toEndOf="@+id/circle_one"
                android:background="@drawable/ic_gray_line" />

            <View
                android:id="@+id/circle_two"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_toEndOf="@+id/line_one"
                android:background="@drawable/ic_gray_hollow_circle" />

            <View
                android:id="@+id/line_two"
                android:layout_width="76dp"
                android:layout_height="15dp"
                android:layout_toEndOf="@+id/circle_two"
                android:background="@drawable/ic_gray_line" />

            <View
                android:id="@+id/circle_three"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_toEndOf="@+id/line_two"
                android:background="@drawable/ic_gray_hollow_circle" />

            <View
                android:id="@+id/line_three"
                android:layout_width="76dp"
                android:layout_height="15dp"
                android:layout_toEndOf="@+id/circle_three"
                android:background="@drawable/ic_gray_line" />

            <View
                android:id="@+id/circle_four"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_toEndOf="@+id/line_three"
                android:background="@drawable/ic_gray_hollow_circle" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/circle_one"
                android:text="Pay"
                android:textColor="#dbdbdb" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/circle_two"
                android:layout_toEndOf="@id/line_one"
                android:text="Amount"
                android:textColor="#dbdbdb" />

        </RelativeLayout>

Any help will be appreciated.

A: Well you can add this layout file on top of each and every activity. And then change the color and text on selection. Here's an example of what I've just said.
First make a layout file.
stepper_layout.xml
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/padding_title"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal"
        android:visibility="visible">

        <View
            android:id="@+id/circle_one"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:background="@drawable/ic_gray_hollow_circle" />

        <View
            android:id="@+id/line_one"
            android:layout_width="76dp"
            android:layout_height="15dp"
            android:layout_toEndOf="@+id/circle_one"
            android:background="@drawable/ic_gray_line" />

        <View
            android:id="@+id/circle_two"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_toEndOf="@+id/line_one"
            android:background="@drawable/ic_gray_hollow_circle" />

        <View
            android:id="@+id/line_two"
            android:layout_width="76dp"
            android:layout_height="15dp"
            android:layout_toEndOf="@+id/circle_two"
            android:background="@drawable/ic_gray_line" />

        <View
            android:id="@+id/circle_three"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_toEndOf="@+id/line_two"
            android:background="@drawable/ic_gray_hollow_circle" />

        <View
            android:id="@+id/line_three"
            android:layout_width="76dp"
            android:layout_height="15dp"
            android:layout_toEndOf="@+id/circle_three"
            android:background="@drawable/ic_gray_line" />

        <View
            android:id="@+id/circle_four"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_toEndOf="@+id/line_three"
            android:background="@drawable/ic_gray_hollow_circle" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/circle_one"
            android:text="Pay"
            android:textColor="#dbdbdb" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/circle_two"
            android:layout_toEndOf="@id/line_one"
            android:text="Amount"
            android:textColor="#dbdbdb" />

    </RelativeLayout>

Add stepper_layout in FirstActivity layout.
FirstActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include layout="@layout/stepper_layout" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="First!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Add stepper_layout in SecondActivity layout.
SecondActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include layout="@layout/stepper" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Second"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

   </android.support.constraint.ConstraintLayout>

Change stepper_layout view as you want.
FirstActivity.java
public class FirstActivity extends AppCompatActivity {

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final View view = findViewById(R.id.circle_one);
    view.setBackground(getResources().getDrawable(R.drawable.ic_green));

    final View view2 = findViewById(R.id.circle_two);
    view2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(intent);
            finish();
        }
    });
}
}

Change stepper_layout view as you want.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    final View view2 = findViewById(R.id.circle_two);
    view2.setBackground(getResources().getDrawable(R.drawable.ic_green));

    final View view = findViewById(R.id.circle_one);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SecondActivity.this, FirstActivity.class);
            startActivity(intent);
            finish();
        }
    });
}
}

Two activities are given as example here. You need to add more of them. And you can change view attributes within activity classes. Hope this helps.


text:
Q: Generate swagger v2 schema by NJsonSchema for .NET or Newtonsoft.Json.Schema I need to use a tool, preferably NJsonSchema for .NET to generate schemas from c# classes. The requirement is to create schemas based on swagger version 2. For example I cannot have oneOf, anyOf, etc, which are new keywords in OAS3 in the schema.
Can we specify the swagger/OAS version in the schema generator?
How can this be done?

A: I just found that there is a setting in NJsonSchema for choosing the version:
var settings = new JsonSchemaGeneratorSettings
            {
                SchemaType = NJsonSchema.SchemaType.Swagger2,
            };


text:
Q: Enterprise Validation Block different rulsets for parent child classes Validation on property of child class does not work when I have 2 different rulesets for The parent and child.
This is the class code: Mytype is the parent and Person is the child
    [HasSelfValidation]
    public class MyType
    {
        [SelfValidation(Ruleset = "RulesetA")]
        [SelfValidation(Ruleset = "RulesetB")]
        public void DoValidate(ValidationResults results)
        {
        }

        [NotNullValidator(Ruleset = "RulesetA")]
        [ObjectValidator("RulesetA", Ruleset = "RulesetA")]
        public Person Person { get; set; }

    }

    public class Person
    {
        [NotNullValidator(Ruleset = "RulesetB")]
        public string GivenName { get; set; }

    }

This is the custom validator class to validate MyType class against all rulesets:
    public interface IValidator<T>
    {
        ValidationResults Validate(T target);
    }

    public class MyValidator : IValidator<MyType>
    {
        public ValidationResults Validate(MyType target)
        {
            return Validation.Validate(target, new string[] {"RulesetA", "RulesetB"});
        }
    }

And this is the test which fails: (IsValid should be set to False but it's True)
    [TestMethod]
    public void Should_return_false_when_validating_MyType_without_PersonApplying_GivenName()
    {
        //arrange
        var myType = new MyType()
                            {
                                Person= new Person()
                            };
        myType.Person.GivenName = null;

        //act
        MyValidator _validator = new MyValidator();
        var resultList = _validator.Validate(myType);

        //assert
        Assert.IsFalse(resultList.IsValid);
    }

Would you please help?

A: VAB validates your object per ruleset and concatenates the validation results. This is what the Validation.Validate method looks like:
var resultsReturned = new ValidationResults();

foreach (string ruleset in rulesets)
{
    var validator = ValidationFactory.CreateValidator(
        targetType, ruleset, source);

    foreach (var validationResult in validator.Validate(target))
    {
        resultsReturned.AddResult(validationResult);
    }
}

return resultsReturned;

In other words, a validation on an object is always performed on a single ruleset. Since the ObjectValidator is only decorated for RulesetA, the Person object will not get validated when running on RulesetB.


text:
Q: Disagreement between Rydberg Equation and Conservation of momentum I have a physics question as my homework and it is as follows:
At what minimum kinetic energy must a hydrogen atom move for its inelastic head-on collision with another, stationary, hydrogen atom to make one of them capable of emitting a photon? both atoms are in ground state before the collision
Attempt 1 at solution:
I simply used the Rydberg Equation for hydrogen
$$\Delta E=E_0(\frac{1}{n_f^2}-\frac{1}{n_i^2})$$
Where $E_0=13.6eV$, I simply plug in the numbers to obtain the numerical solution of $10.2eV$
Attempt 2 at solution:
I consider conservation of momentum and energy
$$E=hf$$
$$p=\frac{hc}{f}$$
Therefore:
$$p_{photon}=p_{H}$$
$$\frac{hc}{f}=p_{H}$$
$$(1)\hspace{5 mm}f=\frac{hc}{p_H}$$
We also know by COE:
$$E_{photon}=E_{H}$$
$$(2)\hspace{5 mm}hf=\frac{p_H^2}{2m_H}$$
Substituting $(1)$ into $(2)$
we obtain
$$\frac{h^2c}{p_H}=\frac{p_H^2}{2m_H}$$
$$\frac{h^2c}{2m_H}=p_h^3$$
Momentum of the hydrogen atom is therefor:
$$\qquad \sqrt[\leftroot{-1}\uproot{2}\scriptstyle 3]{2h^2m_Hc}=p_h$$
Solving for$E_{H}$
$$\frac{\sqrt[3]{2h^2m_Hc}}{2m_H}$$
Solving numericallyy this leads to a disagreement as the solution using COM is $3.9696\times10^{-37}eV$ which is obviously wrong....
Did I mess up somewhere in the COM method or is it completely wrong?


text:
Q: Swtich to New Exepreince I am using SharePoint online on office 365 and the library was set to the classic experience.
I went to library settings, advanced and then changed it to new experience.
Unfortunately, the library hasn't been switched to the new experience.
I am using internet explorer 11.

A: If this issue only occurs on a certain library, In your browser's address bar, delete everything in the URL after .aspx. Then, add ?=contents=1 to the end of the URL and press Enter.
A list or document library hidden web part will be displayed as XsltListViewWebPart. Locate any web part that isn't for the list or document library. Select the web part, and then press Delete.
Browse back to the document library page, and then view the new experience.
If that does not work, Open developer tools(F12) in the browser. Just click F12 function key.
Click on application tab,expand cookies section and select the SharePoint online site which you currently working on.
Delete the one with the name 'spinu' that has the value.
Refresh the browser and that should work.
You can check detailed information here:
SharePoint Online list or library doesn't use the new experience as expected
Switch back to modern view in SharePoint online


text:
Q: Пoгoда html python ошибки Решил повторить создание погоды но получилось что-то не так
<html>
<head>
    <meta charset="UTF-8">
    <title>Пагода</title>

    <script src="eel.js"></script>
    <link rel="icon" type="image/png" href="/favicon.png">

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

</head>
    <input id="location" type="text" placeholder="Город\Страна" required="">

<body>
    <button id="now"> Узнать </button>
    <script type="text/javascript"
        async function display_weather() {
            Let place = document.getElementById("location").value
            Let res = await eel.get_weather(place)();
            document.getElementById('info').innerHTML = res:
        }

        jQuery('#show').on('click',function() {
            display_weather()
        }

    >
</body>

</html>```

PYTHON

```import eel
import pyowm
owm = pyowm.OWM("СКРЫТО")
@eel.expose
def get_weather(place):
    pass

    place = input("Город\Страна :")

    mgr = owm.weather_manager()
    observation = mgr.weather_at_place(place)
    w = observation.weather

    t = w.temperature("celsius")
    t1 = t["temp"]
    t2 = t["feels_like"]
    return "в городе/стране, {place} температура {t1} ,ощущение {t2}"

eel.init("web")
eel.start("index.html", size = (200, 250))```

Могу еще CSS приложить

A: import eel
import pyowm
owm = pyowm.OWM("СКРЫТО")
@eel.expose
def get_weather(place):
    mgr = owm.weather_manager()
    observation = mgr.weather_at_place(place)
    w = observation.weather

    t = w.temperature("celsius")
    t1 = t["temp"]
    t2 = t["feels_like"]
    return f"в городе/стране, {place} температура {t1} ,ощущение {t2}"

eel.init("web")
eel.start("index.html", size = (200, 250))


text:
Q: Java Android: onTouchListener not working I'm new to writing Apps for Java. I managed to build a little Test-App, with a SurfaceView that's constantly redrawn in a Thread based loop.
Now I managed to work all those Graphical things out, though I wanted to implement an onTouchListener. I did as I was told by Google and wrote it into my main activity implementing OnTouchListener and setting my SurfaceView to the OnTouchListener (directly: Panel.p.setOnTouchListener and indirectly: View view = findViewById(R.id.SurfaceView01);view.setOnTouchListener(this);).
I got results in neither case though. My App is set to 'Fullscreen' with the XML only containing a reference to the Panel.
I have no idea where the error in that could be, that everything works but the onTouchListener. I'm gonna add all the Files that are relevant to the problem here in hopes someone knows what I did wrong.
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.example.test.Panel android:id="@+id/SurfaceView01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:maxHeight="40dip">
</com.example.test.Panel>

Main Activity:
//'Constructor'
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
    //View view = findViewById(R.id.SurfaceView01);
    //view.setOnTouchListener(this);
    Panel.p.setOnTouchListener(this);
}

//Called when App's being closed
@Override
public void onPause(){
    super.onPause();
    CanvasThread._run = false;
}

//Touching - Somehow doesn't seem to want to do anything :(
@Override
public boolean onTouch (View v, MotionEvent event){
    int x = (int)event.getX();
    int y = (int)event.getY();
    CanvasThread.scene.bird.setDestination(x, y);
    //Pressing
    if(event.getAction()==MotionEvent.ACTION_DOWN){}
    //Releasing
    if(event.getAction()==MotionEvent.ACTION_UP){}
    //Moving
    if(event.getAction()==MotionEvent.ACTION_MOVE){}
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

Panel (SurfaceView):
CanvasThread canvasthread;
public static Panel p;

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    canvasthread.setRunning(true);
    canvasthread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        canvasthread.setRunning(false);
        while (retry) {
                try {
                        canvasthread.join();
                        retry = false;
                } catch (InterruptedException e) {}
        }

}

public Panel(Context context, AttributeSet attrs) {
    super(context, attrs);
    getHolder().addCallback(this);
    canvasthread = new CanvasThread(getHolder(), this);
    setFocusable(true);
    p = this;
}

public void onDraw(Canvas canvas, Bitmap img, int x, int y) {
    Paint paint = new Paint();
    canvas.drawBitmap(img, x, y, null);
}

public void setBlack(Canvas canvas){
    canvas.drawColor(Color.BLACK);
}

//-----------Image Management----------------------
public Bitmap chest = BitmapFactory.decodeResource(getResources(), R.drawable.chest);
public Bitmap stairs = BitmapFactory.decodeResource(getResources(), R.drawable.stairs);
public Bitmap[][] blueBird = doubleCrop(BitmapFactory.decodeResource(getResources(), R.drawable.bluebird), 4, 2);
public Bitmap[] tileset = cropIt(BitmapFactory.decodeResource(getResources(), R.drawable.tileset), 10);

public Bitmap[] cropIt(Bitmap set, int length){
    int width = set.getWidth()/length;
    int height = set.getHeight();
    Bitmap[] array = new Bitmap[length];
    for(int c=0; c<length; c++){
        array[c] = Bitmap.createBitmap(set, c*width, 0, width, height);
    }
    return array;
}

public Bitmap[][] doubleCrop(Bitmap set, int yLength, int xLength){
    int width = set.getWidth()/xLength;
    int height = set.getHeight()/yLength;
    Bitmap[][] array = new Bitmap[yLength][xLength];
    for(int cy=0; cy<yLength; cy++){
        for(int cx=0; cx<xLength; cx++){
            array[cy][cx] = Bitmap.createBitmap(set, cx*width, cy*height, width, height);
        }
    }
    return array;
}

CanvasThread:
    _surfaceHolder = surfaceHolder;
    _panel = panel;
    scene = new Scene(_panel);
}

public void setRunning(boolean run) {
    _run = run;
}

@Override
public void run() {
    Canvas c;
    while (_run) {
        try{Thread.sleep(FRAMEWAIT);}catch(Exception ex){}
        c = null;
        try {
            c = _surfaceHolder.lockCanvas(null);
            synchronized (_surfaceHolder) {
                scene.circle(_panel, c);
            }
        } finally {
            if (c != null) {
                _surfaceHolder.unlockCanvasAndPost(c);
            }
        }
    }
}

Some advice is much appreciated.
Thank you very much already.

A: You can declare onTouchListener directly into your Panel's constructor:
public class Panel extends SurfaceView{
      Panel(final Context context, AttributeSet attrs){

          setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //put your logics here
            }
          }
      }
}

Also I think that since CanvasThread taking care only about drawings on Panel - nothing except of Panel should know about CanvasThread.
By the way: in your example you just need to set return false to return true into Activity's onTouch method. I think it should solve the problem.
@Override
public boolean onTouch (View v, MotionEvent event){
    //....
    return true; //not false
}


text:
Q: Parallel Bubble sort on GPU i am implementing the simple bubble sort algorithm using CUDA, and i have a question.
i perform the following code in order to swap 2 consecutive elements in the array:
if(a[threadIdx.x]>a[threadIdx.x + 1])
    Swap(a[threadIdx.x] , a[threadIdx.x + 1]);

note that the number of threads in the block is half the size of the array. Is this a good implementation? would threads in a single warp execute in parallel even if there is a branch? therefore it would actually take N iterations in order to sort the array?
also note that i know that there are better sorting algorithms that i could implement,and i can use Thrust, CUDPP, or a sample sorting algorithm from the SDK, but in my case, i just need a simple algorithm to implement.

A: I assume:

*

*The array you want to sort is small (<100 elements)

*It is a part of some bigger GPU algorithm

*The array resides in shared memory space, or can be copied there

If any of these is not true, don't do bubble sort!
the number of threads in the block is half the size of the array. Is this a good implementation?
It is reasonable. When a divergent branch occurs in a warp, all threads execute all branches in a perfect sync, simply some threads have their flag "disabled" set. This way, every branch is executed only once. The only exception --- when no thread from a warp is taking a branch --- then the branch is simply skipped.
BUG!
In your code, however I see a problem. If you want one thread to operate on two elements of the array, make them handle it exclusively, that is:
if(a[2*threadIdx.x]>a[2*threadIdx.x + 1])
    Swap(a[2*threadIdx.x] , a[2*threadIdx.x + 1]);

Otherwise, if Swap is executed by two neighbouring threads, some values may dissapear and some other values may get duplicated in the array.
Another bug!
If your block is bigger than a warp size, remember to put __syncthreads() when needed. Even if your block is smaller (shouldn't be), you should check the __threadfence_block() to ensure that writes to shared memory are visible by other threads of the same block. Otherwise, the compiler may be too aggressive on optimisations and make your code invalid.
Another problem
If you fix the first bug, you will have 2-way bank conflict on your shared memory. It is not very important, but you might want to reorganise the data in your array to avoid them, e.g. have the consecutive elements in the following order:
[1, 3, 5, 7, 9, ..., 29, 31, 2, 4, 6, 8, ... , 30, 32]
This way, elements 1 and 2 belong to the same bank in shared memory.

A: I'm glad you realise that bubble sort on the GPU is likely to perform terribly badly! I'm struggling to figure out how to get sufficient parallelism without having to launch many kernels. Also, you may struggle to work out when you're done.
Anyway, to answer your specific question: yes, it's highly likely that you will have warp divergence in this case. However, given that the "else" branch is effectively empty, this will not slow you down. On average (until this list is sorted), roughly half the threads in a warp will take the "if" branch, the other threads will wait, and then when the "if" branch is complete, the warp threads can go back to being in-step. This is far from your biggest problem :)


text:
Q: Reference Head from custom layout handle I'm having an issue adding JS and CSS files to the head using a custom handle. Here is a simplified version of my controller action:
public function indexAction() {
    $this->loadLayout();
    $this->_initLayoutMessages('customer/session');
    $this->_initLayoutMessages('catalog/session');

    $this->getLayout()->getUpdate()->addHandle('customer_social_index_tour');

    $this->renderLayout();
}

This handle is being conditionally added on existing customer_social_index pages. The XML for customer_social_index looks like this:
<customer_social_index translate="label">
    <update handle="customer_account"/>

    <!-- Other stuff here that all works great -->
</customer_social_index>

While the custom handle's XML looks like this:
<customer_social_index_tour translate="label">
    <reference name="head">
        <action method="addItem"><type>skin_js</type><name>js/my-js-file.js</name><params/></action>
        <action method="addItem"><type>skin_css</type><name>css/my-css-file.css</name><params/></action>
    </reference>
</customer_social_index_tour>

The problem is that the JS and CSS don't get added. Here are the steps I've taken to debug this:

*

*Move the new handle above $this->loadLayout(); - No effect.

*Move <reference name="head"> into <customer_social_index> to make sure that my syntax is right and Magento can find those files. - The files show up correctly.

*Dump the list of handles on the page to make sure the handle is being applied correctly using <?php Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); ?> - Handle is there as it should be.

*Make other layout changes like <remove name="content" /> in <customer_social_index_tour> to make sure that the handle is being effective. - The content was removed.

So from what I can see, the code to add the JS and CSS files is written correctly and works in other handles, and the handle works correctly and can modify the layout. But for some reason I can't add the JS and CSS files from that custom handle.
Thanks for your help!

A: Why didn't your code work ?
Because you added your custom handle customer_social_index_tour after layout get loaded. ie.
$this->loadLayout();
$this->getLayout()->getUpdate()->addHandle('customer_social_index_tour');

What $this->loadLayout()does is, it will generate xml tree based on the available layout handles  and then generate all blocks. Since your custom handle get added after all these process, your handle layout update will not have any effects, since layout process are finished just before that :-) Hell... then ..
Why didn't my first Debug technique work ?
In your first debug technique, you have added your custom layout update handle before loading any layouts. ie like this.
$this->getLayout()->getUpdate()->addHandle('customer_social_index_tour');
$this->loadLayout();

In this case, you are too early. Your custom handle now will be the very first handle that Magento going to process now. This is because action handles are generated inside loadLayout() function. So update handle array will then somwhat look like this.
$handles = array (
    customer_social_index_tour,
    default,
    STORE_{store_id}
    THEME_{area}_{package}_{theme},
    customer_social_index
)

The important thing is your custom handle is placed above default handle. That means default handle processed after customer_social_index_tour processed. Due to this, magento does not understand what is head block that is defined inside your custom handle, since the definition of that block is defined inside head block. OOOOPPSSS..
Why your observer worked
controller_action_layout_load_before is a perfect event for doing custom handle after every action handles. Because this event will get fired after adding default and action handles, but before generating xml and blocks.
So going by this observer is the best solution in my personal opinion. But if you want to do this via controller itself (the only advantage here is, you don't need to declare an observer and then define an observer), then continue reading.
What we need here then ?
Basically this is what you need. You have to add your custom handle after every action handles, but before Magento generates full xml tree and then generate blocks.
It is tricky.. but try this code.
public function indexAction()
{
    $this->loadLayout('', false, false);
    $this->loadLayout('customer_social_index_tour');
    $this->_initLayoutMessages('customer/session');
    $this->_initLayoutMessages('catalog/session');
    $this->renderLayout();
}

Here first loadLayout() call will add all action layout handles (including default handle) but it will not generate xml(second param :false) and blocks((third param :false)). The second loadLayout() will add our custom handle to the layout and then it will generate xml and blocks. Be honest, I didnt try this code. But it should work. If that doesn't work, then you need to manually load your layout. This is what you need to do for that.
public function indexAction()
{
    $this->getLayout()->getUpdate()->addHandle('default');
    $this->addActionLayoutHandles();
    $this->getLayout()->getUpdate()->addHandle('customer_social_index_tour');
    $this->generateLayoutXml();
    $this->generateLayoutBlocks();
    $this->_isLayoutLoaded = true;
    $this->_initLayoutMessages('customer/session');
    $this->_initLayoutMessages('catalog/session');

    $this->renderLayout();
}

Try this and let me know your feedback.

A: I eventually got this handle working by adding the handle to the layout updates in an event observer, which was observing controller_action_layout_load_before.
What I don't understand is why that is necessary, considering that one of my approaches to this issue was to put the addition of the new handle above $this->loadLayout(); instead of below it. (Edit: See Rajeev's answer.)
Better answers and/or clarifications welcome.