Q:

Select last row using ROW_NUMBER function

I am just wondering if there is any way to select the last row based on ROW_NUMBER() function? Basically I would like to select for each department_id THE LAST (max one) emp_id.
SELECT
    department_id, last_name, employee_id,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id) AS emp_id
FROM
    employees;

Output:
DEPARTMENT_ID LAST_NAME                 EMPLOYEE_ID     EMP_ID
------------- ------------------------- ----------- ----------
           10 Whalen                            200          1
           20 Hartstein                         201          1
           20 Fay                               202          2
           30 Raphaely                          114          1
           30 Khoo                              115          2
           30 Baida                             116          3
           30 Tobias                            117          4
           30 Himuro                            118          5
           30 Colmenares                        119          6
           40 Mavris                            203          1
. . .
          100 Popp                              113          6
          110 Higgins                           205          1
          110 Gietz                             206          2

A:

Yes, you could add descending order and then filter using that column:
SELECT *
FROM (
  SELECT department_id, last_name, employee_id,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id) AS emp_id,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id DESC) l_emp_id
   FROM employees
)
WHERE l_emp_id = 1


Q:

Error correction within the long read

I am going to get some data from plasmid sequencing to identify SNPs on the plasmids. What is done in the lab is the following:

The plasmids are purified by size.
We amplify the plasmids using the phi29 polymerase. The polymerase will go through the plasmid multiple times. Hence we get the same sequence concatenated multiple times. My question is related to this step:
Finally, We sequence it using Oxford Nanopore.

My question is:
On step two, I wrote that "we get the same sequence concatenated multiple times". For me, this a potential source of information to correct the base calls prior to aligning them to the reference. Since you have the same sequence multiple times (concatemers).
What I would like to know is if there is a tool that uses the information of the concatemers to improve the base calls. I have tried to find some methods but found none. I know that PacBio has a similar flavour using the "circular consensus calling", but I have not found any methodological explanation.
thanks!

A:

Yes, there is a tool to do this called R2C2 by the Vollmers lab at UC Santa Cruz.
https://www.biorxiv.org/content/early/2018/06/04/338020


Q:

Accessing class definition in xtext

I'm trying to write an DSL for doing typesafe conversions from one object to another.
src classA
dst classB

map valueA to valueB with ConverterX
map valueC to valueD with ConverterY

the result should be something like:
class Converter
{
public void convert(ClassA a, ClassB b)
{
 a.setValueA(ConverterX.convert(b.getValueB))
 b.setValueC(ConverterY.convert(b.getValueD))

}
}

I simply want to generate the code for that, but i'm not able to access the classes I already defined. The reason for that is to be able to use default converters. Only in case I am able to get the type of the parameters, i will be able to choose the implementation for the default converter.

A:

I solved the problem by Using JvmDeclaredType instad of JvmTypeReference. JvmTypeReference doesn't offer access to fields and methods, but JvmDeclaredType does. It is also possible to generate a JvmTypeReference by knowing the QualifiedName that is present in the JvmDeclaredType.


Q:

Collapsing a data frame by factors with multiple criteria

I have a data frame that describes the sequential movements of animals (ID column) and the time spent there (start and end columns). These movements are recorded over small scales but are classified within larger regions (classification column), such that an animal can move multiple times within a region before later moving to another region and moving around. They can also stay in one region for the whole time, or never move at all.
The sequence of movements within each region is tracked in the sequent_moves column (see this question for a more thorough explanation of how these are created). Animals can potentially move back to a region they earlier left. There is also a column of chemical data, Mean_8786Sr which is related to that region.
I want to collapse this data frame so that I end up with a description of only the regional movements. So, subsetting by Sample and sequent_moves I want to keep the minimum start value and the maximum end value, ending up with the start and end time within the region. I further want a mean of the chemical data in Mean_8786Sr. The rest of the columns I want to either keep the minimum value or the factor value as shown in the example code below.
I can do this using by(), but so far it requires a statement for each column. My actual data has quite a few more columns and many thousand rows. I'm pretty sure there is a faster, more elegant way to do this, perhaps with data.table (since I'm liking what I've seen from that package so far).
Below is my result. Is there a more efficient way to do this?
    movement = data.frame(structure(list(start = c(0, 0, 110, 126, 235, 0, 17, 139, 251,
0, 35, 47, 99, 219, 232, 269, 386, 398, 414, 443, 459), end = c(782L,
110L, 126L, 235L, 612L, 17L, 139L, 251L, 493L, 35L, 47L, 99L,
219L, 232L, 269L, 386L, 398L, 414L, 443L, 459L, 765L), Mean_8786Sr = c(0.709269349163555,
0.710120935400909, 0.70934948311875, 0.71042744033211, 0.709296068424668,
0.708621911917647, 0.709358583256557, 0.710189508916071, 0.709257758963636,
0.711148891471429, 0.712470115258333, 0.713742475130769, 0.714572498375,
0.713400790353846, 0.711656338391892, 0.710380629097436, 0.711571667241667,
0.71290867871875, 0.712009033513793, 0.71104293234375, 0.709344687326471
), Sample = c("2006_3174", "2006_3185", "2006_3185", "2006_3185",
"2006_3185", "2006_3189", "2006_3189", "2006_3189", "2006_3189",
"2006_3194", "2006_3194", "2006_3194", "2006_3194", "2006_3194",
"2006_3194", "2006_3194", "2006_3194", "2006_3194", "2006_3194",
"2006_3194", "2006_3194"), ID = c("1", "1", "2", "3", "4", "1",
"2", "3", "4", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12"), return_year = c(2006L, 2006L, 2006L, 2006L, 2006L,
2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 2006L,
2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 2006L), classification = c("CW",
"CW", "SK", "CW", "CW", "SK", "SK", "CW", "CW", "CW", "CW", "CW",
"CW", "CW", "CW", "CW", "CW", "CW", "CW", "CW", "CW"), sequent_moves = c(1L,
1L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), Sample_cptID = c("2006_3174 1", "2006_3185 1",
"2006_3185 2", "2006_3185 3", "2006_3185 3", "2006_3189 1", "2006_3189 1",
"2006_3189 2", "2006_3189 2", "2006_3194 1", "2006_3194 1", "2006_3194 1",
"2006_3194 1", "2006_3194 1", "2006_3194 1", "2006_3194 1", "2006_3194 1",
"2006_3194 1", "2006_3194 1", "2006_3194 1", "2006_3194 1")), .Names = c("start",
"end", "Mean_8786Sr", "Sample", "ID", "return_year", "classification",
"sequent_moves", "Sample_cptID"), class = "data.frame", row.names = 6:26))

Here is my solution using by():
moves = by(movement_dput, INDICES = c(factor(movement_dput$Sample_cptID)), function (x) {

  start = min(x[,"start"])
  end = max(x[,"end"])
  Mean_8786Sr = mean(x[,"Mean_8786Sr"])
  Sample = x[1,"Sample"]
  ID = min(x[,"ID"])
  return_year = x[1,"return_year"]
  classification = x[1,"classification"]
  sequent_moves = x[1,"sequent_moves"]
  move = cbind(start, end, Mean_8786Sr, Sample, ID, return_year, classification, sequent_moves)
  move

  }
)
regional_moves = do.call(rbind.data.frame, moves)
regional_moves

Is there,

a more efficient way to do this?
an easier or more compact way to specify which
columns I want max(), min(), etc...?

Edit: Adding partial data.table solution per Jeannie's comment.
Here is what I have so far using data.table.
require('data.table')
m=setDT(movement)
m[, .(start=base::min(start),
      end=base::max(end),
      Mean_8786Sr=mean(Mean_8786Sr),
      ID = base::min(ID),
      return_year = return_year[1],
      classification = classification[1],
      Sample_cptID = Sample_cptID[1])
  , by=c('Sample', 'sequent_moves')]

If I run this without base::min() I get errors. The current error is:
Error in `g[`(Sample_cptID, 1) : object 'Sample_cptID' not found

in a prior iteration (that didn't work) I got:
    Error in gmin(ID) :
      GForce min can only be applied to columns, not .SD or similar. To find min of all items in a list such as .SD, either add the prefix base::min(.SD) or turn off GForce optimization using options(datatable.optimize=1). More likely, you may be looking for 'DT[,lapply(.SD,min),by=,.SDcols=]'

Running it with base min() and max() functions it works.  I'm trying to understand what GForce is really doing in optimizing the speed, I assume that that has something to do with why it isn't returning the functionality I expected. This thread talks about it, but I haven't digested it completely. Any ideas?
It would be nice to be able to pass min, max and mean to a list that I can populate with colnames. The vast majority of columns I just want the first element. It would be more compact if there was a way to specify the max, min and mean columns directly and then say the equivalent of " for every other column, give me the first element".

A:

The OP has asked if there is a more efficient way to aggregate the movement data frame than by specifying each column individually.
I'm afraid that it is unavoidable to specify which columns need to be aggregated by which aggregation function. However, data.table syntax is quite compact in general. So, the  call to by() can be implemented with data.table as follows:
library(data.table)
setDT(movement)[
  , .(start = min(start), end = max(end), Mean_8786Sr = mean(Mean_8786Sr), ID = min(ID)),
  by = .(Sample, return_year, classification, sequent_moves)]

      Sample return_year classification sequent_moves start end Mean_8786Sr ID
1: 2006_3174        2006             CW             1     0 782   0.7092693  1
2: 2006_3185        2006             CW             1     0 110   0.7101209  1
3: 2006_3185        2006             SK             2   110 126   0.7093495  2
4: 2006_3185        2006             CW             3   126 612   0.7098618  3
5: 2006_3189        2006             SK             1     0 139   0.7089902  1
6: 2006_3189        2006             CW             2   139 493   0.7097236  3
7: 2006_3194        2006             CW             1     0 765   0.7120207  1

Note that all variables which are invariant or constant within each group are treated as grouping variables in by = .... This saves some typing but puts the columns in front of the other (aggregated) columns.


Q:

Ripple effect drawable is distorted when applied over 9patch background

I have a 9 patch drawable which I want to use as a background on a view. I want the view to show a ripple effect that follows the outline of a 9 patch when the view is clicked. Here's my activity, layout, and drawable code.
MainActivity.kt:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val click = findViewById<ConstraintLayout>(R.id.container)
        click.setOnClickListener { Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show() }
    }
}

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.antonc.testapp.MainActivity">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="8dp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        android:paddingTop="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:background="@drawable/tooltip_background"
        android:backgroundTint="#2681d8"
        tools:layout_editor_absoluteX="8dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello test test !!!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            />

    </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>

