text:
Q: How do I package a Mac OS application for install? I know on windows there are a bunch of installer tools you can use to create an installer, but on Mac OS I've seen two ways to install apps:

*

*A DMG file which you download, double-click, then run an application inside - the application typically has you drag an icon to another icon (representing the Applications folder) to install the app

*Another type of file which launches an apparently standard installer, which sometimes brings up a warning like "This installer may run a program to determine if you can go ahead with the install"
What's the "standard" way of packaging an app for install on Mac OS? Is one of the above the Apple-recommended way?
Thanks.

A: Try Iceberg!
Another one package creator.

A: In OS X, many applications are just created as a Relocatable
application bundles that the user just need to copy to the
/Application folder (or any other location). In other cases, when you
need to perform some operations over the machine (such as adding users
or changing permissions) you can use a PKG installer (for example built using PackageMaker), which allows
executing some pre and post install scripts and support some basic
installation configuration, like selecting the installation drive.
Sometimes, as with complex server software, you need more flexibility, for example to show custom pages to
the end user requesting information required to install your
application, like the MySQL port and password or proxy information to
download requirements on the fly (or simply to make it look fancier
:)). For this cases there are other installer solutions like our BitRock
InstallBuilder (disclaimer, I'm one of the developers).
InstallBuilder also has the advantage of generating multiplatform
installers using the same project with very little customization per
platform.

A: Apple is very clearly making the "standard" to be downloading a program from the App Store. This has the benefit of making application installation transparent to the normal user. And, believe it or not, normal people have a lot of trouble with the concept of installing a program. Of course that benefit comes with some costs, but this isn't the place for that debate–there are plenty of other places for that.
Assuming you don't want to or can't go the App Store route, both PKG and DMG are common ways to distribute a program. Use a PKG if you need to install files aside from your application bundle (which should not be a common use case). In all other cases use a DMG that prompts the user to copy the application into the Applications folder. But a lot of your users will not understand that they need to do that (unless your target audience is solely knowledgeable computer users). They will run your application from the disk image. Ideally in this case, your program will detect that it is running from a disk image and offer to copy itself into the Applications folder.

A: Packages works well. If your deployment process must be kept simple, it is great.
The Quick build consists of dragging your .app onto Package and it is done.
For advanced packaging, you can also provide a certificate.
http://s.sudre.free.fr/Software/Packages/about.html

A: We're discussing two things:

*

*first and most importantly, the standard method by which the bits of an executable get laid on the disk in a way that's accessible and properly registered by the system

*second, the mechanism for preparing the .app, as recommended by Apple

An older marketing page on Apple's site says it's recommended to create packages (so the Installer application can move the bits in place) with the PackageMaker application.
Its usage is described here: mactech.com/articles/mactech/Vol.25/25.03/2503MacEnterprise-PackagingforSystemAdministrators/index.html.
But as others have mentioned, the elephant in the room is the MacAppStore(MAS for short). Until it's debut, what was standard for large companies was their own custom scripts rolled into an older-style 'bundle' package or using an executable like the VISE installer. Smaller developers usually tried to make their app installable via drag-drop, distributed in zip archives or disk images(for simplicity's sake).
The MAS is different: as of 10.7 it uses a package format (which debuted in 10.5) referred to as a flat package (really a xar archive, explanation here)
which is transferred over http to a hidden folder, installs directly to Applications(after which the temporary folder it is downloaded to is deleted).  It drops its receipt and a bill or materials file into /private/var/db, and is therefore audit-able by the built-in command line pkgutil tool, described here: mactech.com/articles/mactech/Vol.25/25.12/2512MacEnterprise-PackagesReceiptsandSnow/index.html
A benefit of using the flat package format is you can pull things over the network more safely and efficiently, but it isn't as easy to work with as bundle packages if you are testing and modifying the package regularly, or iterating to ensure scripts that perform actions or checks work well. Even when flat, putting the pkg in a archive or disk image is recommended for flexibility. More distribution tools expect DMG's than zip's, so there's that as well.
Besides what Apple recommends and what is standard, common practice, there's this article: https://www.afp548.com/2010/06/03/the-commandments-of-packaging-in-os-x/ which discusses the why's and hows (although mainly for system administrators) of packaging for wider distribution. It is greatly recommended to get more of a feel of how and why things go wrong, and what to avoid.


text:
Q: C#: Is it possible to declare a local variable in an anonymous method? Is is possible to have a local variable in an anonymous c# methods, i.e. in the following code I would like to perform the count only once.
IQueryable<Enquiry> linq = db.Enquiries;

if(...) linq = linq.Where(...);

if(...) linq = linq.Where(e =>
    (x <= (from p in db.Orders where p.EnquiryId == e.Id select p).Count() &&
        (from p in db.Orders where p.EnquiryId == e.Id select p).Count() <= y));

if(...) linq = linq.Where(...);

var result = (from e in linq select e);

Is there a "let" for anonymous functions?
Update:
Note that I'm adding several Where clauses after this statement so I can't close with a select.
/Niels

A: Yes, you can do exactly what you want, in Linq to objects and Linq to SQL.
There is a let in Linq, allowing you to give a name to an intermediate result in the middle of your query, just as you want to. Based on your example:
... = from e in linq
      let count = (from p in db.Orders where p.EnquiryId == e.Id select p).Count()
      where (x <= count) && (count <= y)
      select e;

By the way, I think there was something syntactically erroneous about your original example, which is easier to spot when the count is just a name:
where (x <= count) && /* <= */ (count <= y);

A: Yes, why not?! After all it's a function, just anonymous!
Example:
 x => { int y = x + 1; return x + y; }

Or alternatively:
 delegate(int x) {
     int y = x + 1;
     return x + y;
 }

So your code can be written as:
  ... = linq.Where(e => {
         var count = (from p in db.Orders where p.EnquiryId == e.Id select p).Count();
         return x <= count && count <= y;
  });

UPDATE: To clarify things about the comment, it's important to know the difference between  anonymous methods and lambda expressions. An anonymous method is just like a normal method, without an explicit name. When you compile it, the compiler generates a normal method with a weird name for you instead, so it will not have any special limitations. However, one representation of an anonymous method is a lambda expression. Lambda expressions can be interpreted in a couple different ways. The first is a delegate. In that way, they are equal to an anonymous method. The second is an expression tree. This way is normally used by LINQ to SQL and some other LINQ providers. They don't execute your expression directly by any means. They parse it as an expression tree and use the tree as input data to generate the equivalent SQL statement to be run on the server. It's not executed like a method and it's not considered an anonymous method. In that case, you can't define a local variable as it's not possible to parse the lambda as an expression tree.

A: If you're using Linq to SQL, you won't be able to use Mehrdad Afshari's answer. Your LINQ expressions need to be Expression Trees, and those don't support the anonymous delegate syntax.
Neither will you be able to create your delegate elsewhere and call it from inside the lambda - Linq to SQL only allows certain operations to be performed in the body of the query, and calling a delegate isn't one of them.
Your best bet, assuming you're using Linq to SQL (as it appears given your example), is to bring down the count in one query, then capture the count variable in the query that requires the count.

A: The Where method takes a Func so what you're passing in there in the second part ins't actually a method, but just a bool expression. My suggestion would be to have an actual method that returns a bool, that takes in the paremeters you need, and in your call to the Where method you just do something like this Where(p=> MyMethod(p,...))

A: With a little background in Scheme you would know that 'let' is just syntax sugar for defining a lambda and invoking it.
So with that knowledge, lets see how it can be done.
(count => x <= count && count <= y)
  ((from p in db.Orders
    where p.EnquiryId == e.Id
    select p).Count())

As a bonus, it looks like Scheme too :)
Disclaimer: I did not test this snippet, but there is no reason it should not work. Personally, I would just use the 'let' construct provided in LINQ.
Update:
It does not work...  :(

A: I've run into a similar problem. The solution is to create a custom expression tree generating method.
I asked my question on MSDN-forums. Please see the question and answer here: Reusing Where expressions.
This may give you an idea on how to proceed, but I must admit that custom expression trees are not for the faint-hearted ;-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Background move in android I am making a project in android studio.I am trying to move background image by Thread on running the app but when i am running the app it gives a message 'unfortunately stopped' . How can I move background image by Thread or anything
using android studio ? Anyone please help me ?
//Xml:
<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/bg2"
    android:scaleType="fitXY"
    android:id="@+id/image_id"
    />

//java:
image=(ImageView)findViewById(R.id.image_id);  // image is an ImageView type object
Thread an=new Thread(){
        @Override
        public void run() {
            super.run();
            for(;x<=200;)
            {
                x++;
                image.setX(x);
                image.setY(0);

                System.out.println("Value of x: "+x);

                try
                {
                    sleep(1000);

                }catch(Exception e)
                {
                    System.out.println("Exception: "+e);
                }
            }
        }
    };an.start();

A: You can use TranslateAnimation in your thread, Checkout here and here for more information
 ImageView img_animation = (ImageView) findViewById(R.id.img_animation);

    TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,
            0.0f, 0.0f);          //  new TranslateAnimation(xFrom,xTo, yFrom,yTo)
    animation.setDuration(5000);  // animation duration
    animation.setRepeatCount(5);  // animation repeat count
    animation.setRepeatMode(2);   // repeat animation (left to right, right to left )
    //animation.setFillAfter(true);

    img_animation.startAnimation(animation);  // start animation

A: First of all, please always post the logs. You can usually see the reason for the crash in there.
This being said, I would assume the reason for your crash it that you try to modify the UI in a non-ui-thread. You can never do that! Here is a SO question with some good explanations. Or here is some more from the android docs.


text:
Q: Is casting a const char array to an integer in the header always safe? Ignoring how repulsive and hacky it is, is the following guaranteed to be safe? If not, why?
//.h
struct foo
{
 const static intptr_t KEY = (intptr_t) "VALUE";
};

//.cpp
void useFoo()
{
 const char * value = (const char *) foo::KEY;
 printf("%s",value);
}

A: Not only is the code not guaranteed to be safe, the code is ill-formed.
"VALUE" is of type char const[6], which cannot be converted to intptr_t via static_cast.

