text:
Q: What's the jumper "enable 1.5GB PHY" on a Western Digital hard disk? I've got a new hard disk. On the label there is a description of the jumper settings:

One of them is:

Jumpered pins 5 and 6 enables 1.5GB PHY

What does PHY stand for?

A: By jumping the two pins, 5 and 6, you limit the transfer rate to 1.5 GB/s.
PHY is simply the physical layer in question, between the drive and cables/transfer.
Take a look at Wikipedia's page on SATA throughput.

A: I bought the same disk 2 days ago.  What everyone else says is right, jumpering those pins will limit the transfer rates to 1.5Gb/s rather that the 3Gb/s it is capable of.
Also,
Pins 1 & 2 enable Spread Spectrum Clocking which reduces the drives electronic noise, at the cost of some performance.
Pins 3 & 4 enable Power-Up In Standby (low power mode).  Your motherboard needs to support this.  I couldn't find any way in Vista to get my external drive out of standby.

A: It's SATA II disk, right?
And if you put jumper on these pins HDDs will be SATA I.
It's there for if your motherboard doesn't support SATA II.

A: PHY stands for "physical layer".  By jumpering pins 5 & 6 will cause the drive to go into a legacy 1.5 Gbit/s mode, rather than its default 3.0 Gbit/s mode.  Check out the Wikipedia article on SATA for a bit more info.


text:
Q: How to set java.util.logging.config.file in AWS Lambda Function? How can you use a custom logging configuration in AWS Lambda?
Specifically, I don't want to use log4j or slf4j or ACL. I'm using java.util.logging.
I tried setting java.util.logging.config.file as an environment variable, but this didn't work as the framework expects a -D parameter.

A: You can use the JAVA_TOOL_OPTIONS to pass the relevant system properties into the lambda function.
Take a look at https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/envvars002.html.

In many environments the command line is not readily accessible to
  start the application with necessary command-line options. This often
  arises with applications that use embedded VMs (meaning they use the
  Java Native Interface (JNI) Invocation API to start the VM), or where
  the startup is deeply nested in scripts. In these environments the
  JAVA_TOOL_OPTIONS environment variable can be useful to augment a
  command line.

In the AWS Lambda Console you can set the JAVA_TOOL_OPTIONS as a env variable with values like -Dfoo=bar and then this will be available as System properties in your program.
Do take a look at difference between System Properties and Env Varibles.
Java system properties and environment variables

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set page orientation to landscape using ps2pdf Is it possible to set page orientation to landscape using ps2pdf on Windows?

A: ps2pdf is a rather limited utility. It is merely a small batch file (on Unix/Linux: a shell script) which constructs and calls the rather complex Ghostscript commandline while itself using a very simple commandline syntax.
If you need the full power of Ghostscript, you'd be better off calling gswin32c.exe directly.
OK, here is how to rotate pages with Ghostscript. However, this may not work for your intentions, because you cannot force a certain orientation for an individual page only. It relies on an internal Ghostscript algorithm that tries to rotate pages automatically, depending on the flow of text inside the PDFs:
* -dAutoRotatePages=/None  -- retains orientation of each page;
* -dAutoRotatePages=/All  -- rotates all pages (or none) depending on a kind of "majority decision";
* -dAutoRotatePages=/PageByPage -- auto-rotates pages individually.
Add one of these to the Ghostscript commandline you're using.
If there is no text on a page (or if there is an automatic page rotation set to /None), then Ghostscript uses the setpagedevice settings. You can pass such setpagedevice parameters on the Ghostscript commandline using the -c switch like this:
* -c "<</Orientation 3>> setpagedevice" -- sets landscape orientation;
* -c "<</Orientation 0>> setpagedevice" -- sets portrait orientation;
* -c "<</Orientation 2>> setpagedevice" -- sets upside down orientation;
* -c "<</Orientation 1>> setpagedevice" -- sets seascape orientation.
Do you require usage of pstopdf or Ghostscript? Would it be acceptable to use another Free, Open Source Software tool running on the commandline, such as pdftk.exe?
In any case, I'd recommend to look at pdftk too (which is also available for Windows). It is a commandline tool that can rotate pages from PDFs, and much more. Easier to use than Ghostscript for your stated purpose, and much faster as well. Especially, it can rotate individual pages inside a PDF document, leaving the other pages untouched. See here for details: http://www.accesspdf.com/pdftk/ .

A: See Setting page orientation, where this rather convoluted text seems to say that this is impossible:

By default Ghostscript determines
  viewing page orientation based on the
  dominant text orientation on the page.
  Sometimes, when the page has text in
  several orientations or has no text at
  all, wrong orientation can be
  selected.
Acrobat Distiller parameter
  AutoRotatePages controls the automatic
  orientation selection algorithm. On
  Ghostscript, besides input stream,
  Distiller parameters can be given as
  command line arguments. For instance:
  -dAutoRotatePages=/None or /All or /PageByPage.
When there is no text on the page or
  automatic page rotation is set to
  /None an orientation value from
  setpagedevice is used. Valid values
  are: 0 (portrait), 3 (landscape), 2
  (upside down), and 1 (seascape). The
  orientation can be set from the
  command line as -c "<>
  setpagedevice" using Ghostscript
  directly but cannot be set in ps2pdf.
  See Limitations below.
Ghostscript passes the orientation
  values from DSC comments to pdfwrite
  driver but they are effectively ignored there. This appears to be
  consistent with Distiller 5 behavior.


text:
Q: Getting the right coordinates of the visible part of a UIImage inside of UIScrollView I have a UIImage which is inside a UIScrollView so I can zoom-in and zoom-out, crop, move around, etc.
How do I get the coordinates of the visible part of the UIImage inside the UIScrollView.
I want to crop the image in it's native resolution (using GPUIImage) but I need to x, y, width and height for the rectangle.

A: I use a scrollview to enable zoom of a UIImage.  A cropping button presents an overlaid resizable cropping view.  The following is the code I use to ensure the user defined crop box in the UIScrollView gets added with the correct coordinates to the UIImageView (can then use to crop image).
To find the x and y coordinates use the scrollview contentOffset multiplied by inverse of zoomscale:
float origX = 0;
float origY = 0;
float widthCropper = 0;
float heightCropper = 0;

if (_scrollView.contentOffset.x > 0){
    origX = (_scrollView.contentOffset.x) * (1/_scrollView.zoomScale);
}
if (_scrollView.contentOffset.y > 0){
    origY = (_scrollView.contentOffset.y) * (1/_scrollView.zoomScale);
}

If you need to create a properly sized cropping box for what is displayed in the scrollview you will need to adjust the width and the height for any zoom factor:
widthCropper = (_scrollView.frame.size.width * (1/_scrollView.zoomScale));
heightCropper = (_scrollView.frame.size.height * (1/_scrollView.zoomScale));

and to add this properly sized rectangle as a cropping view to the UIImageView:
CGRect cropRect = CGRectMake((origX + (SIDE_MARGIN/2)), (origY + (SIDE_MARGIN / 2)), (widthCropper - SIDE_MARGIN), (heightCropper  - SIDE_MARGIN));
_cropView = [[UIView alloc]initWithFrame:cropRect];
[_cropView setBackgroundColor:[UIColor grayColor]];
[_cropView setAlpha:0.7];
[_imageView addSubview:_cropView];
[_imageView setCropView:_cropView];


text:
Q: When does java.net.Socket.setSoTimeout(...) throws SocketException? The documentation says that Socket's setSoTimeout(int) method

throws SocketException - if there is an error in the underlying protocol, such as a TCP error

Have you ever caught this exception? When using TCP sockets, what kind of TCP error could make this method throw the exception?
EDIT:
Let me try to be a bit more specific and deeper. I'm not looking for the trivial (eg, a closed socket will throw this exception) that can be easily found elsewhere.
Suppose the Socket (representing a TCP connection) has just been created, is connected, and not yet closed. I've not yet performed any reads/writes on it. I'm running on Linux (Ubuntu Server 11.04), so we can forget the case in which the TCP implementation doesn't support read timeouts.
Now, can this exception be thrown in this situation? If so, what does it mean? Is it something specific to the current Socket instance? If I simply close() it and somehow obtain a new one, should it work? Is it a bigger problem I cannot recover from (such as a problem in the operating system), and should better shutdown my application?

A: The SocketException, in this scenario, is either thrown if the socket is closed or closing.
It can also be thrown to indicate an error that was generated by the native TCP stack implementation. If, for instance, you are on Windows, setSoTimeout will likely boil down to an invocation of the setsockopt function in the Windows Winsock API. An error from this method would indicate some deeper issue in the winsock subsystem (unable to initialize) or it could also be thrown if you attempt to set socket options when a blocking operation is in progress on the socket (by another thread, for instance). For this reason, you should strive to only modify socket options at creation time, avoiding to change any options once you've connected the socket and started doing I/O on it.
You can read more here if you are curious.

A: java.net.SocketExceptionis thrown when you call setSoTimeout on a closed socket.
As always, use the forc..source.


text:
Q: R error message output goes off the slide in beamer presentation R markdown I'm using R markdown to make a beamer presentation.
When I try to include an error message output from R on the slide it goes off the page.
Here is my code:
---
title: "Untitled"
author: "John Smith"
date: '2022-04-29'
output: beamer_presentation
---

This error message goes off the page

```{r cars, echo = TRUE, error=TRUE}
summary(carrrrrrrrrrrrrrrrs)
```

And, this is what the slides look like:

How do I keep the code on the page, either by putting it on multiple lines or reducing font size?

A: You can use the same technique as in Change representation (background-color & frame) of chunks in RMarkdown (with Beamer-Presentations) to redefine the verbatim environment in such a way that it uses the listings package. The listings package then allows you to both add line breaks and adjust the font size to your liking:
---
title: "Untitled"
author: "John Smith"
date: '2022-04-29'
output:
  beamer_presentation:
    keep_tex: true
header-includes:
  - \let\verbatim\undefined
  - \let\verbatimend\undefined
  - \usepackage{listings}
  - \lstnewenvironment{verbatim}{\lstset{breaklines=true,basicstyle=\ttfamily\footnotesize}}{}
---

This error message goes off the page

```{r cars, echo = TRUE, error=TRUE}
summary(carrrrrrrrrrrrrrrrs)
```


text:
Q: how do i get a GDAL(using gdalwarp) clipped layer projected in pseudo mercator ESPG:3857 to not be shifted? how do i get a GDAL rasterized layer projected in pseudo mercator ESPG:3857 to not be shifted ?
i have a vector layer projected in ESPG:3857,after rasterizing using this command:
gdal_rasterize -a_nodata -999 -te xMin yMin xMax yMax -a theField -tr 10 10 -l LayerName -co TFW=YES -co COMPRESS=LZW  VectorLayerPath outPutFilePath