tooltip_background.xml:
<?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#33000000">
    <item android:drawable="@drawable/tooltip_left_top"/>
    <item android:id="@android:id/mask" android:drawable="@drawable/tooltip_left_top"/>
</ripple>

tooltip_left_top.9.png:

But when I click on it, the ripple drawable is very distorted, as if it's stretched to the view size without observing the stretch rules of 9 patch. How should I configure the ripple to make it be the same as the background?:

A:

Update: I have reworked the answer to refine the issue. The following has been edited to reflect the changes.
TL;DR Do not use android:backgroundTint for ripple backgrounds based on nine-patch drawables at least for API 28. Set the tint in code.

This issue has something to do with the background tint. I will explain how I came to this conclusion by referring to the following video.

I will refer to the bubbles as view1 through view4 from top to bottom. I changed from your nine-patch to better see the patches since your nine-patch was mostly black.
View1, when click, shows the appropriate ripple effect. It has a ripple background but no background tint.
View2 is what you are seeing with your background - it is just messed up. This view has a background tint set in XML.
The height of view3 has been forced to the height of view1 to see how the ripple looks. As you can see, the ripple looks right for the height. It is the non-ripple background image that is distorted.
View4 is the same as view2 except that it has the tint for RippleDrawable added programmatically. As you can see, this view looks and behaves as it should.
Bottom line? Don't set the background tint for a nine-patch in XML. Set it in code. Is this a bug? Maybe.
Here is the support code for the video above.
activity_main.xml
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFFFF"
    android:fillViewport="true"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:backgroundTint="@color/background_tint"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:backgroundTint="@color/background_tint"
            android:clickable="true" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bubble_background"
            android:clickable="true" />

    </LinearLayout>
</ScrollView>

bubble_background.xml
<ripple
    android:color="#33000000">
    <item android:drawable="@drawable/ninepatch_bubble">
    </item>
</ripple>

MainActivity.java
public class MainActivity extends AppCompatActivity {
    private LinearLayout mLayout;
    private ImageView mImageView1;
    private ImageView mImageView2;
    private ImageView mImageView3;
    private ImageView mImageView4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLayout = findViewById(R.id.layout);
        mImageView1 = findViewById(R.id.imageView1);
        mImageView2 = findViewById(R.id.imageView2);
        mImageView3 = findViewById(R.id.imageView3);
        mImageView4 = findViewById(R.id.imageView4);

        int bgTint = getResources().getColor(R.color.background_tint);
        RippleDrawable rippleDrawable =(RippleDrawable) mImageView4.getBackground();
        rippleDrawable.getDrawable(0).setTint(bgTint);
        mImageView4.setBackground(rippleDrawable);

        mLayout.post(new Runnable() {
            @Override
            public void run() {
                mImageView3.getLayoutParams().height = mImageView1.getMeasuredHeight();
                mLayout.requestLayout();
            }
        });
    }
}

colors.xml
These were added to colors.xml:
<color name="background_tint">#2681d8</color>
<color name="ripple_tint">#33000000</color>

ninepatch_bubble.9.png


Q:

CS0118 error in controller from model in asp.net

I'm creating a database with the entity framework, I created the first entity as a carlot and the second car which will list the cars in the respective lots. I keep thinking something is wrong with my model ... here is following model
namespace CarLot.Models
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;

    public class CarModel : DbContext
    {
 public CarModel()
            : base("name=CarModel")
        {
        }

        // Add a DbSet for each entity type that you want to include in your model. For more information
        // on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.

        public DbSet<CarLot> CarLots { get; set; }
        public DbSet<Car> Cars { get; set; }
    }

    public class CarLot
    {
        //Primary Key
        public int CarLotID { get; set; }
        public string Name { get; set; }

        public string Section { get; set; }

        public virtual ICollection<Car> Cars { get; set; }
    }

    public class Car
    {
        public int CarId { get; set; }

        public string Make { get; set; }

        public string Model { get; set; }

        public int Year { get; set; }

        public int Price { get; set; }

        public bool isNew { get; set; }

        //foreign key
        public int CarLotID { get; set; }
        public virtual CarLot Carlot { get; set; }
    }

}

I proceeded to scaffold the controller for Cars, that does not show any errors.
but not my carlot, this is the following CarLot file... its giving me the CS0118 error with CarLot as commented below, 6 following CarLot giving me the CS0118 which states "CarLot is a namespace but is used as a type"
sing System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CarLot.Models;

namespace CarLot.Controllers
{
    public class CarLotsController : Controller
    {
        private CarModel db = new CarModel();

        // GET: CarLots
        public ActionResult Index()
        {
            return View(db.CarLots.ToList());
        }

        // GET: CarLots/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            // It is giving me the CS0118 error with the following CarLot

            CarLot carLot = db.CarLots.Find(id);
            if (carLot == null)
            {
                return HttpNotFound();
            }
            return View(carLot);
        }

        // GET: CarLots/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: CarLots/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "CarLotID,Name,Section")] CarLot carLot)
        {
            if (ModelState.IsValid)
            {
                db.CarLots.Add(carLot);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(carLot);
        }

        // GET: CarLots/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            CarLot carLot = db.CarLots.Find(id);
            if (carLot == null)
            {
                return HttpNotFound();
            }
            return View(carLot);
        }

        // POST: CarLots/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "CarLotID,Name,Section")] CarLot carLot)
        {
            if (ModelState.IsValid)
            {
                db.Entry(carLot).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(carLot);
        }

        // GET: CarLots/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            CarLot carLot = db.CarLots.Find(id);
            if (carLot == null)
            {
                return HttpNotFound();
            }
            return View(carLot);
        }

        // POST: CarLots/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            CarLot carLot = db.CarLots.Find(id);
            db.CarLots.Remove(carLot);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

A:

namespace CarLot.Models
{