A: It is guaranteed not to compile. You cannot use static_cast to convert from pointer to an integral type or viceversa. If it was a reinterpret_cast it would be fragile to say the least as the compiler can do constant folding and the KEY might become non-unique.
Additionally, you should define the static member variable KEY in your application.


text:
Q: Emulate public/private properties with __get() and __set()? I was writing a class that uses __get() and __set() to store and retrieve array elements in a master array. I had a check to make some elements ungettable, basically to re-create private properties.
I noticed that it seemed that __get intercepts all calls to class properties. This sucks for me, because I wanted to have a variable private to the outside world ( unavailable via get ), but I was trying to access it by directly referencing the master array from within the class. Of course, the master array is not in the whitelist of gettable properties :(
Is there a way I can emulate public and private properties in a php class that uses __get() and __set()?
Example:
<?
abstract class abstraction {

    private $arrSettables;
    private $arrGettables;
    private $arrPropertyValues;
    private $arrProperties;

    private $blnExists = FALSE;

    public function __construct( $arrPropertyValues, $arrSettables, $arrGettables ) {

        $this->arrProperties = array_keys($arrPropertyValues);
        $this->arrPropertyValues = $arrPropertyValues;
        $this->arrSettables = $arrSettables;
        $this->arrGettables = $arrGettables;
    }

    public function __get( $var ) {
        echo "__get()ing:\n";
        if ( ! in_array($var, $this->arrGettables) ) {
            throw new Exception("$var is not accessible.");
        }

        return $this->arrPropertyValues[$var];
    }

    public function __set( $val, $var ) {
        echo "__set()ing:\n";
        if ( ! in_array($this->arrSettables, $var) ) {
            throw new Exception("$var is not settable.");
        }

        return $this->arrPropertyValues[$var];
    }

} // end class declaration

class concrete extends abstraction {

    public function __construct( $arrPropertyValues, $arrSettables, $arrGettables ) {
        parent::__construct( $arrPropertyValues, $arrSettables, $arrGettables );
    }

    public function runTest() {

        echo "Accessing array directly:\n";
        $this->arrPropertyValues['color'] = "red";
        echo "Color is {$this->arrPropertyValues['color']}.\n";

        echo "Referencing property:\n";
        echo "Color is {$this->color}.\n";
        $this->color = "blue";
        echo "Color is {$this->color}.\n";

        $rand = "a" . mt_rand(0,10000000);
        $this->$rand = "Here is a random value";
        echo "'$rand' is {$this->$rand}.\n";

    }
}

try {
    $objBlock = & new concrete( array("color"=>"green"), array("color"),  array("color") );
    $objBlock->runTest();
} catch ( exception $e ) {
    echo "Caught Exeption $e./n/n";
}

// no terminating delimiter

$ php test.php
Accessing array directly:
__get()ing:
Caught Exeption exception 'Exception' with message 'arrPropertyValues is not accessible.' in /var/www/test.php:23
Stack trace:
#0 /var/www/test.php(50): abstraction->__get('arrPropertyValu...')
#1 /var/www//test.php(68): concrete->runTest()
#2 {main}.

A:
Is there a way I can emulate public and private properties in a php class that uses __get() and __set()?

Not directly (if you discount debug_backtrace).
But you can have a private method getPriv that does all the work your current __get does. Then __get would only wrap this private method and check accessibility.
function __get($name) {
    if (in_array($name, $this->privateProperties))
        throw new Exception("The property ". __CLASS__ . "::$name is private.");
    return $this->getPriv($name);
}

Inside your class, you would call getPriv, thus bypassing __get.

A: Make abstraction::$arrPropertyValues protected or do what Artefacto wrote (if you need additional checks), except that abstraction::getPriv() should be protected.

A: Rather than manually enlisting private/protected properties, you could use PHPs cumbersome reflection methods:
function __get($name) {

    $reflect = new ReflectionObject($this);
    $publics = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);

    if (in_array($name, $publics)) {
         return $this->{$name};
    }
}


text:
Q: Find $\int (\sin^2 x - 2\cos^2 x)\,dx$
Find $$\int (\sin^2 x - 2\cos^2 x)\,dx$$

$$=\frac{1}3 -\cos^3x - \frac{1}4 \sin^3 x$$
This is of course not the right answer which is
$$-\frac{3}4 \sin 2x - \frac{1}2 x + C$$

A: HINT:
Use $$\cos2x=2\cos^2x-1=1-2\sin^2x$$
and $$\int\cos mx\ dx=\dfrac{\sin mx}m+C$$

A: Hint:
By parts,
$$I=\int\sin^2(x)dx=-\cos(x)\sin(x)+\int\cos^2(x)dx=-\cos(x)\sin(x)+J,$$
and
$$J=\int\cos^2(x)dx=\int(1-\sin^2(x))dx=x-I.$$


text:
Q: http-toolkit HTTP Toolkit allows you to automatically capture HTTP traffic from many clients including Android, browsers, language runtimes (such as Node.js, Python, Ruby & PHP), command-line tools, Docker and others.
Once traffic is being captured, you can use HTTP Toolkit to inspect all details of all requests made by the client, and add rules to automatically breakpoint or rewrite the client's HTTP traffic.


text:
Q: Umoja.Models.Subject at lambda_method(Closure , CreateDto , Subject , ResolutionContext ) Please help, I wish to understand this situation am facing. Am creating a new Subject and every thing looks clear to me, I have other models with the same code and they work find except this
Object that am sending
    {
      "title": "a",
      "summary": "b",
      "teacher": "c",
      "date": "d",
      "churchId": 1
    }

My Model
public class Subject
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    public string Summary { get; set; }
    [Required]
    public string Teacher { get; set; }
    [Required]
    public string date { get; set; }
    [Required]
    public int ChurchId { get; set; }
}

Dto
public class CreateDto
{
    [Required]
    public string Title { get; set; }
    public string Summary { get; set; }
    [Required]
    public string Teacher { get; set; }
    [Required]
    public string date { get; set; }
    [Required]
    public int ChurchId { get; set; }
}

Controller
    [HttpPost]
    public ActionResult <ReadDto> CreateSubject(CreateDto CreateDto)
    {
        var subjectModel = _mapper.Map<Subject>(CreateDto);
        _subjectRepository.CreateSubject(subjectModel);
        _subjectRepository.SaveChanges();

        var ReadDto = _mapper.Map<ReadDto>(subjectModel);
        return CreatedAtRoute(nameof(GetSubjectById), new {Id = ReadDto.Id}, ReadDto);
    }

subjectProfile
    public Subject()
    {
        CreateMap<Subject,ReadDto>();
        CreateMap<CreateDto,Subject>();
        CreateMap<UpdateDto, Subject>();
    }

A: I was not carefull my SubjectProfile class, I wrote Subject instead of SubjectProfile


text:
Q: printing a string backward I'm trying to write a piece of code that reverses strings around. So far it works but there are spaces between every character in the string and it says none before and after the printed result. What could I do to fix this?
def reverse(text):
    length = len(text)
    while length > 0:
        print text[length - 1],
        length -= 1

A: I don't see the "none" problem, just the spaces between the characters.  For the "none" problem, make sure you're passing the function a string and not something like a list.  If you're passing it a string, then the nones are coming from someplace else.  And as PM 2Ring suggested, make sure you aren't attempting to print the result of the function call, since the function as written doesn't return anything.
The spaces are due to the way print works, and the fact that you're printing the result one character at a time.  A better way would be to reverse the string, then print the result in a single print.  This can be done very simply as follows:
rev = text[::-1]

A: I can't reproduce the None issue. And the space you are getting between characters isn't an issue, rather print in python2 works like that.  However you can ignore the spaces with a simple change in your code. Like this:
def reverse(text):
    length = len(text)
    result=''
    while length > 0:
        result += text[length - 1]
        length -= 1
    print result

reverse("I love python!")

Output:
!nohtyp evol I


text:
Q: Why is electric potential scalar? I can't conceptually visualize why it would be so. Say you have two point charges of equal charge and a point right in the middle of them. The potential of that charge, mathematically, is proportional to the sum of their charges over distance from the point ($q/r$). But intuitively, my thought process keeps going back to the concept of direction and how the electric field at that point would be zero. So why would the electric fields cancel while the electric potentials just add up algebraically?

A: Let me first comment that the statement

electric fields cancel while the electric potentials just add up algebraically

is not actually correct.  Electric fields add due to the principle of superposition (see the section on superposition in the wikipedia article).
However, when two electric field vectors are of the same magnitude but point in opposite directions, then their sum is zero; this is what is happening at the midpoint between two equally charged particles.
Given an electric field $\mathbf E$, the electric potential $\Phi$ is defined through the relation
$$
  \mathbf E = -\nabla \Phi
$$
so it is a scalar by definition.  The electric potential also obeys the superposition principle.  Provided we set the zero of potential at infinity, the potential due to a point charge $q$ is given by $q/(4\pi\epsilon_0 r)$, and $r>0$, so the potential of a point charge is either everywhere positive or everywhere negative depending on the sign of the charge.  Therefore, given two point charges of the same sign, the sum of their potentials will cancel nowhere.

