text:
Q: GitLab CI/CD Generic configuration I have to setup almost the same pipeline for 30+ repositories in gitlab. The problem is that I can not find any possibility in gitlab that will let me to setup one pipeline using YAML and reuse it in all other repos with providing additional params.
As a sample, if I do it via Jenkins it is pretty straightforward, but unfortunately I'm not allowed to use anything apart from gitlab ci/cd.
Any ideas about generic pipelines in GitLab?

A: Have you considered causing each of your project pipelines to trigger a child pipeline? The child pipeline can be defined in a file in another project than the pipeline which triggers it. There are some details on parent-child pipelines here: https://docs.gitlab.com/ee/ci/parent_child_pipelines.html


text:
Q: Exception in scala when defining my own toInt method Why does this code throw an exception?
val x = new { def toInt(n: Int) = n*2 }
x.toInt(2)
scala.tools.nsc.symtab.Types$TypeError: too many arguments for method toInteger: (x$1: java.lang.Object)java.lang.Integer
        at scala.tools.nsc.typechecker.Contexts$Context.error(Contexts.scala:298)
        at scala.tools.nsc.typechecker.Infer$Inferencer.error(Infer.scala:207)
        at scala.tools.nsc.typechecker.Infer$Inferencer.errorTree(Infer.scala:211)
        at scala.tools.nsc.typechecker.Typers$Typer.tryNamesDefaults$1(Typers.scala:2350)
        ...

I'm using scala 2.9.1.final

A: Clearly a compiler bug (the compiler crashes, and REPL tells you That entry seems to have slain the compiler.). It's not signalling there's anything wrong with your code.
You're creating a single instance of type AnyRef{def toInt(n: Int): Int}, so creating a singleton object as Kyle suggests might be  a better way of going about it. Or create a named class / trait that you insantiate, which works fine.

A: EDIT: As Luigi Plinge suggested, it's a compiler bug.
Maybe you want something like this...
object x {
   def toInt(n:Int) = n * 2
}

scala> x.toInt(2)
res0: Int = 4

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intent ActionCall is not making phone call in xamarin forms I am working on a app that needs to call a certain phone number when the button is clicked i am using Xamarin Forms to do this here's my code:
IPhoneCall interface:
using System;
using System.Collections.Generic;
using System.Text;

namespace DirectCall.Model
{
    public interface IPhoneCall
    {
        void MakeQuickCall(string PhoneNumber);
    }
}

PhoneCallPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DirectCall.View.PhoneCallPage">
    <ContentPage.Content>
        <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
            <StackLayout>
                <Entry Placeholder="Enter the Your Phone Number" x:Name="Txt_PhoneNumber" WidthRequest="100" HeightRequest="40"/>
                <Button Text="ActionCall" x:Name="Btn_ActionCall" Clicked="Btn_ActionCall_Clicked" WidthRequest="100" HeightRequest="40"/>
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