    public class CarLot
    {

The problem relates this code both namespace and class name is CarLot
Try changing one of them


Q:

html php javascript form popup

Apologies for the ambiguous title, it just goes to show how confused I am with this one.
change image

The link above is inside a form and is supposed to allow a user to change the image on an article. The functional php side of things is sorted - uploading the image, changing the image etc, but this will require the main form being submitted which is fine for the initial upload - not so much for the edit.
When the user clicks the "change image" link, I would ideally like to process that particular request alone in a different form, then update the parent page. I thought of doing it with a javascript new window popup which would have been ideal, except that I can't figure out how to pass the article_id as well as the img_id to the new popup page but above all... is this the most efficient way of doing this nowadays?
If not, How do I carry out this task? I have thought of ajax, jquery... but the same issue of passing the article_id and img_id still limits me.
I hope all of this makes sense and thanks in advance
ps: An article can have multiple images and article id is dynamic.

A:

why cant u receive article_id and img_id?
if you use:
edit

u can get article_id and img_id in $_GET
however, this is a oldfashioned way getting this done.


Q:

Are there any subtle differences between "de nuevo" and "otra vez"?

There are two very common ways in Spanish to say the equivalent of "again":

de nuevo
otra vez

But I use them pretty randomly because I've never been able to pick up on any differences in how native speakers use them. Are there any differences?

A:

I would say that "de nuevo" or "nuevamente" sounds more like "all over again", while "otra vez" is just "again".
Examples:

Tengo que hacerlo de nuevo. — I have to do it all over again.
Tengo que hacerlo otra vez. — I have to do it again.

As noted, these differences are very subtle, in many cases "de nuevo", "nuevamente" and "otra vez" can be used interchangeably. However in some cases "de nuevo" ("nuevamente") is used in meaning "anew", then changing it for "otra vez" changes the meaning of the sentence slightly.

A:

They are used pretty much interchangeably. Check this page, "Saying again in Spanish", it has some examples.
There are some expressions in English where you would use "again", but that in Spanish change form or that are slightly different:

Never again = ¡nunca más! or ¡nunca jamás!;
Again and again = una y otra vez;
Now and again (also from time to time / every so often) = de vez en cuando;
Then again = por otra parte (synonym of además in this case).

A:

Para salir de dudas, recurrí al Servicio de Consultas de la RAE y transcribo aquí la respuesta que recibí:

En relación con su consulta, le remitimos la siguiente información:
Ambas expresiones se emplean con el mismo sentido y en situaciones
  semejantes, sin que quepa establecer diferencias. Tan solo en algunos
  contextos solo se emplearía una, como en el caso de que, por ejemplo,
  alguien muestre hastío ante la reiteración de alguien en alguna acción
  o palabra; en este caso, solo se diría "¿Otra vez?", pero muy
  raramente se diría "¿De nuevo?".
Sin embargo, insistimos, se emplean con idéntico significado y en las
  mismas condiciones.

Así que, las dos expresiones son completamente equivalentes, salvo en algunos contextos muy específicos, como el del ejemplo que aparece en el texto citado.


Q:

mongoose how to prevent user already with username to modify username

I have an auth system where user can either signup with username/password, or facebook signin with provider/providerId
I want to prevent change of username, but if they use facebook, I allow them to set username once. Is it possible to implement it in user model?
Here is my current implementation.
//username check unique
UserSchema.pre('save', true, function(next, done) {
    var self = this //in case inside a callback

    //sns provider, OK not to have username
    if (self.provider && self.provider !== 'local' && !self.username) {
        done()
        return next()
    }
    //not modified
    if (! self.isModified('username')) {
        done()
        return next()
    }

    mongoose.model('User').findOne({username: self.username}, function(err, user) {
        if (err) {
            done(err)
        } else if (user) {
            //todo: put msg in validation.js
            self.invalidate('username', 'username must be unique')
            done(helper.getValidationError('username must be unique'))
        } else {
            done()
        }
    })

    return next()
})

//username check is valid username
UserSchema.pre('save', true, function(next, done) {
    var self = this

    if (self.provider && self.provider !== 'local' && !self.username) {
        done()
        return next()
    }
    //username is required for local strategy
    var msg = helper.validation.user.username(self.username)
    if (msg) {
        self.invalidate('username', msg)
        done(helper.getValidationError(msg))
    }
    else {
        done()
    }

    return next()
})

The helper validation is defined as:
exports.user = {
    username: function(input) {
        if (!input)
            return 'username is required' //Note: required only for Local Strategy
        var min = 3
        var max = 10
        if (input.length < min)
            return 'username min of length is ' + min
        if (input.length > max)
            return 'username max of length is ' + max
        return null
    }
}

A:

You can check if the original user name is empty. All validations are in model. You don't have to modify anything in your controller or router.
UserSchema.post('init', function() {
    this.original = this.toObject()
})

UserSchema.pre('save', true, function(next, done) {
    var self = this

    if (! self.isModified('username')) {
        done()
        return next()
    }

    //To prevent Facebook user to delete username (and recreate a different one) with !self.original.username
    if (self.provider && self.provider !== 'local' && !self.username && !self.original.username) {
        done()
        return next()
    }

    //prevent change of username
    if (self.original.username) {
        self.invalidate('username', 'cannot modify username')
        done(helper.getValidationError('cannot modify username'))
    }

    mongoose.model('User').findOne({username: self.username}, function(err, user) {
        if (err) {
            done(err)
        } else if (user) {
            self.invalidate('username', 'username must be unique')
            done(helper.getValidationError('username must be unique'))
        } else {
            done()
        }
    })

    return next()
})


Q:

Spring data jpa repo, why need interface service and service implementation

I just started work on Spring Boot, using Spring Data JPA. When I generate model from table, I create a modelRepo which extends JpaRepository<myModel, String>
public interface userRepository extends JpaRepository<User, String>{
}

Then from a controller, I can easy call userRepository.findAll() to get data.
However, when I look on some tutorials, they have extra several steps before calling findAll(). Take a look below:
public interface userService{
Iterator findAll();

}
    public class userServiceImpl implements userService{
       @Autowired
       UserRepository userRepository
       @Override
       Iterator findAll(){
        return userRepository.findAll();
       }
    }

Somethings like that, I can query the data directly from userRepository as long as @Autowired to inject userRepository.
In some example, they do same structure at above. Can anyone explain why do we need service and serviceImpl before calling data.

A:

Because the so-called "service" classes ("inherited" with the N-tier architecture) are where the business logic "lives". In the end, it depends on your approach/design guidelines, the way you would like to manage transactions, structure your project, etcetera.
If you only need to make a call to the database and return that data, you can safely skip the "service" call/class. On the other hand, if you are doing something "in the real life", you will end up using those "service" classes a lot since most of the operations (read: business logic) is going to be there, so you would want to have all that behavior isolated in one place — otherwise you would be injecting beans everywhere without following any "project organization" among other things. It's a little bit tedious sometimes, but on the other hand, you know where to look for whenever you need to change something. In medium to large projects this is quite important; even more if you have several people modifying the same code base.
TIP: Keep your classes small. Injecting tons of beans (repositories, services and what not) on a "service" class is bad design and may lead you to other non-senses.

A:

It's good practice to separate out the functionality of your application into separate classes. (See the single responsibility principle https://en.wikipedia.org/wiki/Single_responsibility_principle).
What I mean by this in this context is that if you needed to do some more advanced business logic between your controller and the calls to your JPA repository then this should be included in a service layer. This prevents your controller class from being polluted with business logic when it should only be concerned with handling the request and passing on responsibility to the service layer.
However, if you are just doing some simple CRUD operations then it's absolutely fine to just call the repository directly from your controller. So it depends what your application needs to do really!


Q:

Deleting conditional formatting on blanks withing range

I am trying to delete conditional formatting of blanks within the range,
but below formula gives me an error, what am I doing wrong?
Worksheets("SINGLE REPORT").Range(Cells(34, 3), Cells(64,22)).FormatConditions.Delete _
    Type:=xlCellTypeBlanks

A:

Here is another approach (which might be slightly faster):
Worksheets("SINGLE REPORT").Range(Cells(34, 3), Cells(64,22)).SpecialCells(xlCellTypeBlanks).FormatConditions.Delete


Q:

Detect Visual Studio version from within MSBuild project

The BuildingInsideVisualStudio property provides the ability to detect whether a project is building inside Visual Studio.
Is there any way to determine which version of Visual Studio is being used ?

A:

Use the VisualStudioVersion property.

A:

Since comments aren't formatted, here's investigation showing fsimonazzi is correct.
On 2008, VisualStudioVersion is NOT set. On 2010 (and up presumably) it is.
Created a project in VS2008 with the following added after <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />:
<Target Name="PrintVisualStudioInfo">
  <Message Text="VisualStudioVersion: '$(VisualStudioVersion)'" />
</Target>
<PropertyGroup>
  <CompileDependsOn>
    PrintVisualStudioInfo;
    $(CompileDependsOn)
  </CompileDependsOn>
</PropertyGroup>

Turned VS2008 output up to Normal. Result:
Target PrintVisualStudioInfo:
    VisualStudioVersion: ''

On VS2010 Result:
PrintVisualStudioInfo:
   VisualStudioVersion: '10.0'

A:

According to this post the property exists starting with the VS2012. It is defined in the Microsoft.Common.targets file when .NET 4.5 is installed (checked that original .NET 4.0 doesn't have the property defined).


Q:

Count unique associated values in awk (or perl)

I've already found "How to print incremental count of occurrences of unique values in column 1", which is similar to my question, but the answer isn't sufficient for my purposes.
First let me just illustrate what I want to do:
# Example input
apple   abc jkl
apple   xyz jkl
apple   abc xyz
apple   qrs xyz
apple   abc jkl
banana  abc lmno
banana  lmnop   xyz
banana  lmnopq  jkl
banana  abc jkl
banana  lmnop   pqrs
banana  abcdefg tuv
cucumber    abc lmno
cucumber    abc jkl
cucumber    abc xyz
cucumber    abcd    jkl
cucumber    abc jkl
cucumber    abc lmno

# Desired output
apple   3   2
banana  4   5
cucumber    2   3

So, for each separate value of field 1, print that field, and a count of the unique associated values for field 2, and then for field 3.
The input is sorted by the first field, but sorting by other fields is disallowed (and would do no good as the 2nd and 3rd fields both need to be handled).
I'd much rather accomplish this in awk; it is probably far easier in perl and I'm interested in learning how to do that as well, but I'm dealing with an awk script and I'd rather not rewrite the whole thing.
I came up with one method which works, but is quite lengthy and seems very hacky to me.  I'll post that as an answer (when I get back to the office) but would love to see any actually good approaches.  (I don't think mine is "good".)

A:

With awk:
awk 'function p(){print l,c,d; delete a; delete b; c=d=0}
  NR!=1&&l!=$1{p()} ++a[$2]==1{c++} ++b[$3]==1{d++} {l=$1} END{p()}' file

Explanation:

function p(): defines a function called p(), which prints the values and deletes the used variables and arrays.
NR!=1&&l!=$1 if its not the first line and the variable l equals the first field $1, then run the p() function.
++a[$2]==1{c++} if the increment of the element value of the a array with index $2 equals 1, then that value is first seen, and therefore increment the c variable. The ++ before the element, returns the new value, therefore causes an increment before the comparsion with 1.
++b[$3]==1{d++} the same as above but with the 3rd field and the d variable.
{l=$1} The l to the first field (for the next iteration.. above)
END{p()} after the last line is processed, awk has to print the values for the last block

With your given input the outout is:
apple 3 2
banana 4 5
cucumber 2 3

A:

I like whitespace and descriptive variable names.  What else is there to say?  It's been a while since I've written a lot of awk, I even forgot about the -f on the shebang. However, as I did this I really felt like I was in the zen of it.  Haiku code.
I like this solution because there's a minimum of coded logic.  Only two for loops iterating over array indexes.  No 3 part stepping for loops, no if statements, no explicit value comparisons.  All of those things are statistically correlated to software defects (bugs).  Interestingly, there are no explicit assignments, and only one math operation, the increment on the count.  I think this all indicates maximum usage of the language features.
I feel like something might be missing, but I haven't yet been able to find any holes in it.
Please comment. Opinions and constructive criticism requested. I'd like to hear about the performance considerations of this script.
#!/usr/bin/awk -f

function count(seen, unique_count) {
    for (ij in seen) {
        split(ij, fields, SUBSEP)
        ++unique_count[fields[1]]
    }
}

{
    seen2[$1,$2]
    seen3[$1,$3]
}

END {
    count(seen2, count2)
    count(seen3, count3)
    for (i in count3) {
        print i, count2[i], count3[i]
    }
}

Annotation
I guess one unique feature of this script is that the seen2 and seen3 arrays contain no data, only indexes.  This is because we're only counting unique values, therefore, the only thing that matters is that the values have been seen, we don't care how many times they occur.
#!/usr/bin/awk -f

The count function takes an array, seen, indexed by 2 field values encountered in input records, either fields 1 and 2, or fields 1 and 3, and returns an array internally called unique_count indexed by the first field, containing the counts of unique field values for the column accumulated by the second index:
function count(seen, unique_count) {

The count function iterates over the indexes of the array seen:
    for (ij in seen) {

Splits the index into the two original values, field 1 and either field 2 or field 3:
        split(ij, fields, SUBSEP)

Increment the count for the element indexed by field 1:
        ++unique_count[fields[1]]
    }
}

On every input line encountered, we create an empty array element, if it doesn't already exist, indexed by the first field, and either the second or third field.  Keep a separate array (seen2 and seen3) for each field number that's being counted.  There will be only one array element for each unique value in the given column (2 or 3):
{
    seen2[$1,$2]
    seen3[$1,$3]
}

At the end of data, count the number of unique fields seen for each column:
END {

Pass the arrays accumulated from the input to the count function, and receive the count2 or count3 populated with the unique field counts.
    count(seen2, count2)
    count(seen3, count3)

Step through either of count2 or count3 arrays (doesn't matter which since they all have the first field of each line), and print the field one, followed by the counts of unique values found for each line containing field one:
    for (i in count3) {
        print i, count2[i], count3[i]
    }
}

One-Liner Version
awk 'function c(s,u){for(x in s){split(x,f,SUBSEP); ++u[f[1]];}}
 {a[$1,$2]; b[$1,$3];} END {c(a,d); c(b,e); for(i in d){print i,d[i],e[i];}}'


Q:

How to leave the current app and launch an activity of another app?

I have a simple Android app that needs to launch another app under certain condition, and I will need to check the condition upon the app launch. That is, either continue to launch my app or just launch another app:
if (A == true) {
 launch another activity of another app
 leave the current app without creating the main activity
} else {
 launch the main activity of the current app
}

Could anyone please let me know how to deal with A == true case? I am able to launch another app's activity but I have trouble leaving the current app without even opening the main activity.
Any help will be greatly appreciated!

A:

You can launch other application using following intent
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc");//pass the packagename of app you want to open
startActivity( LaunchIntent );

If you don't know the package name of application that you wanted to launch then try your hand on
PackageManager pm;
pm = getPackageManager();
//  get a list of installed apps.
packages = pm.getInstalledApplications(0);

Pass the packagename of app you want to open
You can use this if A == true
else You can launch the MainActivity as
startActivity(new Intent(CurrentActivity.this,MainActivity.class));


Q:

Flutter cloud function call with parameters

I have a flutter app, my code looks like this:
  dynamic result = await CloudFunctions.instance.getHttpsCallable(functionName: 'getAllItemsAfterDatetime').call(
    <String, dynamic> {"datetime": "1563109861142"}
  );

and a JS file:
exports.getAllItemsAfterDatetime= functions.https.onRequest(async (req, res) => {
  if (!mysqlPool) {
    mysqlPool = mysql.createPool(mysqlConfig);
  }

  let datetime = req.body.datetime;
  if (datetime == null) datetime = req.query.datetime;
  if (datetime == null) datetime = req.params.datetime;
  if (datetime == null) datetime = "3100000012120000";

  mysqlPool.query('SELECT * FROM items as res WHERE datetime > ' + datetime, (err, results) => {
    if (err) {
      console.error(err);
      res.status(500).send(err);
    } else {
      res.status(200).send({cnt: res.length, data: JSON.stringify(results)});
    }
  });

I got allways "3100000012120000", so basically I can't get my datetime param back from mobil. It is working in browser. How to do this in a mobil app?
req.parameters is the correct word or WHAT?
Thanks
UPDATE: The solution
  //from browser
  let datetime = req.body.datetime;

  //from mobile
  if (datetime == null) datetime = req.body.data.datetime;

  //if not set
  if (datetime == null) datetime = "3100000012120000";

A:

solution was
 //from browser
  let datetime = req.body.datetime;

  //from mobile
  if (datetime == null) datetime = req.body.data.datetime;

  //if not set
  if (datetime == null) datetime = "3100000012120000";


Q:

Xcode 6 how to rename copied target

I know that this is not a new question, but I have tried many solution like edit Xcode project file manually or recreating new scheme for target after renaming it.
Can somebody help me with this question how copy target in right way and then rename it.
Right now I just rename scheme and it is displayed as is. But when Xcode is running app, under progress indicator it says: Running ProjectName-copy. But I have renamed target but seems product names or some build settings still has "...-copy" in the name.

A:

Duplicate a target.
Double click the copy of target and change its name to whatever you want.
'New target -> Build Settings -> Packaging -> Product Name', change it to the name you want.
Product (Menu item) > Schemes > Manage Schemes, then click the '+' button, select the new target and click 'OK' button.

All done.
PS:
After Duplicating the target, Xcode make a new Info.plist file named 'xxx copy-Info.plist' in the root path of project. If you want to change its name and path, after doing this, you should go to 'New target -> Build Settings -> Packaging -> Info.plist file' and change the value to the path of new file.

A:

Press on the target name in xcode ( in the same place where you want to select the sim/device type) and select "Manage Schemes...". Highlight the scheme with the copy inside name and press enter on keyboard. You can rename it there.

A:

To copy a target, click on your project, and go to the project inspector tab that looks like this:
Project:
SomeName
Targets:
SomeName
right click on a target, and select duplicate, then double-click slowly on the new target, or select the new target and hit enter, and just put the new name in!
To change running targets, to the top left of your xcode you will see this:
(start button)    (stop Button)      (target name and device)
[|>]              [[]]               [/\ TargetName > TargetDevice]
click the target name, next to the little compass (mathematical compass, not navigational) and select your desired target from the dropdown.
Hope I helped, Matroskin.


Q:

ReportViewer printing questions

Is there a way to autofit a report to the chosen paper type when printing?
I'm trying to print my report in a landscape mode, and even tohugh I set the paper properties to "landscape" and the report itself is set to be landscape - It is still printed in Portait mode.   what's wrong with it?

A:

Try setting the default printer settings under windows if that fails u may have to set length and width of the report manually in code.


Q:

How does this periodic trig function that calculates modulus work?

$$ \arctan(\tan(( \mathrm{dividend} - \frac{\mathrm{divisor}}{2}) \times \frac{\pi}{\mathrm{divisor}}))*\frac{\mathrm{divisor}}{\pi}+\frac{\mathrm{divisor}}{2}=   \mathrm{dividend} \bmod \mathrm{divisor} $$
This is a follow up to https://stackoverflow.com/questions/14841280/a-clever-homebrew-modulus-implementation
I'm not sure where to begin to understand how this works. Any suggestions? I know that I'm supposed to tell you what I have tried, but essentially I don't know where to begin.

A:

I would rewrite it a little bit first. Say you want $a \mod b$ i.e. a real number $r$, such that $0\leq r<b$ and $a=mb+r$ holds for some integer $m$. Your formula can be written as
$$
a \mod b = r = \arctan(\tan(\frac{a\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2
$$
Now enter $a=mb+r$ into that formula and you'll see
$$
r=\arctan(\tan(\frac{a\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2\\
=\arctan(\tan(m\pi + \frac{r\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2\\
=\arctan(\tan(\frac{r\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2\\
=(\frac{r\pi}{b}-\frac{\pi}2)\frac{b}\pi + \frac{b}2\\
=r-\frac{b}2 + \frac{b}2\\
$$
where I've used that $\tan$ is periodic with period $\pi$ (line 2 to 3) and that $\arctan$ is defined on $[-\pi/2,\pi/2]$ and $\arctan(\tan(x))=x$ on that interval (line 3 to 4).


Q:

NA impact in Caret Train

Following the example reported in the link below I have the following error:
Using nnet for prediction, am i doing it right?

Error in na.fail.default(list(y = c(0, 0.0998334166468282, 0.198669330795061,  :    missing values in object

To solve this error I use the condition na.action = na.omit
#Fit model
model <- train(y ~ x1 + x2, te, method='nnet', linout=TRUE, trace = FALSE,
               #Grid of tuning parameters to try:
               tuneGrid=expand.grid(.size=c(1,5,10),.decay=c(0,0.001,0.1)),
               na.action = na.omit)
ps <- predict(model, te)

is.na(te)
nrow(te)
nrow(ps)

Is this condition the only way to proceed?
In fact the consequence is that the number of rows of the ps is different to the number of ps data.

A:

Given that you are lagging the data, this is probably the best approach. Note that:
> sum(!complete.cases(te))
[1] 2

The model can't predict these which is why
> nrow(ps)
[1] 199
> nrow(te)
[1] 201

and this is because:
> formals(predict.train)$na.action
na.omit

(Note that this will probably be changed to na.fail in the next version of the package)


Q:

How do I set up RouterOS to use web proxy on another machine?

The RouterOS docs show how to transparently proxy all web traffic via the HTTP proxy built into RouterOS:
/ip firewall nat
add in-interface=ether1 dst-port=80 protocol=tcp action=redirect to-ports=8080 chain=dstnat
/ip proxy
set enabled=yes port=8080

I'd like to run a proxy on another machine, so that I can take advantage of more sophisticated filtering rules available in Squid or the like. However, if I use NAT to redirect traffic to another machine running Squid it won't work, since the HTTP request will need to be rewritten in order to be a proxy HTTP request; just redirecting the traffic gives bad request errors from Squid.

A:

No need of setting proxy in RouterOS. You can route all outgoing HTTP traffic to the server directly thru NAT:
ip firewall nat add in-interface=eth1 src-address=!<IP of Squid machine> dst-port=80 protocol=tcp action=dst-nat to-addresses=<IP of Squid machine> to-ports=8080

The last parameter "src-address=!..." is needed in case which squid machine communicates thru same interface as the other machines. Otherwise it would go like this:

Computer sends HTTP request
RouterOS destinates this packet to squid
Squid sends HTTP request to webserver
RouterOS destinates squid request again to squid -> loop

A:

It can be done with the parent-proxy setting:
/ip proxy
set parent-proxy=<IP of Squid machine> parent-proxy-port=3128


Q:

Separate float into digits

I have a float:
pi = 3.141

And want to separate the digits of the float and put them into a list as intergers like this:
#[3, 1, 4, 1]

I know to to separate them and put them into a list but as strings and that doesnt help me

A:

You need to loop through the string representation of the number and check if the number is a digit. If yes, then add it to the list. This can be done by using a list comprehension.
>>> pi = 3.141
>>> [int(i) for i in str(pi) if i.isdigit()]
[3, 1, 4, 1]

Another way using Regex (Not - preffered)
>>> map(int,re.findall('\d',str(pi)))
[3, 1, 4, 1]

A final way - Brute force
>>> pi = 3.141
>>> x = list(str(pi))
>>> x.remove('.')
>>> map(int,x)
[3, 1, 4, 1]

Few references from the docs

str.isdigit
re.findall
map

The timeit results
python -m timeit "pi = 3.141;[int(i) for i in str(pi) if i.isdigit()]"
100000 loops, best of 3: 2.56 usec per loop
python -m timeit "s = 3.141; list(map(int, str(s).replace('.','')))" # Avinash's Method
100000 loops, best of 3: 2.54 usec per loop
python -m timeit "import re;pi = 3.141; map(int,re.findall('\d',str(pi)))"
100000 loops, best of 3: 5.72 usec per loop
python -m timeit "pi = 3.141; x = list(str(pi));x.remove('.'); map(int,x);"
100000 loops, best of 3: 2.48 usec per loop

As you can see the brute force method is the fastest. The Regex answer as known is the slowest.

A:

You could also use string.replace along with map, list functions.
>>> s = 3.141
>>> list(map(int, str(s).replace('.','')))
[3, 1, 4, 1]


Q:

"new" Keyword doesn't work with immutable Queue

I tried to create a Queue with new Keyword..I did it for both mutable and immutable Queue.
But when I tried with immutable Queue, it gives error :
<console>:8: error: constructor Queue in class Queue cannot be accessed in object $iw
 Access to protected constructor Queue not permitted because
 enclosing class object $iw in object $iw is not a subclass of
 class Queue in package immutable where target is defined
       val a=new Queue[Int]()
             ^

scala> import scala.collection.immutable.Queue
import scala.collection.immutable.Queue

scala> val a=new Queue[Int]()
<console>:8: error: constructor Queue in class Queue cannot be accessed in object $iw
 Access to protected constructor Queue not permitted because
 enclosing class object $iw in object $iw is not a subclass of
 class Queue in package immutable where target is defined
       val a=new Queue[Int]()

But when I tried this code with mutable Queue, immutable Stack, mutable Stack...It works well
scala> import scala.collection.mutable.Queue
import scala.collection.mutable.Queue

scala> val a=new Queue[Int]()
a: scala.collection.mutable.Queue[Int] = Queue()

scala> import scala.collection.immutable.Stack
import scala.collection.immutable.Stack

scala> val a=new Stack[Int]()
a: scala.collection.immutable.Stack[Int] = Stack()

scala> import scala.collection.mutable.Stack
import scala.collection.mutable.Stack

scala> val a=new Stack[Int]()
a: scala.collection.mutable.Stack[Int] = Stack()

Can anyone tell me, why is it so ???

A:

From a quick look at the sourcecode, I would venture that the immutable version is essentially implemented through a couple of Lists which pivots as needed to give nice performance between reads and writes (queue/dequeue).
This is quite dissimilar from the other collections, in that it needs both mentioned Lists as parameters to the class constructor.
The companion object, on the other side, provides a public factory method that is consistent with other collections, by accepting a variable number of initial values for the Queue content.
What is missing is a public constructor for the class, that would mimic the companion-object apply call, by taking the initial values, and using them to build the "enque/dequeue" Lists.
Maybe it was not deemed essential, or it's been an oversight, or there is a deeper issue that I can't figure out.

A:

The compiler already tells you why it doesn't work, because the conctructor is protected. You have to use the apply method of the companion to create an immutable.Queue:
val queue = immutable.Queue(1,2,3)


Q:

Firebase erroneously shows deleted data / Swift 3 / Xcode 8.2

I am new to coding and just started using Firebase, and I am  running the below function which is basically trying to create 2 nodes, "Tournaments" and "Daily Games" (if they don't exist already).
The database tree should look like this:
-London
  -City Game
      -Date(stringDate)  // getting this from another function, returns 2016-16-12
           -Tournaments
           -Daily Games

And the code looks like this:
     func createTournamentsAndNonTournamentsNodes() {

        let databaseRef = FIRDatabase.database().reference()
        self.getLiveTimestamp()  // this calls a function that returns timestamp

        databaseRef.child("London/City Game/\(stringDate)").observeSingleEvent(of: .value, with:  { (snapshot) in

            if snapshot.hasChild("Daily Games") {
                print ("Daily Games node exists already")
            print(snapshot.key)
            print(snapshot.value as Any)
            } else {
                print ("Daily Games dont exist, creating it now")
                let postTwo : [String : AnyObject] = [("Daily Games") : "Initiated today at : \(self.timeStampString)" as AnyObject]

                databaseRef.child("London/City Game/\(stringDate)").child("Daily Games").updateChildValues(postTwo)
            }
            if snapshot.hasChild("Tournaments") {
                print ("Tournaments node exists already")
            print(snapshot.key)
            print(snapshot.value as Any)
            } else {
                print ("Tournaments dont exist, creating it now")
                let postOne : [String : AnyObject] = [("Tournaments") : "Initiated today at : \(self.timeStampString)" as AnyObject]
                databaseRef.child("London/City Game/\(stringDate)").child("Tournaments").updateChildValues(postOne)
            }
        })
    }

So the result of running the above on an empty database is that the console prints "Daily game node exists already" and "Tournaments node exists already", with key and values as below. But the problem is that those were created by me on a previous run 1 hr ago and immediately deleted manually from the Firebase web console, to test the code, making my database completely empty before running the code again. So reloading the Firebase console shows me an empty database, but my code prints me this, as if the data exists in the database. How is this possible? Does Firebase keep data for some time despite appearing empty on the web console?
Optional({

    "Daily Games" = "Initiated today at : 13:01:19";
    Tournaments =     {
        Tournaments = "Initiated today at : 13:05:22";
    };
})

What am I doing wrong? How to really tell what is and what is not in the database if my code shows me a populated database, but my Web Console shows me an empty one? Many thanks
UPDATE:
I had FIRDatabase.database().persistenceEnabled = true and also running this on a real device. After disabling persistenceEnabled, it works absolutely fine. What is the way to fix this, without disabling persistenceEnabled?

A:

Well, here is my tip.
I had almost the same problem, and to solve this I changed from observeSingleEvent to observe and then Firebase does not only look into your cellphone, because that's exactly what it does when you do it.


Q:

'dependsOn' property error in data factory

I am getting following error in azure data factory pipeline activity
I am using following code:
...
"dependsOn": [
        {
            "activity": "MyFirstActivity",
            "dependencyConditions": [
                "Succeeded"
            ]
        }
      ]
...

"Input is malformed. Reason: batchPipelineRequest.dependsOn : Could not find member 'dependsOn' on object of type 'Activity'. Path 'dependsOn'..
  OK"

Is there any other property we need to put in pipeline or in datasets?

A:

This feature is available only in v2 preview version of ADF. To link and activity to another activity, you will need to use the output of previous activity as the input to the new activity. You can find details here-
https://docs.microsoft.com/en-us/azure/data-factory/v1/data-factory-create-pipelines


Q:

Parsing Flags in Python

I am trying to manually parse out arguments and flags given a string.
For example, if I have a string
"--flag1 'this is the argument'"
I am expecting to get back
['--flag1', 'this is the argument']
for any arbitrary number of flags in the string.
The difficulty I am having is determining how to process multi-word flag arguments.
For example, if I do (parser comes from argparse)
parser.parse_args("--flag1 'this is the argument'".split())
"--flag1 'this is the argument'".split()"
becomes
['--flag1', "'this", 'is', 'the', "argument'"]
which is not what I expect. Is there a simple way to do this?

A:

You're in luck;  there is a simple way to do this.  Use shlex.split.  It should split the string as you want.
>>> import shlex
>>> shlex.split("--flag1 'this is the argument'")
['--flag1', 'this is the argument']


Q:

findViewById() is returning null for custom view - Android

Let me start by saying this: I've already looked through all of the other threads on this issue and combed Google for an answer, but nothing has helped me.
I have a layout that contains a custom view that is added at runtime. My custom view has the super(context, attrs) constructor.
Custom view:
public CustomLinearLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialize some variables...
}

I add views to my activity with the following method:
public void addNewView (boolean isEmpty) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    for (int i = 0; i < amount; i++) {
    if (isEmpty) {
        View v = (ViewGroup) inflater.inflate(R.layout.my_custom_layout, layoutContainer, true);
        viewTracker++;
    }
    }
}

If I use findViewById for my custom view in the addNewView() method above then all is well. However, if I try to use findViewById anywhere else in the activity after the view has been inflated (and obviously after setContentView) I get a null pointer. I've also tried someView.findViewById() which doesn't work. I'm stumped. Any ideas?
Logcat shows a null pointer, but nothing more:
02-16 06:56:10.681: E/AndroidRuntime(11360): FATAL EXCEPTION: main
02-16 06:56:10.681: E/AndroidRuntime(11360): java.lang.NullPointerException
02-16 06:56:10.681: E/AndroidRuntime(11360): at com.nutrifit.Fragments.WorkoutPlannerPopup.resetOtherView(WorkoutPlannerPopup.java:404)
02-16 06:56:10.681: E/AndroidRuntime(11360): at com.nutrifit.customviews.CustomLinearLayout.onTouchEvent(CustomLinearLayout.java:43)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.View.dispatchTouchEvent(View.java:7239)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2168)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1903)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)

Here's my custom view in XML:
<?xml version="1.0" encoding="utf-8"?>
<com.nutrifit.customviews.CustomLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/exercise_container_0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/wpp_background_border" >

<ImageView android:id="@+id/delete_button_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/wpp_background_border" />
...more android child views

</com.nutrifit.customviews.CustomLinearLayout>

A:

Where is the addNewView() method being called? From my understanding, if you do a findViewById() in the constructor of a custom view, you could get a null. I haven't found an authoritative reference that states when it is safe to call findViewById() in a custom view, but I normally do it in onFinishInflate() or later.


Q:

Как подключить ulogin на kohana

Никак не могу понять как подключить ulogin, в README пишет:
 1. Создать таблицу ulogins:
CREATE TABLE `ulogins` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `user_id` INT(11) NOT NULL,
    `network` VARCHAR(255) NOT NULL,
    `identity` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `identity` (`identity`)
)
 2. Добавить 'ulogins' => array(), в protected $_has_many у модели user

таблицу создал, а вот второй пункт никак не могу понять, модель user сам создаешь? подскажите?

A:

Model_User уже есть, если подключить модули Auth и ORM.
См. modules/orm/classes/Model/User.php


Q:

How to call a file path from a sql server database but not show it?

I am using a string to store the file path of an image in a sql server database. I want to call the file path from the database in a vb.net winform project but not show it because I want to just show the image. Can anyone advise me on how to do this? Thanks in advance for your help.
EDIT:
Just to be clear, the image path is stored as a string in the database from one form, I want to call the path in another form, but I don't want to show the path, I want to show the actual image the path points to.

A:

You don't have a lot of info here, but can you do something like:
dim imgReturned as Image

If tblDataTable.Rows.Count > 0 Then

    imgReturned = Image.FromFile(tblDataTable.Rows(0).Item("ImageFilePathAndName"))

End If


Q:

Testing go channel throughput - all goroutines deadlock

I made a small program to benchmark go channel throughput, however it always deadlocks, I tried very hard but cannot understand why:
package main

import (
    "fmt"
    "runtime"
)

const CONCURRENCY = 32
const WORK_PER_WORKER = 100
const TOTAL_WORK = CONCURRENCY * WORK_PER_WORKER

func work() {
    sum := 0
    for i := 0; i < 10000000; i++ {
        sum *= i
    }
}

type WorkItem struct {
    Done chan int
}

func main() {
    runtime.GOMAXPROCS(CONCURRENCY)
    var workQueue [CONCURRENCY]chan *WorkItem
    // initialize workers
    for i := 0; i < CONCURRENCY; i++ {
        workQueue[i] = make(chan *WorkItem)
    }
    // start workers
    for i := 0; i < CONCURRENCY; i++ {
        go func(i int) {
            anItem := <-workQueue[i]
            work()
            anItem.Done <- 1
        }(i)
    }
    completed := make(chan bool, TOTAL_WORK)
    for i := 0; i < TOTAL_WORK; i++ {
        go func(i int) {
            // send work to queues
            workToDo := &WorkItem{Done: make(chan int)}
            workQueue[i/WORK_PER_WORKER] <- workToDo // !! DEADLOCK
            // wait until the work is done
            <-workToDo.Done
            completed <- true
        }(i)
    }
    fmt.Println("Waiting")
    for i := 0; i < TOTAL_WORK; i++ {
        <-completed
    }
}

A:

Your code go func(i int) { anItem := <-workQueue[i]; ... } removes juste 1 item from workQueue[i] but you are trying to stuff WORK_PER_WORKER items into it. You will work on CONCURRENCY many items and after that all reading goroutines have terminated and you have your deadlock.
Looping in the worker goroutines "solves" your deadlock: http://play.golang.org/p/j2pavqnBDv
Just "solves" because these worker goroutines will never terminate. Maybe you can experiment with closeing your channels to notify the worker goroutines when nothing will be sent.


Q:

Why does my dog lay down when he sees another dog?

My dog (~7 year Lab mix) is mostly well-behaved on leash, though he still has a few triggers that we're working on (mostly harmless, but can seem intimidating to other dogs and/or their owners).
One of these actions is laying down when he sees another dog, paws in front of him so he can quickly jump to his feet. It only seems to happen when the other dog is a bit of a distance away but headed in our direction, and doesn't seem to matter the size or breed of the other dog. Unless I intervene or the other dog changes direction, he will always jump to his feet and dash towards the other dog. It's always been in a playful (if intimidatingly energetic) manner, but given the intensity of his focus on the other dog while this is happening, I'm concerned that it may not always be harmless.
I've also seen this behavior in other dogs, sometimes towards my own dog and sometimes with other dogs.

A:

You're misinterpreting this. Our two Huskies show the very same behavior and it's not being aggressive or getting ready to pounce. Quite the opposite.
As Kosh mentioned, it's to show submission to some extent and signal "get over here, I want no harm".
The following "jump start" is more some kind of over-anticipation and the dog no longer wanting to wait.
Overall I wouldn't try to change this behavior as it's basically a positive one. As for the dashing portion: I usually try to hold the leash firm and tense so there's little to no room for the dog to jump forward.


Q:

Solving integral equation with an unknown function under the integral in matlab

Is it possible to solve a equations like this:
$\sin(x) = (1 - \int y(x) dx) * y(x) $
whats matlab code for this equation?

A:

I don’t know matlab. But you asked if ‘it is possible to be solved’, and my answer to that is yes.
Let $u=\frac{\sin x}y$, $u’=\frac{du}{dx}$.
We have
$$u=1-\int\frac{\sin x}{u}dx$$
Differentiating both sides,
$$u’=-\frac{\sin x}u$$
$$\begin{align}
udu&=-\sin x~dx \\
C+\frac{u^2}2&=\cos x\\
u&=\pm\sqrt{C+2\cos x}\\
y&=\pm\frac{\sin x}{\sqrt{C+2\cos x}}\\
\end{align}
$$


Q:

eigen3 type cast / copy from pointer (overflow uint8_t)

i get a uint8_t * array (which is fixed defined) and want to use them with a Eigen3 Matrix.
I started using
typedef Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix8u;

with a memcpy to .data()
but later i noticed that for example .sum() I'm getting an overflow.
Is there a way to make a fast copy between a uint8_t * and a int32_t ? - with Eigen::Map ?
Greetings

A:

I'd use Eigen::Map to map your array onto a Matrix8u and then cast it to something like Matrix32i.
Assuming your data is in a form of an array data[] = {0, 1, 2, ...} here is sample code:
typedef Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix8u;
typedef Eigen::Matrix<int32_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix32i;

uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};

Matrix32i m32i = Eigen::Map<Matrix8u>(data, rows, cols).cast<Matrix32i::Scalar>();

And of course rows*cols must equal the length of your data array.


Q:

Load Image from Website into Tableview

I am trying to load images from a website into a tableview. I can load an image stored in the project, but am unable to get image from the web. I know I am missing something here. Any ideas?
UIImage *cellImage = [UIImage imageNamed:
@"http://www.website.com/thumbs/img_10.jpg"];
cell.imageView.image = cellImage;

Any help would be great! Thank you!

A:

You can use it like this:
NSURL *imageURL = [NSURL URLWithString:@"http://www.gravatar.com/avatar/53789a67f8fffd8ede2ea118165ff962?s=32&d=identicon&r=PG"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *cellImage = [UIImage imageWithData:imageData];

But get image synchronously using this way will block your UI. You'd better get image asynchronously. Send out a request and after get the image update your UI in your request delegate method.


Q:

jqplot: align bars with labels using multiple series bars

I am not able to align bars with labels. This happens because I have multiple series.
I need:
1) bar charts with 5 boxes
2) each box represents seperate item, should have seperate color
3) legend should have 5 items in it
4) bar charts shoudl be aligned with labels (in the best sollution bar charts would be wide)
I have achieved first three, but I cannot achive fourth.
Here is what I have:
var chartData = [
    [['Portfolio Risk', 1]],
    [['Model Risk', 4]],
    [['Recovery Risk', 3]],
    [['Capability Risk', 1]],
    [['Forward flow risk', 5]]
];

var ticks = ['Portfolio Risk', 'Model Risk', 'Recovery Risk', 'Capability Risk', 'Forward flow risk'];

plot2 = $.jqplot('chart1', chartData, {
    seriesColors: ['#85802b', '#00749F', '#73C774', '#C7754C', '#17BDB8'],
    seriesDefaults: {
        renderer: $.jqplot.BarRenderer,
    },
    axesDefaults: {
        tickRenderer: $.jqplot.CanvasAxisTickRenderer,
    },
    axes: {
        xaxis: {
            renderer: $.jqplot.CategoryAxisRenderer,
            tickOptions: {
                angle: 90
            },
        },
        yaxis: {
            tickOptions: {
                formatString: '%d'
            },
            max: 5,
            min: 0
        }
    },
    legend: {
        show: true,
        placement: 'outside',
        labels: ticks
    },
});

JSFiddle: http://jsfiddle.net/renatevidruska/27EPk/
As you see bars are not aligned.

A:

This can be done by simply adding a few options to your seriesDefaults, like so:
seriesDefaults: {
    renderer: $.jqplot.BarRenderer,
    rendererOptions: {
        barWidth: 60,
        barPadding: -60

    }

Note that if you want to center the bars, simply make the barPadding value the negative of the barWidth value.  In this case, I set the width to 60, so I then set the padding to -60.  Here is the fiddle.


Q:

¿Cómo cambiar el formato de fecha y hora en phpmyadmin?

Tengo un campo como tipo datetime en una tabla y los registros me los muestra en este formato:
YYYY-MM-DD 00:00:00
Tengo entendido que es posible modificar eso al entrar en la estructura de una tabla cualquiera, editar el campo y en la pestaña donde dice:
Transformación de visualización en el navegador, dejarlo establecido como:
Date Format (text/plain: DateFormat)
Pero en Opciones de transformación de visualización en el navegador no sé muy bien que poner para que me muestre la fecha y la hora en este formato:
DD-MM-YYYY 00:00:00
Menciono que ya probé con esto:
0,'%d-%m-%Y','local'
Pero me muestra solamente la fecha y no la fecha junto con la hora que es lo que quiero mostrar.
Incluyo además la siguiente imagen que encontré que es como quiero que me muestre la fecha y la hora, presten atención a la columna hora_inicio así es como me gustaría que quedase en mi base de datos.

Me gustaría poder hacerlo sin código, simplemente modificar alguna opción dentro de MyPHPadmin.

A:

Fíjate en el formato que usaste: 0,'%d-%m-%Y','local'
Esto es "Día, Mes y Año" con el formato 03-10-2018. Ahora si quieres agregar la hora, también tienes que añadirla al formato:
0,'%d-%m-%Y %H:%M:%S','local'

Fíjate ahora en H M y S que indican "Hora, Minutos y Segundos". Ahora la fecha se muestra con el formato 03-10-2018 11:13:45.


Q:

String comparison: Actual newline is never recognized as "\n"

I am trying to learn a bit of Python by writing a script to communicate with my switch over a serial connection.
    while char is not "\n":
        char = port.read(1)
        sys.stdout.write(char)

I try to compare the output and end the loop if I find a newline but it never works.
I even tried to encode some of the output to make sure that there really ARE newlines, it looks like this:
0000420   G   I   G   A   l   i   n   e   2   6   0   0   M       l   o
0000440   g   i   n   :      \r  \n   G   I   G   A   l   i   n   e   2
0000460   6   0   0   M       l   o   g   i   n   :      \r  \n   G   I
0000500   G   A   l   i   n   e   2   6   0   0   M       l   o   g   i
0000520   n   :      \r  \n   G   I   G   A   l   i   n   e   2   6   0 ...

What could be the problem?

A:

You want
while char != "\n":

Using is in a comparison checks to see if the two objects in the comparison are the exact same object, it doesn't check to see if they just have the same value.
>>> char = "\n"
>>> char == "\n"
True
>>> char is "\n"
False
>>> a = char
>>> a is char
True
>>> id(a)
139751408202160
>>> id(char)
139751408202160  # char and a have the same id, thus `a == char` is True
>>> id("\n")
139751346017264  # "\n" has a different id, so `char is "\n"` is False

As a rule, you should only use the is comparison in Python when you're dealing with singleton objects, like None, True, and False. For strings, ints, etc. you should use == and !=.


Q:

Как обработать URL?

Когда пользователь заходит на URL: http://www.mysite.ru/page/news001/
как из url взять 'news001'?

A:

Какой вопрос -- такой ответ)
$myPath = explode("/", $SERVER['REQUEST_URI']);
echo $myPath[1];

A:

Для этого есть mod_rewrite в файле .htaccess. После манипуляций данные из URL можно будет получить как обычный GET.


Q:

How to escape a regexp_replace in Oracle?

I am creating a small replaceParam function for Strings and wanted to be able to escape a replacement, e. g.
select regexp_replace('%ABC# %ABC#','%ABC#', 'XXX')
from dual;

leads to
XXX XXX

BUT I want to be able to escape the replacment, e. g. by preceding a \ in front of a string, that would be otherwise replaced.
select regexp_replace('%ABC# \%ABC#','<themagicregexp>', 'XXX')
from dual;

should lead to
XXX \%ABC#

I tried the non-matching character list, but this doesn't work.
select regexp_replace('%ABC#abc\%ABC#','<themagicregexp>', 'XXX')
from dual;

should lead to
XXXabc\%ABC#

In addition because someone mentioned it: I can't go with word boundaries, since this should work also:
yoyo%ABC#yoyo

I have the feeling this can be done in one regexp, but I just don't see it?

A:

This should work provided you don't have an input that looks like %ABC#%ABC#
SELECT REGEXP_REPLACE( '%ABC#abc\%ABC#', '((^|[^\])(\\\\)*)%ABC#', '\1XXX' )
FROM DUAL;

This will either match:

The start of the string ^ or a non-slash character [^\] followed by any number of pairs of slash characters then, finally, the characters %ABC#. This will match %ABC#, \\%ABC#, \\\\%ABC# and so on but will not match \%ABC#, \\\%ABC#, \\\\\%ABC# where there is a slash escaping the % character.

The replacement includes the first capture group as the expression can match a preceding non-slash character and pairs of slashes and these need to be preserved in the output.

Update
This gets a bit complicated but it will do repeated matches:
WITH Data ( VALUE ) AS (
  SELECT '%ABC#%ABC#' FROM DUAL
)
SELECT ( SELECT LISTAGG(
                  REGEXP_REPLACE( COLUMN_VALUE, '((^|[^\])(\\\\)*)%ABC#$', '\1XXX' ),
                  NULL
                ) WITHIN GROUP ( ORDER BY NULL )
         FROM   TABLE(
                  CAST(
                    MULTISET(
                      SELECT  REGEXP_SUBSTR( d.value, '.*?(%ABC#|$)', 1, LEVEL )
                      FROM    DUAL
                      CONNECT BY LEVEL < REGEXP_COUNT( d.value, '.*?(%ABC#|$)' )
                    AS SYS.ODCIVARCHAR2LIST
                  )
                )
       ) AS Value
FROM   Data d;

It uses a correlated sub-query to split the string into sub-strings that end with %ABC# or the end-of-string (this is the bit inside the TABLE( CAST( MULTISET( ) .. ) )) and then re-concatenates these sub-strings after performing the replacement on the end of each sub-string.


Q:

JavaFX tableview not displaying properly

I have a JavaFX application with a scene with two tableviews, the first one works correctly, the second one doesn't.
The second tableview only displays the content of 2 out of the 5 columns it should, and the content on the second column, should be actually on the last column. I have used javaFX a few times before and it's the first time I see something like this, I revised my code 2 or 3 times looking for things that could be wrong or mispelled, but I haven't been able to find it.
This is what the tableview displays.

This is the code of the object class it contains.
public class Producte {

    private int codi;
    private String nom;
    private String descripcio;
    private float preu;
    private int codiFabricant;

    public Producte(String nom, String descripcio, float preu,
            int codiFabricant) {
        this.nom = nom;
        this.descripcio = descripcio;
        this.preu = preu;
        this.codiFabricant = codiFabricant;
    }

    public Producte(int codi, String nom, String descripcio, float preu,
            int codiFabricant) {
        this.codi = codi;
        this.nom = nom;
        this.descripcio = descripcio;
        this.preu = preu;
        this.codiFabricant = codiFabricant;
    }

    public int getCodi() {
        return codi;
    }

    public void setCodi(int codi) {
        this.codi = codi;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getDescripcio() {
        return descripcio;
    }

    public void setDescripcio(String descripcio) {
        this.descripcio = descripcio;
    }

    public float getPreu() {
        return preu;
    }

    public void setPreu(float preu) {
        this.preu = preu;
    }

    public int getCodiFabricant() {
        return codiFabricant;
    }

    public void setCodiFabricant(int codiFabricant) {
        this.codiFabricant = codiFabricant;
    }

    @Override
    public String toString() {
        return "Producte [codi=" + codi + ", nom=" + nom + ", descripcio="
                + descripcio + ", preu=" + preu + ", codiFabricant="
                + codiFabricant + "]";
    }

}

And this is the code from the method that loads the scene.
The first tableview is the dirTable, the second one(the one that doesn't work properly is the prodTable). Thanks in advance for any help :/
static Scene directorScene() {
        GridPane gridPane = new GridPane();
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setVgap(25);
        gridPane.setHgap(25);

        director = DirectorFunctions.director;

        final ObservableList<Director> dirList = FXCollections.observableArrayList();
        dirList.add(director);

        TableView<Director> dirTable = new TableView<>();
        dirTable.setItems(dirList);

        TableColumn<Director, String> fabCol = new TableColumn<>("Fabricant");
        TableColumn<Director, String> dniCol = new TableColumn<>("DNI");
        TableColumn<Director, String> nomCol = new TableColumn<>("Nom");
        TableColumn<Director, String> mailCol = new TableColumn<>("Mail");
        TableColumn<Director, String> passCol = new TableColumn<>("Pass");

        fabCol.setCellValueFactory(new PropertyValueFactory<Director,String>("Nom"));
        dniCol.setCellValueFactory(new PropertyValueFactory<Director,String>("DniDirector"));
        nomCol.setCellValueFactory(new PropertyValueFactory<Director,String>("NomDirector"));
        mailCol.setCellValueFactory(new PropertyValueFactory<Director,String>("MailDirector"));
        passCol.setCellValueFactory(new PropertyValueFactory<Director,String>("PasswordDirector"));

        dirTable.getColumns().setAll(fabCol, dniCol, nomCol, mailCol, passCol);
        dirTable.setMinWidth(450);
        dirTable.setMaxHeight(52);
        dirTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        gridPane.add(dirTable, 0, 0);

        Button modificarDirector = new Button("Modificar");
        modificarDirector.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                // TODO Auto-generated method stub

            }
        });
        gridPane.add(modificarDirector, 1, 0);

        final ObservableList<Producte> prodList = FXCollections.observableArrayList();
        for (Producte p:DirectorFunctions.productes.values()) {
            prodList.add(p);
        }

        TableView<Producte> prodTable = new TableView<>();
        prodTable.setItems(prodList);

        TableColumn<Producte, String> codiPCol = new TableColumn<>("Codi");
        TableColumn<Producte, String> nomPCol = new TableColumn<>("Nom");
        TableColumn<Producte, String> descPCol = new TableColumn<>("Descripció");
        TableColumn<Producte, String> preuPCol = new TableColumn<>("Preu");
        TableColumn<Producte, String> fabPCol = new TableColumn<>("Fabricant");

        codiPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Codi"));
        nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Nom"));
        nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Descripcio"));
        nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Preu"));
        nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("CodiFabricant"));

        prodTable.getColumns().setAll(codiPCol, nomPCol, descPCol, preuPCol, fabPCol);
        prodTable.setMinWidth(450);
        prodTable.setMaxHeight(200);
        prodTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        gridPane.add(prodTable, 0, 1);

        Button nouButton = new Button("Nou");
        nouButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                // TODO Auto-generated method stub

            }
        });
        nouButton.setMinWidth(75);

        Button modButton = new Button("Modificar");
        modButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                // TODO Auto-generated method stub

            }
        });
        modButton.setMinWidth(75);

        Button delButton = new Button("Borrar");
        delButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                // TODO Auto-generated method stub

            }
        });
        delButton.setMinWidth(75);