A: From a more general point of view, electric potential is not a scalar, but a component of a 4-vector (http://en.wikipedia.org/wiki/Electromagnetic_four-potential ) - it is not invariant with respect to boosts.
Edit: in answer to question:

Well the potential is just one component of the four-vector. Not the four-vector itself. So isn't it a scalar after all?

As user Ben Crowell says:

No, the way physicists really think about this is that categories like vector and scalar are defined in terms of their transformation properties. A scalar is something that doesn't change at all under any smooth change of coordinates, e.g., a Lorentz boost.

but also we could say that electric potential is a scalar under the rotation group and more generally under the Galilean Group but only a component of a 4-vector under the Lorentz group.

A: An explanation based on the definition of scalar quantities in physics.
To see why electric potential energy is a scalar quantity you need to understand the following:
A physical quantity is a scalar property of a system, when its value and its effects do not depend on the orientation of the system.
Let us assume we have a system of three electrically charged particles carrying electric charge $+Q_A$, $-Q_B$ and $+Q_C$.  Let us also assume the three particles are at positions $A$, $B$ and  $C$ with position vectors $\bf {r}_A$, $ \bf {r}_B $ and $\bf {r}_C$  with respect to some arbitrary origin O.  We can write the total potential energy of the system of three charged particles as
$E=\frac{1}{4\pi\epsilon_0}(\frac{ Q_AQ_C}{| \bf{r}_A-\bf {r}_C |}-\frac{ Q_AQ_B}{|\bf {r}_A-\bf {r}_B |}- \frac{Q_BQ_C}{| \bf {r}_C-\bf {r}_B|})$.
We can observe that as long as $|\bf{r}_{\mu}-\bf{r}_{\nu}|$ remain fixed, with $\nu\ne\mu$, the three particles can be placed in an infinitely large number of positions in various orientations, and yet $E$ will have the same value. I.e.
The orientation of the system does not bear any measurable effects on the value $E$.
This is why electrical potential/energy is a scalar quantity.

A: Because work and charge both are scalar quantity ie electric potential is scalar quantity

A: When we bring a test charge let us say (+q) to a certain point, we exert some force. Our exerted force has to be equal or greater to the force exerted by the electric field in order to overcome it. Thus the forces being opposite and equal cancel each other and hence the direction is undetermined.
Since it is a compulsion for vector to have both magnitude and direction, hence here there is no direction but magnitude and hence we call it a scalar quantity.

A: Suppose in a equilibrium system where two negative charges is accompanied by one positive test charge in the middle. Here the resultant electric field at the centre is zero. Due to opposite and equal electric line of force from two negative charges but to bring that test charge from zero potential to the middle some work is done which is nothing but the potential energy value you get by adding algebraically. Though I am commenting in 2016 feel free to give me positive rating. :)


text:
Q: Share a resource between AngularJS controllers and service I have a AngularJS service "people" that has associated a people list by requesting a "heavy"(say, ajax) ressource (JSFiddle).
This people list is share between controllers.
I wonder if is the proper way to do it, saving this list as a global variable.
I do it because don't want to perform each time an ajax request to recuperate the initial list:

var people = [];

var myApp = angular.module('myApp', []);

myApp.controller("infoCtrl", function($scope, person) {
  $scope.people = person.get();
});

myApp.controller("filterCtrl", function($scope, person) {
  $scope.$watch("maxAge", function(newValue) {
    if (newValue) { person.filterPeople(newValue); }
  });
});

myApp.service("person", function() {
  return {
    get: function() {
      people = AjaxGetPeople();
      angular.forEach(people, function(p) {
        p.visible = true;
      });
      return people;
    },
    filterPeople: function(maxAge) {
      angular.forEach(people, function(person) {
        person.visible = person.age <= maxAge;
      });
    }
  };
});

function AjaxGetPeople() {
  return [
    { name: 'Marcel Sapin', age: 26  },
    { name: 'Anhel De Niro', age: 42  },
    { name: 'Johny Resset', age: 30  }];
}
input {  width: 40px; }

    People younger than
    <input ng-model="maxAge" type="number" />years:

      {{person.name}}, age {{person.age}}

A: You could cache the results of the AJAX call in the service and return that after the first call like this:
myApp.service("person", function() {
  return {
    get: function() {
      if (this.people) {
        return this.people;
      }
      people = AjaxGetPeople();
      angular.forEach(people, function(p) {
        p.visible = true;
      });
      this.people = people;
      return people;
    },
    filterPeople: function(maxAge) {
      angular.forEach(people, function(person) {
        person.visible = person.age <= maxAge;
      });
    }
  };
});


text:
Q: Angular - FormBuilder, how to group multiple Form Controls I use Formbuilder to create a FormGroup:
myForm = this.fb.group(
            {
                title: [""],
                fixed_grade1: [""],
                fixed_value1: [""],
                fixed_grade2: [""],
                fixed_value2: [""],
                fixed_grade3: [""],
                fixed_value3: [""],
                fixed_grade4: [""],
                fixed_value4: [""]
            });

all the fixed_grade and fixed_value are inputs and dropdowns.
I have 4 pairs of them, and this works correctly.
But now I would like to group these, so I don't have to access each value in my controller one by one, with myForm.get("fixed_grade1").value for each one.
But I would like that all these value are grouped in an array like:
myArray: [{grade, value}, [grade, value}...]

so I can access their value by: myArray[0].grade
Instead of mapping each single value to a new array, I saw there is a FormArray in FormBuilder, I just don't seem to be able to implement it correclty.
What would be the correct syntax to achieve what I described, having exactly 4 pairs of grade/score, and also it's important that in my final array with all these pairs grade/score, I have only the values that are not undefined, so if in my form the user only fills one pair grade/score, then my myArray.length will be 1.

A: You have defined your FormGroup wrong. Your FormGroup should have had a FormArray of FormGroups. Inside each of these FormGroups there should have been two FormControls for grade and value.
Change your form to this:
const grades = [
  {grade: 'Grade 1', value: 'Value 1'},
  {grade: 'Grade 2', value: 'Value 2'},
  {grade: 'Grade 3', value: 'Value 3'},
  {grade: 'Grade 4', value: 'Value 4'}
]

myForm = this.fb.group({
  title: [],
  grades: this.fb.array(this.grades.map(grade => this.fb.group({
    grade: [grade.grade],
    value: [grade.value]
  }))),
});

// OR

myForm = this.fb.group({
  title: [],
  grades: this.fb.array(this.grades.map(grade => this.fb.group({
    grade: [],
    value: []
  }))),
});
...
get gradesArray() {
  return (<FormArray>this.myForm.get('grades')).controls;
}
...
getArrayGroupControlByIndex(index) {
  return (<FormArray>this.myForm.get('grades'))
    .at(index);
}

This is how you'll use it in the template:
<form [formGroup]="myForm">
  <input type="text" formControlName="title">

        Group {{ i + 1 }}
        <input type="text" formControlName="grade">
        <input type="text" formControlName="value">

</form>

Here's a Sample StackBlitz for your ref.


text:
Q: Substracting part of cell So lets say that in one row i have in 2 cells some data and I want to extract the data after the second "_" character:
|   |      A     |           B           |
|---|:----------:|:---------------------:|
| 1 | 75875_QUWR | LALAHF_FHJ_75378_WZ44 | <- Input
| 2 | 75875_QUWR |       75378_WZ44      | <- Expected output

I tried using =RIGHT() function but than i will remove text from this first cell and so on, how can i write this function? Maybe I would compare this old cell and than to do if the second row is empty because maybe function deleted it to copy the one from first? No idea

A: Try:
=MID("_"&A1,FIND("@",SUBSTITUTE("_"&A1,"_","@",LEN("_"&A1)-LEN(SUBSTITUTE("_"&A1,"_",""))-1))+1,100)

Regardless of the times a "_" is present in your string, it will end up with the last two "words" in your string. Source

A: Use following formula.
=TRIM(MID(A1,SEARCH("#",SUBSTITUTE(A1,"_","#",2))+1,100))


text:
Q: Non-blocking infinite loop I have a Raspberry pi with a Sense hat. I've made a binary clock that I want to display and keep updated on the Sense hat's display. However, I want the ability to toggle the clock on and off with joystick middle. Everything's working fine, apart from my clock's update-loop blocking any new input once it's started.
from sense_hat import SenseHat
from signal import pause

def show_clock():
    # clock-logic

def pushed_middle(event):
    while 1:
        show_clock()

sense = SenseHat()

sense.stick.direction_middle = pushed_middle
pause

I've been thinking about how to solve this. How to allow the script/clock to keep running and still accept new actions from the joystick. But once the while-loop starts, I'm stuck. I'm not sure what to google for. I've started looking into async/await, but that seem to be a Python 3.5+ feature, and my pi only has 2.7.9/3.4.2(I just sudo apt-get update/upgrade-ed). I've also tried moving the loop around in the program, but it's blocking everything no matter where I place it.

*

*Is it a non-blocking (infinite) loop I'm looking for?

*Is this what a game-/event-loop is?