the rasterization is perfect, but when i clip using this command:
gdalwarp -dstnodata -999 -q -cutline theMaskVectorLayerPath -crop_to_cutline -of GTiff inputrasterPath outPutRasterPath

the raster is shifted then clipped and the result is wrong.
is this happening to anybody else using pseudo mercator?

A: I have noticed the same error when clipping to Pseudo mercator. It might have something to do with the special treatment of mercator projection on a sphere.
Try any other CRS when clipping to avoid the bug. You can reproject afterwards back to EPSG:3857 if necessary.
It might help to set -s_srs and -t_srs explicitely to EPSG:3857 in both command lines, but I'm not sure that it helps.


text:
Q: Adventure Works: Calculate the yearly sales based on marital status I'm teaching myself MDX and want to know how much married people spend per year vs single people. It sounded simple in my head:

*

*Create a tuple on the columns based on [Sales Amount] and [Marital Status]

*Put [Fiscal Year] on the rows

SELECT
([Measures].[Sales Amount], [Customer].[Marital Status].Children) ON COLUMNS,
NON EMPTY ([Date].[Fiscal Year].Children ) ON ROWS
FROM [Adventure Works]

I was thinking that when the query ran, it would lay out the columns and rows and then create the necessary tuples to retrieve the intersecting values. While the query did run, the results weren't what I expected. It shows that the married people spent the exact same amount as the single people.

The most likely cause is bad query, but I also considered that maybe some dimensions never intersect in a cube. Am I off track with this assumption? I hope I am because with just the little I've learned so far, I can envision some great potential with MDX given a cube with lots of dimensions.
On the other hand, if it is just a bad query, a point in the right direction would be appreciated.
Thank You!

A: The issue is you are using the wrong measure. Try the below query.
SELECT
([Measures].[Internet Sales Amount], [Customer].[Marital Status].Children) ON COLUMNS,
NON EMPTY ([Date].[Fiscal Year].Children ) ON ROWS
FROM [Adventure Works]

The reason that this query works and yours doesnt is that the underlying Fact for "[Measures].[Sales Amount]" is not associated to Customer Dimension. Where as the
"[Measures].[Internet Sales Amount]" underlying fact is.
If you have the SSAS project for adventure works, go to solution explorer, then in cubes double click Adventure works, now select the dimension usage tab. You will see the mapping.


text:
Q: Best state-management for multi language support? I have a small web application that has multi-language support (en, de, it, fr, nl, sl, hr). This application is accessed constantly from a lot of users that use it for a short time (the time to fill their data to get an internet access code).
I have a problem with setting the culture similar to this thread:
InitializeCulture change language of domain
I know how to do it, it's just that I'm not sure which state-management to use. I wanted to ask for suggestions which method to use. Those are my thoughts:
Session - the easiest way and the more elegant, but it's server side and I have a lot of requests so I fear that the server can get too overloaded
Cookie - easy to implement and it's client side, but some users have cookies disabled in their browser
QueryString - not so easy to implement in this phase, but it's client side and can be easily tested because the application has only 3 forms (3 URLs to add query string parameters)
I'd like to hear your ideas and suggestions.
Thank you in advance!

A: Actual persistence store would actually depend upon the scope/life-time of culture selection. For example, if it's user specific selection that has to be persisted over sessions then you can use database or persistent cookie where cookie will remember for a machine and database will remember across machines. The retrieval (from database) will happen when it's needed - and the value can be cached into ASP.NET cache (will need different key per user) or session or view-state (if its single page application) etc.
You shouldn't worry too much about putting that into session if you are already using session state for something else. In such case, it doesn't really consume any significant memory. If you have log out function then you can explicitly clear the session state and release that little bit of memory. If you don't have log out functionality then you can use small value for session timeout.


text:
Q: Storage options for diskless servers I am trying to build a neural network simulation running on several high-CPU diskless instances. I am planning to use a persistent disk to store my simulation code and training data and mount them on all server instances. It is basically a map reduce kind of task (several nodes working on the same training data, the results of all nodes need to be collected to one single results file).
My only question now is, what are my options to (permanently) save the simulation results of the different servers (either at some points during the simulation or once at the end). Ideally, I would love to write them to the single persistent disk mounted on all servers but this is not possible because i can only mount it read-only to more than one server.
What is the smartest (and cheapest) way to collect all simulation results of all servers back to one persistent disk?

A: Google Cloud Storage is a great way to permanently store information in the Google Cloud. All you need to do is enable that product for your project, and you'll be able to access Cloud Storage directly from your Compute Engine virtual machines. If you create your instances with the 'storage-rw' service account, access is even easier because you can use the gsutil command built into your virtual machines without needing to do any explicit authorization.
To be more specific, go to the Google Cloud Console, select the project with which you'd like to use Compute Engine and Cloud Storage and make sure both those services are enabled. Then use the 'storage-rw' service account scope when creating your virtual machine. If you use gcutil to create your VM, simply add the --storage_account_scope=storage-rw (there's also an intuitive way to set the service account scope if you're using the Cloud Console to start your VM). Once your VM is up and running you can use the gsutil command freely without worrying about doing interactive login or OAuth steps. You can also script your usage by integrating any desired gsutil requests into your application (gsutil will also work in a startup script).
More background on the service account features of GCE can be found here.