        Button backButton = new Button("Tornar");
        backButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                // TODO Auto-generated method stub

            }
        });
        backButton.setMinWidth(75);
        gridPane.add(backButton, 1, 2);

        VBox vbox = new VBox(25);
        vbox.getChildren().addAll(nouButton, modButton, delButton);
        gridPane.add(vbox, 1, 1);

        Scene scene = new Scene(gridPane, 640, 480, Color.web("eee"));
        return scene;
    }

This is the Director class for whoever wants to see it as well
public class Director {

    private int codi;
    private String nom;
    private String dniDirector;
    private String nomDirector;
    private String mailDirector;
    private String passwordDirector;

    public Director(int codi, String nom, String dniDirector,
            String nomDirector, String mailDirector, String passwordDirector) {
        this.codi = codi;
        this.nom = nom;
        this.dniDirector = dniDirector;
        this.nomDirector = nomDirector;
        this.mailDirector = mailDirector;
        this.passwordDirector = passwordDirector;
    }

    public int getCodi() {
        return codi;
    }

    public void setCodi(int codi) {
        this.codi = codi;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getDniDirector() {
        return dniDirector;
    }

    public void setDniDirector(String dniDirector) {
        this.dniDirector = dniDirector;
    }

    public String getNomDirector() {
        return nomDirector;
    }

    public void setNomDirector(String nomDirector) {
        this.nomDirector = nomDirector;
    }

    public String getMailDirector() {
        return mailDirector;
    }

    public void setMailDirector(String mailDirector) {
        this.mailDirector = mailDirector;
    }

    public String getPasswordDirector() {
        return passwordDirector;
    }

    public void setPasswordDirector(String passwordDirector) {
        this.passwordDirector = passwordDirector;
    }

    @Override
    public String toString() {
        return "Fabricant [codi=" + codi + ", nom=" + nom + ", dniDirector="
                + dniDirector + ", nomDirector=" + nomDirector
                + ", mailDirector=" + mailDirector + ", passwordDirector="
                + passwordDirector + "]";
    }

}

A:

I would advice you to use JavaFX Property for all your model. You can find samples in here.
PropertyValueFactory<S,T> looks for a property of type T in S with the same name that you typed in the constructor.
For example, in a model class Product which has a StringProperty field name,
new PropertyValueFactory<Product, String>("name")

will look for :
nameProperty()

and if it doesn't find it, it will further look for getName() and wrap it in a  ReadOnlyObjectWrapper before returning it.
From the docs,

If no method matching this pattern exists, there is fall-through
  support for attempting to call get() or is() (that
  is, getFirstName() or isFirstName() in the example above). If a method
  matching this pattern exists, the value returned from this method is
  wrapped in a ReadOnlyObjectWrapper and returned to the TableCell

The problem in your example is that your table column has a cellValueFactory which says,
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Preu"));

but your getter method is returning a float instead of a String
public float getPreu() {
    return preu;
}


Q:

Quick way to insert the same record as copy using Tableadapter

I have a datatable with a bunch of fields, and it's filled data by tableadapter. Usually, records that need to be inserted are a little bit different (only id). I don't want user to retypes everything again so, is there a quick way to insert current record into database. Notice that all my insert, update and delete operations are based on my tableadapter.
//Get only one last record that has been added when the form load.
bookTableAdapter.FillByLastID(bookDataSet.dtBook);

private void btnNew_Click(object sender, EventArgs e)
{
  bookBindingSource.AddNew();
}

private void btnSave_Click(object sender, EventArgs e)
{
  this.Validate();
  bookBindingSource.EndEdit();
  bookTableAdapter.Update(bookDataSet.dtBook);
}

A:

Try this to copy row:
        DataRow row = table.Rows[0]; // row you want to copy