*Can I solve this with out using multiple threads(just curious, not a limitation if it's a must)?

*Is this a general problem in "designing" infinite loops?

*Can I approach this as a (reverse?) race condition? I was thinking about maybe using a semaphore as some kind of tool to not block, but I'm not sure.

A: I solved it by using a global variable:
from sense_hat import SenseHat
from signal import pause

def show_clock():
    global clock_is_on

    while clock_is_on:  # clock-loop
        # clock-logic
        # ...

        events = sense.stick.get_events()

        for event in events:
            if event.direction == "middle" and event.action == "pressed":
              clock_is_on = False

        time.sleep(1) # only need to update clock once every second

def pushed_middle(event):
    if not clock_is_on:
        clock_is_on = True
        show_clock()

sense = SenseHat()

clock_is_on = False

sense.stick.direction_middle = pushed_middle
pause()


text:
Q: Inserting XML data in SQL database How can i get my XML data into the right tables in my database? I have the following code:
DECLARE @XML XML = '<reservering reserveringsnummer="1" status="aanvraag">
<park>Nationaal park Oosterschelde</park>
<accomodatie>Appartement</accomodatie>
<aantalBezoekers>2</aantalBezoekers>
<startdatum>2013-12-12</startdatum>
<einddatum>2013-12-20</einddatum>
<voorkeur>Rustige plaats</voorkeur>
<opties>
    <optie>arrangement</optie>
</opties>
<klant>
    <aanhef>De heer</aanhef>
    <naam>voornaam</naam>
    <adres>adres</adres>
    <postcode>postcode</postcode>
    <email>mailadres@mailadres.com</email>
    <rekeningnummer>012345678</rekeningnummer>
</klant>
</reservering>'

'SELECT
ReserveringNummer = Reservering.value('@reserveringsnummer', 'int'),
ReserveringStatus = Reservering.value('@status', 'varchar(50)'),
Park = Reservering.value('(park)[1]', 'varchar(50)'),
Accomodatie = Reservering.value('(accomodatie)[1]', 'varchar(50)'),
AantalBezoekers = Reservering.value('(aantalBezoekers)[1]', 'int'),
StartDatum = Reservering.value('(startdatum)[1]', 'date'),
EindDatum = Reservering.value('(einddatum)[1]', 'date'),
Voorkeur = Reservering.value('(voorkeur)[1]', 'varchar(50)'),
Opties = Opties.value('(optie)[1]', 'varchar(50)'),
Aanhef = Klant.value('(aanhef)[1]', 'varchar(50)'),
KlantNaam = Klant.value('(naam)[1]', 'varchar(50)'),
Adres = Klant.value('(adres)[1]', 'varchar(50)'),
Postcode = Klant.value('(postcode)[1]', 'varchar(50)'),
Email = Klant.value('(email)[1]', 'varchar(50)'),
Rekeningnummer = Klant.value('(rekeningnummer)[1]', 'varchar(50)')
FROM
@XML.nodes('/reservering') AS ReserveringTable(Reservering),
@XML.nodes('/reservering/opties') AS OptiesTable(Opties),
@XML.nodes('/reservering/klant') AS KlantTable(Klant)

INSERT INTO dbo.PRODUCT(naam)
  VALUES (Opties)
SELECT SCOPE_IDENTITY() AS ProductID;

INSERT INTO dbo.WONING(naam)
  VALUES (Accomodatie)
SELECT SCOPE_IDENTITY() AS WoningID;

INSERT dbo.KLANT(aanhef, naam, adres, postcode, emailadres, rekeningnummer)
  VALUES (Aanhef, KlantNaam, Adres, Postcode, Email, Rekeningnummer)
SELECT SCOPE_IDENTITY() AS KlantID;

INSERT INTO dbo.RESERVERING(reserveringsnummer, status, van_datum, tot_datum,       woning_id, product, voorkeur, prijs, klant, aantal_bezoekers)
   VALUES (ReserveringNummer, ReserveringStatus, StartDatum, EindDatum, WoningID, ProductID, Voorkeur, Prijs, KlantID, AantalBezoekers)

As you can see i'm also trying to get the product and woning id's into my RESERVERING table, is this the right way to do this? Right now the program is giving me an error: invalid column name 'columnname', where columnname is the value. It gives me the same error for all the values i've defined in my INSERT statement.

A: Fixed the problem. For people who are interested in the solution:
DECLARE @XML XML = '<reservering reserveringsnummer="1" status="aanvraag">
<park>Nationaal park Oosterschelde</park>
<accomodatie>Appartement</accomodatie>
<aantalBezoekers>2</aantalBezoekers>
<startdatum>2013-12-12</startdatum>
<einddatum>2013-12-20</einddatum>
<voorkeur>Rustige plaats</voorkeur>
<opties>
    <optie>arrangement</optie>
</opties>
<klant>
    <aanhef>De heer</aanhef>
    <naam>name</naam>
    <adres>adres</adres>
    <postcode>postcode</postcode>
    <email>mail</email>
    <rekeningnummer>012345678</rekeningnummer>
</klant>
</reservering>'

INSERT INTO  [PRODUCT](
[naam])

SELECT
   Opties = Opties.value('(optie)[1]', 'varchar(50)')
FROM
@XML.nodes('/reservering/opties') AS OptiesTable(Opties)

DECLARE @ProductID AS int
SET @ProductID = @@IDENTITY

INSERT INTO  [WONING](
[naam])

SELECT
   Accomodatie = Reservering.value('(accomodatie)[1]', 'varchar(50)')
FROM
   @XML.nodes('/reservering') AS ReserveringTable(Reservering),
   @XML.nodes('/reservering/opties') AS OptiesTable(Opties),
   @XML.nodes('/reservering/klant') AS KlantTable(Klant)

DECLARE @WoningID AS int
SET @WoningID = @@IDENTITY

INSERT INTO  [KLANT](
[aanhef], [adres], [emailadres], [naam], [postcode], [rekeningnummer])

SELECT
   Aanhef = Klant.value('(aanhef)[1]', 'varchar(50)'),
   Adres = Klant.value('(adres)[1]', 'varchar(50)'),
   Email = Klant.value('(email)[1]', 'varchar(50)'),
   KlantNaam = Klant.value('(naam)[1]', 'varchar(50)'),
   Postcode = Klant.value('(postcode)[1]', 'varchar(50)'),
   Rekeningnummer = Klant.value('(rekeningnummer)[1]', 'varchar(50)')
FROM
  @XML.nodes('/reservering') AS ReserveringTable(Reservering),
  @XML.nodes('/reservering/opties') AS OptiesTable(Opties),
  @XML.nodes('/reservering/klant') AS KlantTable(Klant)

 DECLARE @KlantID AS int
 SET @KlantID = @@IDENTITY

 INSERT INTO  [RESERVERING](
   [aantal_bezoekers], [product], [reserveringsnummer], [status], [van_datum],
   [tot_datum], [voorkeur], [woning_id], [klant])

 SELECT
    AantalBezoekers = Reservering.value('(aantalBezoekers)[1]', 'int'),
    @ProductID,
    ReserveringNummer = Reservering.value('@reserveringsnummer', 'int'),
    ReserveringStatus = Reservering.value('@status', 'varchar(50)'),
    StartDatum = Reservering.value('(startdatum)[1]', 'date'),
    EindDatum = Reservering.value('(einddatum)[1]', 'date'),
    Voorkeur = Reservering.value('(voorkeur)[1]', 'varchar(50)'),
    @WoningID,
    @KlantID
 FROM
   @XML.nodes('/reservering') AS ReserveringTable(Reservering),
   @XML.nodes('/reservering/opties') AS OptiesTable(Opties),
   @XML.nodes('/reservering/klant') AS KlantTable(Klant)


text:
Q: Python Image Directories Using PIL in python one must put the full directory for an image, so that the program runs properly. Is there any way to make that directory variable? So that it gets the programs current directory then looks for the images in that same folder?
This is in Windows 7 BTW.

A: You are looking for: os.getcwd


text:
Q: User and profile for REST API only I am developing integration in Salesforce with external application. This app uses my api by OAuth password flow. For this I have created user and profile, restricted access to all tabs etc. Are there more options to restrict UI actions? Like allow login via api only?

A: Yes, you can do following things to restrict integration user depending on your needs.
1) You can make that user as API only.
2) remove access from all unrelated objects from his profile
3) remove modify all , view all permission
4) makes sure there are not any permission set assign to integration user
5) makes sure role as low as possible.


text:
Q: Checking if Visual c++ redistribute pack version 2010 is installed on a machine using vb\c# .net I was looking for a programmatic solution for this.
I found some articles with registry keys, but I would like to see if someone has a graceful way to check whether this is installed or not, and if so, which version, 64 or 32 bit.


text:
Q: Extracting EXIF data (specifically dateTime and GPSLatitude and GPSLongitude) with JavaScript I have a program where a camera is set up to constantly take pictures (about every 10 seconds or so) and the picture is sent to a folder on my server and then another program refreshes that folder constantly so that I always just have the most recent picture in that particular folder.
An HTML document exists that also constantly refreshes, and references that picture location to get and display the newest image.
What I'm trying to do is extract the EXIF data (that I've verified exists when I save the image from the active webpage and look at it's properties).  I want to display the DateCreated (I believe this is DateTime) and the Latitude and Longitude (I believe is GPSLatitude and GPSLongitude).
I came across this library, exif-js, which seems like the go-to for most people trying to do this same thing in JavaScript.  My code looks the same as the code at the bottom of the README.md file, except I changed out my img id="...." and variable names, (see below).  It seems like it should work, but it's not producing any data.  My empty span element just stays empty.
Is there an issue with the short time span that the page has before refreshing?
Thanks for any help!
Here's what my code currently looks like (just trying to get the DateTime info).  I have also tried the GPSLatitude and GPSLongitude tags.

<!-- Library to extract EXIF data -->

<script src="vendors/exif-js/exif-js"></script>
<script type="text/javascript">
window.onload=getExif;
function getExif()
{
    var img1 = document.getElementById("img1");
    EXIF.getData(img1, function() {
        var time = EXIF.getTag(this, "DateTime");
        var img1Time = document.getElementById("img1Time");
        img1Time.innerHTML = `${time}`;
    });

    var img2 = document.getElementById("img2");
    EXIF.getData(img2, function() {
        var allMetaData = EXIF.getALLTags(this);
        var allMetaDataSpan = document.getElementById("Img2Time");
        allMetaDataSpan.innerHTML = JSON.stringify(allMetaData, null, "\t");
    });

}

</script>