A: Marc's answer is definitely best for long-term storage of results.  Depending on your I/O and reliability needs, you can also set up one server as an NFS server, and use it to mount the volume remotely on your other nodes.
Typically, the NFS server would be your "master node", and it can serve both binaries and configuration.  Workers would periodically re-scan the directories exported from the master to pick up new binaries or configuration.  If you don't need a lot of disk I/O (you mentioned neural simulation, so I'm presuming the data set fits in memory, and you only output final results), it can be acceptably fast to simply write your output to NFS directories on your master node, and then have the master node backup results to some place like GCS.
The main advantage of using NFS over GCS is that NFS offers familiar filesystem semantics, which can help if you're using third-party software that expects to read files off filesystems.  It's pretty easy to sync down files from GCS to local storage periodically, but does require running an extra agent on the host.
The disadvantages of setting up NFS are that you probably need to sync UIDs between hosts, NFS can be a security hole, (I'd only expose NFS on my private network, not to anything outside 10/8) and that it will require installing additional packages on both client and server to set up the shares.  Also, NFS will only be as reliable as the hosting machine, while an object store like GCS or S3 will be implemented with redundant servers and possibly even geographic diversity.

A: If you want to stay in the google product space, how about google cloud storage?
Otherwise, I've used S3 and boto for these kinds of tasks

A: As a more general option, you're asking for some sort of general object store.   Google, as noted in previous responses, makes a nice package, but nearly all cloud providers provide some storage option.   Make sure your cloud provider has BOTH key options -- a volume store, a store for data similar to a virtual disk, and an object store, a key/value store.  Both have their strengths and weaknesses.    Volume stores are drop-in replacements for virtual disks.  If you can use stdio, you can likely use a remote volume store.  The problem is, they often have the structure of a disk.   If you want anything more than that, you're asking for a database.   The object store is a "middle ground" between the disk and the database.   It's fast, and semi-structured.
I'm an OpenStack user myself -- first, because it does provide both storage families, and second, it's supported by a variety of vendors, so, if you decide to move from vendor A to vendor B, your code can remain unchanged.   You can even run a copy of it on your own machines (Go to www.openstack.org)   Note however, OpenStack does like memory.  You're not going to run your private cloud on a 4GB laptop!   Consider two 16GB machines.


text:
Q: Passing arguments to function in Python In a simplified example, say I have
class Car:
  def __init__(self, operation):
    self.operation = operation

def change_wheels(car, wheel_type):
  ...
def repair_brakes(car, brake_pads, brake_fluid):
  ...

car_list = [Car(change_wheels), Car(repair_brakes)]

def service_car(car, wheel_type, brake_pads, brake_fluid):
  car.operation(???)

How do I pass the required arguments to the operation function?

A: You could give Car parameters, like wheel type, brake type, etc. And pass the car object to the functions, then retrieve the car's parameters. These attributes is corresponding to each car, because they have different brake types etc... And passing these objects to the functions makes easier to get the needed parameters later.
class Car:
    def __init__(self, wheel, brakes, operation):
        self.wheel     = wheel
        self.brakes    = brakes
        self.operation = operation

def change_wheels(car):
    print('Wheel', car.wheels)

def repair_brakes(car):
    print('Brakes', car.brakes)

car_list = [Car('Wheel type', 'Brake type', change_wheels), Car('Wheel type', 'Brake type', repair_brakes)]

for car in car_list:
    car.operation(car)

Not all parameters were implemented, this is just an example!

A: Not sure what you want, but how about:
class Car:
  def __init__(self, operation):
    self.op = operation

  def __call__(self, *args, **kwargs):
    try: self.op(self, *args, **kwargs)
    except TypeError: print('Unsupported operation.')

def change_wheels(car, wheel_type):
  print('change_wheels()', wheel_type)

def repair_brakes(car, brake_pads, brake_fluid):
  print('repair_brakes()', brake_pads, brake_fluid)

car_list = [Car(change_wheels), Car(repair_brakes)]

def service_car(car, wheel_type, brake_pads, brake_fluid):
  #car.operation(???)
  car(wheel_type)
  car(brake_pads, brake_fluid)

for car in car_list: service_car(car, 'wt', 'bp', 'bf')


text:
Q: How can I decode special characters creating using VIM digraphs using Python 3.7? As part of my studies I want to create flash-cards using online software.
To do this, I use Python 3.7 to parse the files and to generate the fronts and
backs of my flash cards (which I then use pyautogui to add to the flash-card
software). I want to be able to parse the special characters created using VIM
digraphs.
I structure my notes such that every second paragraph is a question, and every
second paragraph is an answer, so that it is easily split along paragraphs.
I am currently studying Chemistry, and there are many symbols that are very
useful to have in such a circumstance, allowing me to write things like:
Vad är den allmänna formeln för syrabas-jämvikter där syran dominerar?

* HA + H₂O ↔ H₃O⁺ + A⁻
* HA ↔ H⁺ + A⁻
* HA = Godtycklig syra
* A⁻ = Syrans konjugerade bas

Hur stor är syrakonstanten (Ionization constant)?

* K_a = {H₃O⁺}{A⁻} / {HA} (Då {H₂O} = 1)

Hur beräknas förändringar i inre energi?

* dU = dq + dw ⇒ ΔU = q + w
  * dU, ΔU = Ändringen i inre energi
  * dq, q = Värme (tillförsel/bortförsel)
  * dw, w = Arbete (tillförsel/bortförsel)

Hur protolyseras flerprotoniga syror?

* H₃A ↔ H⁺ + H₂A⁻ (K_a1)
* H₂A⁻ ↔ H⁺ + HA²⁻ (K_a2)
* HA²⁻ ↔ H⁺ + A³⁻ (K_a3)
* K_a1 > K_a2 > K_a3

This is a tiny sample of the notes I am parsing. When copying these directly
from VIM into the browser, it yields the desired symbols, but I want to
automate the process of creating the cards.
When I try to parse it with Python, all these special characters
disappear, resulting in a lot of manual labor to correct all the small symbols.
I am using pyautogui.typewrite(...) to output the questions.  The code I am
currently using to parse are along the lines of the following:
file_name = "..." # The file with the notes

with open(file_name, encoding="utf-8") as f:
    paragraphs = iter(f.read().split("\n\n"))

questions = ((question, next(paragraphs)) for question in paragraphs)

Is there a way to input and output the symbols in my notes using Python 3.7?
Cheers!


text:
Q: Charts.js - onComplete javascript function coming from JSON I'm using Charts.js with data and options coming from an AJAX request in json.
The problem comes when i need to add, as an option, a callback on onComplete event because the JSON should look like
"animation" : {
      "onComplete" : function(animation){alert('ok')}
    },

which is not valid JSON.
I've tried to retrieve data as simple text (datatype: 'text'), but when passing it too Charts.js i got an error:
Uncaught TypeError: Cannot create property 'data' on string

this could be the json i'm retrieving
 {
  "type" : "line",
  "data" : {
    "datasets" : [ {
      "data" : [ {
        "t" : 1551096300000,
        "y" : 22.8125
      }, {
        "t" : 1551096600000,
        "y" : 22.8125
      }, {
        "t" : 1551096900000,
        "y" : 22.8125
      }, {
        "t" : 1551097200000,
        "y" : 22.8125
      }, {
        "t" : 1551097500000,
        "y" : 22.8125
      }, {
        "t" : 1551097800000,
        "y" : 19.3125
      }],
      "label" : "Sample data",
      "fill" : false,
      "backgroundColor" : "rgba(0,128,0,1.000)",
      "borderWidth" : 2,
      "borderColor" : "rgba(0,128,0,1.000)"
    },
  "options" : {
    "responsive" : true,
    "maintainAspectRatio" : true,
    "title" : {
      "display" : true,
      "position" : "top",
      "text" : "Temperature (°C)"
    },
    "legend" : {
      "position" : "bottom"
    },
    "hover" : {
      "mode" : "dataset"
    },
    "animation" : {
      "onComplete" : function(animation){alert('ok')}
    },
    "scales" : {
      "xAxes" : [ {
        "type" : "time",
        "time" : {
          "displayFormats" : {
            "millisecond" : null,
            "second" : null,
            "minute" : "HH:mm",
            "hour" : "DD/MM HH:mm",
            "day" : "DD/MM HH:mm",
            "week" : null,
            "month" : "DD/MM HH",
            "quarter" : null,
            "year" : null
          },
          "tooltipFormat" : "DD/MM/YY HH:mm"
        }
      } ]
    },
    "elements" : {
      "point" : {
        "radius" : 1,
        "hitRadius" : 2,
        "hoverRadius" : 2
      }
    }
  }
}

A: First of all you forgot to close the array of datasets in line 29.
secondly it is not valid to define functions in JSON results (Line 45).
check this : Is it valid to define functions in JSON results?
And again you forgot to close curly brace at the end .
{
    "type": "line",
    "data": {
        "datasets": [{
                "data": [{
                    "t": 1551096300000,
                    "y": 22.8125
                }, {
                    "t": 1551096600000,
                    "y": 22.8125
                }, {
                    "t": 1551096900000,
                    "y": 22.8125
                }, {
                    "t": 1551097200000,
                    "y": 22.8125
                }, {
                    "t": 1551097500000,
                    "y": 22.8125
                }, {
                    "t": 1551097800000,
                    "y": 19.3125
                }],
                "label": "Sample data",
                "fill": false,
                "backgroundColor": "rgba(0,128,0,1.000)",
                "borderWidth": 2,
                "borderColor": "rgba(0,128,0,1.000)"
            }],
            "options": {
                "responsive": true,
                "maintainAspectRatio": true,
                "title": {
                    "display": true,
                    "position": "top",
                    "text": "Temperature (°C)"
                },
                "legend": {
                    "position": "bottom"
                },
                "hover": {
                    "mode": "dataset"
                },
                "animation": {
                    "onComplete": ""
                },
                "scales": {
                    "xAxes": [{
                        "type": "time",
                        "time": {
                            "displayFormats": {
                                "millisecond": null,
                                "second": null,
                                "minute": "HH:mm",
                                "hour": "DD/MM HH:mm",
                                "day": "DD/MM HH:mm",
                                "week": null,
                                "month": "DD/MM HH",
                                "quarter": null,
                                "year": null
                            },
                            "tooltipFormat": "DD/MM/YY HH:mm"
                        }
                    }]
                },
                "elements": {
                    "point": {
                        "radius": 1,
                        "hitRadius": 2,
                        "hoverRadius": 2
                    }
                }
            }
        }
}


text:
Q: Python: matplotlib plot inside QML layout Consider the following python3 PyQt code to display an interactive matplotlib graph with toolbar
import sys, sip
import numpy as np
from PyQt5 import QtGui, QtWidgets
from PyQt5.Qt import *

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

app = QApplication(sys.argv)
top = QWidget()

fig = plt.figure()
ax = fig.gca()
x = np.linspace(0,5,100)
ax.plot(x,np.sin(x))
canvas = FigureCanvas(fig)
toolbar = NavigationToolbar(canvas, top)

def pick(event):
    if (event.xdata is None) or (event.ydata is None): return
    ax.plot([0,event.xdata],[0,event.ydata])
    canvas.draw()

canvas.mpl_connect('button_press_event', pick)

layout = QtWidgets.QVBoxLayout()
layout.addWidget(toolbar)
layout.addWidget(canvas)
top.setLayout(layout)
top.show()

app.exec_()

Now I'd like to achieve the same by using PyQt with QML instead. I have some experience with creating QML GUIs in C++ and I really like the fact that the layout code is nicely separated from the core logic of the code.
I have found several examples on how to show plots in PyQt and on how to use Python with QML, but nothing that combines the two.
To start off, my python and QML snippets look as follows:
Python:
import sys, sip
import numpy as np
from PyQt5 import QtGui, QtWidgets
from PyQt5.Qt import *

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(QUrl('layout.qml'))
root = engine.rootObjects()[0]
root.show()
sys.exit(app.exec_())

Layout:
import QtQuick 2.7
import QtQuick.Controls 1.4

ApplicationWindow {

    visible: true
    width: 400
    height: 400

    Canvas {
        // canvas may not be the right choice here
        id: mycanvas
        anchors.fill: parent
    }

}

But I am quite lost on how to continue.
More concretely, the question would be: Is there a way to display an interactive matplotlib plot in QML (by interactive I mean not just a figure that has been saved as an image, ideally with the standard toolbar for zoom etc.)
Can anyone help? Or is the combination of QML and plots just simply discouraged (this question suggests python and QML should work together quite well)?

A: I don't have a full solution, but if you're OK with just displaying charts and the fact that you'll have to provide any interactive controls by yourself, then there's a reasonably simple way to do that.
First of all, you will need to convert your matplotlib chart into a QImage. Fortunately doing so is surprisingly easy. The canonical backend (renderer) for matplotlib is *Agg`, and it allows you to render your Figure into a memory. Just make a suitable Canvas object for you Figure, then call .draw(). The QImage constructor will take generated data directly as inputs.
canvas = FigureCanvasAgg(figure)
canvas.draw()

img = QtGui.QImage(canvas.buffer_rgba(), *canvas.get_width_height(), QtGui.QImage.Format_RGBA8888).copy()

The Qt way to provide that image into QML is to use QQuickImageProvider. It will get "image name" as input from QML and should provide a suitable image as output. This allows you to serve all matplotlib charts in your app with just one Image provider. When I was working on a small visualization app for internal use, I ended up with a code like this:
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import PyQt5.QtQuick as QtQuick
import PyQt5.QtQml as QtQml

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg

class MatplotlibImageProvider(QtQuick.QQuickImageProvider):
    figures = dict()

    def __init__(self):
        QtQuick.QQuickImageProvider.__init__(self, QtQml.QQmlImageProviderBase.Image)

    def addFigure(self, name, **kwargs):
        figure = Figure(**kwargs)
        self.figures[name] = figure
        return figure

    def getFigure(self, name):
        return self.figures.get(name, None)

    def requestImage(self, p_str, size):
        figure = self.getFigure(p_str)
        if figure is None:
            return QtQuick.QQuickImageProvider.requestImage(self, p_str, size)

        canvas = FigureCanvasAgg(figure)
        canvas.draw()

        w, h = canvas.get_width_height()
        img = QtGui.QImage(canvas.buffer_rgba(), w, h, QtGui.QImage.Format_RGBA8888).copy()

        return img, img.size()

Whenever I need to draw a plot in python code, I just create Figure using this addFigure to give it a name and let the Qt to know about it. Once you got Figure, rest of matplotlib drawing happens exactly as usual. Make axes and plot.
self.imageProvider = MatplotlibImageProvider()
figure = self.imageProvider.addFigure("eventStatisticsPlot", figsize=(10,10))
ax = figure.add_subplot(111)
ax.plot(x,y)

Then in QML code I can simply refer matplotlib image by name ("eventStatisticsPlot")
Image {
    source: "image://perflog/eventStatisticsPlot"
}

Note that URL is prefixed by "image://" to tell QML that we need to get image from QQuickImageProvider and includes name ("perflog") of a particular provider to use. For this stuff to work we need to register our provider during QML initialization with a call to addImageProvider. For example,
engine = QtQml.QQmlApplicationEngine()
engine.addImageProvider('perflog', qt_model.imageProvider)
engine.load(QtCore.QUrl("PerflogViewer.qml"))

At this point you should be able to see static graphs shown, but they will not be updated properly because Image component in QML assumes that image that we provide does not change. I found no good solution for it, but an ugly workaround is fairly simple. I added a signal called eventStatisticsPlotChanged to my helper class that exposes Python app data to QML and .emit() it whenever the relevant plot is changed. E.g. here's a chunk of code where I get data from QML on a time interval selected by user.
@QtCore.pyqtSlot(float, float)
def selectTimeRange(self, min_time, max_time):
    self.selectedTimeRange = (min_time, max_time)
    _, ax, _ = self.eventStatisticsPlotElements
    ax.set_xlim(*self.selectedTimeRange)
    self.eventStatisticsPlotChanged.emit()

See that .emit() in the end? In QML this event forces image to reload URL like this:
Image {
    source: "image://perflog/eventStatisticsPlot"

    cache: false
    function reload() { var t = source; source = ""; source = t; }
}

Connections {
    target: myDataSourceObjectExposedFromPython
    onEventStatisticsPlotChanged: eventStatisticsPlot.reload()
}

So whenever user moves a control, following happens:

*

*QML sends updated time interval to my data source via selectTimeRange() call

*My code calls .set_xlim on appopriate matplotlib object and emit() a signal to notify QML that chart changed

*QML queries my imageProvider for updated chart image

*My code renders matplotlib chart into new QImage with Agg and passes it to Qt

*QML shows that image to user

It might sound a bit complicated, but its actually easy to design and use.
Here's an example of how all this looks in our small visualization app. That's pure Python + QML, with pandas used to organize data and matplotlib to show it. Scroll-like element on bottom of the screen essentially redraws chart on every event and it happens so fast that it feels real-time.

I also tried to use SVG as a way to feed vector image into QML. It's also possible and it also works. Matplotlib offers SVG backend (matplotlib.backends.backend_svg) and Image QML component support inline SVG data as a Source. The SVG data is text so it can be easily passed around between python and QML. You can update (source) field with new data and image will redraw itself automatically, you can rely on data binding. It could've worked quite well, but sadly SVG support in Qt 4 and 5 is poor. Clipping is not supported (charts will go out of the axes); resizing Image does not re-render SVG but resizes pixel image of it; changing SVG causes image to blink; performance is poor. Maybe this will change one day later, but for now stick to agg backend.
I really love design of both matlpotlib and Qt. It's smart and it meshes well without too much effort or boilerplate code.

A: It's in a fairly basic state, but https://github.com/jmitrevs/matplotlib_backend_qtquick provides a workable model to start from.
To quickly summarize the gist of the example provided with it:

*

*The library provides the types FigureCanvasQtQuickAgg and NavigationToolbar2QtQuick.

*The FigureCanvasQtQuickAgg type is registered with QML:
QtQml.qmlRegisterType(FigureCanvasQtQuickAgg, "Backend", 1, 0, "FigureCanvas")

*This allows you to use it from within QML:
FigureCanvas {
    id: mplView
    objectName : "figure"
    dpi_ratio: Screen.devicePixelRatio
    anchors.fill: parent
}

The objectName property allows the canvas instance to be found from within the Python code.

*The toolbar is made out of QML buttons,

*In the demo, they provide a DisplayBridge Python class that is linked to the canvas and is responsible for the actual plotting and for forwarding events from the various toolbar buttons

Internally, the FigureCanvasQtQuickAgg backend is a QQuickPaintedItem. In its paint function it copies data from the renderer attribute of the matplotlib FigureCanvasAgg base class into a QImage and the QImage is then painted. This is a fairly similar design to how the QWidget version of matplotlib works.


text:
Q: Transfer file from amazon s3 account to another I am writing an app and we need to transfer files between different s3 accounts, we don't want to save file locally before uploading to the destination s3 account.
So we get the source file stream using this:
public Stream GetFileStream(string path)
{
    var pathPieces = path.Split('/');
    string bucket = pathPieces[0];
    string fileName = pathPieces[pathPieces.Length - 1];

    GetObjectRequest request = new GetObjectRequest();
    request.BucketName = bucket;
    request.Key = fileName;

    GetObjectResponse response = Client.GetObject(request);

    return response.ResponseStream;
}

And after that we use this stream to upload on the destination:
    TransferUtility transferUtility = new TransferUtility(Client);
    transferUtility.S3Client.PutBucket(new PutBucketRequest() { UseClientRegion = true }.WithBucketName(bucket));
    TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
    .WithBucketName(bucket)
    .WithKey(key)
    .WithPartSize(1024)
    .WithTimeout(100 * 60 * 60 * 1000)
    .WithAutoCloseStream(true)
    .WithCannedACL(S3CannedACL.PublicReadWrite)
    .WithInputStream(fileStream) as TransferUtilityUploadRequest;

    transferUtility.Upload(request);

But on the last line "Upload" function call i always get this error:
This stream does not support seek operations.
Is there a different way to do what I am trying to do? because it seams not the correct way

A: I came across this question, and am posting the approach I used to solve it.  Borrowed some some code from Jon Skeet.  It worked for me, but I know it's a bit clunky and can probably be improved.
string filename = "nameoffiletocopy"

using (Stream stream = GetS3Stream(filename))
{
    AmazonS3Config config = new AmazonS3Config
        {CommunicationProtocol = Protocol.HTTP};
    AmazonS3 client =
        AWSClientFactory.CreateAmazonS3Client(
            "destinationaccesskey",
            "destinationsecretacceskey",
            config);
    string destinationBucketName = "destinationbucketname";

    PutObjectRequest request = new PutObjectRequest
    {
        BucketName = destinationBucketName,
        InputStream = stream,
        Key = filename,
        CannedACL = S3CannedACL.PublicRead
    };

    PutObjectResponse response = client.PutObject(request);
}

private static Stream GetS3Stream(string filename)
{
    AmazonS3Config config = new AmazonS3Config
        {CommunicationProtocol = Protocol.HTTP};
    AmazonS3 client = AWSClientFactory.CreateAmazonS3Client(
        "sourceaccesskey",
        "sourcesecretacceskey",
        config);
    string sourceBucketName = "sourcebucketname";

    GetObjectRequest request = new GetObjectRequest
        {
            BucketName = sourceBucketName,
            Key = filename
        };

    using (GetObjectResponse response = client.GetObject(request))
    {
        byte[] binaryData =
        ReadFully(response.ResponseStream, -1);
        //ReadyFully from Jon Skeet's blog
        return new MemoryStream(binaryData);
    }
}

ReadFully method explained fully by Jon Skeet

A: I really don't think there is a way to transfer between accounts. The only protocol I know that can do this is FXP. You can make a request to AWS to do this in the future, would be a nice feature.

A: Amazon has a Copy Object Request
AmazonS3Client client = new AmazonS3Client();

CopyObjectRequest request = new CopyObjectRequest {
      SourceBucket = "fromBucket",
      SourceKey = "fromFile",
      DestinationBucket = "toBucket",
      DestinationKey = "toFilename",
      CannedACL = S3CannedACL.BucketOwnerFullControl
 };

 CopyObjectResponse response = client.CopyObject(request);


text:
Q: How to numerically validate a php form ? I am trying to set up form validation for a project app. I keep getting the error that I am calling to an undefined function, but I'm not what I am doing wrong. From what I have learned and found online, this is the right syntax. Basically I only want the ticket number and spot number values to accept numbers as their input, and an error message to appear prompting the user to input a numeric value. This is my code so far:

<?php

if(!is_number($_POST['tick_num'])) {
    echo "please enter a number";
}

$searchBy = $_POST['field'];
$searchFor = $_POST['term'];

$database = 'jy6536';
$db = mysqli_connect('', 'jy6536', '1km4bjRi', $database);

$record = "SELECT * FROM keyfob WHERE $searchBy LIKE '%".$searchFor."%'";
$result = mysqli_query($db, $record);

while($myrow = mysqli_fetch_array($result))
{
  echo "

First Name: ".$myrow['last_name'];
  echo "
 Last Name: ".$myrow['first_name'];
  echo "
 Ticket Number ".$myrow['tick_num'];
  echo "
 Make: ".$myrow['make'];
  echo "
 Spot Number: ".$myrow['spot_num'];
}
?>

Return to Table

Return to Search

A: http://php.net/manual/en/function.is-numeric.php
if(!is_numeric($_POST['tick_num'])) {
    echo "please enter a number";
}

Do you want to allow ticket numbers like "+0123.45e6" and "9.1"? Maybe http://php.net/manual/en/function.ctype-digit.php would be better?
You could use this code instead:
$ticketNumber = $_POST['tick_num'];
if(!ctype_digit((string)$ticketNumber)) {
    echo "please enter a number";
}

This will only accept integers, ss values like 9.1 or +0123.45e6 won't be accepted.


text:
Q: Why python string shows different behavior while indexing? Why does the following indexing throws error
string = "ABC"
string[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

but not when
string[4:]
''


text:
Q: ASP.NET Repeater Eval I am trying to execute the following code in a .aspx page:
<asp:Repeater ID="rptComentarios" runat="server">
            <ItemTemplate>
                <% if (Convert.ToInt32(Eval("int_tipo")) == 1)
                   { %>

                    <%# Eval("txt_nome") %>

                 <%# Eval("txt_comentario") %>

                   <% }
                   else
                   {%>

                       <%# Eval("txt_nome") %>

                    <%# Eval("txt_comentario") %>

                   <% } %>
            </ItemTemplate>
            </asp:Repeater>

It throws a runtime exception in the first line:
  <% if (Convert.ToInt32(Eval("int_tipo")) == 1)

System.InvalidOperationException: Databinding methods such as Eval(), XPath() and Bind() can only be used in the context of a databound control.
What's wrong? Any ideas?

A: I had a similar problem and the following code worked for me:
<asp:Repeater ID="rptComentarios" runat="server">
  <ItemTemplate>

    <asp:PlaceHolder ID="placeholderBlaBlaBla" runat="server" Visible='<%# Convert.ToInt32(Eval("int_tipo")) == 1 %>'>
      Your optional HTML
    </asp:placeholder>

    Other HTML

  </ItemTemplate>
</asp:Repeater>

Some more comments:
Please note that single quotes are used to define the value Visible attribute of asp:placeholder. I tried double quotes too and they didn't work.
Anytime you want to get some optionally displayed HTML you should use a control to show/hide it. asp:placeholder works fine for that purpose. Don't ever do <% if(..) { %> - this is evil.
<%# ... %> is used to calculate or display expressions inside a repeater. These expressions can be displayed as HTML or passed as attributes of server side controls. You can't use if inside it.

A: I think there needs to be a # sign for the enclosure <%# ..Eval...%>
Or try the full Eval version
<%# if (Convert.ToInt32(DataBinder.Eval(Container.DataItem, "int_tipo"))
                                                                    == 1) { %>


text:
Q: Bootstrap Accordian will not collapse with Electron but the HTML file will work fine outside of Electron I have two running examples both using the same HTML page here.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Document</title>

            Skill
            Cost
            Ranks
            Total
            Adjusted Total

          Artistic
          4

            test

If I run this HTML code in a browser by itself, it works.
If i run this in Electron... it will not collapse once it has been expanded. I have no idea why Electron refuses to toggle it correctly.
for what it is worth here is my package.json for electron
{
  "name": "electronproject",
  "version": "1.0.0",
  "description": "Shopping List desktop app",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "package-mac": "electron-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds",
    "package-win": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Shopping List App\"",
    "package-linux": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=linux --arch=x64 --icon=assets/icons/png/icon.png --prune=true --out=release-builds"
  },
  "author": "David Klecker",
  "license": "ISC",
  "dependencies": {
     "jquery": "^3.5.0",
     "boostrap": "^2.0.0",
     "electron": "^8.2.0",
     "electron-reload": "^1.5.0",
     "xml2js": "^0.4.23"
  },
  "devDependencies": {
    "electron-packager": "^14.2.1"
  }
}

A: This could be an issue with getting jQuery to work with Electron. If you have Node integration turned on in your renderer process, jQuery will have issues loading because of some conflicting symbols it tries to define.
There's more information in the Electron FAQ.
The easiest way to solve this is to turn off nodeIntegration in your BrowserWindow.
// In the main process.
const { BrowserWindow } = require('electron')
let win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false
  }
})

If you want to keep nodeIntegration on, you could avoid the naming conflict by renaming the conflicting symbols before importing jQuery in.

I'm able to get your code snippet to work properly with either of the above solutions on Electron 8.0.0.


text:
Q: L is not defined (Leaflet.js node package) I am trying to get the example from the Leaflet quickstart guide to work in Angular 7, but the error ERROR ReferenceError: L is not defined appears. Note: I am not including Leaflet via JS files but installed it through npm via npm install leaflet, and it does show up in my node_modules.
import { Component, OnInit } from '@angular/core';
declare let L;

@Component({
  selector: 'app-mapvisual',
  templateUrl: './mapvisual.component.html',
  styleUrls: ['./mapvisual.component.css']
})
export class MapvisualComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors'
    }).addTo(map);
  }
}

EDIT: I found the solution here.

A: You must include these resources in your index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>

in your component.html file

component.css
#mapid { height: 180px; }

in your component.ts file
import { Component, OnInit } from '@angular/core';
declare let L;

@Component({
  selector: 'app-mapvisual',
  templateUrl: './mapvisual.component.html',
  styleUrls: ['./mapvisual.component.css']
})
export class MapvisualComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const map = L.map('mapid').setView([51.505, -0.09], 13);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors'
    }).addTo(map);
  }
}


text:
Q: Force Generic Type to match function definition Is it possible to force a generic type to not only be of type Function, but to also match a specific function definition?
For example, the closest way I have come up with is:
class MyClass<T = (S : any, E : EventArgs) => void> {
    ...
}

This of course works, but it doesn't not force this type, it is just the default type. I can do both
let myClass = new MyClass<string>();

or
let myClass = newClass<(any, number) => void>();

Both of which I do not want to be possible. I want the type to always match the function definition of (any, EventArgs) => void.
Is this possible in TypeScript?

A: Yes, it is possible. To define constraint extends keyword should be used:
class MyClass<T extends (S: any, E: EventArgs) => void> {
     // ...
}

As you've already figured out, = specifies a default for generic type parameter.


text:
Q: Error splitting .mov file with ffmpeg I have used the following ffmpeg command to split the given media file.
ffmpeg -i test.mov -ss 00:00:00 -t 00:07:00 -acodec copy -vcodec copy test1.mov

The video "test.mov" has the following characteristics:
Dimensions: 320 * 240
Codecs: MPEG-4 Video, ACC
Duration: 00:45
Audio channels: 2
Total bit rate: 1,292

But while splitting it shows the following errors
FFmpeg version 0.6, Copyright (c) 2000-2010 the FFmpeg developers
built on Apr 29 2011 12:03:13 with gcc 4.2.1 (Apple Inc. build 5664)
configuration: --disable-debug --prefix=/usr/local/Cellar/ffmpeg/0.6 --enable-shared --enable-pthreads --enable-nonfree --enable-gpl --disable-indev=jack --enable-libx264 --enable-libfaac --enable-libfaad --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libvpx
  libavutil     50.15. 1 / 50.15. 1
  libavcodec    52.72. 2 / 52.72. 2
  libavformat   52.64. 2 / 52.64. 2
  libavdevice   52. 2. 0 / 52. 2. 0
  libswscale     0.11. 0 /  0.11. 0
[aac @ 0x10181e200]channel element 1.0 is not allocated
    Last message repeated 215 times
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x10180b000]max_analyze_duration reached

Seems stream 0 codec frame rate differs from container frame rate: 30000.00 (30000/1) -> 29.97 (30000/1001)
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/sts-107-/Dev/cloudfactory/tmp/media/test.mov':
  Duration: 00:00:45.14, start: 0.000000, bitrate: 1297 kb/s
    Stream #0.0(eng): Video: mpeg4, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 1195 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 30k tbc
    Stream #0.1(eng): Audio: aac, 0 channels, s16, 97 kb/s
File '/Users/sts-107-/Dev/cloudfactory/tmp/media/ten/ten-1.mov' already exists. Overwrite ? [y/N] y
[mov @ 0x10181cc00]sample rate not set
Output #0, mov, to '/Users/sts-107-/Dev/cloudfactory/tmp/media/ten/ten-1.mov':
    Stream #0.0(eng): Video: mpeg4, yuv420p, 320x240 [PAR 1:1 DAR 4:3], q=2-31, 1195 kb/s, 90k tbn, 30k tbc
    Stream #0.1(eng): Audio: libfaac, 0 channels, 97 kb/s
Stream mapping:
  Stream #0.0 -> #0.0
  Stream #0.1 -> #0.1
Could not write header for output file #0 (incorrect codec parameters ?)
""

I couldn't figure out whats the problem.
Any suggestions are most welcome
Thank you in advance!!!


text:
Q: Every absolute retract (AR) is contractible This is homework.
I need to show that every AR is contractible.
All I can basically do here is list definitions:
A space $Y$ is AR if: $X$ is metrizable, $A$ is closed subset of $X$ and $f: A \mapsto Y$ is continuous, then $f$ has a continuous extension $g: X \mapsto Y$.
A space $Y$ is contractible if $id_Y :Y \mapsto Y$ is homotopic to a constant map.
I was thinking if I could use the fact that every AR is path connected and also every contractible space is path connected.

A: You need to find a continuous function
$$h\colon Y\times[0,1]\to Y$$
and $y_0\in Y$ such that $h(y,0)=y$ and $h(y,1)=y_0$.
Thus it suggests itself to let $X=Y\times[0,1]$ and $A=Y\times\{0,1\}$.
Of course $A$ is closed in the product topology because $Y$ is closed in $Y$ and $\{0,1\}$ is closed in $[0,1]$.
There "only" remains the question whether $X$ is metrizable. Can you take over from there?

A: AR are metrizable. In fact AR = AR(M) = M intersect with ES(M) where M = class of metric spaces and ES(M) class of absolute extensors for metric spaces, AR(M) = absolute retracts for metric spaces..


text:
Q: Origin of "rank hath its privileges" It's often seen with "has," but the frequent appearance of "hath" suggests the saying may be much, much older. Early Modern English always suggests Shakespeare to me, but my Google-fu hath failed me in this instance. Perhaps someone here can shed some light.

A: The oldest instance that I could find in a series of Google Books searches for the expression is from Harriet Lee, The Mysterious Marriage; Or, The Heirship of Roselva: A Play (1798):

Lord Albert. (striking him.) Lying fool, begone!
Rodolphus. Nay, no liar, I swear—nor so much of a fool as not to know that if rank has its privileges, age and fidelity are not without theirs. I humbly wish your Lordship a good night. And when you have a follower more faithful than myself, may heaven and you reward him as he serves!

But it also appears in A Lady, Life and Death of a Monkey; or the Village of Alton: A Tale for Young Persons (1814):

Some persons affect to rail at rank and title. Let such consider, if they can, the beauty, the harmony, the convenience, the happiness, that result from the different ranks in society—and the dependence which each has on the other. In this happy island each rank has its privileges, and all ranks are free.

Almost as old as the first of these instances is an instance arguing (more directly than Rodolphus did) that age has its privileges. From Thomas Gisborne, An Enquiry Into the Duties of the Female Sex (1806):

The spring and summer of life are past; autumn is far advanced; the frown of winter is already felt. Age has its privileges and its honours. It claims exemption from the more arduous offices of society, to which its strength is no longer equal; and immunity from some at least of the exertions, the fruit of which it cannot enjoy. Deprived of many active pleasures, it claims an equivalent of ease and repose.

And, of course, youth put in an early claim as well. From "Revolt at Princeton College," in The Weekly Inspector (May 9, 1807):

"For your individual self, sir, as you feel within a spirit of freedom and independence, capable to revolt from tyranny and resist oppression, we expect you tio adhere to your deliberate resolve, to evince to the world that you are capable of acting for yourself, and that AGE should not sanction IMPERTINENCE, that youth has its privileges, and that the GENIUS of REVOLT shall come forward to support them, whenever the hand of presuming authority shall attempt to level or abridge them."

In approximately the same time period, Edmund Burke, while not acknowledging its claim to privileges, concedes that wealth has its "natural weight." From Burke, "Thoughts on French Affairs" (1791), in The Works of the Right Honourable Edmund Burke, Collected in Three Volumes (1802):

As to the monied men—whilst the Monarchy continued, there is no doubt, that merely as such, they did not enjoy the privileges of nobility, but nobility was of so easy an acquisition, that it was the fault or neglect of all of that description, who did not obtain its privileges, for their lives at least, in virtue of office. ...
What institutions and manners together had done in France, Manners alone do here. It is the natural operation of things where there exists a Crown, a Court, splendid Orders of Knighthood, and an Hereditary Nobility; where there exists a fixed, permanent, landed Gentry, continued in greatness and opulence by the law of primogeniture, and by a protection given to family settlements;—where there exists a standing Army and Navy;—where there exists a Church Establishment, which bestows on learning and parts an interest combined with that of Religion and the State; in a country where such things exist, wealth, new in it's acquisition, and precarious in it's duration, can never rank first, or even near the first ; though wealth has it's natural weight, further, than as it is balanced and even preponderated amongst us as amongst other nations, by artificial institutions and opinions growing out of them.

One possible source of these attributions of privileges to various special class is a 1696 translation of La Bruyère's Characters. From Jean de La Bruyère, Supplement to the Characters, or Manners of the Present Age, sixth edition (1696/1713):

O Times! O Manners! cries HERACLITUS; O miserable Age, fill'd with bad Examples! O wretched, wretched World, where Virtue is persecuted, wjere Wickedness domineers, where it triumphs! ... Who can, with dry Eyes and an undisturb'dd Soul, behold such lamentable Things? There is no Office, no Post but has its Privileges; there is no Incumbent, no Occupant, but is at liberty to talk, plead, sollicite to defend his Rights: The Royal Dignity alone enjoys no longer its Privileges; Kings themselves have renounc'd them.

Conclusions
The earliest exact match I could find in Google Books search results for "rank has its privileges is from a 1798 play by Harriet Lee. However, quite similar assertions were made at approximately the same time about age, youth, and wealth, too.
La Bruyère may have influenced the expression with his observation in 1696 that there is no office and no post but has its privileges—however, it is difficult to assert this connection with any degree of certainty.

A: Looking through Google Books results, I haven't found anything so far that indicates that "rank has/hath its privileges" is a sentence of very great antiquity.
There is a similar sentence in Hood's Magazine, Vol. IX (January to June, 1848):

"Property," it is said, "has its duties as well as its rights;" to this may be added, "Rank has its duties as well as its privileges."

(p. 7; "The Times; or, Modern Philosophy")

It seems likely to me that the "snowclone" "X has/hath its privileges" is older than the specific saying "Rank has/hath its privileges". I'm not sure, though.
Here's an example of "hath its privileges" from 1827:

grief, like impatience, hath its privileges

(Tales of the Crusaders, Tale II. "The Talisman." Tales and Romances of the Author of Waverley, Volume VI, p. 233.)


text:
Q: Library for OpenStreetMap offline rendering and routing I found libosmscout library for OpenStreetMap offline rendering and routing in Github and trying to build iOS demo, but it has lots of issues that I can't solve myself and there is no sufficient guide.
Is there anyone who had experience in building this library?
Thanks in advance


text:
Q: jQuery sum child table row cells to parent row I have an HTML table that is similar to this simplified example:

Player	Score

Jack	7

Green Team

Mark	11

Tom	5

Steven	8

Greg	4

Blue Team

Joe	10

Jill	12

Rachel	9

I am trying to code the necessary jQuery to iterate through all child rows of a parent, sum the scores, and insert the sum to the parent's score cell. The rows that are not associated with a parent should be skipped/ignored.
After the jQuery code executes, the above table should be transformed into this:

Player	Score

Jack	7

Green Team	16

Mark	11

Tom	5

Steven	8

Greg	4

Blue Team	31

Joe	10

Jill	12

Rachel	9

I'm not sure the best way to solve this. Any ideas?

A: You can do something like this:
$("tr:has(td.parent)").each(function() {
  var sum = 0;
  $(this).nextUntil(':not(:has(td.child))').children(':nth-child(2)').each(function() {
    sum += parseInt(this.innerHTML, 10);
  });
  $(this).children(':eq(1)').text(sum);
});

You can give it a try here, this takes each
 that contains  and goes with .nextUntil() until it finds a row without a .  For those rows it loops through the second cell (:nth-child(2)) and adds the value to the sum.


text:
Q: Django inbuilt loginview not working for Non Staff Users Hi I used a custom user model and django inbuilt authentication to login and logout
my urls.py is
from django.contrib.auth import views
.....
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),]

It logs in for superuser credentials but for Non-Staff users it redirects to the login page again. So in order to find out the methods that are being called I tried to print the method names in the console to see what actually happens.
The below output I got for superuser:
dispatch
AnonymousUser
False
Dispatch Inside Class View
If Method
<bound method ProcessFormView.post of <django.contrib.auth.views.LoginView object at 0x7f165c1635b0>>
post
get_form_kwargs
{'initial': {}, 'prefix': None, 'data': <QueryDict: {'csrfmiddlewaretoken': ['kWGzAoldTVleKHXezf98LX4RbgoOs4ZRO3RI2UjAIJoUYpmYPvQj52HztqZRE5mn'], 'username': ['surendersingh1995nov@gmail.com'], 'password': ['Singo*1995'], 'next': ['/profile/']}>, 'files': <MultiValueDict: {}>}
form_valid
<WSGIRequest: POST '/login/'>
surendersingh1995nov@gmail.com
get_redirect_url

First the dispatch method is called then dispatch method inside class View is called and so on.
Similarly for Non-Staff Users the output which I got is:
dispatch
AnonymousUser
False
Dispatch Inside Class View
If Method
<bound method ProcessFormView.post of <django.contrib.auth.views.LoginView object at 0x7f165c1a7940>>
post
get_form_kwargs
{'initial': {}, 'prefix': None, 'data': <QueryDict: {'csrfmiddlewaretoken': ['6ex3Kzt2KNFrGYM3WAvwClLIQqu73vGlAlIcc5rpzBI7UGbNcQcHWqoq8A5afw3R'], 'username': ['arjunsingh1995nov@gmail.com'], 'password': ['Singo*1995'], 'next': ['/profile/']}>, 'files': <MultiValueDict: {}>}
get_context_data
get_context_data
get_redirect_url

The only difference is in this the form_valid method is not being called. But I cannot get exactly why this is not working. Please help me thanks.


text:
Q: How to use @font-face in iText7 pdfHTML? I have added a directory containing Roboto font to the FontProvider. The Pdf can find Roboto font, but it doesn't work as expected. It always uses Roboto-Black when I use font-weight: 900; font-style: Bold; and Roboto-Light instead of Roboto-Regular, when I use font-weight: normal;font-style: normal. That's why I want to use @font-face in CSS. But I'm unable to make it done. Here is what I have done:
FontProvider fontProvider = new DefaultFontProvider(false,false,false);
fontProvider.AddDirectory(fonts);
properties.SetFontProvider(fontProvider);
...

In CSS:
@font-face {
    font-family: 'Roboto';
    src: local('Roboto-Regular.ttf');
    src: local('Roboto-Regular.ttf') format('truetype'), url('Fonts/Roboto/Roboto-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

.test {
    font-family: 'Roboto';
    background-color: #c9c9c9;
    font-weight: normal;
    font-style: normal;
}

<div class="test">
    Hello World. This is Roboto Font.
</div>


text:
Q: Check for relative URLs and replace with absolutes I have a dynamic php code as follows
$url = "http://www.myweb.com/home";
$mycontents = 'These are the contents with relative link and  absolute link and some images with  with relative link and ';

$url and $mycontents are changing depending on the data fetched, even links contained changes. Any function that will SCAN for the variable $mycontents and if found any link with a or src, check first to see if is absolute, if yes, leave it, if no, using str_replace str_replace("src=\"", "src=\"".$url, $mycontents) and change all links before echoing $mycontents, Target is, once $mycontents get echoed, has to be modified with all relative links scanned and found changed to absolute.

A: First you should identify exactly what attributes you need to be looking for and checking their values. The simplest check of course is to simply look for URLcontaining http(s):// at the beginning of them and classing them as absolute already, anything else needs to be replaced.
These attributes would be href and src, as a base.
Of course, it's a very rudimentary check but it should suit your needs at least for now, barring any edge cases that may arise.


text:
Q: Bootstrap Responsive Navbar collapsed only on Phone Mode (No Tablet Mode) I have a responsive bootstrap menu, but I don`t want to collaspe it in tablet mode. I try to dysplay the same Menu in desktop and tablet mode.
the menu is collapsed at 940px or less, I want to do it at 768px or less.
Can anyone help me? Thanks
The code:
div class="navbar">

      Project name

A: The best way to do it would be to recompile using LESS and change the @navbarCollapseWidth variable from 979px to 768px. If you don't want to use LESS you can use the Customize page on the Bootstrap site to change that variable: http://twitter.github.com/bootstrap/customize.html

A: *

*Go to bootstrap-responsive.css file.

*Go to line number 952.

*Change the max-width from 979px to 768px.


text:
Q: JavaScript two objects - overriding each other I am trying to learn Object Oriented Programming in JavaScript. Therefore, I may be wrong in what I am doing.
I have one JS function (class):
function User() {
    //initiating object code goes here
}

//Functions
User.prototype.getEmpId = function() {
    return this.empId;
}

var myUser = new User({'empid':'1'});

console.log(myUser.getEmpId()); //Returns 1

var mynewuser = new User({'empid':'2'});

console.log(myUser.getEmpId()); //Returns 2

console.log(mynewuser.getEmpId()); //Returns 2

I don't understand what is going wrong here. If these two are two different objects then why is it causing problem. I have added the complete code here.
Thanks in advance.

A: User.prototype.getEmpId() {
  return this.empId;
}

should be
User.prototype.getEmpId = function () {
  return this.empId;
}

A: User.prototype.getEmpId gets overridden each time you instantiate the User object. The prototype property is shared between all instances.
Then what to do:
User.prototype.getEmpId = function() {
  return this.empId;
}

A: Check this fiddle :
http://jsfiddle.net/c5yhpav9/2/
function User(obj) {
//initiating object code goes here
this.empId=obj.empid;
}

//getEmpId now shared for all the instances of User
User.prototype.getEmpId=function() {
   return this.empId;
}

var myUser = new User({'empid':'1'});

alert(myUser.getEmpId()); //Returns 1

var mynewuser = new User({'empid':'2'});

alert(myUser.getEmpId()); //Returns 1

alert(mynewuser.getEmpId()); //Returns 2

Now gettting back to the problem you are facing in your sample shared. I found that you are setting properties/values on the User.prototype object itself each time a User object is instantiated. Rather, you should set on each instances of User. Following is the updated jsfiddle which works:
http://jsfiddle.net/L3qs4eg7/
Major Changes done:
first,
formUserObjectFromObject.call(this);//calling with reference of this

and,
function formUserObjectFromObject() {
    //Will only be called for one object.
    for (var userKey in arg[0]) {
        switch(userKey) {
            case "appId":
                //Calling setAppId on this to set value of property
                this.setAppId(arg[0][userKey]);
                break;
            case "empId":
                this.setEmpId(arg[0][userKey]);
                break;
            case "firstName":
                this.setFirstName(arg[0][userKey]);
                break;
            case "lastName":
                this.setLastName(arg[0][userKey]);
                break;
            case "roleId":
                this.setRoleId(arg[0][userKey]);
                break;
            case "emailId":
                this.setEmailId(arg[0][userKey]);
                break;
            case "supervisorId":
                this.setSupervisorId(arg[0][userKey]);
                break;
            default:
                this.setCustom(userKey, arg[0][userKey]);
                break;
        }
    }
}

Hope that helps to understand!


text:
Q: How to attach files using NSSharingService I am preparing a Mail using NSSharingService. I mainly followed the advice given here: NSSharingService to send email and read email body
Effectively I am calling
[self.emailSharingService performWithItems:shareItems];
where shareItems is an NSArray containing one NSString object (the body) and several NSURL objects (the attachements)
With AppleMail the preparation of the mail works fine (e.g. body & attachments) but unfortunately the attachments are not added if I use another mail client (e.g. Thunderbird, Spark)
Does anyone know how I can achieve the addition of the attachments in other mail clients than AppleMail?


text:
Q: Running function only if a certain element isn't burring im making an application that creates a text input where ever you click. I was having a problem where whenever you would click inside the field another text field would appear but i managed to fix that. I have one last major issue that I just can't solve. I know ou can't use blur() and focus() as arguments (though it would be nice) but i need to find a way so that after you enter text into the input field and out click, it just blurs the input box and doesn't create another until the user clicks again.

A: Just create a variable to keep track or only use a certain ID for the input you create, then check for that variable or input element before creation..
if(!$("#myDynamicInputElement").length){
    //TODO: Create your element..
}


text:
Q: How does the PHP IteratorIterator class work? Try as I might I cannot get my head around what the IteratorIterator class actually does. I understand that classes can implement Traversable so the engine knows it can loop using foreach and I realise that IteratorIterator is supposed to convert anything that is Traversable into an Iterator but I cannot for the life of me understand how.
Take for example, the PDOStatement class; how would the standard Iterator methods (next, key, rewind, etc) be implemented to allow iteration over a PDOStatement?
Sorry if my question is unclear, I am just struggling to grasp the exact reason for this class and the documentation on it is scant.
Thanks,
Will
Update: Going through the phpt files, I found one test which uses IteratorIterator:
<?php

$root = simplexml_load_string('<?xml version="1.0"?>
<root>
    <child>Hello</child>
    <child>World</child>
</root>
');

foreach (new IteratorIterator($root->child) as $child) {
    echo $child."\n";
}

?>

The expected output is:
Hello
World

I don't really follow how the IteratorIterator construct takes $root->child as an argument and how it manages to iterate over the child elements.

A: Based on this, I think it allows you to Iterate over Iterated objects.  I.e. you can pull other objects in your master object and using IteratorIterator on your master object, Iterate the child objects as well.
UPDATE:  Based on your update.  This makes sense to me, though there is only one root object, so iterating it doesn't really apply in this example, but you could if there were more root objects.  In other words, I believe IteratorIterator is the same as having nested foreach loops, without having to know all of the elements of each object.  In other words, a nested foreach using object oriented objects... there's a redundant statement. :-)

A: If you didnt find it yet, https://www.phpro.org/tutorials/Introduction-to-SPL.html has a few examples that might help you.

IteratorIterator >

*

*"This iterator wrapper allows the
conversion of anything that is
Traversable into an Iterator."

Traversable >

*

*"Interface to detect if a class is
traversable using foreach."

*"Internal (built-in) classes that
implement this interface can be used
in a foreach construct and do not
need to implement IteratorAggregate
or Iterator."

*"This is an internal engine interface
which cannot be implemented in PHP
scripts. Either IteratorAggregate or
Iterator must be used instead."

The site has some RecursiveIteratorIterator examples that might be handy but, if i get it right, IteratorIterator is from the scripting point of view pretty useless (when used to foreach at least).
It creates Iterateable Objects out of Objects implementing the Traversable interface, but intern classes implementing the Traversable interface are foreachable anyway and scripts cannot implement Traversable...
(Not mentioned in the docs, the SimpleXMLElement is implementing Traversable)

A: i thought example #2 here is quite straight forward...
it basically lets you implement a specific behavior for your class for the next/previous/current/rewind/key array functions, expected by the php foreach parser.
so for implementing your question, one would create an Iterator class with an PDOStatement as its memeber, than for example use the next method to call the PDOStatement::fetch to return its next statement. storing it will let you implement both perivous and current. havn't used this class too much but i bet it isn't that hard o implement a rewind and key. note that this is on the fly so i might be wrong on the details, but i think the concept should be clear


text:
Q: Unable to locate memory leak using Xcode Instruments The problem
I discovered earlier that my memory usage in my game was only going up when the tiles were moved, but it never went back down again. From this, I could tell there was a memory leak.
I then started using Xcode Instruments, which I am very new to. So I followed many things from this article, especially the Recording Options, and then I set the mode to show the Call Tree.
Results of Instruments

What do I need help with?
I have two functions that just move all the tiles along that row/column, and then clones the tile at the end (using node.copy()) so everything can "loopover", hence the project name.
I feel as if the tile cloning may be causing some retention cycle, however, it is stored in the variable within the function scope. After I run the SKAction on the clone, I remove the tile from the scene using copiedNode.removeFromParent().
So what may be causing this memory leak? Could I be looking in the wrong place?

Code
I have shortened this code to what I consider necessary.
Declaration at the top of the class:
/// Delegate to the game scene to reference properties.
weak var delegate: GameScene!
/// All the cloned tiles currently on the board.
private var cloneTiles = [SKSpriteNode]()

Cloning of the tile within the moving tiles functions:
/// A duplicate of the current tile.
let copiedNode = currentTile.node.copy() as! SKSpriteNode // Create copy
cloneTiles.append(copiedNode) // Add as a clone
delegate.addChild(copiedNode) // Add to the scene
let copiedNodeAction = SKAction.moveBy(x: movementDifference, y: 0, duration: animationDuration) // Create the movement action

// Run the action, and then remove itself
copiedNode.run(copiedNodeAction) {
    self.cloneTiles.remove(at: self.cloneTiles.firstIndex(of: copiedNode)!)
    copiedNode.removeFromParent()
}

Function to move tiles immediately:
/// Move all tiles to the correct location immediately.
private func moveTilesToLocationImmediately() {
    // Remove all clone tiles
    cloneTiles.forEach { $0.removeFromParent() }
    cloneTiles.removeAll()

    /* Moves tiles here */
}

Is there something I need to declare as a weak var or something? I know how retain cycles occur, but do not get why it exists in this code, as I remove the cloned tile reference from the cloneTiles array.

Roughly where the leak is occurring (helped by Mark Szymczyk)
Here is what happened after I double-clicked on the move tiles function in the call stack (refer to his answer below):

This is confirming that the memory leak is caused somehow by the node clone, but I still don't know why this node is still being retained after it is removed from the cloneTiles array and the scene. Could the node be having trouble getting removed from the scene for some reason?
Please leave any tips or questions about this, so this problem can be solved!
More investigating
I have now been trying to get to grips with Xcode Instruments, but I am still really struggling to find this memory leak. Here is the leaks panel which may help:

Even after trying [weak self], I still had no luck:

Even the leaks history still looks the same with the [weak self] within the closure.
Continuing to try to resolve the reference cycle
Currently, @matt is helping me with this issue. I have changed a few lines of code, by adding things like [unowned self]:
// Determine if the tile will roll over
if direction == .up && movementDifference < 0 || direction == .down && movementDifference > 0 {
    // Calculate where the clone tile should move to
    movementDifference -= rollOverDistance

    /// A duplicate of the current tile.
    let copiedNode = currentTile.node.copy() as! SKSpriteNode // Create copy
    cloneTiles.append(copiedNode) // Add as a clone
    delegate.addChild(copiedNode) // Add to the scene
    let copiedNodeAction = SKAction.moveBy(x: 0, y: movementDifference, duration: animationDuration) // Create the movement action

    // Run the action, and then remove itself
    copiedNode.run(copiedNodeAction) { [unowned self, copiedNode] in
        self.cloneTiles.remove(at: self.cloneTiles.firstIndex(of: copiedNode)!).removeFromParent()
    }

    // Move the original roll over tile back to the other side of the screen
    currentTile.node.position.y += rollOverDistance
}

/// The normal action to perform, moving the tile by a distance.
let normalNodeAction = SKAction.moveBy(x: 0, y: movementDifference, duration: animationDuration) // Create the action
currentTile.node.run(normalNodeAction) { [unowned self] in // Apply the action
    if forRow == 1 { self.animationsCount -= 1 } // Lower animation count for completion
}

Unfortunately, I could not make copiedNode a weak property as it would always be instantly nil, and unowned caused a crash about the reference being read after being deallocated. Here is also the Cycles & Roots graph if this is helpful:

Thank you for any help!

A: I can help a little on the Instruments front. If you double-click the moveHorizontally entry in the Instruments call tree, Instruments will show you the lines of code that are allocating the leaked memory. At the bottom of the window is a Call Tree button. If you click on that, you can invert the call tree and hide system libraries. Doing that will make it easier to find your code in the call tree.
You can learn more about Instruments in the following article:
Measuring Your App's Memory Usage with Instruments

A: I'm rather suspicious of the way you're managing the copied node; you may be releasing it prematurely, and only the retain cycle was preventing you from discovering this mistake. However, let's concentrate on breaking the retain cycle.
What you want to do is make everything coming into the action method weak, so that there is no strong capture by the action method. Then in the action method you want to immediately retain those weak references so they don't vanish out from under you. That's called the "weak-strong dance". Like this:
    copiedNode.run(copiedNodeAction) { [weak self, weak copiedNode] in
        if let `self` = self, let copiedNode = copiedNode {
            // do stuff here
            // be sure to log so you know we arrived here at all, as we might not
        }
    }


text:
Q: How to remove leading zeros using C# How to remove leading zeros in strings using C#?
For example in the following numbers, I would like to remove all the leading zeros.
0001234
0000001234
00001234

A: Using the following will return a single 0 when input is all 0.
string s = "0000000"
s = int.Parse(s).ToString();

A: TryParse works if your number is less than Int32.MaxValue. This also gives you the opportunity to handle badly formatted strings. Works the same for Int64.MaxValue and Int64.TryParse.
int number;
if(Int32.TryParse(nvarchar, out number))
{
   // etc...
   number.ToString();
}

A: This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:
using System.Text.RegularExpressions;

/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/

Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
    "00123",
    "00000",
    "00000a",
    "00001a",
    "00001a",
    "0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
    Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}

And this regex will remove leading zeroes anywhere inside string:
new Regex(@"(?<!\d)0+(?=\d)");
//  "0000123432 d=0 p=002 3?0574 m=600"
//     => "123432 d=0 p=2 3?574 m=600"

A: This is the code you need:
string strInput = "0001234";
strInput = strInput.TrimStart('0');

A: Code to avoid returning an empty string ( when input is like "00000").
string myStr = "00012345";
myStr = myStr.TrimStart('0');
myStr = myStr.Length > 0 ? myStr : "0";

A: return numberString.TrimStart('0');

A: It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:
String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";

Something like this would
String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
// s = "58757843950000120465875468465874567456745674000004000"

A: Regex rx = new Regex(@"^0+(\d+)$");
rx.Replace("0001234", @"$1"); // => "1234"
rx.Replace("0001234000", @"$1"); // => "1234000"
rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")

// usage
var outString = rx.Replace(inputString, @"$1");

A: I just crafted this as I needed a good, simple way.
If it gets to the final digit, and if it is a zero, it will stay.
You could also use a foreach loop instead for super long strings.
I just replace each leading oldChar with the newChar.

This is great for a problem I just solved, after formatting an int into a string.
    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.


text:
Q: How to show that $AA^*+B^*B$ is invertible if $U\stackrel{A}\to V\stackrel{B}\to W$ is exact? Let $U, V,$ and $W$ be finite dimensional vector spaces with inner products. If $A: U \rightarrow V$ and $B: V \rightarrow W$ are linear maps with adjoints $A^{*}$ and $B^{*},$ define the linear map $C: V \rightarrow V$ by
$$
C=A A^{*}+B^{*} B
$$
If $U \stackrel{A}{\longrightarrow} V \stackrel{B}{\longrightarrow}  W$ is exact , then my question is how to show $C: V \rightarrow V$ is invertible?
Here is my thought. We obviously have $W \stackrel{B^*}{\longrightarrow} V \stackrel{A^*}{\longrightarrow}  U$ is exact. Then $V=\text{Im}(B^*)\oplus \text{Im}(A)=\text{Ker}(A^*)\oplus\text{Ker}(B)$ thanks to it. Hence,
$C(V)=AA^*(\text{Ker}(B))+B^*B(\text{Ker}(A^*))=AA^*(\text{Im}(A))+B^*B(\text{Im}(B^*)),$ but what should I do next? I still wonder how to solve this problem by the matrix method.
Any help would be appreciated. Thanks a lot!

A: As you observed, there is a decomposition $V=E\oplus F$ where $E=\ker(B)=\operatorname{im}(A)$ and $F=\ker(A^*)=\operatorname{im}(B^*)$.  Note that $AA^*$ vanishes on $F$ and maps $E$ to itself.  Moreover, $\ker(AA^*)=\ker(A^*)=F$ (if $AA^*v=0$ then $0=\langle AA^*v,v\rangle=\langle A^*v,A^*v\rangle$ so $A^*v=0$), so $AA^*$ is injective when restricted to $E$.  This means that the restriction of $AA^*$ to a map $E\to E$ is invertible.  Similarly, $B^*B$ vanishes on $E$ and restricts to an invertible map $F\to F$.
So, writing $C$ as a block matrix with respect to the decomposition $V=E\oplus F$, it is $\begin{pmatrix} AA^* & 0 \\ 0 & B^*B\end{pmatrix}$ where both diagonal entries are invertible (as maps $E\to E$ and $F\to F$).  Thus $C$ is invertible.


text:
Q: Helm list does not show anything when I have a kubectl context of my cluster I just setup helm on my home PC and wanted to use it right away. However helm list / helm ls does not show anything even tho I configured kubectl properly. kubectl is able to fetch any information. Tiller is already installed since we use helm at work all the time.
This is what I tried to far:
PS C:\WINDOWS\system32> kubectl config current-context
gke_mycompany-cluster_europe-west3_mycompany-cluster
PS C:\WINDOWS\system32> helm ls
NAME    NAMESPACE       REVISION        UPDATED STATUS  CHART   APP VERSION
PS C:\WINDOWS\system32>

As you can see the context is available but helm ls is not returning anything.

A: TL;DR  You may want to try listing releases in all namespaces helm list --all-namespaces
There is not enough information to draw definite conclusion, but helm 3 introduced some changes in how helm find releases that may affect you. And since your install is recent I suspect you have helm 3 client, furthermore chances are high your work cluster is still on helm 2.
In helm 3 information about releases is stored in the the same namespace as the chart (this used to be stored by tiller in kube-system or in each namespace when using RBAC) therefore you can only see releases that are installed in the current namespace.

helm list command no longer lists all releases by default. Instead, it
will list only the releases in the namespace of your current
kubernetes context.

You may want to try listing releases in all namespaces helm list --all-namespaces
For more information see official documentation

A: You may have deployed your releases with helm 2 and then updated your client to helm 3.
This would result in no releases showing.
To fix, either install helm 2 again (e.g. Helm: Incompatible versions between client and server) or complete the upgrade to helm 3.


text:
Q: How to find wherther the JAR file is Compatible with JAVA 8 ? Is thery any short way or tool to find it Out? I am updating my APP  from JAVA 6 to  JAVA 8..  I have 100+ jars in my  Web-INF lib folder whiich are required to run the applications. So i need to make up this jars to be compatiblle with JAVA 8 verission. Suggest the possible ways to find the solution for  this ..

A: Yes java is backward compatible. for your case it should just work fine , so just go ahead and solve if and as you see them .
But to answer your question, you  can't tell from the JAR file itself, which java version it has been compiled .
If you want to know this, download a hex editor and open one of the class files inside the JAR and look at byte offsets 4 through 7. The version information is built in.
See more details here


text:
Q: Rows added to gridview don't persist when save event is triggered I have a gridview on my webpage that can have rows added dynamically. There is a for loop that adds the rows like this:
protected void AddNewJob(object sender, EventArgs e)
    {
        for(int i = 0; i < Convert.ToInt32(newJobCount.Text);i++)
        {
            TableRow tr = new TableRow();
            tr.Cells.Add(ServicesDDL("-- Select Service Type --"));
            tr.Cells.Add(JobsDDL("-- Select Job Type --"));
            tr.Cells.Add(TextBoxCell());
            tr.Cells.Add(TextBoxCell());
            tr.Cells.Add(TextBoxCell());

            assetTable.Rows.Add(tr);
        }
    }

After the rows are added and changed from their default values the rows are looped through and data is saved to the database. I'm having problems getting the rows added to the gridview to persist and exist on the gridview when the page's save event is triggered. That code looks like this:
foreach (TableRow row in assetTable.Rows)
{

if (isFirst)
{
    isFirst = false;
    continue;
}

DropDownList service = (DropDownList)row.Cells[0].Controls[0];
string assetText = service.SelectedItem.Value;
DropDownList jobDescription = (DropDownList)row.Cells[1].Controls[0];
string serialText = jobDescription.SelectedItem.Value;
TextBox equipmentCount = (TextBox)row.Cells[2].Controls[0];
string leaseText = equipmentCount.Text;
TextBox jobSize = (TextBox)row.Cells[3].Controls[0];
string originText = jobSize.Text;
TextBox serialNo = (TextBox)row.Cells[4].Controls[0];
string deliveryText = serialNo.Text;
string oNo = orderNo.Text;

if (assetText != "0" && serialText != "0")
{
    APICallClass.Job j = new APICallClass.Job();
    j.JobTypeID = Convert.ToInt32(serialText);
    j.serviceID = Convert.ToInt32(assetText);
    j.equipment = leaseText;
    j.jobSize = originText;
    j.serialNumbers = deliveryText;
    j.orderID = Convert.ToInt32(global.GlobalID);

    APICallClass.API.AddJob(j, Session["Variable"].ToString());
}
}

When the code pasted above runs, it only sees the rows that are pulled in from the database. I think my problem could be fixed by calling something like .databind() somewhere that I'm not, but I've tried a few places and they have not fixed the problem.
Thanks in advance for any help, and helping me become a more robust ASP.NET developer.

A: When a GridView is DataBind()-ed, the contents of the GridView are "rebuilt" based on the the GridView's DataSource. If you need the new row to stay in the GridView, either do not call DataBind() after the new row is added, or ensure that the contents of your new row are in the GridView's DataSource before future calls to DataBind().
In a page I wrote once I had a similar situation and did the latter. The data for the initial rows was pulled from the database on the first page load and persisted in ViewState. As the user added, removed, and reordered rows in the GridView, the page just changed the data in ViewState and re-DataBind()ed the GridView.


text:
Q: Exporting Shapefile to SpatiaLite format using QGIS? I am trying to export a shapefile of 3221 mixed POLYGON and MULTIPOLYGON geometry elements and every time, I get this same error:

Does anyone have any idea what's going on?
And no, this is not an exact duplicate of https://stackoverflow.com/questions/15203403 as I am working solely within QGIS.

A: You won't be able to fix this with "Save As..." because there is no way to control the geometry type in that dialog. It only lets you enter Data Source Creation Options(-dsco) and Layer Creation Options(-lco). You will have to either use the DBManager or ogr2ogr command line.

I get this error when trying to mix geometry types when importing data to a spatialite db.
The only option I see in the DBManager is the checkbox for Create single-part geometries instead of multi-part. You can try toggling this or you may need to fallback to ogr2ogr commandline tool.
So the solution is to tell it to force all geoms to a single geometry type, either POLYGON or MULTIPOLYGON. You might want MULTIPOLYGON so that the existing multipolygons are retained.
Using ogr2ogr the option that does this is -nlt where PROMOTE_TO_MULTI looks promising and I've used it with success in the past:

-nlt type: Define the geometry type for the created layer. One of NONE, GEOMETRY, POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION,
  MULTIPOINT, MULTIPOLYGON or MULTILINESTRING. Add "25D" to the name to
  get 2.5D versions. Starting with GDAL 1.10, PROMOTE_TO_MULTI can be
  used to automatically promote layers that mix polygon or multipolygons
  to multipolygons, and layers that mix linestrings or multilinestrings
  to multilinestrings. Can be usefull when converting shapefiles to
  PostGIS (and other target drivers) that implements strict checks for
  geometry type.

Ref:http://www.gdal.org/ogr2ogr.html

A: When trying to save a multipolygon shapefile to Spatialite (I tested polygons but I assume it is the same for other geometries) using the "save as" dialog the operation fails. Actually the fail is by ogr2ogr. As already told here when using ogr2ogr from the command line it is enough to add
-nlt MULITPOLYGON
option to get rid of the error, but in the QGIS "save as" dialog is not clear if such option can be added in the "custom options" of the same dialog.
The real issue seems that QGIS is not consistent, in fact importing into a Spatialite DB works fine for multigeometry input layers both using the Drag and Drop from the QGIS browser and using the import function of DB manager.
It also works ok using the "convert format" tool (based on ogr2ogr) of the processing toolbox (without needed to add manually any parameter).
See http://hub.qgis.org/issues/10584


text:
Q: how to create an array of hashes by looping over array of objects I have following array of hash. I am trying to loop over it and build an array of hash of values of id and product_order_id.
objects =
[
  #<Product: 0x00007ffd4a561108
  @id="1",
  @product_id="2",
  @product_order_id="23",
  @description="abc",
  @status="abcde",
  @start_date=nil,
  @end_date=nil>,
  #<Product: 0x00007ffd4a560c80
  @id="45",
  @product_id="22",
  @product_order_id="87",
  @description="ahef",
  @status="gesff",
  @start_date=nil,
  @end_date=nil>
......more objects.....
    ]

This is what it should look like
[{ "1": "23" }, { "45": "87" }] -->its going to be uuid

I tried doing this but no luck
def mapped_product(objects)
    mapping = []
    objects.each do |object|
      mapping << {
        object.product_order_id: object.id
      }
    end
end

Any idea?

A: inline solution:
> Hash[objects.map{|p| [p.id, p.product_order_id] }]
# Output : [{ 1=>23 }, { 45=>87 }]

A: I'd usually implement it using an each_with_object
objects.each_with_object({}) { |obj, acc| acc[obj.id] = obj.product_order_id }

Unless I reaaaly want to squeeze some performance, than I'd go with Gagan's answer

A: Have you tried this?
def mapped_product(objects)
    mapping = []
    objects.each do |object|
      mapping << {
        object.id => object.product_order_id # I'm using an `=>` here
      }
    end
    mapping # return the new mapping
end

I've just changed the : on the hash for a => to "make it dynamic" and swapped the values of id and product_order_id
You can also use a map here:
def mapped_product(objects)
    objects.map do |object|
     {  object.id => object.product_order_id }
    end
end