        DataRow newRow = table.NewRow();
        newRow.ItemArray = row.ItemArray.ToArray();
        newRow["Id"] = 10;  // change Id

        table.Rows.Add(newRow);


Q:

Is it acceptable to edit other people's answers to include new information?

Recently I have noticed a few suggested edits that included adding new information to an existing answer. Is that acceptable?
My intuition is that edits should not add new information that the author did not include -- because it may compromise the responsibility and trustworthiness. E.g. if a nonsensical edit is suggested and somehow passes the review, it will look as if the original answerer had this bad idea, while it actually belongs to the editor of the answer. I think that in such situations, a new answer should be posted instead, or perhaps a comment under the existing answer prompting the original answerer to update his answer accordingly (so that the original answerer can decide on it himself/herself).

A:

I'd say No in broad terms, but as usual much depends on the details.
Positively, substantial new information could help a thread considerably, but that should typically be added through comments or very possibly as part of an answer.
But what's substantial? For example, if someone edited a literature reference to add detail or to add a URL, that's an excellent contribution in my view. If the editor wanted to do that without claiming credit, that's fine too.
Negatively, the purpose of editing (see e.g. Editing questions: dos and don'ts) is essentially to clarify a question, including correcting trivial errors,  but not to amplify it.
The possibility of a misguided or incorrect edit being accepted by mistake exists always, independently of this issue, and is to be matched by a rollback and/or further editing.

A:

I agree with @NickCox that as a general policy answer edits should only be "minor" (copy editing), i.e. improve grammar, fix spelling and LaTeX mistakes, format the quotes and code blocks, insert full references and hyperlinks to papers, etc.
Substantial (major) changes should not be made via edits; if you think that an answer is incorrect or not entirely correct, consider downvoting, and/or commenting, and/or posting an alternative answer.
However, I have encountered some situations where I think it is justified (with extreme care!) to violate this rule. For example, if a highly upvoted / accepted answer in a popular thread contains some sloppiness or misinformation and if the answerer is not with us anymore or simply does not react to the comments, it might be worth to edit. It is practically impossible for a new answer in such a thread to get more upvotes than an existing popular answer; and there might be so many comments already present that a new comment would not be very noticeable.
I did it a couple of times, e.g. with the accepted answer here: What are principal component scores?
Very rarely I have even decided to edit to improve an answer that was correct but I felt could be extended or clarified. E.g. the accepted answer here: PCA on correlation or covariance?
That said, I re-iterate: I do agree that our policy should remain that such edits are generally not allowed.


Q:

openCV image Stitching wide angle 160 degrees

I'm trying to Stitching image wide angle 160.5 degree but the result is not a good
i'm using OpenCV 4 and ffmpeg to get frames from video
ffmpeg command  to get 15 frame per sec :
ffmpeg -i first.mp4 -vf fps=15  preview%05d.jpg

OpenCV Stitching code
import cv2
import numpy as np

images = []
for i in range(70):
    name = ('preview%05d.jpg' % (i+1))
    print(name)
    images.append(cv2.imread(name , cv2.IMREAD_COLOR))

print("start ")
stitcher = cv2.Stitcher_create()
ret, pano = stitcher.stitch(images)

if ret == cv2.STITCHER_OK:
    cv2.imshow('panorama', pano)
    cv2.waitKey()
    cv2.destroyAllWindows()
else:
    print(cv2.STITCHER_ERR_NEED_MORE_IMGS)
    print(cv2.STITCHER_ERR_HOMOGRAPHY_EST_FAIL)
    print(cv2.STITCHER_ERR_CAMERA_PARAMS_ADJUST_FAIL)
    print(ret)
    print('Error during stiching')

actual result :

expected result :

A:

Before the code line stitcher = cv2.Stitcher_create() you have to append some more algorithms that transform your trapezoid image view into a rectangle image view via the homography method.
use: cv2.findHomography(srcPoints, dstPoints[, method[, ransacReprojThreshold[, mask]]])

srcPoints – Coordinates of the points in the original plane, a matrix of the type CV_32FC2 or vector .
dstPoints – Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or a vector .

See also here for findHomography at OpenCV.
In particular: in your case the base (bottom side of the image) shows most information whereas topside has more non relevant information. Here you should keep the aspect ratio topside the same and narrow the bottom. This should be done for every image. Once done you can try stitching them again.
Approach example to transform Trapezium based image information in e.g. square image:
                 (information ratio x)
----+++++++----  (1)
---+++++++++---  (1)
--+++++++++++--  (1)
-+++++++++++++-  (1)
+++++++++++++++  (1)

into Squared image information:
                (information ratio x)
----+++++++---- (1)
----+++++++---- (1.1)
----+++++++---- (1.2)
----+++++++---- (1.3)
----+++++++---- (1.4; most compressed information ratio)

Once this is done you can stitch it. Don't forget to post the result ;-)
Another approach is to treat the camera as a line-inspector. This method you use when you take information from each image for lets say line y1060 to 1080 (e.g. image size 1920x1080px) and then fill a new array with the information from those 20 lines in ascending order.
Update Jan 2019:
As homography appears not to do 100% the job due to the steep 60 degree angle you can try to correct the angle by performing the PerspectiveTransform first.
# you can add a for-loop + image counter here to perform action on all images taken from
# the movie-file. Then its easily replacing numbers in the next part for the name
# of the image.

scr_array = []  # source e.g. pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
dest_array = [] # destination e.g. pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])

Matrix1 = cv2.getPerspectiveTransform(scr_array,dest_array)
dst = cv2.warpPerspective(image, Matrix1 , (cols, rows))

label = 'CarImage1' # use ('CarImage%s' % labelnr) here for automated annotation.

# cv2.imshow(label , dst) # check the image
# cv2.imwrite(('%s.jpg' % label), dst)

See also the docs here on PerspectiveTransform.


Q:

What does the AdvAgg bundler do?

I tried to read the description but I didn't understand what this component does. The description says:

If not checked, the bundler will not split up aggregates.

I know that the purpose of aggregation is the join files so I guess this splitting isn't de-aggregation, so what is it?

In CSS bundling option it says:

If file count is selected then each bundle will try to have a similar
  number of original files aggregated inside of it.
If file size is
  selected then each bundle will try to have a similar file size.

An answer on the question above could help me decipher what's written here as well...

A:

The short answer is to take advantage of the browser cache. It can also be used to take advantage of the number of parallel connections that the browser can make.
Example:
Front page has a.css and b.css; node 1 has a.css, b.css and c.css. If using one aggregate then the user going from the front page to node 1 would have to download all of the CSS again. By splitting up the aggregate in a smart manner the user will only need to download c.css


Q:

Display view to right of text

I want to display text (track title) and a view to right of the text. Like on the image below.

The view (image on the screenshot above) should always be visible. The view should be displayed right after the text if there is more room than necessary. The text should be truncated if there is not enough room.
The issue is: if the text is long enough the view is not displayed or displayed in smaller size.
Please don't recommend me to use text view with a drawableEnd attribute because the view not always will be an image view.
Here is the layout I use:
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <TextView
        android:id="@+id/trackTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:lines="1"
        android:ellipsize="end"
        android:text="@string/placeholderTrackTitle"
        android:textSize="@dimen/track_name_height"
        android:textColor="@color/queue_text_color"
        android:layout_weight="0"/>

    <ImageView
        android:id="@+id/downloadedIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_downloaded"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/queue_horizontal_margin"
        android:layout_marginRight="@dimen/queue_horizontal_margin"
        android:layout_weight="1"
        android:contentDescription="@string/downloaded_icon_description"/>
</LinearLayout>

A:

Use the maxWidth attribute on the TextView and ellipsize the text in case of overflow.
edit: or MaxLength, MaxLines, or MaxEms, whichever works better for your purposes