A: go into ur exif.js file and then go to line 930 and then change it to
EXIF.getData = function(img, callback) {
if ((self.Image && img instanceof self.Image
|| self.HTMLImageElement && img instanceof self.HTMLImageElement)
&& !img.complete)
return false;

A: I know this may be already solved but I'd like to offer an alternative solution, for the people stumbling upon this question.
I'm a developer of a new library exifr you might want to try. It's maintained, actively developed library with focus on performance and works in both nodejs and browser.
    async function getExif() {
        let output = await exifr.parse(imgBuffer)
        console.log('latitude', output.latitude) // converted by the library
        console.log('longitude', output.longitude) // converted by the library
        console.log('GPSLatitude', output.GPSLatitude) // raw value
        console.log('GPSLongitude', output.GPSLongitude) // raw value
        console.log('GPSDateStamp', output.GPSDateStamp)
        console.log('DateTimeOriginal', output.DateTimeOriginal)
        console.log('DateTimeDigitized', output.DateTimeDigitized)
        console.log('ModifyDate', output.ModifyDate)
    }

You can also try out the library's playground and experiment with images and their output, or check out the repository and docs.


text:
Q: Can't add Campaign Influence Apex Trigger to packages? I'm trying to create an unlocked package that uses an Apex trigger to create campaign influence records for a custom campaign influence model. I keep running into errors that seem to be caused by the Apex trigger that creates the campaign influence records.
I used a playground org to develop the Apex trigger as well as the other components for the package (Apex test class, custom campaign influence model record, permission sets...). I tried to add the trigger to an unmanaged package so I could retrieve it with sfdx, but the trigger was not visible when I was trying to add it as a package component. I could add everything else to the package, including the test class for the trigger.
I was able to retrieve the Apex trigger separately without adding it to the package, but now when I try to create the first unlocked package version with sfdx, I'm getting this error:
"Multi_Touch_Campaign_Model: Not available for deploy for this organization, CampaignInfluenceRecordCreationTest: Invalid type: CampaignInfluence,.."
My playground org has dev hub, unlocked packages, and campaign influence enabled. My apex api version is 48. I'm relatively new to developing in SF, but I can't find any similar scenario online.
I guess I should add that the Apex trigger works fine along with the other components I developed for this package in the trailhead playground.

A: You need to include the appropriate settings file in order for this to work in an Unlocked Package.
The CampaignInfluenceModel metadata is supported in Unlocked Packages. You will need to include a Settings file in your Unlocked Package in order to "enable" this for your package, as it is not enabled by default in any org.
Enabling this will also require orgs where the package is to be installed to have this feature enabled before installing the package.

A: I'm actually op, but I can't log in with guest account to mark as solved for some reason.
But sfdcfox's answer worked!
To be more specific, I had to add a definitionfile reference to the sfdx project json file that points to my scratch org config json file. In the scratch org file, I added a campaign setting: "enableCampaignInfluence2": true.

A: I encountered another problem trying to create another package version. I'm trying to add custom reports based on the standard "Campaigns with Influenced Opportunities (Customizable Campaign Influence) report type, but I'm getting this error:
ERROR running force:package:version:create:  MultiTouchCampaignAttributionReports/Campaigns_Responses_Timeline_32e: ReportType: CustomizableCampaignInfluence is not available,CampaignDashboards/LVifBmlFPZfCzLyPdtRuoaDwcPJgdR: In field: report - no Report named MultiTouchCampaignAttributionReports/Campaigns_Responses_Timeline_32e found,MultiTouchCampaignAttributionReports/Campaigns_with_Influenced_Opportunities_2Pg: ReportType: CustomizableCampaignInfluence is not available
This is a standard report type that i think gets generated when an org enables customizable campaign influence, but I already have that setting in my definition file. Is there another setting I need to add, or is there no way to deploy reports based on this report type?


text:
Q: Bind multiple listener to the same port I am using UdpClient class in .net 3.5
I need to bind multiple applications to the same port .
So, if UDP servers broadcast any request - all the applications thats listen on the port can receive the message but the problem is, when I try bind to an application to the same port, only one application receive the message and the other does not.
Below is some sample code for the two application:
    UdpClient udpClient = new UdpClient();
    Thread thread;
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 11000);
    public Form1()
    {
        //CheckForIllegalCrossThreadCalls = false;

        InitializeComponent();
        udpClient.ExclusiveAddressUse = false;
        udpClient.Client.SetSocketOption(
        SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpClient.Client.Bind(endPoint);
    }

    private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            thread.Abort();
            udpClient.Close();
            Close();
        }
    }

    private void ReceiveMessage()
    {
        //while (true)
        //{
        // IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 11000);
        //  byte[] content = udpClient.Receive(ref endPoint);
        udpClient.BeginReceive(new AsyncCallback(Read_Callback), null);

        //if (content.Length > 0)
        //{
        //    string message = Encoding.ASCII.GetString(content);

        //    this.Invoke(myDelegate, new object[] { message });
        //}
        // }
    }

    public void Read_Callback(IAsyncResult ar)
    {
        try
        {
            byte[] buffer = udpClient.EndReceive(ar, ref endPoint);
            // Process buffer
            string s = Encoding.ASCII.GetString(buffer);
            // richTextBox1.Text = s;
            udpClient.BeginReceive(new AsyncCallback(Read_Callback), null);

        }
        catch (Exception ex)
        { }
    }

PS : I am unable to figure out the reason or am I missing something. ?

A: That's the nature of sockets. Even in cases (such as UDP) where multiple applications can access the same port, the data is handed out first-come, first-serve.  UDP is also designed with minimum overhead, so there isn't even an opportunity to "check the queue," like you (hypothetically) could with TCP.
It's designed around having multiple processes share a server load, alternating who receives the request based on who's idle.
You'd need to build something external to get around this, like a retransmission protocol or a database to make sure every inbound message is shared.
If you can deal with the changes, a smarter way to handle this would be UDP Multicast, where multiple programs essentially enroll to receive group messages.  In that case, the single-port restriction can (and should) be abandoned.


text:
Q: r shiny: Creating widgets in ui.R vs. renderUI + uiOutput I have a question that falls more into a "best practice" type of inquiry. When using shiny package in r, is it better to create all widgets on the server side using renderUI and then pushing those to the ui via uiOutput? Or, when possible, should all widgets be created on the ui side?
For instance, the two apps below do the same thing but in the second one, I create the sliderInput on the server side and then push that to the ui rather than creating it in the ui side. (Note, this code is pulled from the Hello Shiny page on R Studio)
App 1 - "Standard Approach" creating widget in ui
#ui.R

# Define UI for application that plots random distributions
library(shiny)
ui1 <- shinyUI(fluidPage(

    # Application title
    titlePanel("Hello Shiny!"),

    # Sidebar with a slider input for number of observations
    sidebarLayout(
        sidebarPanel(
            sliderInput("obs",
                        "Number of observations:",
                        min = 1,
                        max = 1000,
                        value = 500)
        ),

        # Show a plot of the generated distribution
        mainPanel(
            plotOutput("distPlot")
        )
    )
))

#server.R

# Define server logic required to generate and plot a random distribution
library(shiny)
server1 <- (function(input, output) {

    output$distPlot <- renderPlot({

        # generate an rnorm distribution and plot it
        dist <- rnorm(input$obs)
        hist(dist)
    })

})

runApp(shinyApp(ui = ui1, server = server1))

App 2 - Alternative Approach - Creating Widget on server side
#ui.R

# Define UI for application that plots random distributions
library(shiny)
ui2 <- shinyUI(fluidPage(

    # Application title
    titlePanel("Hello Shiny!"),

    # slider comes from the si object created in server.R
    sidebarLayout(
        sidebarPanel(
            uiOutput("si")
        ),

        # Show a plot of the generated distribution
        mainPanel(
            plotOutput("distPlot")
        )
    )
))

#server.R

# Define server logic required to generate and plot a random distribution
library(shiny)
server2 <- (function(input, output) {

    #create slider with renderUI
    output$si <- renderUI(
        sliderInput("obs",
                    "Number of observations:",
                    min = 1,
                    max = 1000,
                    value = 500)
    )

    output$distPlot <- renderPlot({

        # generate an rnorm distribution and plot it
        dist <- rnorm(input$obs)
        hist(dist)
    })

})

runApp(shinyApp(ui = ui2, server = server2))

To me, the second approach is more generalizable so it should win. However, I am no expert and I rarely see this approach being used unless there is a specific reason why you need the widgets to be responsive in some way. The ways in which I have required responsiveness include:

*

*There is data loaded on the server side which ends up feeding the widget choices so it is better to only load the data one time on the server side and create the widgets there, rather than load it on the server and ui side.

*We need to turn off/on widgets and/or allow them to react to other user input

Since the second approach I've presented can handle the above two options, it makes sense to me that it should be used in all cases, even when there is no real need to create the widget on the server side. I notice that when using the second approach, there is a delay, sometimes accompanied by warnings/errors prior to the widgets being loaded. That is the only downside I've noticed about the approach.
Is one of these approaches considered a "best practice?"
Thanks.


text:
Q: (discord.py) How can I get a list of how many permissions a user has I am currently making a "userinfo" command for my bot which returns general stuff like the user's ID, roles, profile picture, etc. And I also wanted it to display a list of how many permissions the mentioned user has. Here's the part of the code where I defined member just for context:
@client.command(aliases=["whois"])
async def userinfo(ctx, member: discord.Member = None):
    if not member:  # if member is no mentioned
        member = ctx.message.author  # set member as the author
    ...

I am aware that you can do member.guild_permissions.<permission> which returns whether the user has a permission or not but I wanted to know if there was a way to just get a list of how many permissions a user has without having to check for every permission.
So is there a way to do that?

A: You can actually use Member.guild_permissions:
@client.command(aliases=["whois"])
async def userinfo(ctx, member: discord.Member = None):
    if not member:
        member = ctx.message.author
    perm_list = [perm[0] for perm in member.guild_permissions if perm[1]]

Member.guild_permission returns a list of tuples (eg. (manage_permissions, True)). You can explore this list and add the permission to another list if it is True.


text:
Q: I stand by you vs I'll stand by you Is the phrase "I stand by you" grammatically correct on its own?
I know there is a song called "I'll stand by you" and understand the implication of "will". I want to use the phrase "I stand by you" so that it doesn't infringe on a potential copyright issue.
Many thanks


text:
Q: How to remove all default Anchor styles so element is unaffected? Is there a set of styles that you can set to remove all anchor styles?
The most I can do is remove the text decoration but I don't want to define a color because each text field could be a different color:

#text {
    color: green;
}
a {
    text-decoration: none;
    color: none;
}
<a href="" id="text">
    Text
</a>

UPDATE:
There was a typo in my code. So the link was not connected to the style rule.

A: a { color: inherit; }

… will cause the element to take on the colour of its parent (which is what I think you are looking for).
explanation of inherit property

A: a {

    text-decoration: none;
    color: unset;
}

/* Global values */
color: inherit;
color: initial;
color: unset;

https://developer.mozilla.org/fr/docs/Web/CSS/color
use unset instead of none


text:
Q: exim is not accepting external connections Update: It's definitely my ISP blocking port 25. I told Exim to listen on a non-standard port, and then checked from a remote computer to that port, and it went through just fine.
So, I guess I have a new question. Is there a good way to get around this?
I no I can't specify a port in the MX record (why didn't anyone think of this when they were coming up with DNS?), but a service that can forward mail to a server on a non-standard port would work.
I've seen no-ip.com has such a service called Reflector. It's not very expensive, but if there are any other, cheaper methods, I'd love to hear about them.
I'm still baffled as to why it just today stopped working, though.