PhoneCallPage.xaml.cs:
using DirectCall.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace DirectCall.View
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class PhoneCallPage : ContentPage
    {
        public PhoneCallPage ()
        {
            InitializeComponent ();
        }

        private void Btn_ActionCall_Clicked(object sender, EventArgs e)
        {
            try
            {
                if (Txt_PhoneNumber.Text == "")
                {
                    DisplayAlert("Alert", "Specify the number to start the call.", "OK");
                }
                else
                {
                    DependencyService.Get<IPhoneCall>().MakeQuickCall(Txt_PhoneNumber.Text.ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

PhoneCall_Droid interface implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using DirectCall.Droid;
using DirectCall.Model;
using Xamarin.Forms;

[assembly: Dependency(typeof(PhoneCall_Droid))]
namespace DirectCall.Droid
{
    public class PhoneCall_Droid : IPhoneCall
    {
        public void MakeQuickCall(string PhoneNumber)
        {
            try
            {
                var uri = Android.Net.Uri.Parse(string.Format("tel:+91{0}", PhoneNumber));
                var intent = new Intent(Intent.ActionCall, uri);
                Forms.Context.StartActivity(intent);
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(Android.App.Application.Context).SetPositiveButton("OK", (sender, args) =>
                {
                    //User pressed OK
                })
                .SetMessage(ex.ToString())
                .SetTitle("Android Exception")
                .Show();
            }
        }

    }
}

How to make an Action Call when clicking on Button? I'm getting the following error:
System.BadImageFormatException: Format of the executable (.exe) or library (.dll) is invalid

Target Framwork:.NET Standard 2.0
VisualStudio 2017

A: Xamarin forms has a direct method for the same :
   Device.OpenUri("tel:738284739");


text:
Q: Generating unattached dynamic components in Angular I went through this issue while working on the ScheduleJS framework. At some point I am provided with a HTMLCanvasElement which I want to replace with a dynamically generated component programatically. To do so, and to keep the code as clean as possible, I'd like to create my own Angular components at runtime and use the HTMLCanvasElement.replaceWith(component) method from the provided HTMLCanvasElement replacing the canvas with the dynamically created component.
Here is the Angular service I came up with, which does the job the way I expected:
import {ApplicationRef, ComponentFactoryResolver, ComponentRef, Injectable, Injector, Type} from "@angular/core";

import {ReplacementComponent} from "xxx"; // This is a higher order type of Component

@Injectable({providedIn: "root"})
export class DynamicComponentGenerator {

  // Attributes

  private _components: Map<string, ComponentRef<ReplacementComponent>> = new Map();
  private _currentKey: number = 0;

  // Constructor

  constructor(private _appRef: ApplicationRef,
              private _resolver: ComponentFactoryResolver,
              private _injector: Injector) { }

  // Methods

  create(componentType: Type<ReplacementComponent>): ComponentRef<ReplacementComponent> {
    const componentRef = componentType instanceof ComponentRef
      ? componentType
      : this._resolver.resolveComponentFactory(componentType).create(this._injector);
    this._appRef.attachView(componentRef.hostView);
    this._components.set(`${this._currentKey}`, componentRef);
    componentRef.instance.key = `${this._currentKey}`;
    this._currentKey += 1;
    return componentRef;
  }

  remove(componentKey: string): void {
    const componentRef = this._components.get(componentKey);
    if (componentRef) {
      this._appRef.detachView(componentRef.hostView);
      componentRef.destroy();
      this._components.delete(componentKey);
    }
  }

  clear(): void {
    this._components.forEach((componentRef, key) => {
      this._appRef.detachView(componentRef.hostView);
      componentRef.destroy();
      this._components.delete(key);
    });
    this._currentKey = 0;
  }

}

So basically this service lets me create a component with .create(ComponentClass) remove it by providing the component key .remove(key) and clear() to remove all the components.
My issues are the following:

*

*The ComponentFactoryResolver class is deprecated, should I use it anyways?

*Could not manage to use the newer API to create unattached components (not able to have access to an Angular hostView)

*Is there a better way to do this?

Thank you for reading me.

A: You could try using new createComponent function:
import { createComponent, ... } from "@angular/core";

const componentRef =
    createComponent(componentType, { environmentInjector: this._appRef.injector});
this._appRef.attachView(componentRef.hostView);


text:
Q: C++/QT: Using constant pointer to private member as read-only data-sharing I am writing a program in QT, which currently has a GameEngine class and a MainWindow class.
GameEngine.h:
#include "Player.h"

class GameEngine : public QObject
{
    Q_OBJECT

public:
    void test();

signals:
    void newPlayerDataReady(const std::vector<Player>* playerList);

private:
    std::vector<Player> mPlayers; // List of player objects
}

GameEngine.cpp
#include "GameEngine.h"

// Omitting constructor and destructor for simplicity of the example

void GameEngine::test() {
    emit newPlayerDataReady(&mPlayers);
}

The GameEngine is storing a lot of data in the array of Player instances (Player is a rather complex class itself with a lot of different members), which has to be stored there for centralizing the logic of the program (long-story short).
The MainWindow is a GUI class, which is supposed to visualize the data, when the signal newPlayerDataReady is emitted and represent a lot of the data on a graph, a list etc. This is done by connecting the signal to a dedicated slot in the MainWindow class. The connection is created in Main.cpp, which owns the instance of both classes.
So, my question is:
If I want to share all this data from one class to another without letting the receiver alter the data (read-only access), is there a better common practice to do this, rather than using constant pointers to the data?
It is not that I don't like this solution. I just want to be absolutely sure that I doing it right from the beginning instead of having to rework a lot later in the process.
I know that one alternative could be done exchange the data as copies of the private member, but I don't think it would be a smooth solution, as the amount of data will increase to a point, where it might affect the speed of the program.

A:
So, my question is: If I want to share all this data from one class to another without letting the receiver alter the data (read-only access), is there a better common practice to do this, rather than using constant pointers to the data?

Sharing via const-pointers is fine, although sharing a const-reference (i.e. const std::vector<Player> &) might be very slightly preferable, if only because any code receiving a const-reference can be 100% assured that any reference it receives isn't NULL, since NULL references aren't allowed by the language (whereas NULL pointers are allowed).
One other thing to consider is object-lifetime issues -- i.e. if you pass a const std::vector<Player>* to your MainWindow class, and the MainWindow class keeps a copy of that pointer-value (i.e. copies the passed-in pointer to a local member-variable), and then the vector is destructed, the MainWindow will be left holding a dangling pointer that will invoke undefined behavior (i.e. probably crash, or worse, silently corrupt your program's memory space in some very-hard-to-debug fashion) if/when it ever tries to dereference the pointer.  If you want to avoid any possibility of that particular fiasco, you can pass the data via a smart-pointer instead (i.e. either a shared_ptr, or if you prefer to use the Qt-specific APIs, a QSharedPointer or QPointer object)


text:
Q: Spring JPA Data: Custom Generic Repositories and Services: UnsatisfiedDependencyException I'm working on a restful service with a lot of entities. If we consider two groups of father resources and child resources, both group members has same implementation for CRUD operations in their group scope
So, there is not only one generic class for each layer. Here's my Code:
REPOSITORIES:
base repository which have methods used by all entities:
@Repository
public interface GenericRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
    Page<T> findAll(Pageable pageable);
}

father resources repository
@Repository
public interface EntityGenericRepository<T, ID extends Serializable> extends GenericRepository<T, ID> {
    T findByName(String name);
}

and child resources repository
@Repository
public interface NestedEntityGenericRepository<T, ID extends Serializable> extends GenericRepository<T, ID> {
    Page<T> findByFatherId(ID fatherId, Pageable pageable);
}

SERVICES:
for base:
public interface GenericService<T,ID extends Serializable> {
    Page<T> findAll(int page, int size);

    T findById(ID id);
}

for father:
public interface EntityGenericService<T, ID extends Serializable> extends GenericService<T, ID> {
    T findByName(String name);

    T save(T t);

    void update(ID id, T t);

    void softDelete(ID id);
}

and for child:
public interface NestedEntityGenericService<T, ID extends Serializable> {
    Page<T> findBySensorId(ID fatherId, int page, int size);

    T save(ID fatherId, T t);

    void update(ID fatherId, ID id, T t);

    void softDelete(ID fatherId, ID id);
}

SERVICE IMPLEMENTATIONS:
base:
@Service
public class GenericServiceImpl<T,ID extends Serializable>
        implements GenericService<T,ID> { //codes }

for father:
@Service
public class EntityGenericServiceImpl<T, ID extends Serializable>
        extends GenericServiceImpl<T, ID>
        implements EntityGenericService<T, ID> {//codes}

and for child:
@Service
public class NestedEntityGenericServiceImpl<T, U, ID extends Serializable>
        extends EntityGenericServiceImpl<T, ID>
        implements NestedEntityGenericService<T, ID> {//codes}

When I run it, it just throws UnsatisfiedDependencyException. The whole message:
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating
bean with name 'entityGenericServiceImpl': Unsatisfied dependency expressed through
field 'genericRepository': Error creating bean with name 'nestedEntityGenericRepository':
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
Not a managed type: class java.lang.Object; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'nestedEntityGenericRepository': Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

Searched a lot but found nothing that fix this issue. Any Help is appreciated
Regards

A: I fixed this Problem by creating concrete repositories for each entity.
I was trying to reduce number of classes. So I defined 3 generic repositories to do the job of all other repositories defined to serve all entities. But I understood it's impossible and concrete repositories must be defined in last level of custom repository for interaction with service layer.
The reason is reflection. Spring uses reflection to do all the behind the curtain and it must know for which entity it must use provider (Hibernate)
It's necessary to note that if you want to create generic service layer, it must have concrete implementation in its last level as well. because concrete repositories must be declared somewhere


text:
Q: when a python list iteration is and is not a reference Could someone please offer a concise explanation for the difference between these two Python operations in terms of modifying the list?
demo = ["a", "b", "c"]

for d in demo:
    d = ""

print demo
#output: ['a', 'b', 'c']

for c in range(len(demo)):
    demo[c] = ""

print demo
#output: ['', '', '']

In other words, why doesn't the first iteration modify the list? Thanks!

A: The loop variable d is always a reference to an element of the iterable object. The question is not really a matter of when or when isn't it a reference. It is about the assignment operation that you are performing with the loop.
In the first example, you are rebinding the original reference of an element in the object, with another reference to an empty string. This means you don't actually do anything to the value. You just assign a new reference to the symbol.
In the second example, you are performing an indexing operation and assigning a new reference to the value at that index. demo remains the same reference, and you are replacing a value in the container.
The assignment is really the equivalent of: demo.__setitem__(c, "")
a = 'foo'
id(a)  # 4313267976
a = 'bar'
id(a)  # 4313268016

l = ['foo']
id(l)  # 4328132552
l[0] = 'bar'
id(l)  # 4328132552

Notice how in the first example, the object id has changed. It is a reference to a new object. In the second one, we index into the list and replace a value in the container, yet the list remains the same object.

A: In the first example, the variable d can be thought of a copy of the elements inside the list. When doing d = "", you're essentially modifying a copy of whatever's inside the list, which naturally won't change the list.
In the second example, by doing range(len(demo)) and indexing the elements inside the list, you're able to directly access and change the elements inside the list. Therefore, doing demo[c] would modify the list.
If you do want to directly modify a Python list from inside a loop, you could either make a copy out the list and operate on that, or, preferably, use a list comprehension.
So:
>>> demo = ["a", "b", "c"]
>>> test = ["" for item in demo]
>>> print test
["", "", ""]

>>> demo2 = [1, 5, 2, 4]
>>> test = [item for item in demo if item > 3]
>>> print test
[5, 4]

A: When you do d = <something> you are making the variable d refer to <something>.  This way you can use d as if it was <something>.  However, if you do d = <something else>, d now points to <something else> and no longer <something> (the = sign is used as the assignment operator).  In the case of demo[c] = <something else>, you are assigning <something else> to the (c+1)th item in the list.
One thing to note, however, is that if the item d has self-modifying methods which you want to call, you can do
for d in demo:
    d.<some method>()

since the list demo contains those objects (or references to the objects, I don't remember), and thus if those objects are modified, the list is modified too.


text:
Q: Gaussian distribution with gaussian parameters Let $X \sim \mathcal{N}(M, S)$, where $M,S$ are themselves gaussian random variable with mean $\mu_{M,S}$ and variance $\sigma_{M,S}$.
Does this distribution have a particular name/form? Can we compute its CDF?

A: If S is Gaussian then it could be negative which does not work.  This problem is common in Bayesian statistics. Possibly specifying the precession $=1/S^2$ will work better. It will be easy to integrate out the M, this will just give a new Gaussian where the mean depends on $\mu_M$, $S$ and $\sigma_M$. Integrating out the S will be messy and possibly not possible.


text:
Q: Debian package : where is the right place to put temporary installation files? I am trying to build a binary package for Debian (with dpkg-deb --build) and I need to copy some files into the target machine to complete the installation with a postinst script (and remove them just after).
But I don't know where to put them.
I have tried /tmp/mypkg, /bin/mypkgtmp/, /usr/share/mypkg/tmp.
But Lintian has produced error/warning for all of them :

*

*dir-or-file-in-tmp

*arch-dependent-file-in-usr-share

*subdir-in-usr-bin
It's a directory with some binaries so the only place I can use seems to be /usr/bin/mh.
But /usr/bin/mh seems to be related to mail handling (not really clear).
What's the right place to put my temporary files without producing a Lintian error or warning ?
Here is my actual tree :
.tmp
├── DEBIAN
│   ├── control
│   └── postinst
└── usr
    ├── bin
    │   ├── mypkg
    │   └── mh
    │       └── mypkgtmp
    │           ├── build
    │           │   └── lib.linux-x86_64-3.4
    │           │       ├── myClib.cpython-34m.so
    │           │       └── mytools.py
    │           └── setupCython.py
    └── share
        └── doc
            └── mypkg
                ├── changelog.gz
                └── copyright

Thx.

A: You can put files in /usr/lib/mypkg/ and just leave them there even if they are not necessary or useful after postinst.
There is a (weak) hint that the packager may opt for convenience to use this for both architecture-independent and architecture-dependent files in Policy section 9.1.1 though of course your specific postinst scenario isn't covered there.

A: Keep them inside the source directory. Maybe there you create there a tmp. Object file (.o) and other intermediate file are generated and keep there. Just do no put them in the output directory $(DESTDIR), so they will not be included in the package. And do no put outside building directory, so that building tools have no problems insulating your package from the rest of build system).

A: If the files are only useful to the postinst script, perhaps you could simply embed them into it? A here document is a convenient way to keep a set of data chunks inside your script (maybe base64-encoded or similar if they are not plain text).
#!/bin/sh
set -e
t=$(mktemp -t -d mypostinst.XXXXXXXXXX) || exit
trap 'rm -rf "$t"' EXIT ERROR INT HUP TERM
cat <<\: >"$t"/somedata.txt
some
verbatim
text
:
base64 <<\: >"$t"/somebinary.dat
deadbeefc0ffeeman===
:

If your needs are slightly more complex, maybe also look into shar.


text:
Q: how to bottom align div using css? I have div which have some text content. I want to make that div  align to bottom . or in other words it bottom never change when text grow .
here is my code
https://codepen.io/naveen-1234/pen/ExXNRbZ
when I have small text it looks good

but when my text increase it overflow the container like this

but the expected output is it should grow in upward direction
Expected output

is there any way in css grid using minmaxval or auto-fit or auto fill to grow div in upward direction .?
.abc{
  display:grid;
    grid-template-columns: repeat(12,6.697%);
    grid-template-rows: 18px repeat(4, 1fr);
   border:1px solid green;
  height:320px
}
.one{
  grid-column: 2/5;
   grid-row: 3/5;
    border:1px solid;
}
.two {
  grid-row: 1/5;
    border:1px solid #ee0;
}

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates culpa iste facaudantium Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates culpa iste facaudantium
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates culpa iste facaudantium
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates culpa iste facaudantium

    tooo

A: Add this changes:
.abc{
  height: auto;
}
.one{
  grid-row: 1/5;
  display: flex;
  align-items: flex-end;
}

A: I guess this is what you are looking for. as far as my understanding the requirements are for the container to start from the end of the todo container and grow upwards, this css fulfills the requirements
.abc{
  display:grid;
height:auto;
    grid-template-columns: repeat(12,6.697%);
    grid-template-rows: 18px repeat(4, 1fr);
   border:1px solid green;
  /* height:320px */
}
.one{
  grid-column: 2/5;

  grid-row-start: 4;
  grid-auto-flow: row;
    border:1px solid;
  display: flex;
  height: fit-content;
  background-color:red;
  justify-content: center;

}
.two {
  grid-row: 1/5;
    border:1px solid #ee0;
}


text:
Q: Fails to run Rspec due to Reform error: "undefined method `feature' for Reform::Form:Class (NoMethodError)" I'm just trying to run some tests, and I get this error:
undefined method `feature' for Reform::Form:Class (NoMethodError)

It happens in /usr/local/bundle/gems/reform-2.2.3/lib/reform/form.rb:75,
that line in form.rb is the first time the DSL word feature is used.
Of course this does not happen when I run my rails app but only when I run rspec..
It is defined in the Disposable gem used by reform. At first I thought that the problem is with an older version of rspec but even after I updated to the latest versions, things are still broken. Reading the code or documentation did not lead me to any specific behavior of loading that is different between tests and application runs.
The versions of gems I use are:
rspec-3.3.0, reform-2.2.3, disposable-0.3.2
Does anyone have a clue?
-- Update --
After removing the entire test framework (removing RSpec and deleting all related files) and installing again I got to the point that RSpec is running by itself but when trying to load my environment in the test file it fails on the same error.

A: Well, the problem was that we added an override of Reform's Contract and did not do it too gracefully, thus not requiring all the things the original Reform Contract required. As a fix we now created a base
Contract that inherits from Reform::Contract instead of overriding it and now all works well. The only reason we found it when running RSpec and not in running Rails c is because of different loading order of things.


text:
Q: Match column name to data in MYSQL I have data like in table.
Item | 7/7/15 | 7/8/15 | 7/9/15
  1  |   23   |   24   |   25
  2  |   26   |   74   |   96

and
I have table which has,
Item |  Date   | Number
1    | 7/9/15  | 56
1    | 7/7/15  | 75
1    | 7/8/15  | 63

I want to find sum of Number from 7/7/15 to 7/8/15 from table 1 and sum of the number from second table.
My table should look like
Item | StartDate | EndDate | no. | TotalNumber

A: item 7/7/15 7/8/15  7/9/15
1   23      24     25
2   26      74     96

item date number
1   7/9/15  56
1   7/7/15  75
1   7/8/15  63

.
SELECT
    i1.Item,
    '7/7/15' AS "StartDate",
    '7/8/15' AS "EndDate",
    (SELECT SUM(`7/7/15`)+SUM(`7/8/15`) FROM table1 WHERE item=i1.item) AS no,
    (SELECT SUM(number) FROM table2 WHERE item=i1.item) "TotalNumber"
FROM
    table2 i2
RIGHT OUTER JOIN table1 i1 on i1.item=i2.item;
item startdate enddate no TotalNumber
1   7/7/15     7/8/15  47     194
1   7/7/15     7/8/15  47     194
1   7/7/15     7/8/15  47     194
2   7/7/15     7/8/15  100

.
It's working..


text:
Q: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG) I'm on visual studio 2015 trying to use a com object. The com object is srxCOM.dll to call the API of the titan ftp server.
Some documentation here
Download here (I installed the 64bit version)
Now what I've done is:

*

*List item

*Install the titan ftp server

*Register the com object (both from windows\system32 and windows\syswow64 as well) succeeded and can be found in the registry

*Add the reference to the COM object

*Add some code (Dim srxcom As New SRXCOMLib.SRXTitanClass())

*Set solution is set to compile to "Target CPU: x86"

*Start in debug mode.

Then I get the error telling me that the class is not registered although it clearly is. Did anyone work with Titan FTP in the past and share some tips?
Thanks

A: Okay I figured out what the problem was. Essentially when you open the project file (.proj) of visual studio in a text editor you'll find all the settings etc in XML format. So I did that and found the line that specifies the target CPU:
<PlatformTarget>AnyCPU</PlatformTarget>

Removed the line and it started working.


text:
Q: brightness control with ddcci and gnome slider I have connected an external touch to my mini pc. DDCCI module seems to work for me.
eg
echo 90 > /sys/class/backlight/ddcci5/brightness

results in a change of brightness. But unfortunately I cannot use the slider. The slider still controls intel_backlight. How can I change the slider to ddcci5? Is there a way to suppress the intel device to be populated during startup? acpi_brightness=none didn't work out.
Thanks for any hint


text:
Q: Client side connection issues need help I'm having issues connecting to a Web based Sharepoint share. When I attempt to connect to the server it appears to reject my username and password. It appears to be an issue with the image on our Desktops, as other systems that are not using this image can connect(from our network). The login box pops up, I enter in the username/password and then it immediatley pops back up again almost as if the user name/PW has been rejected.
The sharepoint that I am trying to connect to is on a seperate Domain that has nothing to do with us.
I'm not really sure what I am missing. Our client side machines are Windows XP SP3. Any ideas or tips would be greatly appriciated.

A: If it's on a separate domain, then you'll probably need to login with the appropraite domain\username and password in your authentication prompt that the SharePoint site is expecting.
You can also login with your full email address and password.


text:
Q: Causes of a Mac's SuperDrive refusing to accept blank DVDs My iMac (quad-core i7 2.93 GHz, 27") frequently refuses to accept blank DVDs when I insert them for burning.  What could be the cause of this?  The machine is just over two years old now; does dust build up in there?
OS is Mountain Lion (10.8.0).

A: I had a similar problem. It accepts DVDs and CDs but spat out some software disks.
A solution that worked for me was to tilt iMac backwards (at least 90°)  and then insert the disk.
This loaded fine!


text:
Q: To find the limit of a given function Find the limit of $$\lim_{(x,y)\to (0,0)}\sin{\frac{y}{x}}$$
I found out that the function tends to $0$ as $\left|\sin{\frac{y}{x}}-0\right| <1$, but I am not sure whether the method is correct or not.

A: Let $f(x,y):= \sin (y/x)$ for $x \ne 0$.
Then we have $f(0,x)=0 \to 0$ as $x \to 0$ and $f(x,x)= \sin(1) \to \sin(1)$ as $x \to 0$.
Hence, $\lim_{(x,y) \to (0,0)}f(x,y)$ does not exist !

A: We have that

*

*$x=y=t \to 0$
$$\sin{\frac{y}{x}}=\sin 1 \to \sin 1$$

*

*$x=t,\,y=t^2,\, t\to 0$
$$\sin{\frac{y}{x}}=\sin t \to 0$$
therefore the limit doesn't exist.


text:
Q: How to use smarty to translate a website? I want to use SMARTY to make a multi langage website.
I read this article:
http://www.freesoftwaremagazine.com/articles/creating_multilingual_website_smarty
However it does not work with smarty3 and I don't know exactly how these configs work: I am new to smarty.
ex: my website content is now
hello world, how are you
Can I use spaces in my variables so, I don't have to rewrite it all like:
{$hello_world_how_are_you}
but I would rather keep something like
{hello world, how are you}
or
/#hello world, how are you#/
To avoid to rewrite slugs to each phrase I have to translate

A: You can use array syntax
For example
{$lang['hello world, how are you']}

This have another advantage that you don't pollute your variable scope.


text:
Q: Error Domain=AVFoundationErrorDomain Code=-11800 i have a problem downloading file from url end export it in device "https://sdkapis.ringme.vn:8443/sdk/fileupload/2022/12/15/2cc0f2058e1c7b8f655ca6f9a04b42d9.aac" , i download it and store it but it is working error occurs in exportSession?.exportAsynchronously

error : Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x28164f060 {Error Domain=NSOSStatusErrorDomain Code=-16979 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-16979), NSURL=file:///var/mobile/Containers/Data/Application/96A04F25-2F8D-4CE5-A2E9-D67884A318FD/Library/Caches/tmp_audio.m4a, NSLocalizedDescription=The operation could not be completed}
func downloadFile(_ messageFile: Message) {
        guard let fileUrl = messageFile.mediaLink, let offline_url = messageFile.offline_url else {
            return
        }

        let tmpFileUrl = URL.init(fileURLWithPath: self.cachePath(with: "tmp_audio"))

        self.updateDownloadFile(messageFile, isSuccess: nil)
        if self.listDownloadingFile.firstIndex(of: messageFile.messageId) != nil {
            return
        }

        self.listDownloadingFile.append(messageFile.messageId)
        HttpClient.shared.requestData(fileUrl, method: .get) { [weak self] (data, error) in
            if let data = data {
                do {
                    try data.write(to: tmpFileUrl)

                    let audioAsset = AVURLAsset.init(url: tmpFileUrl, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])
                    let exportSession = AVAssetExportSession.init(asset: audioAsset, presetName: AVAssetExportPresetAppleM4A)
                    exportSession?.outputURL = offline_url
                    exportSession?.outputFileType = AVFileType.m4a

                    exportSession?.exportAsynchronously(completionHandler: {
                        DispatchQueue.main.async {
                            if exportSession?.error == nil || exportSession?.status == AVAssetExportSession.Status.completed {
                                self?.updateDownloadFile(messageFile, isSuccess: true)
                            }
                            else {
                                self?.updateDownloadFile(messageFile, isSuccess: false)
                            }
                        }
                    })
                } catch {
                    RingmeLog.shared.error(error)
                    self?.updateDownloadFile(messageFile, isSuccess: false)
                }
            }
            else {
                self?.updateDownloadFile(messageFile, isSuccess: false)
            }
        }
    }

I tried many ways but it doesn't work


text:
Q: Is it possible to set a default value for a parameter of a function in Dart? Like in JS, we can define default values like,
function location(lat = 20, lng = 20) {}

Can we set such default values like lat and lng in Dart? If yes, how? If no, why?

A: You can set default values on optional parameters.
// optional positional parameters
location([num lat = 20, num lat = 20]) {}
// optional named parameters
location({num lat = 20, num lat = 20}) {}

Note that the default values must be compile-time constants.


text:
Q: How to run scheduled Coded UI Tests on Virtual Machine without having a RDP connection Situation in short:

*

*Virtual Machine with Visual Studio 2013 installed. PowerShell script
runs on the VM to execute Get Latest, Build and Execute Coded UI
Tests. Windows Scheduled Task to execute PowerShell nightly.

*auto-logon is enabled (or I'm doing something wrong?)

*yes, I've read post Is it possible to run Coded UI tests without having to connect via remote desktop?

*I've seen posts about TCM. Does this help and how can I use it in my
situation?

I made some tests in Microsoft Test Manager and I also executed and recorded them.
I've loaded these tests in a test project (and changed the script providing categories and custom checks).
I then categorized these (as Development or Acceptance).
I executed out using a PowerShell script on a VM (with Visual Studio 2013 installed) with following actions:

*

*Get Latest

*Build

*Run latest build with a selected set aka category using mstest.exe

So far everything is going perfectly. All the tests pass.
However, when I create a Scheduled Task on my VM run the PowerShell script everything fails because of a missing session.
Do I have the VM (I have no knowledge of Virtual Machines) then unlock or something?
Side-Note:
I also tried to fix this with a Test Agent and Controller, but once I had installed these, all other users of TFS lost their rights, so I prefer not to do this again.
I would be very grateful if you know something that can solve this.
I spent hours on Google finding a solution for this issue, but no solution helped me.
Do I need to provide more information?

A: The problem you're seeming to have is that the testagent is not setup correctly. You need an active desktop session for Coded UI to be able to run (it needs it to perform all the actions such as clicks).
Microsoft has some nice info about setting up your test agent here.
But to tackle your exact problem of the test failing because of a missing session I'd suggest the following:

*

*Run AutoLogOn.exe from the sysinternals suite (can be found at http://live.sysinternals.com/). It will automatically log in with specified user when the machine starts, and keeps the desktop session active.

A: Alright...I'm making progress.
I've installed test agent and controller. It's all running fine.
Next I've opened Lab Center on my own MTM to create a new environment.
Test Controller is found, but I receive the message in this post "Microsoft Test Manager cannot install test agent on these machines" when creating new Lab Center environment
File and Printer sharing exception is enabled. I don't get the other message.
I don't understand what is wrong.
Maybe I'm completely on the wrong track and it's not necessary to use the Lab Center.
Then the only remaining issue is the non-active desktop issue.


text:
Q: run Qt app with dependent libraries on mac with no admin rights I am trying to build and run (and fix) an application that was written in Qt 4.8 for windows and then built on Linux. Trying to run it on Mac now.
The app requires certain lib dependencies - some of them built separately that I have control over, and a couple purchased sdks.
I can build the app fine, having set the location of all the dependent dylibs in the pro file.
Unfortunately I cannot execute the app, because the linker doesn't know where my dependencies are located... i guess it ignores my pro file.
I have tried to place the dependent dylibs in the same directory as the app (which I built either as a bundle or not) but I am still getting an error about missing dependencies.
I have read that I can put my libs in places where the linker will automatically find them, like /usr/local/lib. Unfortunately I don't have admin access. is there any other place to place them ?
What I am trying right now: packaging it, using the install_name_tool ... it is very tedious and I don't know if it will work... But that means I will have to run the packaging steps every time I rebuild the app - which is likely lots of times !
What can I do to place my dependencies in a location that the linker will find, with no access to sudo ? (or unable to view System folders... though I seem able to ls from terminal....very odd that I can... but no write rights on system folders)
Or what tool can I use on mac, with no admin rights, to make linker recognize a path to he libraries ?

A: I am following this answer
http://qt-project.org/forums/viewthread/5469:
macx {
 LIBS += ../mylib/mylib-build-desktop/mylib.dylib

 PRE_TARGETDEPS = ../mylib/mylib-build-desktop/mylib.dylib

 mylib.path = Contents/MacOS
 mylib.files = ../mylib/mylib-build-desktop/mylib.1.dylib
 QMAKE_BUNDLE_DATA += mylib
}


text:
Q: Private interfaces within a package This is basically the same as Coding to interfaces, but played out in the real world of com when there are various engineering complexities such as immutability of published interfaces and implementations, etc.

Consider the following situation:
A OS-level object-oriented library with a set of published interfaces and an implementation provided by the OS.
Some extension points are provided so that third parties can extend specific behaviors by implementing a subset of the published interfaces and registering them with the OS.
A programmer looks at the whole set of published interfaces, and says to self, "it seems like I can re-implement most of the functionalities (with better algorithms), including those areas which aren't designated as extensible." And so the programmer worketh.
Only when the programmer's own implementation mash up (COM-style) with the OS implementation and fails miserably, did the programmer realize that the suite of objects as implemented by the OS rely heavily on communications using non-published interfaces, because the published interface was minimalistic and blocked many opportunities to optimizations(*).
(*) In encoding/decoding/trans-coding (of data/image/sound/video compression) tasks, it is well known that certain pipelines stages can cancel each other if they perform the exact opposite operation / inverse, e.g. G(F(x)) == x.
A typical interaction is like:

*

*Consumer asks Producer if it implements a special interface X that only vendor V knows.

*If yes, Consumer talks to Producer using interface X and see if they are exact opposite (#1).

*If yes, Consumer asks Producer for its "upper stage" (i.e. bypassing Producer) (#2) so that in effect both are being cancelled out.

(#1) and (#2) are capabilities that are missing in the minimalistic published interface. On first glance it seems that the vendor might have a chance to provide them as well, but choose not to.
It might also be the case that providing those performance-oriented interfaces would severely pollute the namespace.

The end result is that whenever a programmer provides its own implementation of a certain class, it would either (i) fail miserably, or (ii) perform very slowly, because it could not interact with the rest of the suite using the performance-enhanced internal interfaces only known to that suite.
Is this a more frequent problem with some flavors of Object-Oriented technology? Or is it more common with some flavors of Component-based Engineering?
Advocates of OOP will argue that Refactoring and Publishing those interfaces would solve the problem. This assumes that it is possible to distribute a new version of the library along with new set of interface. For some technology this is not possible.

The way it matters to com is that its QueryInterface method allows run-time query (and run-time response) of additional interfaces implemented by a class. Its Java equivalent would be like a library that makes heavy use of instanceof for interfaces internal to the package.
To Reviewers: I'm open to suggestions on trimming down the question to its essence.
The correct term seems to be Mixin, thanks to this question.

This answer is partly relevant, but my example focuses on the lost opportunities for optimizations within a single library. Basically, if a third-party implementer didn't do both:

*

*Implement both encoder and decoder

*Implement its own proprietary interface on both the encoder and decoder, in order to detect and bypassing operations that cancel out each other

Then the implementation will only get "baseline performance" when inter-operating with different encoders/decoders from other vendors.

A: As a general rule, Public API should not change over time (or should at least be stable) so that existing applications that depends on them doesn't break while more functionality for additional applications are supported.
On the contrary, Private API should be allowed (nearly freely) without which it is not quite possible to effectively bring that evolution we really need.
If you are finding that given Public API is cause of bottleneck, then it is the issue with the prior API at the first place. In your specific case, for transcoding example (which is what i work on), the Encoding API and Decoding API should NOT change, but both modules should have additional API that support transcoding.
Of courses, within such API, the change should be controlled such that internal/private classes don't arbitrary change their roles/ else there are chances to break the original behavior.

Is this a more frequent problem with some flavors of Object-Oriented
  technology? Or is it more common with some flavors of Component-based
  Engineering?

NO. It's only dependent on the design not inherently a limitation of OO or Components.


text:
Q: cognos 8 - how to get a set of more sets I have created a report , and faced some problem
i have a course reference number that have many sections
and have meeting type
the course reference number may have an Exam and Class
for example
course reference Number    Meeting type
12345                       class
12345                       Exam

and some courses reference number doesn't have at all exam
only class
how to retrieve and extract only the reference number that doesn't have exam at all ..

A: Can we assume if there is just one [Meeting Type] that it is "Class", and two would be "Class", "Exam"? If so, create a data item which is count([Meeting Type]). Next, create a summary filter where count([Meeting Type]) = 1
If a course can have one [Meeting Type]  that is either "Class" or "Exam", I would do through two queries. It can't be done in just one query (without the use of custom SQL). Conceptually, first query is Courses of type "Exam". Second query is all Courses. Connect them using the "Except" operator in the Toolbox.


text:
Q: What to commit when using Carthage? This is my first time using Carthage! I'm using a library called "https://github.com/LeoNatan/LNPopupController" and I got it to work on my project. The issue is I want to commit these changes but when I do I got a popup saying that a certain file was bigger then 10MB!
The question again is, What are you suppose to commit and not commit when using Carthage?
Picture of such file:

On source tree:

A: The Carthage/Carthage issue 393 covers this.
It refers to github/gitignore/Swift.gitignore as a possible example:
# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts/

Carthage/Build/

This leaves Cartfile, Cartfile.private, and Cartfile.resolved to be committed.
But: do refer to the Carthage Artifacts page:
For the Checkouts folders:

You are not required to commit this folder to your repository, but you may wish to, if you want to guarantee that the built versions of each dependency will always be accessible at a later date.

So in your case, it is simpler to add Carthage/Checkouts/ to your .gitignore.
Then SourceTree won't list all those files as unstaged.


text:
Q: Spring data JPA throwing duplicate key value violates unique constraint I am using Spring data JPA in my application. From design the save() of Spring Data makes an insert in DB when the element is not present in DB and performs an update when the PK of that element is given.
The problem in this case is happening when the PK is present. To my surprise sometimes I get a

ERROR: duplicate key value violates unique constraint...

How is this even possible to be thrown since Spring Data should make an update in this case? Anyone else faced the same issue? How did you fixed it?
EDIT:
Entity:
@Entity
@Table(name = "table_name")
public class Entity {

  @Id
  @Type(type = "pg-uuid")
  private UUID id;
  @Column(name = "name")
  private String name;
  @Column(name = "surname")
  private String surname;
  ...
}


text:
Q: DropWizard JAR Signing Bug I am trying to unit test my DropWizard 0.7.0 app, just like the docs recommend:
@Test
public void runRegisertsLocationResource() {
    given:
    Environment environment = Mockito.mock(Environment)
    JerseyEnvironment jersey = Mockito.mock(JerseyEnvironment)
    MyApplication fixture = new MyApplication()
    MyConfiguration config = new MyConfiguration()

    Mockito.when(environment.jersey()).thenReturn(jersey)

    when:
    fixture.run(config, environment)

    then:
    Mockito.verify(jersey).register(Mockito.any(LocationResource))
}

When I run this I get:
java.lang.SecurityException: class "javax.servlet.DispatcherType"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:952)
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:666)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:794)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at io.dropwizard.Configuration.<init>(Configuration.java:62)
    at io.auditcloud.micros.backend.service.config.BackendConfiguration.<init>(BackendConfiguration.groovy)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:102)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:57)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:182)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:186)
    at io.auditcloud.micros.backend.service.BackendApplicationTest.runRegisertsAllProviders(BackendApplicationTest.groovy:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Here are my dependencies defined inside build.gradle:
dependencies {
    compile (
        'com.codahale.metrics:metrics-core:3.0.2',
        'com.codahale.metrics:metrics-json:3.0.1',
        'com.wordnik:swagger-jaxrs_2.10:1.3.4',
        'io.dropwizard:dropwizard-core:0.7.0',
        'io.dropwizard:dropwizard-auth:0.7.0',
        'org.apache.commons:commons-lang3:3.3.2',
        'io.dropwizard:dropwizard-client:0.7.0',
        'org.eclipse.jetty:jetty-servlets:8.1.14.v20131031',
        'com.google.inject:guice:3.0'
    )

    testCompile(
        'org.mockito:mockito-all:1.9.0'
    )
}

What's going on here?

Update: How to reproduce (step by step)

*

*Create a new DropWizard project and use the exact dependencies mention above (I use Gradle but whatever works should be fine).

*Create a new JUnit test class, say, under src/test/java, and make it look exactly like my JUnit test above, except replace MyApplication with whatever is the name of your DropWizard app's main class, and replace MyConfiguration with the respective configuration impl. Note: my app is written in Groovy, hence the Groovy syntax; you may need to "Java-ify" my code snippet above to get it to compile.

*Run the test; you should get the same exception as I have posted above.

A: Edit: See UPDATE below
This is not an answer. Please don't vote on it. It will be deleted upon confirmation from the OP
So I'm wondering if you have tested the above steps for yourself. I followed the steps as you've stated, of course creating my own classes (super simple with little to no implementation, since you haven't specified any. And I don't get the result you are experiencing. I am also using Maven and Java. Whether or not the problem is with groovy, I am not sure, as I am not a groovy user.
Below you will find my Minimal, Complete, and Verifiable example (MCVE) implementation of your step-by-step. I suggest you create something similar that reproduces the problem. Create a project from scratch, as you have described (maybe using the below example as a starting point), then start adding features until it reproduces the problem. This is also a good way to discover the root of the problem yourself.
I would start with a simple Groovy project, and if a simple project, like the one below causes the problem, then it may be a Groovy problem, and you should edit your post with the MCVE so others familiar with Groovy can try and find the problem.
If it's not a Groovy problem, and you discover the problem by building on top of my MCVE, and you can't figure out the cause and how to fix it, then please do post the MCVE also.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.stackoverflow.spring</groupId>
    <artifactId>dropwizard-stackoverflow</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <dropwizard.version>0.7.0</dropwizard.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-core</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-auth</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-client</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-json</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

MyConfiguration
import io.dropwizard.Configuration;

public class MyConfiguration extends Configuration {}

MyApplication
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;

public class MyApplication extends Application<MyConfiguration> {
    @Override
    public void initialize(Bootstrap<MyConfiguration> btstrp) {}

    @Override
    public void run(MyConfiguration t, Environment e) throws Exception {
        e.jersey().register(new LocationResource());
    }
}

LocationResource
import javax.ws.rs.Path;

@Path("/location")
public class LocationResource {}

Test
import dropwizard.stackoverflow.resource.LocationResource;
import io.dropwizard.jersey.setup.JerseyEnvironment;
import io.dropwizard.setup.Environment;
import org.junit.Test;
import org.mockito.Mockito;

public class SimpleDropWizardTest {
    @Test
    public void runRegisertsLocationResource() throws Exception {

        Environment environment = Mockito.mock(Environment.class);
        JerseyEnvironment jersey = Mockito.mock(JerseyEnvironment.class);
        MyApplication fixture = new MyApplication();
        MyConfiguration config = new MyConfiguration();

        Mockito.when(environment.jersey()).thenReturn(jersey);

        fixture.run(config, environment);

        Mockito.verify(jersey).register(Mockito.any(LocationResource.class));
    }
}

Test Result

UPDATE
So I seem to have made my MCVE incorrectly. For some reason I missed
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-servlets</artifactId>
    <version>8.1.14.v20131031</version>
</dependency>

And it just so happens, this appears to be the the smoking gun. When I added this dependency to the above project, I would get a similar exception, which was not exactly the same, but detailed the same problem during class loading.
If you get rid of this dependency, it will work with the above example. Seems to be a conflict of versions. Dropwizard is already dependent on Jetty 9.0.7.v20131107. You can see the Maven dependency tree
[INFO] +- io.dropwizard:dropwizard-core:jar:0.7.0:compile
...
[INFO] |  +- io.dropwizard:dropwizard-jetty:jar:0.7.0:compile
[INFO] |  |  +- com.codahale.metrics:metrics-jetty9:jar:3.0.1:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-server:jar:9.0.7.v20131107:compile
[INFO] |  |  |  \- org.eclipse.jetty:jetty-io:jar:9.0.7.v20131107:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-servlet:jar:9.0.7.v20131107:compile
[INFO] |  |  |  \- org.eclipse.jetty:jetty-security:jar:9.0.7.v20131107:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-servlets:jar:9.0.7.v20131107:compile
[INFO] |  |  |  \- org.eclipse.jetty:jetty-continuation:jar:9.0.7.v20131107:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-http:jar:9.0.7.v20131107:compile

Basically when you declare a top level dependency (as you have with Jetty), it will supersede any transitive dependencies. So you have a Jetty 9.0.7 artifacts trying to interact with your declared 8.1.14 servlets artifact.


text:
Q: LINQ to Objects Performance - Huge dataset for long running process I have a detail list (200,000 records) which was pulled from database and I need to find the locations for each detail and below is the code which is looping through the detail list and assigning location to the list. This loop is taking more than 15 minutes to execute but if don't populate the Locations property then it takes less than a minute.
How can I optimize this code?
class Program
{
    static void Main(string[] args)
    {
        List<Details> databaseDetailList = GetDetailsFromdatabase();
        List<Location1> databaseLocation1List = GetLocations1Fromdatabase();
        List<Location2> databaseLocation2List = GetLocations2Fromdatabase();

        List<Details> detailList = new List<Details>();
        foreach (var x in databaseDetailList)
        {
            detailList.Add(new Details
            {
                DetailId = x.DetailId,
                Code = x.Code,
                //If I comment out the Locations then it works faster
                Locations = new LocationIfo {
                    Locations1 = databaseLocation1List
                                .Where(l=>l.DetailId == x.DetailId && l.Code == x.Code).ToList(),
                    Locations2 = databaseLocation2List
                                .Where(l => l.DetailId == x.DetailId && l.Code == x.Code).ToList()
                }
            });
        }
    }

    private static List<Details> GetDetailsFromdatabase()
    {
        //This returns 200,000 records from database
        return new List<Details>();
    }

    private static List<Location1> GetLocations1Fromdatabase()
    {
        //This returns 100,000 records from database
        return new List<Location1>();
    }

    private static List<Location2> GetLocations2Fromdatabase()
    {
        //This returns 100,000 records from database
        return new List<Location2>();
    }
}

public class Details
{
    public string DetailId { get; set; }
    public string Code { get; set; }
    public LocationIfo Locations { get; set; }
}

public class LocationIfo
{
    public List<Location1> Locations1 { get; set; }
    public List<Location2> Locations2 { get; set; }
}

public class Location1
{
    public int LocationId { get; set; }
    public string DetailId { get; set; }
    public string Code { get; set; }
    public string OtherProperty { get; set; }
}

public class Location2
{
    public int LocationId { get; set; }
    public string DetailId { get; set; }
    public string Code { get; set; }
    public string OtherProperty { get; set; }
}

A: What you're doing conceptually here is a Join.  Using the proper operations will ensure that it executes much more effectively.  Ideally you would even be doing the Join on the database side of things, rather than after pulling all of the data down into lists, but even if you do pull all of the data down, joining it in memory using Join will be much more efficient.
var query = from detail in databaseDetailList
            join location1 in databaseLocation1List
            on new { detail.DetailId, detail.Code }
            equals new { location1.DetailId, location1.Code }
            into locations1
            join location2 in databaseLocation2List
            on new { detail.DetailId, detail.Code }
            equals new { location2.DetailId, location2.Code }
            into locations2
            select new Details
            {
                Code = detail.Code,
                DetailId = detail.DetailId,
                Locations = new LocationIfo
                {
                    Locations1 = locations1.ToList(),
                    Locations2 = locations2.ToList(),
                }
            };

A: This is a bit hacky - but you could use lookups:
If it's the look-up portion of your code that is taking the longest - and you can't change the database code, as suggested with a Join - you could consider indexing your Location return-types in an in-memory Lookup.
Build a Lookup key, that's a combination of your two values - this will need to be specifically unique, dependent on your requirements.
DetailId-Code - "123123-343"

private static ILookup<int, Location1> GetLocations1Fromdatabase()
{
    //This returns 100,000 records from database
    return new List<Location2>()
        .ToLookup(l => l.DetailId + "-" + l.Code);
}

Then:
Locations1 = databaseLocation1List[l.DetailId + "-" + l.Code].ToList()

A: This is a very similar problem I faced a couple of days ago (in Ruby).
Finally the best solution I found was to convert the List(or Array) into a Dictionary(or Hash)
Create a Dictionary with your searching fields concatenated as a key and your list item as as value:
var dict1 = databaseLocation1List.ToDictionary(x => x.DetailId.ToString() + x.Code.ToString(), x);

And then the search in the Dictionary by key will be very fast:
Locations1 = dict1[x.DetailId.ToString() + x.Code.ToString()].ToList()


text:
Q: Reading a text file to a HashMap in Java I have a text file in the following format:
Student1 Marks
Student2 Marks

The first column is the key.
This is what I have tried so far
Scanner scanner = new Scanner(new FileReader("marks.txt"));

    HashMap<String,Integer> map = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split("\t");

        map.put(columns[0],columns[1]);
    }

    System.out.println(map);

}

A: Just make sure you parse the marks and that the values are indeed tab separated, otherwise code worked for me right away
    Scanner scanner = new Scanner(new FileReader("marks.txt"));

    HashMap<String,Integer> map = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split("\t");

        map.put(columns[0],Integer.parseInt(columns[1]));
    }

    System.out.println(map);

A: (With a little help from the comments) your code should be reading into the HashMap already, so i assume your problem is printing the HashMap after reading it in.
System.out.println(map) only gives you the representation of the map object.
I suggest reading this:
Convert HashMap.toString() back to HashMap in Java
To print all elements of that HasMap you could iterate over it, like shown here: Iterate through a HashMap


text:
Q: Jest - unexpected identifier - Component testing w Jest react-native I keep getting this error when trying to test a button component. I have changed Jest's config settings here and there but nothing has worked, can anyone tell me the answer so I can stop pulling my hair out?
I am using expo to demo the app, the problem seems to lie within the font that it's trying to render on the nav button, Jest/React doesn't understand it.
The failure:
 FAIL  tests/Components/NavigationButton.test.js
  ● Test suite failed to run
C:\..\node_modules\@expo\vector-icons\Zocial.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Zocial from './build/Zocial';
                                                                                ^^^^^^

SyntaxError: Unexpected identifier

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.<anonymous> (node_modules/react-native-elements/src/helpers/getIconType.js:1:1)

NavigationButton.js:
import React from "react";
import { StyleSheet } from "react-native";
import { Button } from "react-native-elements";
import Icon from "react-native-vector-icons/FontAwesome";
import { withNavigation } from 'react-navigation';

const NavigationButton =(props) => {
    return (
        <Button data-test="nav_button"
        icon={<Icon name={props.icon} size={30} color="white" style={styles.iconStyle} />}
        raised
        color="white"
        buttonStyle={styles.button}
        title={props.title}onPress={() => props.navigation.navigate(props.navName)}
    />
    );
};

const styles = StyleSheet.create({
    button: {
        minWidth:150,
        alignSelf:'center',
    },
    iconStyle:{
        marginHorizontal:10
    }
});

export default withNavigation(NavigationButton);

NavigationButton.test.js:
/**
* @format
*/

import 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAtt } from '../../Utils/test_utils';
import NavigationButton from '../../src/Components/NavigationButton'

// Note: this is just for use with Jest snapshot testing
// and comes packaged with react-native init project.
// You do not need this if using Enzyme 'toMatchSnapshot' etc.
import renderer from 'react-test-renderer';

// setup for shallow rendering component, saves having to do it in every test in this file
const  setup = (props = {}) => {
 const component = shallow(<NavigationButton {...props} />);
 return component;
};

describe('NavigationButton tests: ', () => {

let component;
beforeEach(() => {
 component = setup();
});

it('Button renders correctly: ', () => {
  console.log(component.debug());
  const wrapper = findByTestAtt(component, 'nav_button');
  expect(wrapper.length).toBe(1);
});

});

A: Using the jest-expo preset solved the problem for me. The documentation explains it well: https://www.npmjs.com/package/jest-expo. The issue seemed to be that the import keyword wasn't being transformed, I'm not clear on why but it came up in an issue here: https://github.com/expo/expo/issues/5296


text:
Q: Array manipulation with space char; iteration I'm writing a program that receives an array and an integer x. To each word of the array (text[i]!=' '), the program should reduce the word to x integers and apply this to all the words. E.g.
If the user writes "Hello Im Kevin" and defines x=2, the program should return "he Im Ke".
This is what I have for now, but it only works for the first word...
The problem is that I don't know how to tell the program to run the algorithm again after a space and before the end of the string '\0'
char text[SIZE], new[SIZE];
int x, i, length;

void truncW ()
{
    printf("Insert text!\n");

    fgets (text, SIZE, stdin);

    printf("\nInsert number of chars per word.\n");

    scanf("%d",&x);

    while (text[i]!=' '){
        i++;
        memmove(new, text, x);
    }

    printf("%s", new);
}

int main()
{
    truncW();
    return 0;
}

A: I would suggest,

*

*Read the line using fgets()
 fgets (text, SIZE, stdin);

*define a temporary char array to hold the modified o/p.
char buf[SIZE] = {0};

*Tokenize using strtok() using space (" ") as delimiter
char * token = NULL;
token = (text, " \n");

*If the token is not NULL, print exactly n number (taken from user) of chars using snprintf() to the temporary array.
snprintf(buf, n+1, "%s ", token);

*Go to step 3 and continue until strtok() returns NULL.

*Finally, print the temporary array.
printf("%s", buf);

A: void truncW(void){
    char text[SIZE], new[SIZE];
    int x, i, j, n;

    printf("Input text!\n");
    fgets(text, SIZE, stdin);

    printf("\nInput number of chars per word.\n");
    scanf("%d", &x);

    for(i=j=n=0; text[i] != '\0'; i++){
        if(text[i]!=' '){
            if(n < x){//Copy restrictions
                new[j++] = text[i];
                ++n;
            }
        } else {
            new[j++] = text[i];
            n = 0;
        }
    }
    new[j] = '\0';

    printf("%s\n", new);
}

A: I suggest something like this:
#include <stdio.h>
#include <string.h>

#define MAXLEN 50

void TruncateWords(char* Str, int WordLen)
{
    char Temp[MAXLEN];
    memset(Temp, 0, sizeof(Temp));

    char* pch = strtok(Str, " ");
    while (pch != NULL)
    {
        strncat(Temp, pch, WordLen);
        strcat(Temp, " ");
        pch = strtok(NULL, " ");
    }

    size_t Len = strlen(Temp) - 1;      // Don't copy the last added space
    strncpy(Str, Temp, Len);
    Str[Len] = '\0';        // strncpy doesn't null-terminate it in this case
}

int main()
{
    char Text[MAXLEN];
    int WordLen;

    printf("Insert text!\n");
    fgets(Text, sizeof(Text), stdin);
    Text[strlen(Text) - 1] = '\0';      // Get rid of fgets's \n

    printf("\nInsert number of chars per word.\n");
    scanf("%d", &WordLen);

    TruncateWords(Text, WordLen);

    puts(Text);

    return 0;
}

You should also add some checks for the value of WordLen - probably shouldn't be greater than MAXLEN.

A: try this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int rendsiz(char* str, char* delimiters, int x)
{
   char*h = NULL, *data = strdup(str);
   h = strtok(data, delimiters);
   int count = 0, lg = 0;
   while(h)
   {
     lg = strlen(h);
     if(lg>=x)count+=x+1;
     else count+=lg+1;
     h = strtok(NULL, delimiters);
   }
   free(data);
   return count;
}

void custprintf(char *data, char* delimiters, int x)
{
   char* st = strdup(data); //dup string, strtok mage change on the passed string
   int offset = 0, siz = 0, lg = 0, bufsiz = rendsiz(data, delimiters, x);
   char* t=NULL, *buf=(char *)malloc(bufsiz);
   memset(buf, 0, bufsiz);
   t = strtok(st, delimiters); #split string by " "
   while(t)
   {
     lg = strlen(t);
     if(lg>=x)siz = x;
     else siz = lg;
     memcpy(buf+offset, t, siz);
     buf[offset+siz]=' ';
     offset+=siz+1;
     t = strtok(NULL, delimiters);
   }
   printf("%s\n", buf);
   free(buf);
   free(st);
}

this actually work

A: Here's another approach that modifies the string in-place with no need for a temporary array:
void truncate( char *str, size_t len )
{
  size_t r; // index from which we read the next character (source)
  size_t w; // index to which we write the next character (target)
  size_t l; // Temp counter

  r = w = 0;
  l = len;

  while ( str[r] )
  {
    if ( str[r] == ' ' )    // If we see a blank, reset the counter
    {                       // and write the blank to the target index
      l = len;
      str[w++] = str[r++];
    }
    else if ( l )           // If we don't see a blank and our counter
    {                       // isn't 0, write the character to the
      --l;                  // target index, advance both source and
      str[w++] = str[r++];  // target indices, decrement the counter
    }
    else                    // If we don't see a blank and the counter
    {                       // is 0, advance the source index.
      r++;
    }
  }
  str[w] = 0;             // Make sure the result is 0-terminated
}

A: Should this be marked "homework":-)?
I would avoid using memmove. That can only lead to trouble. Since you are already willing to allocate a fixed buffer you can simply iterate over the array, filling the new array on the fly:
/* x is max characters per word (as per your example);
   y counts those characters */
int y = 0;

while (*text) {
    int is_space = *text == ' ';
    int must_show = y <= x;

    if (must_show) {
        *new++ = *text++;
        y++;
    } else {
        while (*text != ' ') text++;
    }
    if (is_space || !must_show) y = 0;
}
*new = '\0';

I have not tested this though. And the style may not conform to your requirements.


text:
Q: Reorder the whole MySQL table based on column values I have a MySQL table with about 17mn records with an auto_increment field. The structure is something like this:
+--------+-------------------+-----------+
| ID     | Year1             |  Year2    |
+--------+-------------------+-----------+
| 1      | 2001              | 2         |
| 2      | 2001              | 1         |
| 3      | 1999              | 3         |
| 4      | 2004              | 2         |
+--------+-------------------+-----------+

I'd like to reorder the physical structure of the whole table by changing the auto_increment ID to match the Year1 and Year2 columns when ordered in ascending order. Something like this..
+--------+-------------------+-----------+
| ID     | Year1             |  Year2    |
+--------+-------------------+-----------+
| 1      | 1999              | 3         |
| 2      | 2001              | 1         |
| 3      | 2001              | 2         |
| 4      | 2004              | 2         |
+--------+-------------------+-----------+

Is this possible with a query in MySQL or should I use PHP and loops, et al.?
Update
The use case is this: The actual data I have is stored in a specific pattern. I wouldn't want the end user to identify the pattern (2001, then 2001, then 1999, etc).. Hence I'd like to rearrange the data in a standard, sorted fashion..
There are no foreign keys for this table.

A: First of all take a backup of your database
Instead of re arranging your actual table create a new table and insert values from the old one. like this:
Create table with auto increment, primary key
CREATE TABLE Table2
    (`ID` int auto_increment primary key, `Year1` int, `Year2` int)
;

Insert with SELECT statement
INSERT INTO Table2
       (`Year1`, `Year2`)
SELECT Year1, Year2
FROM Table1
ORDER BY Year1, Year2;

See this SQLFiddle


text:
Q: populating GridView with sql data I need to select from my users table the username of the user that has the roleID that I will have to get from the dropdownlist. The data are not appearing in the GridView. Can't see what's wrong, help me please.
Already tried 2 ways
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {
       SqlConnection con = new SqlConnection(cs);
       con.Open();
       SqlCommand cmd = new SqlCommand("select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'", con);

       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataTable dt = new DataTable();
       da.Fill(dt);
       GridView2.DataSource = dt;
       GridView2.DataBind();
       con.Close();
   }

protected void Button2_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(cs);
    con.Open();
    SqlCommand cmd = new SqlCommand("select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'", con);

    SqlDataReader reader = cmd.ExecuteReader();

    GridView2.DataSource = reader;
    GridView2.DataBind();
    con.Close();
}

A: Okay, so this one worked for me. And you also must check the sources. Like what happened to my GridView, it says AutoGenerateColumns = false, I removed it. And it all worked!
protected void Button2_Click(object sender, EventArgs e)
{
    string cs = ConfigurationManager.ConnectionStrings["roleDB"].ConnectionString;
    SqlConnection con = new SqlConnection(cs);
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'";
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView2.DataSource = dt;
    GridView2.DataBind();
    con.Close();
}


text:
Q: set utf8 in database - can I remove SET NAMES utf8 from php code I have set utf8 in mysql database
now it shows
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+

+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database   | utf8_unicode_ci |
| collation_server     | utf8_unicode_ci |
+----------------------+-----------------+

I have the below in the php code
mysql_query("SET NAMES 'utf8'");

and
$database = mysqli_connect('host','user','pass','database');
mysqli_query($database,"SET NAMES 'utf8'");

Since I set utf8 in database, can I remove mysql_query("SET NAMES 'utf8'") and mysqli_query($database,"SET NAMES 'utf8'") from the code?

A: You can use the mysqli_set_charset
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Change character set to utf8
mysqli_set_charset($con,"utf8");

mysqli_close($con);
?>


text:
Q: Setup nginx with react and express I have a nginx server currently up and running, however I can only acces my website and not mywebsite/contact for exemple.
I have a react build as frontend @ : /usr/share/nginx/site/front
And a express server running with pm2 @ port 5000. in /usr/share/nginx/site/express
I would like all requests to /api go to the express server running on port 5000.
The rest should go to my react front end, Normally the react build will automatically proxy all /api/ requests to the port 5000 express server, this works locally.
How would I have to change the default nginx config @ sites-available/
I currently have :
server{
  listen 80 default_server;
  listen [::]:80 default_server
  root /usr/share/nginx/site/front

  index index.html
}

A: Try this
    server {
    listen      80  default_server;
    listen      [::]:80 default_server;
    server_name _;

    location /api/ {    # Backend
        proxy_pass  http://127.0.0.1:500;

        access_log  /var/log/nginx/back.out.log;
        error_log   /var/log/nginx/back.err.log;
    }

    location / {    # Frontend
        root        /usr/share/nginx/site/front;
        index       index.html;
        try_files   $uri $uri/ /index.html;

        access_log  /var/log/nginx/front.out.log;
        error_log   /var/log/nginx/front.err.log;
    }
}


text:
Q: MySQL Getting the return of a substraction We are trying to get the length of a physical exercise by using the timestamps on our sensor data.
We currently have the following query:
SELECT UNIX_TIMESTAMP(
    SELECT HAAS2.trainingsdata.timestamp
    FROM HAAS2.trainingdata
    WHERE HAAS2.trainingsdata.training_id= 1
    ORDER BY timestamp DESC LIMIT 1)
- UNIX_TIMESTAMP(
    SELECT HAAS2.trainingsdata.timestamp
    FROM HAAS2.trainingdata
    WHERE HAAS2.trainingsdata.training_id= 1
    ORDER BY timestamp ASC LIMIT 1)
AS output

(enters added for readability)
When testing this query in phpMyAdmin we get the following error:

#1064 - You have an error in your SQL syntax; check the manual that
      corresponds to your MySQL server version for the right syntax to use
      near 'SELECT HAAS2.trainingsdata.timestamp FROM HAAS2.trainingdata
      WHERE HAAS2.trainin' at line 1

We've tried different ways to write down the query all resulting in the same error. We don't understand where the syntax error lies.

A: SELECT max(UNIX_TIMESTAMP(timestamp)) -
       min(UNIX_TIMESTAMP(timestamp)) AS output
FROM HAAS2.trainingdata
WHERE training_id = 1


text:
Q: Facebook permissions confusion I am trying to retrieve the user id and name using the iO SDK. As I understand, no additional authorization is needed to get these parameters.
Therefore I do this:
FBRequest *userIDRequest = [facebook requestWithGraphPath:@"http://graph.facebook.com/me?fields=id,name"
                                              andDelegate:self];

And then deal with the data. However when I do this I get an error:
The operation couldn't be completed. (facebookErrDomain error 10000.)

The only thing I could find regarding this error was a lack of user permissions, but as I said above these items should be gotten for free. Any idea what I'm doing wrong here?

A: RequestWithGraph path already have the URL in the method call. You'd only have to add the graph path to the method:
FBRequest *userIDRequest = [facebook requestWithGraphPath:@"me" andParams: params andDelegate:self];

Just make sure you fill the params appropriately.


text:
Q: sites down but server up, what to do? I could ping my websites but I got a 404 going there.
My server was running normally, no new mail for root.

*

*Is there a service to alert you when your websites are down ?

*What do you usually do to understand why it's down?
I took a look at the apache2/error.log and saw that it couldn't access one of the website I had deleted a few hours ago. I just did a a2dissite and restarted and it was fixed, I could access my websites.
I either got lucky or I postponed a problem. Any idea what I should do next to make sure everything is alright? (I'm on debian by the way)


text:
Q: django foreign key I have the following in my models.py:
from django.db import models

class LabName(models.Model):
    labsname=models.CharField(max_length=30)
    def __unicode__(self):
     return self.labsname

class ComponentDescription(models.Model):
       lab_Title=models.ForeignKey('Labname')
       component_Name = models.CharField(max_length=30)
       description = models.CharField(max_length=20)
        purchased_Date = models.DateField()
       status = models.CharField(max_length=30)
       to_Do = models.CharField(max_length=30,blank=True)
       remarks = models.CharField(max_length=30)

       def __unicode__(self):
           return self.component

I have the following in my admin.py:
from django.contrib import admin
from Lab_inventory.models import ComponentDescription,LabName

class ComponentDescriptionAdmin(admin.ModelAdmin):
    list_display= ('lab_Title','component_Name','description','purchased_Date','status','to_Do','remarks')
    list_filter=('lab_Title','status','purchased_Date')

admin.site.register(LabName)
admin.site.register(ComponentDescription,ComponentDescriptionAdmin)

What I want is to display the fields under the component description to be displayed under the lab title(the fields related to each lab title by should be displayed under that lab name)

A: What you are doing with list_display and list_filter pertain to the list that is shown in the admin screen where the list of LabName objects are listed.
Assuming one LabName has one-to-many ComponentDescription entities, you need Django's InlineModelAdmin to display the list of ComponentDescription objects belonging to LabName within the admin page for a specific LabName entity. The code would be of the following structure:
from django.contrib import admin
from Lab_inventory.models import ComponentDescription,LabName

class ComponentDescriptionInline(admin.TabularInline):
    model = ComponentDescription

class LabNameAdmin(admin.ModelAdmin):
    inlines = [
        ComponentDescriptionInline,
    ]

admin.site.register(LabName, LabNameAdmin)

where TabularInline is a subclass of the generic InlineModelAdmin.


text:
Q: Null value is considered an existing value I have a validation into if conditional like:
IF(EXISTS
    (SELECT TOP 1 [TaskAssignationId]
     FROM [Task] AS [T]
          INNER JOIN @TaskIdTableType AS [TT] ON [T].[TaskId] = [TT].[Id]
))

But it returns NULL  value because TaskAssignationId is NULL so in consequence IF condition it's true because it exist with NULL value, but I don't want to consider NULL as a value. How can add an exception of nulls? Regards

A: If you don't want to include rows where [TaskAssignationId] is null then add that to a WHERE clause.
IF(EXISTS
    SELECT TOP 1 [TaskAssignationId]
    FROM [Task] AS [T]
    INNER JOIN @TaskIdTableType AS [TT] ON [T].[TaskId] = [TT].[Id]
    WHERE [TaskAssignationId] is not null
))

A: Exists works like "Did the (sub)query return more than zero (correlated) rows" not "did the (sub)query return a non null value"
These are perfectly valid exists:
SELECT * FROM person p
WHERE EXISTS (SELECT null FROM address a WHERE a.personid = p.id)

SELECT * FROM person p
WHERE EXISTS (SELECT 1 FROM address a WHERE a.personid = p.id)

SELECT * FROM person p
WHERE EXISTS (SELECT * FROM address a WHERE a.personid = p.id)

It doesn't matter what values you return, or how many columns, exists cares whether the rowcount is 0 or greater when determining whether results exist
Hence you have to make sure your (sub)query returns no rows if you want the exists check to fail. If Addresses that have a null type are unacceptable, the (sub)query has to exclude them with WHERE a.type IS NOT NULL so that only rows with a non null type are considered
There's also little point doing a TOP 1 in the (sub)query; the optimiser knows that the only condition it cares about is 0 or not-0 rows, so it automatically do a TOP 1 (i.e. it will stop retrieving data when it knows there is at least one row)

A: If you want to check the existence then no need to assign the column name, you can use select 1
IF(EXISTS
    SELECT TOP 1 1
    FROM [Task] AS [T]
    INNER JOIN @TaskIdTableType AS [TT] ON [T].[TaskId] = [TT].[Id]
))
begin
----code---
end


text:
Q: Memory allocated for Python process By default how much memory is allocated by the operating system for a python process?
Usually operating system allocates memory for each process. So when we execute a python file, a process will initiated and the operating system will allocate memory for this python process. So what is the default memory allocated by operating system for a python process.
I also want to know how the code, data, heap segments work in Python. Is there any good document for understanding Python internals?


text:
Q: QMenuBar items style in inactive window How to disable changing menuItems look in QMenuBar when window loses focus?
Now, when window has focus, menu items are clearly visible, but when it loses focus, items are gray, looks like disabled. I want them to look normal all the time.
My platform is Qt4 on Windows7.
Some simple screenshot of menu item on active and inactive window:

A: Use QStylesheets and leverage the states of your QMenuItems.
http://www.qtcentre.org/threads/37560-QPushButton-different-stylesheets-for-focus-pressed-released-combinations
QPushButton{ background-color: blue; }
QPushButton:disabled{ background-color: yellow; }
QPushButton:pressed{ background-color: orange; }
QPushButton:focus:pressed{ background-color: black; }
QPushButton:focus{ background-color: green; }
QPushButton:hover{ background-color: red; }
QPushButton:checked{ background-color: pink; }

http://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar
The other option if you want to ignore stylesheets, you could try the palette.
http://doc.qt.io/qt-5/qpalette.html#details

The color groups:

*

*The Active group is used for the window that has keyboard focus.

*The Inactive group is used for other windows.

*The Disabled group is used for widgets (not windows) that are disabled for some reason.

So you should be able to get the copy of the palette for your QMenuItem, copy the active palette into the inactive palette, and then call setPalette on your QMenuItem.  Tada, now it always looks active.
Hope that helps.


text:
Q: How to send .caf file via email in iphone? I want to send an audio file with .caf extension via email in iphone. Can anyone help me to do this? I have written mimeType:@"audio/caf" but I think it is not supporting that. Please help me to do this small task.

A: Use below code :-
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filepath = [documentsDirectory stringByAppendingPathComponent:memo.memoUrl];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filepath];
NSData *dataToSend = [[NSData alloc] initWithContentsOfURL:fileURL];
[fileURL release];

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"Recording"];

// Set up recipients
NSArray *toRecipients = nil;
NSArray *ccRecipients = nil;
NSArray *bccRecipients = nil;

[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];

[picker setMessageBody:@"" isHTML:YES];
[picker addAttachmentData:dataToSend mimeType:@"audio/x-caf" fileName:[NSString stringWithFormat:@"voice-memo.caf", memo.memoName]];


text:
Q: Want to echo variable, however no results are echoed i receive "echo "Klaida!!!!"" meaning there is no results.
Could you please point out my mistake in code.
    $dezesdezesId = $_GET["dezesId"];
        $query        = "SELECT * FROM dezes WHERE dezesId = '$dezesdezesId'";
        $result       = mysqli_query($connection, $query);

            if (mysqli_num_rows ($result) > 0)
            {
                while ($row = mysqli_fetch_assoc($result))
                {
                    $dezesPavadinimas = $row["pavadinimas"];
                    $dezesLikutis     = $row["likutis"];
                }

                echo $dezesLikutis;

            }

                    else
                    {
                        echo "Klaida!!!!" . mysqli_error($connection);
                    }

A: echo this inside your while loop.
while ($row = mysqli_fetch_assoc($result))
{
                $dezesPavadinimas = $row["pavadinimas"];
                $dezesLikutis     = $row["likutis"];
                echo $dezesLikutis;
}

and try to use '{$dezesdezesId}' your variable inside your query string


text:
Q: Reuse binding in Rust closure I am attempting to generate a Vec<(Point, f64)>:
let grid_size = 5;

let points_in_grid = (0..grid_size).flat_map(|x| {
    (0..grid_size)
        .map(|y| Point::new(f64::from(x), f64::from(y)))
        .collect::<Vec<Point>>()
});

let origin = Point::origin();

let points_and_distances = points_in_grid
    .map(|point| (point, point.distance_to(&origin)))
    .collect::<Vec<(Point, f64)>>();

I get the following error:
use of moved value: point

I understand that I cannot use point in both elements of the tuple, but when I attempt to store a reference, I get an error regarding lifetime.

A: I am presuming your Point struct looks like the following:
#[derive(Debug)]
struct Point(f64, f64);

impl Point {
    fn new(x: f64, y: f64) -> Self { Point(x, y) }
    fn origin() -> Self { Point(0.,0.) }
    fn distance_to(&self, other: &Point) -> f64 {
        ((other.0 - self.0).powi(2) + (other.1 - self.1).powi(2)).sqrt()
    }
}

Now let's look at an even simpler example that will not compile:
let x = Point::new(2.5, 1.0);
let y = x;
let d = x.distance_to(&y);

Which gives the error:
error[E0382]: use of moved value: `x`
  --> <anon>:15:13
   |
14 |     let y = x;
   |         - value moved here
15 |     let d = x.distance_to(&y);
   |             ^ value used here after move
   |
   = note: move occurs because `x` has type `Point`, which does not implement the `Copy` trait

Because x has been moved into y, it now can't have a reference taken in order to call the distance_to function.
The important thing to note here is that order matters - if we swap the lines over we can call distance_to by borrowing x, the borrow will end and then x can be moved into y.
let x = Point(0., 0.);
let d = x.distance_to(&y);
let y = x; // compiles

In your case, a very similar thing is happening when constructing the tuple. point gets moved into the tuple, and then tries to borrow it to form the second element. The simplest solution is to do the same thing as here: swap the order of the elements of the tuple.
let points_and_distances = points_in_grid
    .map(|point| (point.distance_to(&origin), point))
    .collect::<Vec<(f64, Point)>>(); // compiles

Playground link
N.B. if you want to retain the order:
.map(|(a, b)| (b, a))


text:
Q: How much time will it take for an object to fall to the center of the Earth? The reason I want to know is because many years ago in Sunday school I learned a story that in probably 600 AD some sinner was swallowed up by a hole, and that he's still falling as of today.
I can't use the formulas I know because they all assume g as constant, and I realized that I can't assume g=9.8 the entire fall because he's getting closer and closer to the center of the earth, so I tried to use my fairly bad calculus skills and failed miserably. Can anyone do this problem? Is it even possible?

A: It would help if you provide your calculations; probably I or someone else will see and correct your errors.  However, a correct approach would recognize that at any distance $r$ from the center of the Earth, Earth's radius R, the gravity the falling man experiences is only $r^3 / R^3$ times the gravity experienced at the surface of the Earth. -- that is, assuming the density of the Earth is uniform.  It comes to about 21 minutes, if there is no air resistance, to reach the center.