text:
Q: What alien bits should I sell in XCom 2? It would be nice to have an XCom 2 version of the XCom: EU question: What alien bits should I sell?.
It's not obvious which alien corpses or bits of alien tech are safe to sell on the black market. e.g. I know that Faceless Corpses are used to build Mimic Beacons, but are they used for anything else? ...If I've built all the mimic beacons I'm going to want to use, should I just sell all the rest of the Faceless Corpses I find?). After I do an autopsy/breakdown of an ADVENT Officer Corpse or Turret ADVENT Wreck, are those safe to sell? etc..
What corpses and other inventory items are necessary to keep around, and what are safe to sell on the Black Market?

A: You always need 1 corpse for autopsy/breakdown. You also have a minimum number of corpses needed to unlock instant autopsy/breakdown, which means that, if you want to save research time, you will only sell corpses after the autopsy is done. An exhaustive list of other uses for corpses is:

*

*ADVENT Trooper: 2 for Hybrid Materials (4 on Legend), 6 for Predator Armor (12 on Legend), 2 per EXO Suit (4 on Legend), 2 per Nanoscale Vest (3 on Legend).

*ADVENT Stun Lancer: 2 per Spider Suit (3 on Legend).

*Sectoid: 2 for Advanced Psi Amp (3 on Legend), 1 per Mind Shield (2 on Legend).

*Faceless: 2 per Mimic Beacon.

*Viper: 2 for Battlefield Medicine (3 on Legend), 1 per Nanomedkit (2 on Legend).

*Berserker: 1 per Overdrive Serum (2 on Legend).

*Chryssalid: 2 per Hellweave.

*Gatekeeper: 1 for Alien Psi Amp (2 on Legend).

A: The Blackmarket Usage mod displays that information in-game.


text:
Q: Yii CGridView can't show custom SQL attribute In the Type model's search() function, I want to display three attributes in CGridview:
type.name, type.description and count(dataset_type.dataset_id)
public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;
            $criteria->alias='t';
            $criteria->select='t.name, t.description, count(dataset_type.dataset_id) as number';
            $criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=t.id';
            $criteria->group='t.id';

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