Original Question
I hate asking this, but I've already Googled everything I can think to no avail, but this seems like such a simple thing, so I don't know why I can't figure it out. But, here it goes anyway.
I have a home server set up with Apache for HTTP and Exim for SMTP. I need to be able to accept mail straight to my home computer. Up until today, I had no problems. I don't believe I changed anything on my end, but suddenly, I'm not getting any email.
I checked MX setting in DNS, and they're fine. I checked the port forwarding on my router, and it looks fine (and external connections to Apache are still coming through).
So, I check that Exim is working properly. From localhost, I can telnet into Exim, and it works fine. Additionally, I can telnet into Exim from other computers on the network, and it works fine. However, if I try to telnet from outside, I get Unable to connect to remote host: Connection timed out.
So, I tried to do dpkg-reconfigure exim4-config (I'm on Ubuntu 12.10, by the way), and make sure that everything's set up properly there. No problems. I look in my config and find this:
# listen on all all interfaces?
.ifdef MAIN_LOCAL_INTERFACES
local_interfaces = MAIN_LOCAL_INTERFACES
.endif

Some googling leads me to believe that local_interfaces controls what exim will listen to. So I try to change this according to the exim documentation, and make it this:
# listen on all all interfaces?
#.ifdef MAIN_LOCAL_INTERFACES
#local_interfaces = MAIN_LOCAL_INTERFACES
#.endif
local_interfaces = <; ::0 ; 0.0.0.0

I restart exim, and nothing changes.
So, that's where I'm at now. It's kind of important that I get this fixed soon, so any ideas what else I might check would be appreciated.
P.S. Since commenting won't give my proper formatting, I'm replying here:
lsof -i:25: I'm not really sure what I'm looking for, but here's the output:
COMMAND   PID        USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
exim4   12386 Debian-exim    3u  IPv6 24476126      0t0  TCP *:smtp (LISTEN)
exim4   12386 Debian-exim    4u  IPv4 24476127      0t0  TCP *:smtp (LISTEN)

P.P.S. According to this page, my ISP blocks port 25 inbound (and outbound). But that page was written several months ago, and the problem just appeared today (or maybe yesterday), so is there any way I can check to see if that's the problem?

A:
I'm still baffled as to why it just today stopped working, though.

Maybe your mail server had a busy day yesterday so the ISP noticed your abuse of the ToS?
Notice, that sending mail to another port would probably still conflict with your ISPs terms if it was running on some non-standard port, so I won't give explicit advice or recommend that to you.
I, for example, did receive a warning once from my ISP regarding "excessive" incoming and outgoing mail.
Discussing legitimation for this rule is something to do somewhere else.
You could, however, set up a cheap VPS somewhere to handle mail.
How to process that mail (directly on the VPS, or at home) is your task to evaluate.
Your remote node not necessarily needs to run its own mail server. Using a mail proxy like nginx - or even plain TCP proxying - would be fine, too.

A: I have had a similar problem but not quite the same. My mail server kept getting flagged as a spammer by Spamhaus. I checked everything including outgoing connections on port 25.
None, niente, nada!
I tried to turn off the mail server. Still reported by Spamhaus.
Turned off the router … and no more Spamhaus flagging! Turned it back on and within an hour flagged again.
The router belonged to the ISP so I talked to them and guess what? They did not care. After complaining a couple of times they did the only sensible thing (at least in their opinion, apparently) they blocked port 25 incoming. It did stop the spamming, indeed, but it also rendered my mailserver useless. I complained several times to the ISP, but they did not care.
Luckily, I had other problems with this ISP and had just received a new (cheaper and faster) incoming line. This line had the problem of not having a permanent IP address, which I skirted by automatically updating the DNS on a regular basis.
I have subsequently set up a cheap virtual server at one of the international providers and use that for outgoing mail and as a backup for incoming mail, should my main connection again suffer from port 25 blocking. The reason for using a hosted server for outgoing mail is the fact that almost everyone now blocks incoming mail from ISPs they either consider domestic or are not big enough to be able to complain hard enough for the main mail providers to care. (Google, Microsoft, Mimecast and other, do you listen????)


text:
Q: Save, Update and Delete is not working in Hibernate and Spring This is my application-context, Dao Implementation class, and Service class. if I try to fetch any record, in response I have all the record in my objects but when I try to save or update or try to delete the object from database nothing happen without any exception.
<?xml version="1.0" encoding="UTF-8"?>

    <context:annotation-config />

    <context:component-scan base-package="org.prosigns.adminity.model.layers" />

    <mvc:annotation-driven />

    <tx:annotation-driven transaction-manager="transactionManager" />

    <context:property-placeholder location="classpath:hibernate.properties" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}"/>

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
          p:basename="Messages" />

    <bean id="sessionFactory" class="org.prosigns.adminity.model.common.annotation.ScanningAnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedPackages">
            <list>
                <value>org.prosigns.adminity.model.layers.domain.**.*</value>
                <value>org.prosigns.adminity.model.layers.dao.**.*</value>
                <value>org.prosigns.adminity.model.layers.services.**.*</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
                <prop key="org.hibernate.transaction">false</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
                <prop key="hibernate.max_fetch_depth">${hibernate.fetch_depth}</prop>
                <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
                <prop key="hibernate.transaction.factory_class">${hibernate.transaction_factory_class}</prop>
                <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.use_reflection_optimizer}</prop>
                <prop key="hibernate.connection.release_mode">${hibernate.connection_release_mode}</prop>
                <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc_batch_size}</prop>
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache_use_second_level_cache}</prop>
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
            </props>
        </property>
    </bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

</beans>

@Repository
public class PersistenceDaoImpl<T, PK extends Serializable> implements PersistenceDao<T, PK> {

    /** Class type. */
    Class<T> type;

    /**
     * Gets the current session in use (creates one if necessary).
     * @return Session object
     */
    public Session getSession() throws DatabaseException{
        return SessionManager.getSessionFactory().openSession();
    }

    /**
     * Default bean constructor for spring.
     */
    public PersistenceDaoImpl() {
        // default constructor for spring
    }

    /**
     * Constructor.
     * @param type class type
     */
    public PersistenceDaoImpl(Class<T> type) {
        this.type = type;
    }

    /** Helper functions.
     * @return the currently set class
     */
    public Class<T> getPersistentClass() {
        return this.type;
    }

    /**
     * Delete persistentObject from DB.
     * @param persistentObject object to delete.
     */
    public void delete(T persistentObject) throws DatabaseException{
        getSession().delete(persistentObject);

    }

    /** Deletes an object of a given Id. Will load the object internally so consider using delete (T obj) directly
     * @param id Delete key
     */
    public void delete(PK id) throws DatabaseException{
        getSession().delete(load(id));
    }

    /**
     * Loads the given Object.
     * @param id to load
     * @return T Loaded object
     */
    @SuppressWarnings("unchecked")
    public T load(PK id) throws DatabaseException{
        T t = (T) getSession().load(this.type, id);
        if (t == null){
            return (T) new Object();
        }
        return t;
    }

    /**
     * Loads the given Object.
     * @param id Id to load
     * @return An object of type T
     */
    @SuppressWarnings("unchecked")
    public T get(PK id) throws DatabaseException{
        return (T) getSession().get(this.type, id);
    }

    /**
     * Item to save.
     * @param o object to save
     * @return PK
     */
    @SuppressWarnings("unchecked")
    public PK save(T o) throws DatabaseException{
        return (PK) getSession().save(o);
    }

   /**
     * Item to refresh.
     * @param o object to refresh
     */
    public void refresh(T o) throws DatabaseException{
        getSession().refresh(o);
    }

    /**
     * Item to saveOrUpdate.
     * @param o item to save.
     */
    public void saveOrUpdate(T o) throws DatabaseException{
        getSession().saveOrUpdate(o);
    }

    /**
     * Update object.
     * @param o object to update
     */
    public void update(T o) throws DatabaseException{
        getSession().update(o);
    }

    /**
     * Get query.
     * @param s Query to execute.
     * @return Query object
     */
    public Query getQuery(String s) throws DatabaseException{
        return getSession().createQuery(s);
    }

    /** Delete object.
     * @param persistentObject to delete
     * @param session to use
     *
     */
    public void delete(T persistentObject, Session session) throws DatabaseException{
        getSession().delete(persistentObject);
    }

    /** Deletes an object of a given Id. Will load the object internally so consider using delete (T obj) directly.
     * @param id to delete
     * @param session to use
     */
    public void delete(PK id, Session session) throws DatabaseException{
        getSession().delete(load(id));
    }

    /**
     * Loads the given Object.
     * @param id to load
     * @param session to use
     * @return  an object of type T
     */
    @SuppressWarnings("unchecked")
    public T load(PK id, Session session) throws DatabaseException{
        return (T) session.load(this.type, id);
    }

    /**
     * Loads the given Object.
     * @param id Id to load
     * @param session Session to use
     * @return An object of type T
     */
    @SuppressWarnings("unchecked")
    public T get(PK id, Session session) throws DatabaseException{
        return (T) session.get(this.type, id);
    }

    /** Save object.
     * @param o to save
     * @param session to use
     * @return the id of the saved object
     *
     */
    @SuppressWarnings("unchecked")
    public PK save(T o, Session session) throws DatabaseException{
        return (PK) session.save(o);
    }

    /** Save Or Update object.
     * @param o to save
     * @param session to use.
     *
     */
    public void saveOrUpdate(T o, Session session) throws DatabaseException{
        session.saveOrUpdate(o);
    }

    /** Update record.
     * @param o to update
     * @param session to use
     *
     */
    public void update(T o, Session session) throws DatabaseException{
        session.update(o);
    }

    /**
     * GetQuery.
     * @param s to return
     * @param session  to use
     * @return Query object
     */
    public Query getQuery(String s, Session session) throws DatabaseException{
        return session.createQuery(s);
    }

    /** Wrapper around hibernate functions.
     * @param criterion to use
     * @return A list of matching objects
     */
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(Criterion... criterion) throws DatabaseException{
        Criteria criteria =  getSession().createCriteria(getPersistentClass());

        for (Criterion c : criterion) {
            criteria.add(c);
        }
        return criteria.list();
    }

    /** FindAll.
     * @return A list of all the objects
     */
    public List<T> findAll() throws DatabaseException{
        return findByCriteria();
    }

    /** Flushes the cache of the currently-used session.
     * @throws DatabaseException
     * @throws HibernateException
     *
     */
    public void flush() throws DatabaseException {
        getSession().flush();
    }

    /** Object to evict from cache.
     * @param obj Object to evict
     */
    public void evict(Object obj) throws DatabaseException{
        getSession().evict(obj);
    }

    /** FindByExample.
     * @param exampleInstance to use
     * @param excludeProperty to use
     * @return List of matching objects
     */
    @SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String... excludeProperty) throws DatabaseException{
        Criteria criteria = getSession().createCriteria(getPersistentClass());
        Example example = Example.create(exampleInstance);
        for (String exclude : excludeProperty) {
            example.excludeProperty(exclude);
        }
        criteria.add(example);
        return criteria.list();
    }
}

@Service("crmAuthenticationService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class CrmAuthenticationServiceImpl implements CrmAuthenticationService{

    @Transactional (readOnly = false, propagation = Propagation.REQUIRED)
    public void saveUpdate(CrmAuthenticationVO vo) throws GenericException {
        if (vo.isForUpdate()){
            vo.setUpdatedBy(WebUtils.getLoggedUserId());
            vo.setUpdatedDate(CommonUtils.getCurrentDate());
        }else {
            vo.setAddedBy(WebUtils.getLoggedUserId());
            vo.setAddedDate(CommonUtils.getCurrentDate());
        }
        CrmAuthentication domain = new CrmAuthentication();
        domain.setValueObject(vo.getValueObject());
        DaoManager.getInstance().getCrmAuthenticationDao().update(domain);
    }
}

A: You need to make the save, update and delete calls within a transaction.
Try adding the @Transactional annotation to your DAO. Spring will create a transaction-aware proxy to wrap your DAO. When the transaction finishes it will cause Hibernate to flush and commit.


text:
Q: Parse date in ZF2 I'm having a problem.
I'm using ZF2, and getting an error here.
$inputFilter->add($factory->createInput(array(
    'name' => 'dataInicial',
    'required' => true,
    'validators' => array(
        array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'A data do feriado deve ser preenchida.'
                )
            )
        ),
        array(
            'name' => 'callback',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\Callback::INVALID_CALLBACK => 'Data no formato inválido.'
                ),
                'callback' => function ($value, $context = array()) {
                        $dataInicial = \DateTime::createFromFormat('d/m/Y', $value);
                        return $dataInicial->format('d/m/Y');
                }
            )
        )
    )
)));

I'm getting this error:
DateTime::__construct(): Failed to parse time string (25/12/2014) at position 0 (2): Unexpected character

When I execute the same code in pure php, without zend, it works ok.
echo DateTime::createFromFormat('d/m/Y', '25/12/2014')->format('d/m/Y');

Maybe someone knows what's causing the error? Sorry for my english

A: Don't know what kind of database backend and relationship mapping but the issue is related to how the date is being stored I imagine, most likely like: Y/m/d
If you saving and getting this error then it's because you need the date in this format. If you are hydrating you may also need a date strategy to deal with hydration like:
// InputFilter.php
class yourInputFilter()
{

    $hydrator->getHydrator()->addStrategy('my_attribute', new MyDateHydrationStrategy());

    $this->add( array(
        'name' => 'registration_starts',
        'type' => 'Zend\Form\Element\DateTime',
        'options' => array (
            'format'=>'Y/m/d',
        )
    ));
}

// YourForm.php
class YourForm Extends ....
{
    $dateTime = new Element\DateTime('youDate');
    $dateTime->setLabel('Date')
             ->setOptions(array(
                'format' => 'Y-m-d\TH:iP'
    ));
}

// Strategy.php
class myDateTimeStrategy implements StrategyInterface
{
    public function hydrate($value)
    {
        if (is_string($value)) {
            $value = new DateTime($value);
        }

        // Could return in a different format, probably can't though because of when you need to edit
        // return $value->format("m-d-Y")

        return $value;
    }
}

You will also need to change js settings if you using a datetime widget picker:
Which will be something like:
$('.datepicker').datepicker('format', 'yyyy/mm/dd');

Depending on which one you using.


text:
Q: Can I produce a synthetic sound using OpenAL? I'm learning Java OpenAL bindings (version 3.1.2) and I would like to make a custom sound (synthetic).
I've searched the web for this, but I haven't found what I'm looking for - all tutorials show how to play sound files.
I want to make an app in which I can "program" the sounds. So far I understand that the data of sound files is being passed into a buffer. Can I figure out what data must be put in those buffers in my case?
Here is my application's base. It is written in Groovy.
package alexiy.openal

import javafx.application.Application
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.layout.GridPane
import javafx.stage.Stage
import javafx.stage.WindowEvent
import org.lwjgl.BufferUtils
import org.lwjgl.openal.*
import org.lwjgl.system.libc.LibCStdlib

import java.nio.ByteBuffer
import java.nio.IntBuffer

class OALP extends Application {
    static ALCapabilities alCapabilities;
    static ALCCapabilities alcCapabilities;

    @Override
    void start(Stage primaryStage) throws Exception {

        String deviceinfo= ALC10.alcGetString(0,EnumerateAllExt.ALC_DEFAULT_ALL_DEVICES_SPECIFIER);

        println('Device: '+deviceinfo)
        long device= ALC10.alcOpenDevice(deviceinfo);
        if(device==0) throw new RuntimeException("Couldn't find such device")
        println device

        int[] attributes=[ALC11.ALC_STEREO_SOURCES,1,0]
        long context=ALC10.alcCreateContext(device,attributes)
        println context
        boolean b=ALC10.alcMakeContextCurrent(context)
        alcCapabilities= ALC.createCapabilities(device)
        AL.createCapabilities(alcCapabilities)
        alCapabilities= AL.getCapabilities()
        GridPane gridPane=new GridPane();
        gridPane.setVgap(6)
        gridPane.setHgap(6)
        Scene scene=new Scene(gridPane,300,100)
        primaryStage.setScene(scene)
        Button decode=new Button("Decode")
        decode.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            void handle(ActionEvent event) {
                File track=new File("Fields.ogg")

            }
        })
        gridPane.add(decode,0,0)
        primaryStage.show();
        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            void handle(WindowEvent event) {
                ALC10.alcMakeContextCurrent(0)
                ALC10.alcDestroyContext(context)
                ALC10.alcCloseDevice(device)
            }
        })
        int seconds=4;
        int samplerate=44100
        int buffersiz=seconds*samplerate
        int buffer=AL10.alGenBuffers()
        float freq=1
        float incr=0.1f
//        IntBuffer intBuffer=IntBuffer.allocate(buffersiz)
        ByteBuffer intBuffer=LibCStdlib.malloc(buffersiz)
        for (int i = 0; i < buffersiz; i++) {
            intBuffer.put(i,(byte) (32760 * Math.sin( 2 * 3.14 *freq)/samplerate * i))
            freq+=incr
            if (100.0 > freq || freq > 5000.0) {

                incr *= -1.0f;
            }
        }
        AL10.alBufferData(buffer,AL10.AL_FORMAT_STEREO16, intBuffer,300)
        LibCStdlib.free(intBuffer)
        int souirce=AL10.alGenSources()
        AL10.alSourcei(souirce,AL10.AL_BUFFER,buffer)
        AL10.alSourcePlay(souirce)
        Thread.sleep(3000)
        printError()
    }

    static void printError(){ println AL10.alGetString(AL10.alGetError())}
}

A: Here is some c code where I use OpenAL to render audio which is synthesized locally from calling sin function in a loop ... translating to java should be straight forward
// sudo apt-get install libopenal-dev  #  install OpenAL on linux

// gcc -o openal_play_monday   openal_play_monday.c  -lopenal -lm

#include <stdio.h>
#include <stdlib.h>    // gives malloc
#include <math.h>
#include <unistd.h>    // gives sleep

#ifdef __APPLE__
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#elif __linux
#include <AL/al.h>
#include <AL/alc.h>
#endif

ALCdevice  * openal_output_device;
ALCcontext * openal_output_context;

ALuint internal_buffer;
ALuint streaming_source[1];

int al_check_error(const char * given_label) {

    ALenum al_error;
    al_error = alGetError();

    if(AL_NO_ERROR != al_error) {

        printf("ERROR - %s  (%s)\n", alGetString(al_error), given_label);
        return al_error;
    }
    return 0;
}

void MM_init_al() {

    const char * defname = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);

    openal_output_device  = alcOpenDevice(defname);
    openal_output_context = alcCreateContext(openal_output_device, NULL);
    alcMakeContextCurrent(openal_output_context);

    // setup buffer and source

    alGenBuffers(1, & internal_buffer);
    al_check_error("failed call to alGenBuffers");
}

void MM_exit_al() {

    ALenum errorCode = 0;

    // Stop the sources
    alSourceStopv(1, & streaming_source[0]);        //      streaming_source
    int ii;
    for (ii = 0; ii < 1; ++ii) {
        alSourcei(streaming_source[ii], AL_BUFFER, 0);
    }
    // Clean-up
    alDeleteSources(1, &streaming_source[0]);
    alDeleteBuffers(16, &streaming_source[0]);
    errorCode = alGetError();
    alcMakeContextCurrent(NULL);
    errorCode = alGetError();
    alcDestroyContext(openal_output_context);
    alcCloseDevice(openal_output_device);
}