This is the view:
<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'type-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'itemsCssClass' => 'table table-bordered',
    'columns' => array(
        'name',
        'description',
        'number',
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

but in this way the columns in CGridView can only display model attributes, it shows type.number can't find in model Type, how can I display the count()?

A: You will also have to add the attribute to your model to be able to use it as a column in your CGridView:
class Type extends CActiveRecord {

    public $number;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как обойти AuthKeyDuplicatedError? Делаю скрипт,который работает в многопотоке с множество аккаунтами телеграмма через библеотеку telethon,но перенося свой проект на удаленный сервер стала возникать ошибка AuthKeyDuplicatedError
Как ее правильно обходить?
try:
    # await client.connect()
    # if (await client.get_me())==None:
    await client.start(phone=client.number,password=client.password)
    #await client.start(phone=client.number,password=client.password)
except errors.PhoneNumberBannedError as e:

    await client.logs_out()
    with lock:
        db.delete_account(id=client.id)
except errors.ApiIdInvalidError as e:

    console.error(f"Account {client.number} ApiIdInvalidError")
    print(client.number,client.session.filename)
    await client.logs_out()
    with lock:
        db.delete_account(id=client.id)

except errors.AuthKeyDuplicatedError as e:
   await client.disconnect()

A: Ошибка исходит от Telegram, и Telethon мало что может сделать, чтобы ее обойти. Вы можете только попытаться на 100% убедиться, что ключ используется только под одним IP-адресом за раз.
Под ключом подразумевается auth key


text:
Q: How to use the factory pattern with functors? I have a set of functors for calculating specific stuff on ranges on objects. Essentially, each functor implements operator():
template <typename Iterator1,
          typename Iterator2> double operator()( Iterator1 it1,
                                                 Iterator2 it2 ) const
{
  return( 0.0 );
}

I now have a set of objects that can be created with different functors. I solved this by templating the creator function:
template <class Functor> Foo createFoo( ... // some parameters for foo objects
                                        Functor f = Functor() )
{
  // calculate stuff for "foo" using functor "f"
}

I now want to delegate functor selection to the user of my program, so I decided to create a functor factory. Given a descriptive name of a functor, I want to create the appropriate functor so that it can be used in the creation of all Foo objects, as above.
This is where I get stuck, though: I cannot create a factory that returns a templated functor because I cannot call this function without coding the exact type of functor I want to create.
I thought about making operator() a virtual function of some base class, i.e. FunctorBase, but I don't want the performance overhead associated with virtual function calls. Avoiding said overhead was why I chose to use templates in the first place.
I am at an impasse here and would sure appreciate some comments.
EDIT:
What I intend to do (invalid code):
DistanceFunctor f = createFunctor( "Bar" ); // Create a functor from a client-supplied string

Foo createFoo( ..., // parameters for foo
               f );

In the comments, the use of virtual functions was suggested as well. The current functor design as described above would not work with virtual functions, though, because the compiler cannot make function templates virtual. Adjusting the functor class to take two Iterator types as template parameters would be possible, but very clunky.
EDIT:
The functors work similar to the ones used in FLANN. See the git repository for an example. I don't see how to specify these functors any differently.

A: Having thought a bit about your requrements, this is the first thing that I came up with:
Your different functors obviously cannot be derived from a common base class the way they are defined now, since you can't make the templated operator() virtual. But you can make that operator virtual if you push the template parameters away from the operator, up to the functor itself:
template <class Iterator>
struct Functor {
  virtual double operator()(Iterator it1, Iterator it2) const = 0;
};

How does that help? Having the template at the Functor level at first sight does not look good, since you now will have to know the parameter outside the call of createFunctor, in fact, you will have to explicitly specify the iterator type if you call it:
//some concrete functors
template <class It>
struct FuncImpl_Bar : Functor<It> { /* ... implement op()(It, It) ... */ }:

template <class It>
struct FuncImpl_Meow : Functor<It> { /* ... implement op()(It, It) ... */ }:

template <class Iterator>
std::shared_ptr<Functor<Iterator>> createFunctor(std::string const& str)
{
  if (str == "Bar") return std::make_shared<FuncImpl_Bar<Iterator>>(/* args *);
  else return return std::make_shared<FuncImpl_Meow<Iterator>>(/* args *);
}

//...
auto MyFunctor = createFunctor<???>("Bar"); //what iterator type???

But AFAICS you don't nee to know the exact type of the functor outside createFoo - it's sufficient if createFoo knows that type:
Foo createFoo( ... // some parameters for foo objects
                                        std::string const& str ) //look mum, no templates!
{
  typedef whatever_the_container_i_use::iterator Iter;
  Functor<Iter> MyFunctor = createFunctor<Iter>(str);
  // calculate stuff for "foo" using functor "f"
}

//...
auto myFoo = createFoo(args, "Bar");
auto myOtherFoo = createFoo(args, "Moo");

In short: pass the factory parameter down to the point where you know the Iterator type, i.e. the type you have to parametrize the functor factory with. Call the factory where you know every input needed, i.e. type and nontype arguments.


text:
Q: LINQ compare 2 lists I'm actually having some problems about a query. I'll try to make it simple to understand
I have a class that contains two attributes likes this
public class LanguageAndKnowledge{
public String LanguageCode{get;set;}
public int LanguageKnowledge{get;set;}
}

I use an other class which is from the EntityFramework mapped according to  the database
public class Student{
...
  public virtual ICollection<StudentLanguage> StudentLanguage { get; set; }
}

and the StudentLanguage class ..
 public partial class StudentLanguage
    {
        public int StudentLanguageID { get; set; }
        public System.Guid StudentID { get; set; }
        public string LanguageCode { get; set; }
        public int KnowledgeLevelID { get; set; }
        public Nullable<System.DateTimeOffset> C_CreationDate { get; set; }

        public virtual Student Student { get; set; }
        public virtual Language Language { get; set; }
    }

Now , it starts to be tricky. I have a list LanguageAndKnowledge so it looks like this
List<LanguageAndKnowledge> listLanguageKnowledge;

So I started to filter my data on my Student object with a query like this and it works
   IQueryable<Student> students = model.Student.Where(stud => stud.StudentStudy.Any(study => selectedStudyType.Contains(study.StudyTypeID.Value)
                                                                                && selectedStudyDegree.Contains(study.StudyDegreeID.Value)
                                                                                && selectedYears.Contains(study.CompletionDate.Value.Year)));

The second step is to select from Student.StudentLanguage all the student that have the corresponding data from my List . The language code and the knowledge id are the some in both classes. But I dont get how I should build the query.    I tried different things, like using the Any(),Contains() but I didnt get what I wanted.
I dont really get how I should compare the two lists and I need help :(
For example, I tried things like this..
students.Where(stud=> stud.StudentLanguage
.Any(lang=>listLanguageKnowledge.Contains(lang.LanguageCode)&&listLanguageKnowledge.Contains(lang.KnowledgeLevelId);
//or
students.Where(stud=> stud.StudentLanguage
.Any(lang=>listLanguageKnowledge.Any(lang.LanguageCode)&&listLanguageKnowledge.Any(lang.KnowledgeLevelId);

Edit
Data

StudentLanguage
Stud1 EN  4
Stud1 NL  4
Stud1 FR  4
Stud2 FR  3
Stud2 NL  4
Stud3 EN  4
Stud3 NL  4
Stud3 FR  2
List<LanguageAndKnowledge>
EN    4
NL    4
FR    4
Expected Result : Stud1

So I have to get all the data that match the list. I need to get all the student who has the code and the correct knowledge id

A: So I understood that you need to find Students who knows all the language codes with required KnowledgeLevelId. I managed to Replicate to found the fix (unless I understood the problem wrong).
My Result does match your expected result.
I created these classes:
public class Student
    {
        public string Name { get; set; }
        public List<StudentLanguage> StudentLanguages { get; set; }
    }

    public class StudentLanguage
    {
        public string Name { get; set; }
        public string LanguageCode { get; set; }
        public int KnowledgeLevelId { get; set; }
    }

    public class LanguageKnowledge
    {
        public string LanguageCode { get; set; }
        public int KnowledgeLevelId { get; set; }
    }

Then I wrote this code to populate your mentioned data:
private static List<Student> PopulateData()
        {
            var students = new List<Student>
            {
                new Student()
                {
                    Name = "Student1",
                    StudentLanguages = new List<StudentLanguage>()
                    {
                        new StudentLanguage {KnowledgeLevelId = 4, LanguageCode = "EN"},
                        new StudentLanguage {KnowledgeLevelId = 4, LanguageCode = "NL"},
                        new StudentLanguage {KnowledgeLevelId = 4, LanguageCode = "FR"},
                    }
                }
                ,
                new Student()
                {
                    Name = "Student2",
                    StudentLanguages = new List<StudentLanguage>()
                    {
                        new StudentLanguage {KnowledgeLevelId = 3, LanguageCode = "FR"},
                        new StudentLanguage {KnowledgeLevelId = 4, LanguageCode = "NL"},
                    }
                },
                new Student()
                {
                    Name = "Student3",
                    StudentLanguages = new List<StudentLanguage>()
                    {
                        new StudentLanguage {KnowledgeLevelId = 4, LanguageCode = "EN"},
                        new StudentLanguage {KnowledgeLevelId = 4, LanguageCode = "NL"},
                        new StudentLanguage {KnowledgeLevelId = 2, LanguageCode = "FR"}
                    },
                }
            };
            return students;
        }

And then this method to Find The Required data:
private void FindData()
        {
            var students = PopulateData();

            var languageKnowledges = new List<LanguageKnowledge>
            {
                new LanguageKnowledge { KnowledgeLevelId = 4, LanguageCode = "EN"},
                new LanguageKnowledge { KnowledgeLevelId = 4, LanguageCode = "NL"},
                new LanguageKnowledge { KnowledgeLevelId = 4, LanguageCode = "FR"},
            };

            var studentLanguage = students.Where(
                    student => DoesStudentHaveAllSkills(languageKnowledges, student.StudentLanguages));

            foreach (var student in studentLanguage)
            {
                MessageBox.Show(student.Name);
            }
        }

        public bool DoesStudentHaveAllSkills(List<LanguageKnowledge> languageKnowledges, List<StudentLanguage> studentLanguages)
        {
            return
                languageKnowledges.All(langKnow => studentLanguages.Any(studLang => studLang.KnowledgeLevelId.Equals(langKnow.KnowledgeLevelId)
                                                           && studLang.LanguageCode.Equals(langKnow.LanguageCode)));
        }

A: I'm not sure what do you mean by

all the student that have the corresponding data from my List

but this might work for you:
students.Where(stud => stud.StudentLanguage.Any(
    lang => listLanguageKnowledge.Any(lk => lk.LanguageCode == lang.LanguageCode &&
                                            lk.KnowledgeLevelId == lang.KnowledgeLevelId)));

A: Try this, if it doesn't work, please provide a sample of both lists.
students.Where(stud=> stud.StudentLanguage
    .Any(lang=>listLanguageKnowledge
         .Any(listItem => (listItem.LanguageCode == lang.LanguageCode) &&
                          (listItem.LanguageKnowledge == lang.KnowledgeLevelId)
             )
        ));


text:
Q: Not getting token from ionic push.register when debug mode is false I am implementing push notification in my ionic app.
I have setup initial steps successfully. In mu debug mode When I use this code:
     $ionicPlatform.ready(function() {
    var push = new Ionic.Push({
        "debug": true,
      "onNotification": function(notification) {
      var payload = notification.payload;
      console.log(notification, payload);
      }
    });

    push.register(function(token) {
                  alert("Hello");
        console.log("Device token:",token.token);
        });
    });

I have already run this command:
    ionic config set dev_push true

I am getting device token value and receiving push successfully.
But when I run this command
   ionic config set dev_push false

and put "debug": true, I am not receiving any token.
I have successfully uploaded the .p12 file in Online Acccount of ionic.

A: If you set dev_push false. You won't get a notification.
Reason.
The variable is named as development_push meaning it is to be used in development mode only. Which means you are on a laptop/PC and testing the API in development mode. But if you switch to, development_push = false then it means you ain't testing on a system anymore and you need to put that .apk or ios equivalent in your phone and test it out in the real world.
So If I were you.
I would set it to false
Build my application.
and install the app in my phone.
and see if it works.
Hope it helps

A: After spending one complete day. I found one simple solution.
I don't know whether it will work for others or not. But still I am posting may be it helps someone.
After changing:
  ionic config set dev_push true

to
  ionic config set dev_push false

You have to first remove the Platform whether it is iOS/Android.
  ionic platform rm ios/androind

Then add again and build your project. Now it will work for sure.
  ionic platform add ios/android
  ionic build ios/android


text:
Q: Lodash + TypeScript _.property iteratee shorthand Is it possible to use _.property iteratee shorthand somehow with TypeScript?
Consider the following example. How can you make it compile?
let someCollection: Type1[] = [obj1, obj2];
let result: Type2[] = _(someCollection).filter('some.nested.property').map('another.nested.property');

How do you do it in TypeScript?

A: This seems to be shortest solution:
let result: Type2[] = _(someCollection).filter('some.nested.property').map <Type2> ('another.nested.property');

By explicitly giving the Type in <> the compiler is satisfied (<Type2>). Of course you're only really type safe if your expectations regarding the path 'another.nested.property' really yield objects of Type2, i.e. changing the _.property string later to something different (like 'another.thing.that.is.different') the compiler still thinks everything is ok, while in reality your code will break when running it.


text:
Q: Script to check if iptables is running is not working I have the following simple script to check if iptables is running or not.  Why does it always returns 'OK' no matter what the status is?
#!/bin/bash

#IPT='iptables'
SERV='/sbin/service iptables status'
EXPR='Firewall is stopped.'
        if [ "$SERV" = "$EXPR" ]
                 then
                        echo 'Firewall is not Running'
                        exit 2
                else
                        echo 'OK'
                        exit 0
        fi

A: The init script for iptables will never return exactly that string; it will always have something else in it, and there are also failure conditions which don't match that string at all.
Instead, you should check the exit code from the script, as it (on EL and Fedora) returns non-zero if the firewall is not active and zero if it is active.
/sbin/service iptables status >/dev/null 2>&1
if [ $? = 0 ]; then
    echo "All systems go."
else
    echo "Houston, we have a problem."
fi

A: You are setting $SERV to equal the literal string value "/sbin/service iptables status", you need it to execute the command and store the result.  You can verify this by echoing $SERV.  As written, it will always evaluate to not-equal.
SERV=$(/sbin/service iptables status)
Also, make sure the output is as expected.  My version returns iptables: Firewall is not running.  (Yours of course may vary.)
Read more about subshells at the Advanced Bash-Scripting Guide.

A: The scripts is doing what it says.
Bear in mind that [ "$SERV" = "$EXPR" ] is comparing strings , and they are non-equal.
So, exit status of test will be always non-zero, so will go always to "else".
What you need is to use Command Subtitution, instead of SERV='/sbin/service iptables status' you should use either
SERV="$(/sbin/service iptables status)"

or
SERV=`/sbin/service iptables status`

HTH


text:
Q: getAttachmentsAsync() return different IDs when it is call is JS and in C# I am working on an outlook web add-in that gets attachments. But I found out that's API returns different ID for JS and in backend(C#)
In JS when I call Office.context.mailbox.item.getAttachmentsAsync() it is return this ID:
AAMkADhlZGM3ZDRiLTc3ODEtNGRhZi05NDNhLWFiMWNkOTc1YWNkZQBGAAAAAAAvp5uuw9HTToIFsfv180ZsBwCYtBG78gMyRLPMDVxMNy4UAAAAAAEPAACYtBG78gMyRLPMDVxMNy4UAAHoiefYAAABEgAQAEK4dcJBHC5Hso8DtB+2NaQ=
In C#
var graph = new GraphServiceClient(url, authToken);
var request = graph.Me.Messages[itemId].Attachments.Request();
var attachments = await request.GetAsync();

this code return this ID
AAMkADhlZGM3ZDRiLTc3ODEtNGRhZi05NDNhLWFiMWNkOTc1YWNkZQBGAAAAAAAvp5uuw9HTToIFsfv180ZsBwCYtBG78gMyRLPMDVxMNy4UAAAAAAEPAACYtBG78gMyRLPMDVxMNy4UAAHoiefYAAABEgAQAEK4dcJBHC5Hso8DtB_2NaQ=
Is there a way to avoid this?

A: Use Office.context.mailbox.convertToRestId to convert an item ID formatted for EWS into REST format.
Get Item ID


text:
Q: How can I redirect all address bar requests to one index page? And use a requested subfolder as input I am using PHP, Ajax, JS, and HTML and after many searches, I am per-google-plexed.
How can I take a user visiting www.foo.com/bar to www.foo.com/index.php and use bar as input?
I want to avoid creating a folder for each possible value.
I would like to keep /bar in the address bar

A: Using Apache mod_rewrite here an example or using php but with uri like this:
http://example.com/index.php/controller/action/variables

A: You want to look into mod_rewrite.

A: Check the location and change to whatever you want via javascript:
<script type="text/javascript">
// var x = ( cut out part of the current location )
// Then replace with whatever:
location.replace('http://www.example.com/');
</script>

Examples:
http://www.tizag.com/javascriptT/javascriptredirect.php
http://andylangton.co.uk/articles/javascript/javascript-redirect-scripts/
http://www.javascriptredirect.com/timed.htm

Also, here is a php alternative to mod_rewrite (which is what you should be using instead but if you cant, there are other ways):
php alternative to mod_rewrite


text:
Q: PHP SOAP client data formatting issues I'm trying to format a SOAP request with PHP.  If I put the following request through with SOAPUI I get the correct results:
  <urn:getCallInfoSearch>
     <UserInfo>
        <UserID>USERID</UserID>
        <Password>PASS</Password>
        <SvcrAcct>USERID</SvcrAcct>
     </UserInfo>
     <FromDateTime>12/10/2011 12:00:00</FromDateTime>
     <ToDateTime>12/30/2011 12:00:00</ToDateTime>
  </urn:getCallInfoSearch>

I'm trying to format it in PHP with SoapClient as follows:
$getCallInfoSearch = array(
    'UserInfo'      => array('UserId' => 'USERID', 'Password' => 'PASS', 'SvcrAcct' => 'USERID'),
    'FromDateTime'  => '12/10/2011 12:00:00',
    'ToDateTime'    => '12/30/2011 12:00:00',
);
$client->getCallInfo($getCallInfoSearch);

And I'm getting a response from the server that "UserID can not be null or blank".  Is there any reason the array wouldn't translate exactly into the functional request from SoapUI?
The WSDL defines getCallInfoSearch as follows:
<complexType name="getCallInfoSearch">
<sequence>
<element name="UserInfo" nillable="true" type="impl:UserInfo"/>
<element name="FromDateTime" nillable="true" type="xsd:string"/>
<element name="ToDateTime" nillable="true" type="xsd:string"/>
</sequence>
</complexType>

And UserInfo:
<complexType name="UserInfo">
<sequence>
<element name="UserID" nillable="true" type="xsd:string"/>
<element name="Password" nillable="true" type="xsd:string"/>
<element name="SvcrAcct" nillable="true" type="xsd:string"/>
</sequence>
</complexType>

Update, I've also tried to build the request with standard classes as follows, and I still get the same result:
$getCallInfoSearch = new stdclass();
$getCallInfoSearch->UserInfo = new stdclass();
$getCallInfoSearch->UserInfo->UserId    = 'USERID';
$getCallInfoSearch->UserInfo->Password  = 'PASS';
$getCallInfoSearch->UserInfo->SvcrAcct  = 'USERID';
$getCallInfoSearch->FromDateTime = '12/10/2011 12:00:00';
$getCallInfoSearch->ToDateTime = '12/30/2011 12:00:00';

UPDATEx2: Either of these solutions works correctly (posted above).  The issue all along has been case sensitivity.  UserID vs UserId.

A: Just a guess, but "UserID" != "UserId":
Try this:
$getCallInfoSearch = array(
    'UserInfo'      => array('UserID' => 'USERID', 'Password' => 'PASS', 'SvcrAcct' => 'USERID'),
    'FromDateTime'  => '12/10/2011 12:00:00',
    'ToDateTime'    => '12/30/2011 12:00:00',
);
$client->getCallInfo($getCallInfoSearch);


text:
Q: Hibernate Interceptor incorrect mapped table data I have a ManyToMany mapping using a join table.
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "access_management")
public class AccessMgmt
    extends CommonColumns
    implements Serializable {

@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
@JoinTable(
        name = "access_management_role_mapping",
        joinColumns = @JoinColumn(name = "access_management_id"),
        inverseJoinColumns = @JoinColumn(name = "roles_id"))
@CsvBindByName(column = "roles")
private List<Role> roles = new ArrayList<>();

}

When data is updated (onFlushDirty) previousState and currentState consist of the exact same data for the ManyToMany field (which is what should only be in currentState). I figure there is something going on with the join mapping table, because I don't have an entity for this table (access_management_role_mapping) its being updated and not hitting the interceptor, and then the parent object (access_management) is hitting the interceptor after the update. Just a suspicion, but its something like that because all the data is correct in the non-Audit Log tables.
public class AuditLogInterceptor extends EmptyInterceptor {

@Override
public boolean onFlushDirty(
        final Object entity, final Serializable id,
        final Object[] currentState, final Object[] previousState,
        final String[] propertyNames, final Type[] types) {
... }
}

Second issue is that I really only want "parent" entities to hit the interceptor and have their previousState and currentState be "correct" object hit the custom interceptor. And by correct i mean to have the full object with the mappings in a previousState and currentState, the currentState has always been correct with the current setup. Currently tables with OneToMany Mappings have each Entity hit the interceptor individually which is fine-ish, but ultimately the parent object (the one the user had saved/edited) hits the interceptor last and has incorrect data for the previousState for any mapped fields (OneTo.. ManyTo.. ect)
I can add more of the code, but I figured most of it was unnecessary.
I think i can work around this by doing a few things.

*

*Use envars... - (No thanks, would mean a full rewrite of this part.)

*Change the ManyToMany to OneToMany and create the mapping table as an entity and handle it in the interceptor. (If I have too, but doesn't solve my second issue)

*Add a transient of the parent object to save the previous state with a @PreLoad so I always have the previous state. (This fixes both issues, but seems like an odd thing todo, but what I will go with if someone here doesn't have a better idea.)(how to get previouseState without fetching from the db using hibernate interceptor to create audit trail table?)

UPDATE
Option 3 did not work how I expected and did not get the data I wanted at the time. So thats out.
I also tried using Hibernate Event Listeners instead of the interceptor with the same results.
Ultimately I might need to implement this without hibernate at all and do it at the Controller level.


text:
Q: Groovy Binding: rebind value I have an application in which some of configurations are stored in database and upon launching they are being injected into config object.
The way they're stored are in object path string like: "some.config.value".
So after parsing it becomes into this kind of map:
[some: [config: [value: [:]]]]
I achieved this using Binding, here is the code:
Binding bind = new Binding()
bind.tmp = bean // Bean is an object where it is being injected

String[] traverse = stringPath.split(/\./)
def shift = bind.tmp
traverse.eachWithIndex { String it, int i ->
    if (it) {
        if (!(shift instanceof Map)) {
            shift = ["$it": [:]] // <-- Doesn't work
        } else {
            if (!shift?.containsKey(it)) {
                // val - is a value to assign to last key in path
                shift[it] = (i + 1 == traverse.size()) ? val : [:]
            } else if (shift?.containsKey(it) && (i + 1 == traverse.size())) {
                shift[it] = val
            }
        }

        shift = shift[it]
    }
}

The problem with this approach is that if I have already defined key in binding, I cannot seem to re-define it (in shift = ["$it": [:]]).
e.g.: if I have config.val and config.val.moreConfig - then moreConfig will not be assigned.
After sometime I just decided to assign values by declaring value key in all paths automatically, but I'm still curious if there is a way to redefine value in binding?
Or does value declared through Binding in groovy becomes mutable?
UPDATE:
bean is a hash map with hardcoded configs. It may be just an empty map.
What basically I'm doing is injecting there more maps with value at the end.
If I have a chain of values:

*

*"config.some.var" = 10

*"config.some.var2" = 20

*"config.some.var.more" = 30
Will result in:
[config: [
    some: [
        var: 10,
        var2: 20
    ]
]]

The latest as expected will be discarded, as it has already a value of 10. What I want is to override the first value with latest, while preserving all other values on the same level of depth.
The code above produce the following:
def bean = [someOtherConfig: []]
convert bean, 'config.var', 10
convert bean, 'config.var2', 20
convert bean, 'config.var.more', 30
assert bean == [someOtherConfig: [], config: [var: 10, var2: 20]]

A: I can't see from your question what you're trying to do, but this gives you the output you say you'd expect from the input you describe:
def build = { name ->
  name.split( /\./ ).reverse().inject( [:] ) { m, n ->
    [ (n): m ]
  }
}

def map = build( 'some.config.value' )

assert map == ['some':['config':['value':[:]]]]

You can also do interesting things like this by playing with Closure delegates:
def map = new ConfigBuilder().build {
  config.some.var = 10
  config.some.var2 = 20
  config.some.var.more = 30
}

assert map == [config:[some:[var:10, var2:20]]]

// Implementation

class ConfigBuilder {
  private Map map, curr
  private boolean ignore = false

  ConfigBuilder( Map initial=[:] ) {
    this.map = initial
    this.curr = this.map
  }

  def build( Closure c ) {
    c.delegate = this
    c.resolveStrategy = Closure.DELEGATE_FIRST
    c()
    map
  }

  def propertyMissing( String name ) {
    if( ignore ) return this
    if( curr[ name ] == null ) {
      curr[ name ] = [:]
      curr = curr[ name ]
    }
    else if( curr[ name ] instanceof Map ) {
      curr = curr[ name ]
    }
    else {
      ignore = true
    }
    this
  }

  void setProperty( String name, value ) {
    if( !ignore ) {
      curr[ name ] = value
    }
    // Reset and go again
    ignore = false
    curr = map
    value
  }

}

A: I don't know if it is possible to make the binding of key to value mutable but you should be able to get almost the same effect with a single mutable value that you bind only once.


text:
Q: replace gives different result on same string? Why replace function gives different results on the same string? The only difference I see is whether the string is in a variable or is a literal?
I am trying this in node REPL:
> "2015/05/21 23:59:59".replace(/^[0-9]/g, '')
'015/05/21 23:59:59'

> var time = "2015/05/21 23:59:59"
> time.replace(/[^0-9]/g, '')
'20150521235959'


text:
Q: RDS snapshot: how long does I/O suspension occur? As we're relying on RDS Postgresql manual backup for our backup strategy, we encountered the issue with the possible downtime of the RDS instance (single AZ) during snapshot creation. According to AWS:

Creating this DB snapshot on a Single-AZ DB instance results in a
  brief I/O suspension that can last from a few seconds to a few
  minutes, depending on the size and class of your DB instance.

which is not really clear how we can be sure if the DB instance I/O is functioning normally during snapshotting period, as if the DB is down for a short period we'd like to stop our corresponding web server or take it out of the load balancer to ensure no connection interruption could happen from customer side.
What made us quite wondering are:

*

*Does the DB really have downtime during snapshotting, AWS just says about "I/O suspension" and "latencies"? I read somewhere that the downtime lasts for short period (from few seconds to minute) just during snapshot initialization, can we know if that downtime has passed and the DB instance is ready to serve (while its snapshot still being created)?

*What is general best practice to deal with these IO suspensions? As seems it happens even with automated backup, does it mean the site could possibly have a downtime everyday when DB snapshot creation is in progress?

A: The answer comes from understanding how snapshotting works.
At the start of a snapshot, a message (command) is sent to all applications to come to a consistent state and flush necessary data to disk.
How long this flush takes depends on how much data is in memory, what state the data is in, and how long it takes to write the data to disk.
Once each application that supports snapshotting completes its preparation for freezing, the snaphot process then snaps the file systems, which means that if any further data blocks are written to, a copy is made first for the backup process (COW - Copy on Write). Then the thaw (resume) message / command is sent to each application.
For a lightly used database this freeze / thaw process may take only a few hundred milliseconds. For a large database with GBs of memory that need to be flushed to disk, a number of seconds will be required.
During the time that the freeze / thaw cycle is occurring, disk I/O for new user requests is suspended. The database is still running but all requests will pause while the disks / file systems are synchronized. Everything resumes with receipt of the thaw message.
For Master-Slave databases, the master is not affected. The snapshot will be taken on a slave. This is one of the nice AWS RDS features.


text:
Q: How to get HttpRequest getEntity data in Spring MVC controller? private ArrayList<NameValuePair> mParams;
HttpClient client = new DefaultHttpClient();

mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("testKey", "John"));
mParams.add(new BasicNameValuePair("testSerial", "003-100"));
HttpPost request = new HttpPost("http://localhost:8080/test/getRequiredEnv");

request.setEntity(new UrlEncodedFormEntity(mParams, HTTP.UTF_8));
HttpResponse response = client.execute(request);

// TestController.java
@RestController
public class TestController {

private static final Logger logger = Logger.getLogger(TestController.class);

@RequestMapping(value = "/getRequiredEnv", method = RequestMethod.POST)
public @ResponseBody ResponseInfo getRequiredEnv(
                @RequestParam("testKey") String testKey,
                @RequestParam("testValue") String testValue,
                @RequestHeader HttpHeaders headers) {

    logger.info("Test Key [" + testKey + "]");
    logger.info("Test Value [" + testValue + "]");

    return new TestResponseInfo("0001", "ABC");
}

Can someone please tell me is this the correct way to get data from 'Request.setEntity' in SpringMVC rest controller or I am missing something?
Secondly, in postman "httpPost" request I pass the parameters (testKey & testValue) as headers or as body?
Thirdly, without knowing the parameters in httpPost request can I able to parse the incoming request and extract the parameters from it in Spring controller?

A: First of all it would be good to know the content-type of the request that is sent.
So I guess you want to get the body of the request. To get all request parameters if you don't know the parameter names beforehand you can use @RequestParam with type Map<String, String> to get all params:
@RequestMapping(value = "/getRequiredEnv", method = RequestMethod.POST)
public @ResponseBody ResponseInfo getRequiredEnv(
            @RequestParam Map<String, String> allParams,
            @RequestHeader HttpHeaders headers)

But I am not sure if this works because it also depends on the content-type. E.g. for form data (application/x-www-form-urlencoded) have a look at the Spring documentation about @RequestBody which states about one of the default message converters FormHttpMessageConverter:

FormHttpMessageConverter converts form data to/from a MultiValueMap.

So try:
@RequestMapping(value = "/getRequiredEnv", method = RequestMethod.POST)
public @ResponseBody ResponseInfo getRequiredEnv(
            @RequestBody MultiValueMap<String, String>,
            @RequestHeader HttpHeaders headers)

Alternatively there is also HttpServletRequest.getParameterMap() which gets you a Map. You can get the request by just including HttpServletRequest request as a method argument.
If you know the paramters beforehand, annotating your POJO that resembles the form data with @ModelAttribute should also work like so:
@RequestMapping(value = "/getRequiredEnv", method = RequestMethod.POST)
public @ResponseBody ResponseInfo getRequiredEnv(
        @@ModelAttribute Test myTestPojo,
        @RequestHeader HttpHeaders headers)

Or you could also send data as application/json and when including jackson as a dependency, @Requestbody will map your data to a POJO. Have a look at e.g. Spring JSON request body not mapped to Java POJO.
In regard to your second question httpPost will pass the parameters as body since it is a POST request.


text:
Q: Using PlotLabel with ParametricPlot I cannot get the label to appear on this vertical line!
(Mma 9.0.1 OS 10.8)
ParametricPlot[{.5, t}, {t, 0, .5}, PlotStyle -> Blue, PlotLabel -> "z"]

A: The question is not clear, so far, but I assume you mean the PlotLegends and not PlotLabel.
Mathematica 10
ParametricPlot[
 {.5, t}
 , {t, 0, .5}
 , PlotStyle -> Blue
 , PlotLabel -> "here the plot Label"
 , PlotLegends -> {"here your legend"}
 , FrameLabel -> {"botoom", "left", "top", "right"}
 , PlotTheme -> "Detailed"
 ]

Mathematica 9
ParametricPlot[
 {.5, t}
 , {t, 0, .5}
 , PlotStyle -> Blue
 , Frame -> True
 , PlotLabel -> "here the plot Label"
 , PlotLegends -> {"here your legend"}
 , FrameLabel -> {"botoom", "left", "top", "right"}
 ]

A: (Stumbled upon this question while looking for something similar. I'm not sure if a more elegant way to add labels to ParametricPlot exists, but this is what I've decided to go with...)
Assuming you did mean "PlotLabel" and not "PlotLegends", you can add the label manually.
Show[{
  ParametricPlot[{.5, t}, {t, 0, .5}, PlotStyle -> Blue,
   PlotRange -> {Automatic, {0, 0.6}}],
  Graphics[Text["z", {1/2, 0.55}]]
  }]

That would give the following plot:


text:
Q: Firefox "Browse by Name" not functioning I'm trying to enable Firefox's "Browse by Name" feature, which lets you type a random string into the location bar and automatically have it searched using the search provider of your choice. This is what I did:

*

*Set keyword.enabled to true in about:config

*Set keyword.URL to http://www.google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=, which is used for Google's "I'm Feeling Lucky" feature, as described here.

But if I type google into the location bar and hit Enter, I get redirected to http://google/, a blank page which obviously isn't the site I want.
If I see what DNS info google gives using dig, I get the following output:
; <<>> DiG 9.8.1 <<>> google
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 63911
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;google.                IN  A

;; Query time: 62 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Sat Mar  3 16:06:03 2012
;; MSG SIZE  rcvd: 24

So it seems to be properly getting the NXDOMAIN result to a DNS lookup of google (I'm using OpenDNS as my DNS provider, so it was important to make sure of that). But I'm still not getting to http://www.google.com/ when I enter google in the location bar, like I should.

A: DNS is (probably) not the problem.  Either keyword.url is not in effect (despite the setting) or Firefox thinks that "google" is a valid URL.
Try this: change keyword.enabled to false, restart Firefox, change it back to true and restart.  This worked for me.

A: Your Firefox parameters (Keyword.enabled and Keyword.url) are correct.
Btw: we don't have your Firefox version and Operationg System ...
1) Check in the Firefox Safe Mode
Press shift key and click on the Ff icon [Detailled info:  http://kb.mozillazine.org/Safe_Mode ]
If the problem disappear in this mode the "culprit" is an add-on or plugin. At this stage of troubleshooting you have to find which one. First update all add-on and plugins. Then disable one plugin at the time, restart Firefox and check again with the keyword...
Check in detailled your Ff parameters by typing about:support in the address bar.
2) Check with another profile [Detailled info:  http://kb.mozillazine.org/Command_line_arguments ]
Set the two parameters we're talking about in this new profile. If the problem disappear, somethings wrong in the other profile but not an add-on or plugin. At this stage you may try to find the problem's source but the easiest way is to recover your important data from the old profile to the new one. Check for "Recovering important data from an old profile" in the Firefox help pages.
3) Check the HOSTS file
Backup the HOSTS file and use a minimal one instead with only these lines:
127.0.0.1  localhost loopback
::1        localhost

If the problem disappear at this stage you know where the problem is...
4) Check an alternate DNS server. Try temporarely Public Google DNS 8.8.8.8 and 8.8.4.4 for example...
Hope this help. Let us know.

A: I've found that Firefox only searches from the address bar if what is entered cannot be interpreted as a valid URI. A single word usually can be.
As a workaround I've been using InstantFox. It works as expected. It's generally used with one (or more) letter at the start of your search to specify the search engine, though the standard search without shortcuts option will search when any phrase is entered, and search suggestions can be enabled.


text:
Q: How to backup in memory database or restore memory database from file? I use ORMLite and SQLite in memory database for speed. After operation, I need to backup the in memory database to a file, but could's find a method to do that.
In another thread (Backup and restore sqlite from disk to memory in Java) shown a method with JDBC Connection, therefor my question can be narrowed down to: If I have had a ORMLite ConnectionSource object, how can I get a JDBC Connection object from it?
Thanks


text:
Q: Powerapps Get Extended Reports vs Direct Reports In powerapps we can get a users direct reports via
Office365Users.DirectReportsV2(ID).value

which returns a table of users, where we can grab the email or user id for example. This works great as the Items function for a DataTable.
I want to create a global variable on start to load not only the current users direct reports but (this is what it was called in SharePoint on premise) extended reports. So a manager can see everyones records underneath them regardless of how many levels exists between the two.
First battle is I cant seem to copy the DirectReports into a proper variable on start. I tried adding the following function to OnStart (which works for a button).
Collect(Reports_1,
  {
    UserPrincipalName:"All"
  },
    Office365.Users.DirectReportsV2(ID).value
);

They show up in the global variable list, with the current column names but with 0 records. While as a button these run and populate properly.
Which to me should return a table array with the direct reports, which hopefully I could loop through, find all their direct reports, and keep going until direct reports for each person is either recorded. Assuming the above collect worked you could run something similar to this
Collect(Reports_1,{UserPrincipalName:"All"},Office365,Users.DirectReportsV2(ID).value);
ForAll(Reports_1, Collect(Reports_2,Office365,Users.DirectReportsV2(mail).value));
ForAll(Reports_2, Collect(Reports_3,Office365,Users.DirectReportsV2(mail).value));
ClearCollect(Reports_All,Reports_1,Reports_2,Reports_3)

Then I should have a table I can query to see if a record has john@abc.com is a report to a manager.


text:
Q: MISRA-C Rule 11.2: conversion from array to pointer I have two structs:
typedef struct {
    uint8 valid;
    uint8 identifier[20];
    uint8 parentIdentifier[20];
    /* etc */
} CustomData;

#define max_data_size 10
typedef struct {
    CustomData data[max_data_size];
    uint32 numberOfUsedData;
    /* etc. */
} MyContext;

and a function with the signature
uint8 parentInList(CustomData *data,
                   const CustomData* const list,
                   uint32 length);

I try to call my function as follows:
MyContext ctx = /* some proper initialization */;
result = parentInList(&ctx.data[0], ctx.data, ctx.numberOfUsedData);

My static analysis to says that ctx.data is a cast violating rule 11.2 of MisraC:
"Conversions shall not be performed between a pointer to an
incomplete type and any other type"
However I can't see how this is incorrect. Arrays aren't an incomplete type if they have a fixed size right?
Is this my static analyzer giving a false positive because of the macro? Or have I made a mistake and how would I fix it?


text:
Q: Millage calculation in android? I want to display the mileage between two cities in the android program, for that i have written the following code:
package com.example.distancebcities;

import java.io.IOException;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends  MapActivity {
    //extending the MapActivity here
    Geocoder geocoder = null;
    MapView mapView = null;

    @Override
    //location display
    protected boolean isLocationDisplayed() {
        return false;
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.geoMap);
        mapView.setBuiltInZoomControls(true);

        // lat/long of Jacksonville, FL
        int lat = (int) (30.334954 * 1000000);
        int lng = (int) (-81.5625 * 1000000);

        GeoPoint pt = new GeoPoint(lat, lng);
        mapView.getController().setZoom(10);
        mapView.getController().setCenter(pt);
        geocoder = new Geocoder(this);
    }

    public void doClick(View arg0) {
        try {
            EditText loc = (EditText) findViewById(R.id.location);

            //getting the dittext id

            String locationName = loc.getText().toString();
            List<Address> addressList = geocoder.getFromLocationName(locationName, 5);
            if (addressList != null && addressList.size() > 0) {
            int lat = (int) (addressList.get(0).getLatitude() * 1000000);
            int lng = (int) (addressList.get(0).getLongitude() * 1000000);

            //getting the lat and long postions of the cities

            GeoPoint pt = new GeoPoint(lat, lng);
            mapView.getController().setZoom(15);
            mapView.getController().setCenter(pt);

            //zooming and display the place of the edit text entered value .
        }

        catch (IOException e){
            e.printStackTrace();
        }
    }
}

I am getting the places but now I want to display the distance between two cities.
How can I proceed for this program or is there any alternative to achieve this?
Please send any useful links to me so that i can move forward.

A: There is inbuilt code to find distance between two locations,
distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
Refer this link for Location class

A: For find distance between two location use below code.
public double CalculationByDistance(Location Start, Location End)
{
        double Radius = 6371;
        double lat1 = Start.getLatitude();
        double lat2 = End.getLatitude();
        double lon1 = Start.getLongitude();
        double lon2 = End.getLongitude();
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double km = Radius * c;
        return km * 1000;
}

This distance will return in Meters


text:
Q: Access all medias loaded in a web page c# i would like to display the URL and type of all the backgrounds, images, and embedded content (including audio and video) that loads with a given web page, exactly like in the media panel page info of firefox :

Or in firebug network panel > media :

How can i achieve this in C#, using selenium ? (or without, but i don't think it's possible)
Thanks !

A: Java code is as below :-
List<WebElement> myElements = driver.findElements(By.xpath(" //link[@href]"));
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

In C#
IList<IWebElement> all = driver.FindElements(By.XPath("//link[@href]"));

String[] allText = new String[all.Count];
int i = 0;
foreach (IWebElement element in all)
{
    allText[i++] = element.Text;
}

Hope it will help you :)


text:
Q: Limit of $\frac{1}{\sqrt{4 \pi}} \int_{t}^{+ \infty} \sqrt{z} e^{-z(1 - 2 \sqrt{y} + y)} y^{1/4} dy$? What is the limit of $\frac{1}{\sqrt{4 \pi}} \int_{t}^{+ \infty} \sqrt{z} e^{-z(1 - 2 \sqrt{y} + y)} y^{1/4} dy$ when $z \rightarrow + \infty $ ?
If $t > 1$, by the dominated convergence theorem, the limit should be 0.
But there is a problem when $y=1$.

A: The substitution $y=\big(1+w/\sqrt{z}\big)^2$ transforms it into
$$\frac{1}{\sqrt{\pi}}\int_{\sqrt{z}(\sqrt{t}-1)}^{+\infty}\big(1+w/\sqrt{z}\big)^{3/2}e^{-w^2}\,dw,$$
making the limit (again by DCT) seen to be
$$\big(1+\operatorname{sgn}(1-t)\big)/2=\begin{cases}1&\text{if }t<1\\1/2&\text{if }t=1\\0&\text{if }t>1\end{cases}$$


text:
Q: Отправка формы без ведома пользователя. Нужно отправлять форму на другой сайт(домен) что бы пользователь не видел. Т.е он зашел и на другой сайт отправились данные формой. Без нажатия кнопки и переадресации как?
A: @istem, не соглашусь с Вами. Политика безопасности браузера наложит ограничение лишь на получение данных, а не как на их отправку. Т.е. достаточно сделать просто ajax-запрос, и данные отправятся, браузер даже получит ответ, и тут он уже создаст исключение.
С помощью jQuery можно вот так просто отправить запрос:
$.ajax({
  url: "http://somesite.com",
  type: "POST", // для отправки GET-запроса используйте GET
  data: {param1 : "val1", param2 : "val2"},
});

Такой вариант подойдёт, если Вам не нужно получать ответ от удалённой стороны. Иначе же может помочь JSONP-запрос.
A: Ajax не будет работать по Same Origin Policy. В вашем случае, подходит несколько вариантов. Если метод формы GET - тогда можно через тег img или script средствами JS сформировать запрос и добавить элемент в тело документа. Второй вариант - добавить атрибут target="iframe" к форме, и соответственно сам iframe на страницу. При срабатывании DOM Ready - отправлять форму. Форма отправится, результат отобразится в iframe, а уж его можно спозиционировать: left: -9999px;
Если заинтересует - напишите подробнее что там у вас, помогу с кодом, как это сделать.
A: <body onLoad="submitForm()">
<form id="fm">
...
</form>

<script type="text/javascript">
//JS
function submitForm()
{
   document.getElementById('fm').submit();
}

//jQuery
document.ready(function(){
   $('#fm').submit();
});

</script>

Я показал два варианта сабмита формы. Один - на чистом JS, другой - с использованием jQuery. При использовании jQuery, тэгу body не нужен onLoad.
Если нужна асинхронная отправка, тогда юзаем к примеру jQuery так:
$.get('http://site.com', {'param': 'val', 'param2': 'val2'}, function(data) {
   //result into data
});

либо
$.post('http://site.com', {'param': 'val', 'param2': 'val2'}, function(data) {
   //result into data
});


text:
Q: Jquery Event Trigger Keyboard Simulation i'm doing a minimal example http://jsfiddle.net/PSYCKIC/SQZVH/1/
Can't not put it work, but the idea is to simulate a keyboard event as keypress,keydown or keyup that works for every browser(Firefox, Safari, Chrome , IE).
Not sure why the code isn't working, any ideia how can i do it?

A: This is the current solution working for Chrome and Firefox, still need to check if work Opera and IE
// put cursor and input text in correct position

function setCaretPosition(elem, caretPos) {
    if (elem != null) {
        if (elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {

            if (elem.selectionStart) {
                elem.setSelectionRange(caretPos, caretPos);
                elem.focus();

                // Workaround for FireFox overflow no scroll problem
                if ($.browser.mozilla) {

                    // Trigger a "space" keypress.
                    var evt = document.createEvent("KeyboardEvent");
                    evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, 32);
                    elem.dispatchEvent(evt);

                }
                // for webkit
                if ($.browser.webkit || $.browser.msie) {
                    var te = document.createEvent('TextEvent');
                    // Trigger a "space" keypress.
                    te.initTextEvent('textInput', true, true, window, ' ');
                    elem.dispatchEvent(te);
                }

            }
            else
                elem.focus();
        }
    }
}

A: $("#test").trigger(event.type);


text:
Q: Get Google Analytics API token / Google_Client getAccessToken returns null / empty I'm trying to get a Google access token for a service account so I can access the Analytics API from the client side.
On the server side I have the following code:
    $keyFile = base_path() . '/keys/xxxxxxxx-xxxxxxxxx.json';
    $client = new Google_Client();
    $client->setApplicationName('Analytics Demo');
    $client->setAuthConfig($keyFile);
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

    $token = $client->getAccessToken();  // Returns null

At some point it returned a token, but after a couple of calls it started returning null.
Trying to get the $client->getRefreshToken() also returns null.
When I put $client in a Google_Service_Analytics object everything seems to work just fine, so I know the key file is correct and properly read:
    $analytics = new Google_Service_Analytics($client);
    $accounts = $analytics->management_accounts->listManagementAccounts(); // Returns proper data

Any ideas on what might be going wrong?
UPDATE:
Calling $client->isAccessTokenExpired() results in true so I guess I have to refresh the token, but I have no clue how.

A: After a lot of trial and error I found that I had to use $client->fetchAccessTokenWithAssertion() instead of $client->getAccessToken().
public static function getGoogleServiceToken():?string {
    $keyFile = base_path() . '/keys/xxxxxxxx-xxxxxxx.json';
    $client = new Google_Client();
    $client->setAuthConfig($keyFile);
    $client->setApplicationName('Analytics Demo');
    $client->setAccessType('access_type');
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

    if ($client->isAccessTokenExpired()) {
        $token = $client->fetchAccessTokenWithAssertion();
    }
    else {
        $token = $client->getAccessToken();
    }

    return $token['access_token'];
}

Client side:
...
private _handleGetResponse(response) {
    ...
    gapi.analytics.auth.authorize({
            serverAuth: {
                access_token: response.token,
            }
        });
    ...

Not sure why there is no decent documentation on this at all. Even knowing that I have to use this method I can't find documentation on what this method is actually doing. Any explanation or links to some documentation are still welcome!


text:
Q: Legend seems not to work with scale_discrete when trying to group by multiple variables I would like to plot the content of a data frame, containing experimental data of a continuous variable Y which depends on another continuous variable X, and on two categorical variables groups and level.
x=seq(2,7,length.out=5)
sigma=0.25
y1l=1.5*x1+4+rnorm(5,sd=sigma)
y1h=1.5*x1+5+rnorm(5,sd=sigma)
y2l=1.5*x1+7+rnorm(5,sd=sigma)
y2h=1.5*x1+8+rnorm(5,sd=sigma)
y3l=1.5*x1+9+rnorm(5,sd=sigma)
y3h=1.5*x1+10+rnorm(5,sd=sigma)
X=rep(x,6)
Y=c(y1l,y1h,y2l,y2h,y3l,y3h)
groups=rep(c("A","B","C"),each=10)
level=rep(rep(c("low","high"),each=5),times=3)
df=data.frame(groups,level,X,Y)

My idea is to use a geom_point and a geom_line layer, because in the real data frame, the experimental points are extremely noisy, and not always well separated by groups and level. Thus, adding a line layer to the obvious point layer to connect points having the same values of groups and level, makes the plot more readable. In practice I use
library(ggplot2)
p <- ggplot()
p <- p + geom_point(data=df,aes(x=X, y=Y, fill = groups,size=level),
                    shape=21, color=NA) +
         geom_line(data=df,aes(x=X, y=Y, color = groups,linetype=level)) +
         scale_size_discrete("level", range=c(1,2)) +
         scale_linetype_discrete(name=NULL,labels=NULL,breaks=NULL)
p

I get

It looks nice enough (suggestions for improvement are welcome, though :) The only problem is the level legend. Why doesn't it show the small and large circles used for plotting? How to fix that?

A: Creating your plot as follows works:
p <- ggplot()
p <- p + geom_point(data=df,aes(x=X, y=Y, colour = groups, size=level)) +
  geom_line(data=df,aes(x=X, y=Y, color = groups,linetype=level)) +
  scale_size_discrete("level", range=c(1,2)) +
  scale_linetype_discrete(name=NULL,labels=NULL,breaks=NULL)
p

So, what was wrong with your original plot? You used shape = 21 which is a dot has a border and a filling. The colour of the filling is determined by fill and the border by colour. But then set colour = NA which means that there is no border at all.
Since each point size came with various values for fill, the legend for size ignored the fill colour and only used the colour aesthetic. You can check that this is true with the following plot, where I also used shape = 21, but omitted colour = NA:
p <- ggplot()
p <- p + geom_point(data=df,aes(x=X, y=Y, fill = groups, size=level),
                    shape=21) +
  geom_line(data=df,aes(x=X, y=Y, color = groups,linetype=level)) +
  scale_size_discrete("level", range=c(1,2)) +
  scale_linetype_discrete(name=NULL,labels=NULL,breaks=NULL)
p

As you see, the size legend is drawn with empty circles that have a black border. If you set the border colour to NA, they will be "drawn" with an invisible border.
The solution is thus to omit shape = 21, which will plot points that don't have a border and have their colour determined by colour. Now also the size legend is drawn with filled dots, as you probably wanted.


text:
Q: Class term with Kuratowski pair As usual  $(x, y)$ is an abbreviation for $\left\{\{x\}, \{x,y\}\right\}$.
Given the class term:
$\left\{(x,y) \ |\  x\in A \wedge y\in A  \right\}$
for every $x$ is in $A$ and every $y$ in $A$ the $(x,y)$ pair belongs to the class.
I would like to build a class consisting of every $x$ in $A$ and only a given (single)  $y$ in $A$.
Is the following  the correct/best way?
$\left\{(x,y) \ |\  x\in A \wedge y=z \wedge z\in A  \right\}$

A: When we write $\{u\mid\varphi(u)\}$ then $u$ is a free variable in $\varphi$. If you are given $y$, then $y$ is no longer a free variable, range over all possible values.
So it should be written as $\{(x,y)\mid x\in A\}$, and just make sure that the reader understands that $y$ is given and fixed.
What you wrote, $\{(x,y)\mid x\in A\land y=z\land z\in A\}$ is effectively just writing $\{(x,y)\mid x\in A\land y\in A\}$ again. So it's definitely not the right way.


text:
Q: PHP Git Hook works directly when test execution but not when executing via git I created the following git hook to automate some tasks for me and to pipe it back down when I push a commit to my server. The code works fine when I run it directly. When the git push pushes to the server and the server executes the hook it says
remote: Deployment [BETA]: updating.
remote: git fatal not a git repository.
remote: Deployment [BETA]: complete.
remote: git fatal not a git repository.

My hook code is:
#!/usr/bin/php
<?php

chdir("/var/www");

echo "Deployment [BETA]: updating." . PHP_EOL;
exec("git pull");
echo "Deployment [BETA]: complete." . PHP_EOL;

// Get the last commit message.
$log = shell_exec("git log -n 1 HEAD");

if (stripos($log, "[trigger:composer]"))
{
    echo "Composer: starting." . PHP_EOL;
    system("php /home/root/bin/composer.phar update");
    echo "Composer: completed." . PHP_EOL;
}

if (stripos($log, "[trigger:phpunit]"))
{
    system("./vendor/bin/phpunit");
}

If anyone can help me that would be really appreciated.

A: (From #git) The issue was actually that within the context of the hook GIT_DIR and GIT_WORK_TREE are set appropriately for the repository you're working with. If you're going to cd within the hook script then you should generally set GIT_DIR and GIT_WORK_TREE appropriately: either unset them if you're moving to a Git working tree, or set them to point to the appropriate working tree and repository directory.


text:
Q: String to an array and then foreach I have a variable string which is passed to an and array then foreach that just does not want to work. Below is the code im using.
$explode = $_obj->getModDependencies();
//this variable will returns/echos the string as @ModA,@Mod_b,@Mod3 etc (yes @ is in each value)

and the foreach and array php code im using
$arr = array($explode);
foreach ($arr as $value) {
echo 'getUrl().'mod?mod_id='.$value.'">'.$value.'';
}

if i use the above code it echos one hyperlink with each value at the end of it (http://myurl/mod?mod_id=@ModA,@Mod_b,@Mod3) but i want to echo each hyperlink for each value.
Which would be
http://myurl/mod?mod_id=@ModA
http://myurl/mod?mod_id=@Mod_b
and so forth.
But if i place the actual variable output string directly into the array it echos out how i want it (see below code that works)
$arr = array(@ModA,@Mod_b,@Mod3);
foreach ($arr as $value) {
echo 'getUrl().'mod?mod_id='.$value.'">'.$value.'';
}

Any help wold be awesome!!

A: $arr = array($explode);

Thats the issue, just by saying something is within array() doesnt really make it an array as you expect it to be. You only gave it 1 argument.
You also mentioned the value of $explode is like this @ModA,@Mod_b,@Mod3. Just by naming something $explode doesn't explode it. You have to explode it yourself
$arr=explode(",","@ModA,@Mod_b,@Mod3");
//$arr=explode(",",$explode) in your case

Once that is done, your loop is already fine
foreach ($arr as $value) {
echo 'getUrl().'mod?mod_id='.$value.'">'.$value.'';
}

Fiddle

A: When your variable $explode will be a string as '@ModA,@Mod_b,@Mod3' then you have to explode it.
$arr = explode(',', $explode);
foreach ($arr as $value) {
    echo 'getUrl().'mod?mod_id='.$value.'">'.$value.'';
}


text:
Q: How to loop over multiple levels of tag elements by xpath in Selenium or BeautifulSoup I am trying to create a data frame in python of a ecommerce site's menu items. Below is an example of what the menu looks like. It is very nested and has several submenus within the main navigation bar.
Menu Example
Because there are several submenus I am having trouble creating a loop that will parse out the values for all the elements at each level. Here is an example of what the HTML looks like.
Full HTML Example

            Furniture

Living Room Furniture

                                 Sofa & Sectional Collections

I would like the final data frame to look like this:

Category 1
Category 2
Category 3
Category 3 Link Path

Furniture
Living Room Furniture
Sofas & Sectionals
https://www.xx./furniture/living_room/sofa

Furniture
Living Room Furniture
Chairs
https://www.xx./furniture/living_room/chairs

Furniture
Living Room Furniture
Coffee Tables
https://www.xx./furniture/living*room/coffee_*table

I have tried using both beautiful soup and selenium to parse each of the levels out but have not been successful in getting it to iterate.
For Category 1 I used to below code and it gave me my expected result.
input:
nav = soup.find_all("a", {"class" : lambda L: L and L.startswith('c-nav-category_link topnav')})
for item in nav:
    level1 = {
        'cat_1': item.find("span").text}
    print(level1)

output:
{'cat_1': 'Furniture'}
{'cat_1': 'Outdoor & Garden'}
{'cat_1': 'Rugs'}...

This method also worked for Category 2, however, when I tried to repeat this for category 3, I was only able to pull out the first item under each submenu instead of all the items under each submenu.
input:
final_link = soup.find_all("div", {"class" : lambda L: L and L.startswith('col col-')},"li")
for final_item in final_link:
    level3 = {
        'cat_3': final_item.find("a").text.replace('\n',"")}
    print(level3)

output:
{'cat_3': 'Sofa & Sectional Collections'}
{'cat_3': 'Bedroom Collections'}
{'cat_3': 'Dining Collections'}...

This should return: Sofas & Sectionals, Sectionals, Sofas & Loveseats. But instead it skips to the next submenu. I also tried to parse using selenium and XPATH but was unsuccessful.
from selenium.webdriver.common.by import By
title = driver.find_elements(by=By.XPATH, value='//*[@id="topnav-container"]/ul/li')
for li in title:
    product_data = {'title': li.text}
print(product_data)

Would anyone have any suggestions on how to parse this correctly?


text:
Q: Spring 4.3.0.RELEASE + 5.2.0.Final, org.springframework.transaction.interceptor.TransactionInterceptor#0 I have Exaption and after i search it in google there is no spsific solution fr this version of Hibernate and Spring.
Please Try to help if you can :)
Ok Thank you @M. Deinum i changed to hibrnate 5 and build new tomcat server its looking good and this is my log now: you see any more problems in my work?
The console log:
    יונ 29, 2016 2:45:03 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Searcher' did not find a matching property.
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.36
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Jun 9 2016 13:55:50 UTC
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.36.0
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.8.0_92\jre
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_92-b14
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\Home\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Users\Home\Documents\DropShiping\apache-tomcat-8.0.36
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\Home\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Users\Home\Documents\DropShiping\apache-tomcat-8.0.36
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\Home\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\Home\Documents\DropShiping\apache-tomcat-8.0.36\endorsed
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1255
יונ 29, 2016 2:45:03 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_92\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_92/bin/server;C:/Program Files/Java/jre1.8.0_92/bin;C:/Program Files/Java/jre1.8.0_92/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:Python27;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Users\Home\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\TortoiseSVN\bin;C:\xampp\php\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 & MySQL Utilities 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 & MySQL Utilities 1.5\Doctrine extensions for PHP\;C:\Program Files\Java\jdk1.8.0_92\bin;C:\Users\Home\Documents\DropShiping\Framework\eclipse-jee-mars-2-win32-x86_64\eclipse;;.
יונ 29, 2016 2:45:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
יונ 29, 2016 2:45:03 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
יונ 29, 2016 2:45:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
יונ 29, 2016 2:45:03 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
יונ 29, 2016 2:45:03 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 877 ms
יונ 29, 2016 2:45:03 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
יונ 29, 2016 2:45:03 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.36
יונ 29, 2016 2:45:06 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
יונ 29, 2016 2:45:06 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
log4j:WARN No appenders could be found for logger (org.springframework.web.servlet.DispatcherServlet).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
יונ 29, 2016 2:45:06 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'searcher'
יונ 29, 2016 2:45:10 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
יונ 29, 2016 2:45:10 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
יונ 29, 2016 2:45:10 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7110 ms

searcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Searcher-Servlet Context: defines this servlet's request-processing
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving
    up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources
    in the /WEB-INF/views directory -->
<beans:bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"
    /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix"
    value=".jsp" /> </bean> -->

<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url"
        value="jdbc:mysql://localhost:3306/SearcherDB" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="root" />
</beans:bean>

<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource" />
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.searcher.entity.EcommerceEntity</beans:value>
            <beans:value>com.searcher.entity.ImageEntity</beans:value>
            <beans:value>com.searcher.entity.ProductEntity</beans:value>
            <beans:value>com.searcher.entity.ProductRequestEntity</beans:value>
            <beans:value>com.searcher.entity.RequestEntity</beans:value>
            <beans:value>com.searcher.entity.SellerEntity</beans:value>
            <beans:value>com.searcher.entity.UserEntity</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
            <beans:prop key="hibernate.format_sql">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<!-- eCommerce -->
<beans:bean id="ecommerceDAO" class="com.searcher.dao.EcommerceImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="ecommerceService" class="com.searcher.service.EcommerceServiceImp">
    <beans:property name="ecommerceDAO" ref="ecommerceDAO">
    </beans:property>
</beans:bean>

<!-- Image -->
<beans:bean id="imageDAO" class="com.searcher.dao.ImageImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="imageService" class="com.searcher.service.ImageServiceImp">
    <beans:property name="imageDAO" ref="imageDAO">
    </beans:property>
</beans:bean>

<!-- Product -->
<beans:bean id="productDAO" class="com.searcher.dao.ProductImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="productService" class="com.searcher.service.ProductServiceImp">
    <beans:property name="productDAO" ref="productDAO">
    </beans:property>
</beans:bean>

<!-- ProductRequest -->
<beans:bean id="productRequestDAO" class="com.searcher.dao.ProductRequestImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="productRequestService"
    class="com.searcher.service.ProductRequestServiceImp">
    <beans:property name="productRequestDAO" ref="productRequestDAO">
    </beans:property>
</beans:bean>

<!-- Request -->
<beans:bean id="requestDAO" class="com.searcher.dao.RequestImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="requestService" class="com.searcher.service.RequestServiceImp">
    <beans:property name="requestDAO" ref="requestDAO">
    </beans:property>
</beans:bean>

<!-- Seller -->
<beans:bean id="sellerDAO" class="com.searcher.dao.SellerImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="sellerService" class="com.searcher.service.SellerServiceImp">
    <beans:property name="sellerDAO" ref="sellerDAO">
    </beans:property>
</beans:bean>

<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
    <beans:property name="userDAO" ref="userDAO">
    </beans:property>
</beans:bean>

<context:annotation-config />

<context:component-scan base-package="com.searcher" />

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

<beans:bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <beans:property name="sessionFactory"
        ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Searcher</groupId>
<artifactId>Searcher</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.0.RELEASE</version>
        <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
             </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-orm</artifactId>
         <version>4.3.0.RELEASE</version>
    </dependency>

    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.0.Final</version>
    </dependency>

    <!-- Apache Commons DBCP -->
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <!-- Spring ORM -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.0.RELEASE</version>
    </dependency>

    <!-- AspectJ -->
    <dependency>
        <groupId>aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.5.4</version>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
        <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.21</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.21</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
        <exclusions>
            <exclusion>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
        </exclusions>
        <scope>runtime</scope>
    </dependency>

    <!-- @Inject -->
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <!-- Test -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>jta</artifactId>
    <version>1.1</version>
</dependency>

</dependencies>

<!-- Build -->
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
    <plugin>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.9</version>
        <configuration>
            <additionalProjectnatures>
                <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
            </additionalProjectnatures>
            <additionalBuildcommands>
                <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
            </additionalBuildcommands>
            <downloadSources>true</downloadSources>
            <downloadJavadocs>true</downloadJavadocs>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
            <compilerArgument>-Xlint:all</compilerArgument>
            <showWarnings>true</showWarnings>
            <showDeprecation>true</showDeprecation>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <configuration>
            <mainClass>org.test.int1.Main</mainClass>
        </configuration>
    </plugin>

    <!-- Old

    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.3</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
    <plugin>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.6</version>
      <configuration>
        <warSourceDirectory>WebContent</warSourceDirectory>
        <failOnMissingWebXml>false</failOnMissingWebXml>
      </configuration>
    </plugin>
    -->

</plugins>
</build>
<!--  Old 2
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>org.test.int1.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
    <finalName>${project.artifactId}</finalName>
</build>
-->

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>Searcher</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>searcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>searcher</servlet-name>
        <url-pattern>/welcome.jsp</url-pattern>
        <url-pattern>/welcome.html</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>


text:
Q: The cleaner way to upgrading a Mac This page list a way to do a clean install of Snow Leopard without losing any of your settings.  This sounds pretty darn good since my mac did get a bit slower over time.
The method basically involves copying your existing drive to an external one, then doing an Erase and Install from the installation DVD.
After the installation, supposedly, I'll be presented with an option to migrate settings from another Mac.
I am not all that familiar with the Mac, hence what is probably a simple question.  With this migration option, will I be able to copy over all my applications or will I have to reinstall them from scratch?

A: The application that helps you migrate all your data to your new Mac is called Migration Assistant. If you start it, it tells you the following:

You can use Migration Assistant to
  transfer important information from
  one Mac to another, such as:

*

*User accounts

*Applications

*Network and computer settings

*Files

*Volumes

Apparently transferring applications works, but I could imagine that some applications with an overly complicated installer cannot be simply transfered.
Why don't you just try it? If it doesn't work to satisfaction for you, just reinstall your backup.

A: Depends on the applications. Some have ridiculously complicated activation schemes which require reinstallation, some don't. If you do your migration through Time Machine it generally copies just about everything.


text:
Q: sourceSets with gradle kotlin DSL in grade 4.10rc I am using the following code:
java.sourceSets["main"].java {
    srcDir("src/main/extraSource")
}

works perfectly in gradle 4.9, but in 4.10 rc1 gives the following error:
  Line 5: java.sourceSets["main"].java {
               ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
                   public val Project.sourceSets: SourceSetContainer defined in org.gradle.kotlin.dsl

Any ideas? Has there been a change to what is needed?
Many other answers (eg. this one  and every suggested answer to this question) will also need updates if this has changed

A: This is an expected breaking change and is listed at https://docs.gradle.org/4.10-rc-2/release-notes.html#changes-to-the-gradle-kotlin-dsl
But unfortunately it's missing in the Kotlin DSL release notes, it'll be fixed for 4.10 GA.
In a nutshell, java.sourceSets is now sourceSets. For your example the fixed script is:
sourceSets["main"].java {
    srcDir("src/main/extraSource")
}

It's a change in gradle/gradle, see https://github.com/gradle/gradle/pull/5867 for some background.


text:
Q: Creation of custom contracts on the server? Converting DOCX to PDF in Nodejs this kind of question has already been asked here, but I found no satisfactory answers. They either require libre office to be installed on the system or to use third party API's.
Our usecase is that we generate contracts for each user, the issue is that PDF's are hard to replace placeholder values, so we are doing that with a .docx file but for printing and  integrity of the layout we'd like to have them be PDF's after they've been populated with the correct data.
What would be the best approach here, should we scrap .docx template entirely and try and go with the PDF's from the start? Should we deploy our own API for converting the docs?


text:
Q: asignar una variable global Twig hola estoy aprendiendo a usar twig, y no puedo asignar una variable para usar en todos los templates, en la documentacion dice
$twig = new Twig_Environment($loader);
$twig->addGlobal('text', new Text());

y yo lo uso asi
$twig = new Twig_Environment($loader);
$twig->addGlobal('tsConfig', $tsCore->settings);

y no me da nada en el template, como tendria que hacerlo?

A: Primero en la sintaxis no veo problema guiandome de la documentacion asi que la pregunta seria como estas usando dicha variable??
Mira aqui la informacion de twig en español.
http://gitnacho.github.io/Twig/advanced.html#globales


text:
Q: How does std::string length() function work? I can't understand why this loop prints "INFINITE". If the string length is 1, how can length()-2 result in a big integer?
for(int i=0;i<s.length()-2;i++)
{
    cout<<"INFINITE"<<endl;
}

A: std::string.length() returns a size_t. This is an unsigned integer type. You are experiencing integer overflow. In pseudocode:
0 - 1 = int.maxvalue

In your case specifically it is:
(size_t)1 - 2 = SIZE_MAX

where SIZE_MAX usually equals 2^32 - 1

A: std::string::length() returns a std::string::size_type.
std::string::size_type is specified to be the same type as allocator_traits<>::size_type (of the string's allocator).
This is specified to be an unsigned type.
Hence, the number will wrap (defined behaviour) and become huge. Precisely how huge will depend on the architecture.
You can test it on your architecture with this little program:
#include <limits>
#include <iostream>
#include <string>
#include <utility>
#include <iomanip>

int main() {

    using size_type = std::string::size_type;

    std::cout << "unsigned : " << std::boolalpha << std::is_unsigned<size_type>::value << std::endl;
    std::cout << "size     : " << std::numeric_limits<size_type>::digits << " bits" << std::endl;
    std::cout << "npos     : " << std::hex << std::string::npos << std::endl;
}

in the case of apple x64:
unsigned : true
size     : 64 bits
npos     : ffffffffffffffff


text:
Q: How to view locally stored HTML files on Ubuntu Touch? I am looking for an option to open html files rather than URLs on the web in the browser on my phone with Ubuntu Touch. As there's no 'open file' option I have been experimenting with file:// type URLs in the address bar but that only results in 'Network Error' messages. Clicking on an html file in the File Manager doesn't work either. Any suggestions?

A: You may write a .desktop file. Read:
http://www.mail-archive.com/ubuntu-phone%40lists.launchpad.net/msg18884.html
Following the suggestion the asker created a .desktop file in .local/share/applications with the following contents:
[Desktop Entry]
Name=Usage statistics
Type=Application
Exec=webapp-container /home/phablet/Usage/index.html
Terminal=false
X-Ubuntu-Touch=true

The asker says it does the trick for him. It is not very flexible but suits his needs.


text:
Q: Kaplan Meier Curve is not showing ticks for censored data I am drawing a Kaplan Meier Curve in python. My KMC is fine but it does not show ticks for right-censored cases in my data. I tried a lot to show the ticks and here is the code that I wrote for this.  I don't know why they are not appearing. I will be very thankful if someone could help to figure out the issue and the way to fix it. Here is my figure https://ibb.co/bPfFMxY
Many Thanks!
Python code:

def draw_KMC():
  # In actual code file, here are some code lines before drawing the KMC but for the sake of simplicity I am not adding those

  # ---- First Curve
  legend_label_1 = "Category A"

  kmf_1 = KaplanMeierFitter()
  kmf_1.fit(durations = survival_times_A, event_observed=events_A, label=legend_label_A)

  # ---- Second Curve
  legend_label_2 = "Category B"
  kmf_2 = KaplanMeierFitter()
  kmf_2.fit(durations = survival_times_B, event_observed=events_B, label=legend_label_B)
  # ---- Third Curve
  legend_label_3 = "Category C"
  kmf_3 = KaplanMeierFitter()
  kmf_3.fit(durations = survival_times_C, event_observed=events_C, label=legend_label_C)

  ax = plt.subplot(111)
  plt.yticks(np.arange(0.0, 1.1, 0.1), ['0', '10', '20', '30', '40', '50', '60', '70',
  '80', '90', '100'])
  kmf_1.plot(ax=ax,  show_censors=True,ci_show=False,censor_styles={"marker": "|", "ms":
  6} )

  kmf_2.plot(ax=ax, show_censors=True,ci_show=False,censor_styles={"marker": "|", "ms":
  6})
  kmf_3.plot(ax=ax,show_censors=True,ci_show=False,censor_styles={"marker": "|", "ms": 6})

  plt.xlabel('Months since the completion date', fontsize=12)
  plt.ylabel('Proportion of studies w.r.t categories (%)')
  plt.grid(True)
  from lifelines.plotting import add_at_risk_counts
  add_at_risk_counts(kmf_1, kmf_2,kmf_3, ax=ax)
  plt.show()

I even tried by replacing the kmf.plt() with kmf.plot_survival_function () as well, but it did not make any difference and no ticks appear for censored data.

A: I tried to repro your problem locally, but didn't see your observed behaviour. Can you try the following, simplified, code:

survival_times_A = [10.9, 15.5, 20.3, 25.6, 30.8]
events_A = [True, False, False, True, True]
legend_label_A="test"

# In actual code file, here are some code lines before drawing the KMC but for the sake of simplicity I am not adding those

# ---- First Curve
legend_label_1 = "Category A"

kmf_1 = KaplanMeierFitter()
kmf_1.fit(durations = survival_times_A, event_observed=events_A, label=legend_label_A)

ax = plt.subplot(111)
plt.yticks(np.arange(0.0, 1.1, 0.1), ['0', '10', '20', '30', '40', '50', '60', '70',
'80', '90', '100'])
kmf_1.plot(ax=ax,  show_censors=True,ci_show=False, censor_styles={"marker": "o", "ms":
60} )

plt.xlabel('Months since the completion date', fontsize=12)
plt.ylabel('Proportion of studies w.r.t categories (%)')
plt.grid(True)
from lifelines.plotting import add_at_risk_counts
add_at_risk_counts(kmf_1, ax=ax)
plt.show()

What might be happening is that you have so many data points that the censored markings are getting "squeezed" out.
Also, can you tell us what version of lifelines you are using?


text:
Q: TypeScript: pass rejected promise as a parameter I have the following function signature:
public myCustomFunction(): Promise<string> {
// Insert code here
}

I'm interested in returning a rejected promise with error.
How can I create one? The promise should be already rejected, I'm not interested in creating a new promise with reject/success handlers.

A: You can create a promise in a pre-rejected state using Promise.reject:

The Promise.reject() method returns a Promise object that is rejected with a given reason.

As that quote suggests, you can pass a reason as an argument.


text:
Q: How does @@ work in input statement? I am trying to understand how does sas read this code.
         data scores;
    input Grade : $1. @@;
     check='abcdf';
   if verify(grade,check)>0 then
  put @1 'INVALID ' grade=;
   datalines;
 a b c b c d f a a q a b d d b z
     ;
     run;

The log gives the following result:
    INVALID Grade=q
    INVALID Grade=z

Can anyone tell me how does SAS read the data and what does @@ stand for?Is each observation of the field - Grade read for each "grade= "?

A: data scores;
    input Grade : $1.;

would only read the first character on each line. This is because, after each execution of an input statement, a new line from the file is read into the input buffer, even if there is a lot left on the current line.
With Grade : $1. @@;, you instruct SAS not to read another line, unless all data on the current line is processed.