void MM_render_one_buffer() {

    /* Fill buffer with Sine-Wave */
    // float freq = 440.f;
    float freq = 100.f;
    float incr_freq = 0.1f;

    int seconds = 4;
    // unsigned sample_rate = 22050;
    unsigned sample_rate = 44100;
    double my_pi = 3.14159;
    size_t buf_size = seconds * sample_rate;

    // allocate PCM audio buffer
    short * samples = malloc(sizeof(short) * buf_size);

   printf("\nhere is freq %f\n", freq);
    int i=0;
    for(; i<buf_size; ++i) {
        samples[i] = 32760 * sin( (2.f * my_pi * freq)/sample_rate * i );

        freq += incr_freq;
        // incr_freq += incr_freq;
        // freq *= factor_freq;

        if (100.0 > freq || freq > 5000.0) {

            incr_freq *= -1.0f;
        }
    }

    /* upload buffer to OpenAL */
    alBufferData( internal_buffer, AL_FORMAT_MONO16, samples, buf_size, sample_rate);
    al_check_error("populating alBufferData");

    free(samples);

    /* Set-up sound source and play buffer */
    // ALuint src = 0;
    // alGenSources(1, &src);
    // alSourcei(src, AL_BUFFER, internal_buffer);
    alGenSources(1, & streaming_source[0]);
    alSourcei(streaming_source[0], AL_BUFFER, internal_buffer);
    // alSourcePlay(src);
    alSourcePlay(streaming_source[0]);

    // ---------------------

    ALenum current_playing_state;
    alGetSourcei(streaming_source[0], AL_SOURCE_STATE, & current_playing_state);
    al_check_error("alGetSourcei AL_SOURCE_STATE");

    while (AL_PLAYING == current_playing_state) {

        printf("still playing ... so sleep\n");

        sleep(1);   // should use a thread sleep NOT sleep() for a more responsive finish

        alGetSourcei(streaming_source[0], AL_SOURCE_STATE, & current_playing_state);
        al_check_error("alGetSourcei AL_SOURCE_STATE");
    }

    printf("end of playing\n");

    /* Dealloc OpenAL */
    MM_exit_al();

}   //  MM_render_one_buffer

int main() {

    MM_init_al();

    MM_render_one_buffer();
}


text:
Q: How AWS DynamoDB query result is a list of items while partition key is a unique value I'm new to AWS DynamoDB and wanted to clarify something.
As I learned when we use query we should use the partition key which is unique among the list of items, then how the result from a query is a list!!! it should be one row!! and why do we even need adding more condition?
I think I am missing something here, can someone please help me to understand?
I need this because I want to query on list of applications with specific status value or for specific range of time but if I am supposed to provide the appId what is the point of the condition?
Thank you in advance.

A: Often your table will have sort key, which together with your partition key will create composite primary key. In this scenario a query can return multiple items. To return only one value, not a list, you can use get_item instead if you know unique value of the composite primary key.


text:
Q: How to 2-way bind localStorageService in AngularJs? I am right now building a customer-cashier type of app using browser's local storage. I figured how to use local storage but it is not updating cashier side if I give a new order from customer side.
app.controller('posController', function($scope,localStorageService,Data,$rootScope,$window){
  console.log(localStorageService.get("placedOrder"));
  $scope.orders = localStorageService.get("placedOrder");
});

app.controller("orderController",function($scope,Data,localStorageService){
  var arr = localStorageService.get("placedOrder") || [];
  arr.push({"name":$scope.name,
                        "order": $scope.order,
                         "time": Data.time,
                         "email": Data.email
                       });
  localStorageService.get("placedOrder",arr)
  console.log(Data.placedOrder);
});

so the posController should get updated as soon ordercontroller updates the localStorage.

A: Assuming you mean the cashier and customer are using different systems this will not work. Local Storage is for the browser and not meant for these types of transactions. You will need to use a database thats hosted on a network for this type of application.

A: You need to communicate to other controller, that something is changed, please update your data.
That is possible by using
event communication, it allows you to decouple your logic.
You have to call/ fire event like this
$rootScope.$brodcast("myevent");
And other side you have to use like below for listening fired event.
$rootScope.$on("myevent",function(){
....Update your other controller data...
});


text:
Q: GetModuleFileName like APIs in WinRT I'm writting a dll for windows phone 8, and need to know which module are calling my functions in dll. Howerver, the GetModuleFileName API is not compatible with WinRT. So is there any C++ API that is able to do the same thing?
Thanks for any help.


text:
Q: What should I do? The RecyclerView I used on a fragment in a TabLayout fragment won't show I am trying to show a RecyclerView on a fragment in a TabLayout that is also a fragment. However, the RecyclerView still refuses to show up even if there is no errors. Based on information I have gathered, it should be possible for a fragment of a TabLayout to have a RecyclerView. However, I don't know if the problem lies within the fact that I built my TabLayout on a fragment causing the recyclerview to not show. I figure I must be doing something wrong and I need some help. Here is my code:
TabLayoutFragment
    var viewPager = root.findViewById(R.id.viewPager) as ViewPager
    var tablayout = root.findViewById(R.id.tabLayout) as TabLayout

    val fragmentAdapter = FragmentAdapter(requireActivity().supportFragmentManager)
    fragmentAdapter.addFragment(OpenLoansFragment(), "Active")
    fragmentAdapter.addFragment(ClosedLoansFragment(), "Closed")

    viewPager.adapter = fragmentAdapter
    tablayout.setupWithViewPager(viewPager)

RecyclerView Fragment
private lateinit var swipeRefreshLayout:SwipeRefreshLayout
private lateinit var loanRecRcv:RecyclerView
private var list: ArrayList<LoanRecordModel> = ArrayList()
private var loanRecRcvAdapter = LoanRecRcvAdapter(list, this)

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    _binding = FragmentOpenLoansBinding.inflate(inflater, container, false)
    val root: View = binding.root

    return root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    list = arrayListOf(
        LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
        LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
        LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
        LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
        LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open")

    )

    initView()

    loanRecRcv.apply{
        layoutManager = LinearLayoutManager(activity)
        adapter = loanRecRcvAdapter
    }
}

private fun initView() {

    swipeRefreshLayout = requireActivity().findViewById(R.id.swipeRefresh)
    loanRecRcv = requireActivity().findViewById(R.id.loanRecRcv)

}

A: You're displaying an empty list in your RecyclerView. First you create an empty adapter at construction time:
// empty list
private var list: ArrayList<LoanRecordModel> = ArrayList()
// adapter created with the empty list
private var loanRecRcvAdapter = LoanRecRcvAdapter(list, this)

And later you apply that adapter to your RV:
loanRecRcv.apply{
    ...
    adapter = loanRecRcvAdapter
}

You're creating a list of items in onViewCreated
list = arrayListOf(
    LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
    ...
)

but that's replacing the list stored in your list variable. You already created your Adapter earlier (at construction) using the original list, so it's still using that empty list internally. It's not referencing your list variable.

Two basic options - either make list a MutableList and update its contents instead of replacing it:
// empty mutable list - you never need to actually use ArrayLists or whatever
// made it a val so you can't replace it!
private val list = mutableListOf<LoanRecordModel>()
// pass that list object to the adapter, so it's shared
private var loanRecRcvAdapter = LoanRecRcvAdapter(list, this)

...

// update your list contents
list.addAll(listOf(
    LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
    ...
))
// notify the adapter that it needs to refresh since its data set (the shared list) has changed
adapter.notifyDataSetChanged()

or (better) just pass new data to the adapter and let it store that internally, handle updating itself etc:
// in your adapter

// store the current data here - initially an empty list, so it can still display
private var list: List<LoanRecordModel> = emptyList()

fun setData(data: List<LoanRecordModel>) {
    // calling toList makes a new list object - even if the 'data' list object gets
    // modified later, we have our own internal list object that won't be affected
    list = data.toList()
    // update the display however you like
    notifyDataSetChanged()
}

// in your fragment

adapter.setData(listOf(
    LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"),
    ...
))

This way's better because the adapter's data set is held internally, instead of in your fragment. You have a simple setData function that takes the new data, and handles updating the adapter as required. The caller doesn't need to know about any of this, it just passes in data. You can remove your List parameter from the Adapter's constructor too - you weren't initialising it to anything but an empty list anyway - and now that's the default value for that internal list property

btw, to initialise that list of identical things, you could do
// create an immutable list
val list = List(5) { LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open") }

// or add to a mutable list
list.addAll(List(5) { LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open") })

// or another way
repeat(5) {
    list.add(LoanRecordModel("", "Petty Cash Loan", "12/05/2022", "Open"))
}

if you like


text:
Q: Share image to SMS, Mail, Save Image with UIDocumentInteractionController I want to share image to SMS, Mail and Save Image with UIDocumentInteractionController.  just social apps to shared image.
self.documentationInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];
self.documentationInteractionController.delegate = self;
[self.documentationInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

Can you help me ?
Thank You !


text:
Q: Redis HashOperations dependency not found? I'm following a Spring tutorial on how to use hash mapping for Redis. http://docs.spring.io/spring-data/redis/docs/1.8.4.RELEASE/reference/html/#redis.hashmappers.root
Here is my class:
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;

import com.commercehub.jackson.datatype.mongo.MongoModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import model.Event;

public class HashMapping {

@Autowired
private HashOperations<String, byte[], byte[]> hashOperations;

private ObjectMapper objectMapper = new ObjectMapper();

    public void writeHash(String key, Event event) throws JsonProcessingException {
    objectMapper.registerModule(new MongoModule());
    String json = objectMapper.writeValueAsString(event);

    Map<byte[], byte[]> mappedHash = new HashMap<byte[], byte[]>();
    mappedHash.put(key.getBytes(), json.getBytes());

    hashOperations.putAll(key, mappedHash);
    }
}

When I register this class as bean and start the server here is my error message:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hashMapping': Unsatisfied dependency expressed through field 'hashOperations': No qualifying bean of type [org.springframework.data.redis.core.HashOperations] found for dependency [org.springframework.data.redis.core.HashOperations<java.lang.String, byte[], byte[]>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.redis.core.HashOperations] found for dependency [org.springframework.data.redis.core.HashOperations<java.lang.String, byte[], byte[]>]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

How do I fix this? I'm following exactly like the Spring tutorial says

A: I have solved the issue. HashOperations is one of the many operational views that is part of the RedisTemplate. To use one of the views, you must declare the view as a dependency and then inject the RedisTemplate.
Here is how I did it:
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.data.redis.hash.ObjectHashMapper;

import foo.Person;

public class HashMapping {

@Resource(name = "redisTemplate")
private HashOperations<String, byte[], byte[]> hashOperations;

private HashMapper<Object, byte[], byte[]> mapper = new ObjectHashMapper();

public void writeHash(String key, Person person) {

    Map<byte[], byte[]> mappedHash = mapper.toHash(person);
    hashOperations.putAll(key, mappedHash);
}

public Person loadHash(String key) {

    Map<byte[], byte[]> loadedHash = hashOperations.entries(key);
    return (Person) mapper.fromHash(loadedHash);
}
}