text:
Q: Convert a table array to JSON object I am working on a function for converting a table array to JSON and this is my code. I have checked strJSON is the JSON format I want, but it is a string instead of an JSON object. An error message prompts out saying that "Darren is not defined" when I try to convert it into JSON with "eval". I dont know what is happening.
var myArray=[["Name","Age","Gender"],["Darren",31,"Male"],["Gakki",25,"Female"]];

//expected output
var myJSON=[{"Name":"Darren","Age":31,"Gender":"Male"},{"Name":"Gakki","Age":25,"Gender":"Female"}];

function convertJSON(tableData){
    var objJSON=[];
    var strJSON=[];
    tableData.forEach(function(rowData,i){
        if (i==0){
            rowData.forEach(function(cellData){
                head.push(cellData);
            });
        }
        else{
            var objData=[];
            var objEntry=[];
            rowData.forEach(function(cellData,j){
                 objData=head[j] + ":" + cellData;
                objEntry.push(objData);
             });
            strJSON.push("{" + objEntry + "}");
        }
    });
    objJSON=eval("[" + strJSON + "]");
    return objJSON
}

A: *

*Get 1 element and remove it in original array by Array#shift

*Then use Array#map to build your expect result

var myArray=[["Name","Age","Gender"],["Darren",31,"Male"],["Gakki",25,"Female"]];

var properties = myArray.shift();

var result = myArray.map( a => {
  var newObj = {};
  properties.forEach ( (p, idx) => {
    newObj[p] = a[idx];
  });
  return newObj;
})

console.log(result);

A:     function html2json() {
   var json = '{';
   var otArr = [];
   var tbl2 = $('#dest_table tr').each(function(i) {
      x = $(this).children();
      var itArr = [];
      x.each(function() {
         itArr.push('"' + $(this).text() + '"');
      });
      otArr.push('"' + i + '": [' + itArr.join(',') + ']');
   })
   json += otArr.join(",") + '}'

   return json;
}

A: Don't try to create a JSON string manually. Put together a normal object and use JSON.stringify to convert.

var myArray=[["Name","Age","Gender"],["Darren",31,"Male"],["Gakki",25,"Female"]];

//expected output
var myJSON=[{"Name":"Darren","Age":31,"Gender":"Male"},{"Name":"Gakki","Age":25,"Gender":"Female"}];

function convertJSON(tableData){
    var keys = tableData[0],
        objects = [];

    for(var i = 1; i < tableData.length; i++){
        var rowObject = {};
        tableData[i].forEach(function(item, index){
            rowObject[keys[index]] = item;
        });
        objects.push(rowObject);
    }

    return JSON.stringify(objects);
}

document.write(convertJSON(myArray));


text:
Q: Propagation of UITouch events I have views arranged as shown in attached figure.

*

*MAINVIEW is an added subview to UISCROLLVIEW
class NotewallController:UIViewController, UIScrollViewDelegate {

    var bgImage:UIImageView?
    var bgScrollView:UIScrollView?
    var masterView:UIView?

    override func viewDidLoad() {

        self.bgScrollView = UIScrollView(frame: self.view.bounds)
        self.bgScrollView!.contentSize = CGSizeMake(1000, 1000)
        self.bgScrollView!.delegate = self
        self.bgScrollView!.minimumZoomScale = 1.0
        self.bgScrollView!.maximumZoomScale = 4.0
        self.view.addSubview(self.bgScrollView!)

        masterView = UIView(frame: CGRectMake(0,0,1000,1000))
        masterView!.backgroundColor = UIColor.clearColor()
        masterView!.userInteractionEnabled = true
        bgScrollView!.addSubview(masterView!)

        let note = WALLVIEW(frame: CGRectMake(20, 20, 30, 30))
        self.masterView!.addSubview(note)

    }

*WALLVIEW is a subclass of UIVIEW
class WallView:UIView {
override init(frame: CGRect) {

   super.init(frame: frame)

    let bgImageView = UIImageView(frame: frame)
    bgImageView.image = UIImage(named: "stickynote.png")
    bgImageView.userInteractionEnabled = true
    self.addSubview(bgImageView)

    let tap = UITapGestureRecognizer(target: self, action: "WallNoteTapped:")
    bgImageView.addGestureRecognizer(tap)

}

My issue is in WALLVIEW. As you can notice, I have a TAP GESTURE in WALLVIEW. When the program is executed, a tap of WALLVIEW object doesn't call the "WallNoteTapped:" method. Suspecting the touch events are not passed to WALLVIEW object "note".
I am not able to understand why "WallNoteTapped:" method is not triggered.
Thanks
EDIT:
I made WALLVIEW subclass of UIImageView rather than UIView and it worked finally.

A: Adding an UITapGestureRecognizer cancel te touches in its subviews.
Try to set cancelsTouchesInView to false.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What exactly are tuples in Python? I'm following a couple of Pythone exercises and I'm stumped at this one.
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
  # +++your code here+++
  return

What is a Tuple? Do they mean a List of Lists?

A: A tuple and a list is very similar. The main difference (as a user) is that a tuple is immutable (can't be modified)
In your example:
[(2, 2), (1, 3), (3, 4, 5), (1, 7)]

This is a list of tuples
[...] is the list
(2,2) is a tuple

A: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −
tup1 = ('Dog', 'Cat', 2222, 555555);
tup2 = (10, 20, 30, 40, 50 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing −
tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (45,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

A: The best summary of the differences between lists and tuples I have read is this:

One common summary of these more interesting, if subtle, differences is that tuples are heterogeneous and lists are homogeneous. In other words: Tuples (generally) are sequences of different kinds of stuff, and you deal with the tuple as a coherent unit. Lists (generally) are sequences of the same kind of stuff, and you deal with the items individually.

From: http://news.e-scribe.com/397

A: The tuple is the simplest of Python's sequence types. You can think about it as an immutable (read-only) list:
>>> t = (1, 2, 3)
>>> print t[0]
1
>>> t[0] = 2
TypeError: tuple object does not support item assignment

Tuples can be turned into new lists by just passing them to list() (like any iterable), and any iterable can be turned into a new tuple by passing it to tuple():
>>> list(t)
[1, 2, 3]
>>> tuple(["hello", []])
("hello", [])

Hope this helps. Also see what the tutorial has to say about tuples.

A: *

*Why are there separate tuple and list data types? (Python FAQ)

*Python Tuples are Not Just Constant Lists

*Understanding tuples vs. lists in Python

A: Tuples are used to group related variables together. It's often more convenient to use a tuple rather than writing yet another single-use class. Granted, accessing their content by index is more obscure than a named member variable, but it's always possible to use 'tuple unpacking':
def returnTuple(a, b):
    return (a, b)

a, b = returnTuple(1, 2)

A: In Python programming, a tuple is similar to a list. The difference between them is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
data-types-in-python


text:
Q: Eigen: Modifyable Custom Expression I'm trying to implement a modifyable custom expression using Eigen, similar to this question. Basically, what I want is something similar to the indexing example in the tutorial, but with the possibility to assign new values to the selected coefficients.
As suggested in the accepted answer in the question mentioned above, I have looked into the Transpose implementation and tried many things, yet without success. Basically, my attempts are failing with errors like 'Eigen::internal::evaluator<SrcXprType>::evaluator(const Eigen::internal::evaluator<SrcXprType> &)': cannot convert argument 1 from 'const Eigen::Indexing<Derived>' to 'Eigen::Indexing<Derived> &'. Probably, the problem lies in my evaluator struct which seems to be read-only.
namespace Eigen {
namespace internal {
    template<typename ArgType>
    struct evaluator<Indexing<ArgType> >
        : evaluator_base<Indexing<ArgType> >
    {
        typedef Indexing<ArgType> XprType;
        typedef typename nested_eval<ArgType, XprType::ColsAtCompileTime>::type ArgTypeNested;
        typedef typename remove_all<ArgTypeNested>::type ArgTypeNestedCleaned;
        typedef typename XprType::CoeffReturnType CoeffReturnType;
        typedef typename traits<ArgType>::Scalar Scalar;
        enum {
            CoeffReadCost = evaluator<ArgTypeNestedCleaned>::CoeffReadCost,
            Flags = Eigen::ColMajor
        };

        evaluator(XprType& xpr)
            : m_argImpl(xpr.m_arg), m_rows(xpr.rows())
        { }
        const Scalar& coeffRef(Index row, Index col) const
        {
             return m_argImpl.coeffRef(... very clever stuff ...)
        }

        Scalar& coeffRef(Index row, Index col)
        {
             return m_argImpl.coeffRef(... very clever stuff ...)
        }

        evaluator<ArgTypeNestedCleaned> m_argImpl;
        const Index m_rows;
    };
}
}

Also, I've changed all occurences of typedef typename Eigen::internal::ref_selector<ArgType>::type to ...::non_const_type, but this had no effect.
Due to the complexity of the Eigen library, I cant figure out how to puzzle the expression and the evaluator together correctly. I don't understand, why my evaluator is read-only or how to get a write-enabled evaluator.
It would be great if someone could provide a minimal example for a modifyable custom expression.

A: With help of ggael's hint I've been able to sucessfully add my own modifyable expression. I've basically adapted the IndexedView of the Eigen development branch.
As the originally requested funcionality is covered by the IndexedView, I've written a modifyable circular shift function as simple example of a modifyable custom expression. Most of the code is directly taken from the IndexedView, so credits go to the authors of that.
// circ_shift.h
#pragma once
#include <Eigen/Core>

namespace helper
{
        namespace detail
    {
        template <typename T>
        constexpr std::true_type is_matrix(Eigen::MatrixBase<T>);
        std::false_type constexpr is_matrix(...);

        template <typename T>
        constexpr std::true_type is_array(Eigen::ArrayBase<T>);
        std::false_type constexpr is_array(...);
    }

    template <typename T>
    struct is_matrix : decltype(detail::is_matrix(std::declval<std::remove_cv_t<T>>()))
    {
    };

    template <typename T>
    struct is_array : decltype(detail::is_array(std::declval<std::remove_cv_t<T>>()))
    {
    };

    template <typename T>
    using is_matrix_or_array = std::bool_constant<is_array<T>::value || is_matrix<T>::value>;

    /*
     * Index something if it's not an scalar
     */
    template <typename T, typename std::enable_if<is_matrix_or_array<T>::value, int>::type = 0>
    auto index_if_necessary(T&& thing, Eigen::Index idx)
    {
        return thing(idx);
    }

    /*
    * Overload for scalar.
    */
    template <typename T, typename std::enable_if<std::is_scalar<std::decay_t<T>>::value, int>::type = 0>
    auto index_if_necessary(T&& thing, Eigen::Index)
    {
        return thing;
    }
}

namespace Eigen
{
    template <typename XprType, typename RowIndices, typename ColIndices>
    class CircShiftedView;

    namespace internal
    {
        template <typename XprType, typename RowIndices, typename ColIndices>
        struct traits<CircShiftedView<XprType, RowIndices, ColIndices>>
            : traits<XprType>
        {
            enum
            {
                RowsAtCompileTime = traits<XprType>::RowsAtCompileTime,
                ColsAtCompileTime = traits<XprType>::ColsAtCompileTime,
                MaxRowsAtCompileTime = RowsAtCompileTime != Dynamic ? int(RowsAtCompileTime) : int(traits<XprType>::MaxRowsAtCompileTime),
                MaxColsAtCompileTime = ColsAtCompileTime != Dynamic ? int(ColsAtCompileTime) : int(traits<XprType>::MaxColsAtCompileTime),

                XprTypeIsRowMajor = (int(traits<XprType>::Flags) & RowMajorBit) != 0,
                IsRowMajor = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1
                                 : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0
                                 : XprTypeIsRowMajor,

                FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0,
                FlagsLvalueBit = is_lvalue<XprType>::value ? LvalueBit : 0,
                Flags = (traits<XprType>::Flags & HereditaryBits) | FlagsLvalueBit | FlagsRowMajorBit
            };
        };
    }

    template <typename XprType, typename RowShift, typename ColShift, typename StorageKind>
    class CircShiftedViewImpl;

    template <typename XprType, typename RowShift, typename ColShift>
    class CircShiftedView : public CircShiftedViewImpl<XprType, RowShift, ColShift, typename internal::traits<XprType>::StorageKind>
    {
    public:
        typedef typename CircShiftedViewImpl<XprType, RowShift, ColShift, typename internal::traits<XprType>::StorageKind>::Base Base;
        EIGEN_GENERIC_PUBLIC_INTERFACE(CircShiftedView)
        EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CircShiftedView)

        typedef typename internal::ref_selector<XprType>::non_const_type MatrixTypeNested;
        typedef typename internal::remove_all<XprType>::type NestedExpression;

        template <typename T0, typename T1>
        CircShiftedView(XprType& xpr, const T0& rowShift, const T1& colShift)
            : m_xpr(xpr), m_rowShift(rowShift), m_colShift(colShift)
        {
            for (auto c = 0; c < xpr.cols(); ++c)
            assert(std::abs(helper::index_if_necessary(m_rowShift, c)) < m_xpr.rows()); // row shift must be within +- rows()-1
            for (auto r = 0; r < xpr.rows(); ++r)
            assert(std::abs(helper::index_if_necessary(m_colShift, r)) < m_xpr.cols()); // col shift must be within +- cols()-1
        }

        /** \returns number of rows */
        Index rows() const { return m_xpr.rows(); }

        /** \returns number of columns */
        Index cols() const { return m_xpr.cols(); }

        /** \returns the nested expression */
        const typename internal::remove_all<XprType>::type&
        nestedExpression() const { return m_xpr; }

        /** \returns the nested expression */
        typename internal::remove_reference<XprType>::type&
        nestedExpression() { return m_xpr.const_cast_derived(); }

        EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
        Index getRowIdx(Index row, Index col) const
        {
            Index R = m_xpr.rows();
            assert(row >= 0 && row < R && col >= 0 && col < m_xpr.cols());
            Index r = row - helper::index_if_necessary(m_rowShift, col);
            if (r >= R)
                return r - R;
            if (r < 0)
                return r + R;
            return r;
        }

        EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
        Index getColIdx(Index row, Index col) const
        {
            Index C = m_xpr.cols();
            assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < C);
            Index c = col - helper::index_if_necessary(m_colShift, row);
            if (c >= C)
                return c - C;
            if (c < 0)
                return c + C;
            return c;
        }

    protected:
        MatrixTypeNested m_xpr;
        RowShift m_rowShift;
        ColShift m_colShift;
    };

    // Generic API dispatcher
    template <typename XprType, typename RowIndices, typename ColIndices, typename StorageKind>
    class CircShiftedViewImpl
        : public internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type
    {
    public:
        typedef typename internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type Base;
    };

    namespace internal
    {
        template <typename ArgType, typename RowIndices, typename ColIndices>
        struct unary_evaluator<CircShiftedView<ArgType, RowIndices, ColIndices>, IndexBased>
            : evaluator_base<CircShiftedView<ArgType, RowIndices, ColIndices>>
        {
            typedef CircShiftedView<ArgType, RowIndices, ColIndices> XprType;

            enum
            {
                CoeffReadCost = evaluator<ArgType>::CoeffReadCost + NumTraits<Index>::AddCost /* for comparison */ + NumTraits<Index>::AddCost /*for addition*/,

                Flags = (evaluator<ArgType>::Flags & HereditaryBits),

                Alignment = 0
            };

            EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& xpr) : m_argImpl(xpr.nestedExpression()), m_xpr(xpr)
            {
                EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
            }

            typedef typename XprType::Scalar Scalar;
            typedef typename XprType::CoeffReturnType CoeffReturnType;

            EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
            CoeffReturnType coeff(Index row, Index col) const
            {
                return m_argImpl.coeff(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col));
            }

            EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
            Scalar& coeffRef(Index row, Index col)
            {
                assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < m_xpr.cols());

                return m_argImpl.coeffRef(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col));
            }

        protected:

            evaluator<ArgType> m_argImpl;
            const XprType& m_xpr;
        };
    } // end namespace internal
} // end namespace Eigen

template <typename XprType, typename RowShift, typename ColShift>
auto circShift(Eigen::DenseBase<XprType>& x, RowShift r, ColShift c)
{
    return Eigen::CircShiftedView<XprType, RowShift, ColShift>(x.derived(), r, c);
}

And:
// main.cpp
#include "stdafx.h"
#include "Eigen/Core"
#include <iostream>
#include "circ_shift.h"

using namespace Eigen;

int main()
{

    ArrayXXf x(4, 2);
    x.transpose() << 1, 2, 3, 4, 10, 20, 30, 40;

    Vector2i rowShift;
    rowShift << 3, -3; // rotate col 1 by 3 and col 2 by -3

    Index colShift = 1; // flip columns

    auto shifted = circShift(x, rowShift, colShift);

    std::cout << "shifted: " << std::endl << shifted << std::endl;

    shifted.block(2,0,2,1) << -1, -2; // will appear in row 3 and 0.
    shifted.col(1) << 2,4,6,8;  // shifted col 1 is col 0 of the original

    std::cout << "modified original:" << std::endl << x << std::endl;

    return 0;
}


text:
Q: POST To WCF Service I'm trying to POST a serialized object to my WCF service. However, I keep receiving a "NotFound" error. I have been beating my head on this for three days. Can someone tell me what I'm doing wrong? Below is my client-side code, my WCF service operation, and the class definition I'm trying to serialize.
Client-Side Code
// Build a wrapper exception that will be serialized
Exception ex = e.ExceptionObject;
MyException exception = new MyException(ex.Message, ex.StackTrace, "silverlight app", ex.GetType().FullName, string.Empty);

string json = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
  // Serialize the object
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectType);
  serializer.WriteObject(memoryStream, objectToSerialize);

  // Convert the data to json
  byte[] bytes = memoryStream.ToArray();
  int count = (int)(memoryStream.Length);
  json = Encoding.UTF8.GetString(bytes, 0, count);
}

 // Submit the information to log
string url = "http://localhost:90/services/MyService.svc/LogError";
WebClient loggingService = new WebClient();
loggingService.UploadStringCompleted += new UploadStringCompletedEventHandler(loggingService_UploadStringCompleted);
loggingService.Headers["Content-type"] = "application/json";
loggingService.Encoding = Encoding.UTF8;
loggingService.UploadStringAsync(new Uri(logExceptionUrl), "POST", json);

MyException (Client-Side Version)
public class MyException : Exception
{
  private readonly string stackTrace;
  public override string StackTrace
  {
    get {
      return base.StackTrace;
    }
  }

  private readonly string message;
  public override string Message
  {
    get {
      return base.Message;
    }
  }

  private readonly string component;
  public string Component
  {
    get { return component; }
  }

  private readonly string typeName;
  public string TypeName
  {
    get { return typeName; }
  }

  private readonly string miscellaneous;
  public string Miscellaneous
  {
    get { return miscellaneous; }
  }

  public MyException()
  { }

  public MyException(string message) : base(message)
  { }

  public MyException(string message, Exception inner) : base(message, inner)
  { }

  public MyException(string message, string stackTrace) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
  }

  public MyException(string message, string stackTrace, string component, string typeName, string miscellaneous) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
    this.component = component;
    this.typeName = typeName;
    this.miscellaneous = miscellaneous;
  }
}

WCF Service
[OperationContract]
[WebInvoke(UriTemplate = "/LogError", BodyStyle=WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public string LogError(MyException exc)
{
  try
  {
    // Write the details of exc to the database
    return "ok";
  }
  catch (Exception ex)
  {
    return "error";
  }
}

MyException in the WCF Project
[Serializable]
public class MyException : Exception
{
  public override string StackTrace
  {
    get { return base.StackTrace; }
  }
  private readonly string stackTrace;

  public override string Message
  {
    get { return base.Message; }
  }
  private readonly string message;

  public string Component
  {
    get { return component; }
    set { /* */ }
  }
  private readonly string component;

  public string TypeName
  {
    get { return typeName; }
    set { /* */ }
  }
  private readonly string typeName;

  public string Miscellaneous
  {
    get { return miscellaneous; }
    set { /* */ }
  }
  private readonly string miscellaneous;

  public MyException()
  {}

  public MyException(string message) : base(message)
  { }

  public MyException(string message, Exception inner) : base(message, inner)
  { }

  public MyException(string message, string stackTrace) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
  }

  public MyException(string message, string stackTrace, string component, string typeName, string miscellaneous) : base()
  {
    this.message = message;
    this.stackTrace = stackTrace;
    this.component = component;
    this.typeName = typeName;
    this.miscellaneous = miscellaneous;
  }

  protected MyException(SerializationInfo info, StreamingContext context) : base(info, context)
  {
    component = info.GetString("component");
    typeName = info.GetString("typeName");
    miscellaneous = info.GetString("miscellaneous");
  }

  public override void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    base.GetObjectData(info, context);
    info.AddValue("component", component);
    info.AddValue("typeName", typeName);
    info.AddValue("miscellaneous", miscellaneous);
  }
}

Thank you for your help!

A: In order to invoke a web service in .NET you usually generate a client proxy. You could use the svcutil.exe utility or Add Service Reference... dialog in Visual Studio. Once you have the strongly typed client proxy you simply invoke the service without using any WebClients, MemoryStreams, DataContractJsonSerializers, ...
using (var client = new MyWebServiceClient())
{
    var result = client.SomeMethod();
}

The WCF infrastructure takes care of the rest.


text:
Q: Microsoft JScript runtime error: Unable to get value of the property 'toLowerCase': object is null or undefined
Microsoft JScript runtime error: Unable to get value of the property 'toLowerCase': object is null or undefined

//--Customer Reviews
//--Display when current locale is EN-US
var IsReviewable = $(".tab-content-doc:eq(2) span")[0].innerText || $(".tab-content-doc:eq(2) span")[0].textContent;
if (IsReviewable.toLowerCase() == "true" && currentLocale()=="en-us" ) {
   $("ul.tabs li").eq(2).show();
   $("#BVRRSummaryContainer").show();
}

I try to execute the code and this error is showing. It gives me three options: Break,Continue and Ignore. If i continue then it will not display Customer Reviews but if i ignore then it display Customer Review.I need to display Customer Review. How can i get that? Its running on Internet Explorer 9.
Any Suggestions?

A: Change your condition to
if (IsReviewable &&  IsReviewable.toLowerCase() == "true" && currentLocale()=="en-us" )

This will make sure the value is not falsy and only then apply the toLowerCase method


text:
Q: Error when initializing Firebase in flutter
how can i solve this error with Platform exception, i tried to add firebase_core_performance and to run flutter clean and flutter run, but it didn't help

A: it says no firebase app has been created. Run this flutterfire configure to your terminal and choose your firebase project. if you haven't created one, choose new

A: it's caused by not adding firebase core in pubspec.yml maybe you can see a similar case here


text:
Q: Pass Java Object from servlet to HTML I have one html page "organization.html" and I want to get Java Object value into this html page.
My Java Object
public class User_Objects {
    public String firstName;
    public String lastName;
}

My organization.html page code
<!DOCTYPE html>

<title>Organization</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" href="css/jquery-ui.css">

    <form name="orgname" action="org_name" method="post">

Hello

Enter your organization Name to determine if there is a current terms of service agreement with app.

                        *Oraganisation:
                        <input type="text" id="txtOrgName" name="txtOrgName"
                        class=" form-group" placeholder="enter your organisation"
                        style="float: none; margin-left: 8px;" />

                <input type="submit" name="btnOrgName" id="btnOrgName" class="bg-primary btn"
                    value="Validate" onclick="return validateOrg();" />
                <input type="hidden" name="myJObject" id="myJObject" value='${reqJSONObj}' />

    </form>

My Java code is given below
JSONObject jObj = new JSONObject(fillObj);
request.setAttribute("reqJSONObj", jObj);
request.setAttribute("reqObj", fillObj);
forward = "/organization.html";
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);

But When my organization.html page is loaded, I am getting reqfirstName>>>>>>>${reqObj.firstName} alert.
I am getting ${reqObj.firstName} not value of firstName of reqObj Object.
I am using Java with Eclipse Mars1.


text:
Q: Async /await not working on making a fetch API call in javascript I am making a fetch API call from my js file ,I have a doubt that when i am using Async/await still the code is executing in asynchronous manner.
I have also tried await at differnt place but its doesn't work.
 let info
 async function weather(){
 // API call
 let data=await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY)
  console.log("inside API")
  const res= await data.json();
  console.log(res)
 }
weather()
console.log("last part")

OUTPUT:
last part
inside API
"VALUE OF RES"
WHAT I EXPECT:
inside API
"VALUE OF RES"
last part
Any help will be highly appreciated..

A: The easiest way is to wrap it all in another async function so that you can await weather().
// this function fetches the weather then logs the result
async function weather() {
  // API call
  let data = await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY);
  console.log('inside API');
  const res = await data.json();
  console.log(res);
}

// this async function awaits for weather() to return
async function run() {
  await weather();
  console.log('last part');
}

// this runs first
run();

A: // async function
async function fetchAsync () {
  // await response of fetch call
  let response = await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY);
  // only proceed once promise is resolved
  let data = await response.json();
  // only proceed once second promise is resolved
  return data;
}

// trigger async function
// log response or catch error of fetch promise
fetchAsync()
    .then(data => console.log(data))
    .catch(err => console.log(err))

A: A solution in a script that run in node environment:
(async function () {

  // API call
  const data = await fetch('http://api.openweathermap.org/data/2.5/weather?'+'&lat=20&lon=44'+'&units=metric'+'&APPID='+WEATHER_KEY)
  console.log("inside API")

  const res = await data.json();
  console.log(res)

  console.log("last part")
})()

The messages will are in expected order.


text:
Q: PHP MYSQL Query Issues I'm stumped as to why my PHP mysqli queries are not returning consistent results.
For example I run the following query and it gives me all the email addresses.
SELECT id, companyname, contactname, address1, city, postalcode, primaryphone, email
FROM installers
WHERE email LIKE '%@%'

If I run this query I get no results:
SELECT id, companyname, contactname, address1, city, postalcode, primaryphone, email
FROM installers
WHERE email LIKE '%gmail%'

Both queries work fine when executed locally on the database. Any ideas of where to look next would be much appreciated.
Updating with code as requested:
<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');
$search_output = "";

include '../sqlconnect.php';

if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
$searchquery = mysqli_real_escape_string($conn, $_POST['searchquery']);
if($_POST['category'] == "id"){

    $sqlCommand = "SELECT id, email FROM installers WHERE id = '$searchquery'";

} else if($_POST['category'] == "email"){

    $sqlCommand = "SELECT id, email FROM installers WHERE email LIKE '%$searchquery%'";
}

    $query = $conn->query($sqlCommand) or die($conn->error.__LINE__);
    $count = $query->num_rows;

if($count > 1){
    $search_output .= "
$count results for $searchquery
$sqlCommand
";
    while($row = $query->fetch_assoc()){
        $id = $row["id"];
        $email = $row["email"];
        $search_output .= "

 Company ID: &nbsp $id

 Email: &nbsp $email

        ";
            } // close while
} else {
    $search_output = "
0 results for $searchquery
$sqlCommand";
}
}
?>

<!doctype html>

Search

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="form`horizontal">

        Search Term

          <input type="text"  name="searchquery" class="form-control" id="searchquery" placeholder="Type search term here..">

 <button type="submit" name="search-btn" class="btn btn-default btn-default">
                     Search
                </button>

        Search category:

                <select class="form-control" name="category" id="category">

                    <option value="id" selected="selected">Company ID</option>
                    <option value="email">Email</option>
                </select>

    </form>

    <?php echo $search_output; ?>

A: As per OP's request, comment(s) to answer option to close the question.
Instead of LIKE '%$searchquery%'"; change it to LIKE '%".$searchquery."%'"; but either should work, as they have in my test.
Nota/edit: "The count would never be greater than 1 when searching for ID because it is primary key. Resolved by if($query->num_rows) The wildcards weren't working properly because they needed to be concatenated with the var $searchquery." / OP's comment.
Yet, instead of $count = $query->num_rows; if($count > 1){ replace it with just if($query->num_rows){
Even using if($count > 0) would work, since you're looking to see if results are more than zero, meaning one or more, and if($query->num_rows) would act the same way; if rows found containing your query.
What was probably happening was that, if your column only contained "one" Gmail address, then using > 1 would be FALSE. Use >0 if TRUE (if row contains query of one or more).

Another method instead of if($count > 0) is if($count == true) which also works.

A: Would it be that there isn't any email with gmail?
If not, you could try this following codes, I hope it worked for you.
$queryform = "SELECT * FROM installers WHERE email LIKE '%".gmail."%'";


text:
Q: Querying for multiple valules in array I have an Order record that looks like:
{   cust_id : 5     , ordered_pdts : [ 1,2,3 ] }

I have Vendors collection. Each vendor record has a list of products the vendor maintains:
{   vendor_id : 342     , pdts : [ 4, 5, 6, 1, 2, 7, 3 ] }

When an order is placed, I need to find the vendors who have ALL the products listed in the Order.
Can this be done with a query operation or Aggregation Framework?

A: You can try with this query :
db.Vendor.find({'pdts' : {$all : [1,2,3]}})


text:
Q: Use the recursive definition of summation together with mathematical induction to prove a sequence Use the recursive definition of summation together with mathematical induction to prove that for all positive integers n, if a1, a2, ... , an and b1, b2, ... , bn are real numbers, then
n              n     n
∑(2ak −3bk) = 2∑ak −3∑bk.
k=1            k=1   k=1

A: Let's first check the base case:
$$\sum_{k = 1}^1 (2a_k-3b_k) = 2a_1-3b_1 = 2\sum_{k = 1}^1 a_k-3\sum_{k = 1}^1 b_k$$
So, we've verified our base case.
Now, assume the $n$th case holds.
So, we have that:
$$\sum_{k = 1}^n (2a_k-3b_k) = 2\sum_{k = 1}^n a_k-3\sum_{k = 1}^n b_k$$
Now, try adding $2a_{n+1}-3b_{n+1}$ to both sides.  We get that:
\begin{align*}
\sum_{k = 1}^n (2a_k-3b_k)+2a_{n+1}-3b_{n+1} &= 2\sum_{k = 1}^n a_k-3\sum_{k = 1}^n b_k +2a_{n+1}-3b_{n+1}\\
\sum_{k = 1}^{n+1}(2a_k-3b_k) & = 2\sum_{k = 1}^n a_k+2a_{k+1}-3\sum_{k = 1}^n b_k-3b_{n+1} \\
& = 2\left(\sum_{k = 1}^n a_k+a_{n+1}\right)-3\left(\sum_{k = 1}^n b_k+b_{n+1}\right) \\
& = 2\sum_{k = 1}^{n+1}a_k-3\sum_{k = 1}^{n+1}b_k
\end{align*}


text:
Q: jQuery UI Tabs go to specific div in tab I have basic tabs setup using JqueryUI (simplified to only the two tabs relevant)

Home

Benefits

            <UCHome:UCHome runat="server" />

            <UCBenefits:UCBenefits runat="server" />

In the usercontrol for tabs-1 (simplified to the relevant code)

     Modularity
     <asp:Image runat="server" ImageUrl="../Images/Benefits1.png"/>

    Flexibility<asp:Image runat="server" ImageUrl="../Images/Benefits2.png" />

In the usercontrol for tabs-5 (again simplified)

            (Modularity)

            Hello

            (Flexibility)

             World

homecontent class is simply for styling.
Now basically, I want to redirect from tabs-1 to tabs-5 when a user clicks an image on tabs-1 AND I want it to go to the div relevant to the image. For example if the user clicks Benefits2.png then I want it to go to tabs-5 and have focus on .
So far I have in the document.ready
var $tabs = $("#tabs").tabs();

$('.benefitc').click(function () { // bind click event to link
   $tabs.tabs('select', 4); // switch to tab
   return false;
});

This gets me to the tab correctly but I can't figure out how to get to the correct div. Note, all the clicks should take me to tabs-5 which is index 4.
Any help would be much appreciated. Please let me know if I haven't been clear enough on the question.

A: The active option can also be used to set active tab (note - active tab can be used differently when assigned a boolean value and collapsible is true): http://api.jqueryui.com/tabs/#option-active
[text below taken from above link, modified format]
active - Which panel is currently open. Type: Boolean or Integer. Default: 0
Code examples:
Initialize the tabs with the active option specified:

        $( ".selector" ).tabs({ active: 1 });

Get or set the active option, after initialization:

        // getter
        var active = $( ".selector" ).tabs( "option", "active" );

        // setter
        $( ".selector" ).tabs( "option", "active", 1 );

A: Aaaaaaaaaargh said the code monkey when he did something stupid.
This was a silly one from me.
The anchor tags do work but since I was using
$('.benefitc').click(function () { // bind click event to link
   $tabs.tabs('select', 4); // switch to tab
   return false;
});

The return false was stopping the event propogation and default action of the a tags never fired.
So changing that to
return true;

achieved the desired result.

A: Here is a working example of activating a specific tab.
<!doctype html>

<meta charset="utf-8" />
<title>jQuery UI Tabs - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<link rel="stylesheet" href="/resources/demos/style.css" />

HOME

About Us

Contact

Home Page

<button>Page 2</button>

This is what we are all about.

Name First Last

Town, City, Zip


text:
Q: Difference between Crosses & Intersects - Shapely (Python) I have two questions :
I have some lines (eg: road network). I want to find coordinates of each junction.

*

*Should i use crosses or intersects function from python's Shapely module? They are giving different counts.

*Moreover these functions return boolean value. How to get the junction coordinates ?
with open('./lines.geojson') as f:
    lines = json.load(f)

line = []

for feature in lines['features']:
    line.append(feature['geometry']['coordinates'])

count = 0
for i in range(len(line)-1):
   j =i+1
   while (j < len(line)):
        l1 = LineString(line[i])
        l2 = LineString(line[j])
        if l1.crosses(l2)== True :
            count =count+1
        j = j+1

A: *

*From Shapely's doc:

intersects() is equivalent to the OR-ing of contains(), crosses(), equals(), touches(), and within().

So there might be some cases where two lines intersect eachother without crossing, in particular when one line contains another or when two lines are equals.
More specifically:

crosses() returns True [...] if the dimension of the intersection
is less than the dimension of the one or the other.

So if two lines overlap, they won't be considered as "crossing".

*intersection() will return a geometric object.


text:
Q: How to call scalar function in Fluent NHibernate Can't find it in the Internet.
If someone helps I'll appreciate it greatly!

A: I suggest you read the NHibernate documentation, there's a chapter on querying.


text:
Q: (Angular 2/4/5/6) Changing navigation for browser back button Previous Question:
I was trying to navigate the user to the main page (instead of the previous page) if the user clicked on the browser back button.
Solution:
I used a combination of candeactivateguard, hostlistener. Remember to declare your guard in the provider under your module file.
deactivate.guard.ts
import { Injectable } from "@angular/core";
import { CanDeactivate } from "@angular/router";

export interface CanComponentDeactivate {
  canDeactivate(): boolean;
}

@Injectable()
export class DeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): boolean {
    return component.canDeactivate();
  }
}

lastpage.component.ts
import { Component, OnInit, Inject, HostListener } from "@angular/core";
export class LastPageComponent implements OnInit {
   disableSuccessNav = false;
   ngOnInit() {}
   constructor()
   //detects browser back button
   @HostListener("window:popstate")
   onPopState() {
     this.disableSuccessNav = true;
   }

   canDeactivate() {
      return !this.disableSuccessNav;
    }


text:
Q: Is there a way to use Spring @Profile annotation at a package level? I'm trying to put all my bean definitions for a specific profiles together, and would rather not push them all into one giant AppConfig.java class.  I was wondering if there was a way to annotate at a package level using package-info.java and have all configuration files within that package inherit the profile.
I've tried the following in package-info.java:
@Profile("test")
package com.system.configuration.test;
import org.springframework.context.annotation.Profile;

But the @Configuration classes within the package seem to be used whether it is the "test" profile or not.
Is the only choice to annotate each class individually?

A: You can do it in different way by creating separate @Configuration classes for different profiles:
@Configuration
@Profile("test")
@ComponentScan("com.system.configuration.test")
public class TestProfile {
}

And then on your main configuration class you need to do imports:
@Configuration
@Import(TestProfile.class)
public class MainConfiguration {
}


text:
Q: Creating report from Excel to Word Hi the following code is used to export values form Excel into a word document:
 Sub Createrapport()
    Dim WS As Worksheet

    Set WS = Worksheets("Rapport")
    Application.ScreenUpdating = False
        Sheets("Rapport").Visible = True

    Dim UserName As String
    UserName = InputBox(Prompt:="Var vänligen och ange ditt namn nedan:")
    If UserName = vbNullString Then
    Exit Sub
    Else
    WS.Range("I1").Value = UserName
    End If

        Dim wdApp As Object
        Dim wd As Object
        Dim Tbl As Object

        On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
        If Err.Number <> 0 Then
            Set wdApp = CreateObject("Word.Application")
        End If
        On Error GoTo 0

        Sheets("Rapport").Activate
        Set wd = wdApp.Documents.Add
        wdApp.Visible = True

        'sidhuvud
        wdApp.ActiveWindow.ActivePane.View.SeekView = 9
        With wd
            Set Tbl = .tables.Add(wdApp.Selection.Range, 2, 3, wdWord8TableBehavior)
            Tbl.cell(1, 1).Range.Text = WS.Range("K4").Text
            Tbl.cell(1, 2).Range.Text = WS.Range("L4").Text
            Tbl.cell(1, 3).Range.ParagraphFormat.Alignment = 2 'wdAlignParagraphRight
            Tbl.cell(1, 3).Range.Text = WS.Range("I1").Text
            Tbl.cell(2, 1).Range.Text = WS.Range("K5").Text
            Tbl.cell(2, 3).Range.ParagraphFormat.Alignment = 2 'wdAlignParagraphRight
            Tbl.cell(2, 3).Range.Text = WS.Range("M5").Text
        End With
        wdApp.ActiveWindow.ActivePane.View.SeekView = 0

        'sidnummer
        'Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="PAGE  ", PreserveFormatting:=True

        '***** copy image from cell H11:M411 in Excel
        Worksheets("Rapport").Range("H11:M41").Copy
        '***** past image at the current position in Word
        wdApp.Selection.Paste

    Set rng = Worksheets("Rapport").Range("A1:E203")

    rng.Copy
       With wd.Range
            .collapse Direction:=0                  'Slutet av dokumentet
            .InsertParagraphAfter                   'Lägg till rad
            .collapse Direction:=0                  'Slutet av dokumentet
            .PasteSpecial False, False, True        'Pasta som Enhanced Metafile
       End With
       Sheets("Rapport").Visible = False
       Application.ScreenUpdating = True

Set newDoc = Documents.Add
Set myTable = _
    newDoc.Tables.Add(Range:=Selection.Range, NumRows:=3, _
    NumColumns:=3)
myTable.Cell(2, 1).SetWidth _
    ColumnWidth:=InchesToPoints(1.5), _
    RulerStyle:=wdAdjustNone

    End Sub

The report obtained then looks like this:

How can I make the values fit within the margins of the word document? this is the prt that does it and it is "InchesToPoints(1.5)" which bugs:
Set newDoc = Documents.Add
    Set myTable = _
        newDoc.Tables.Add(Range:=Selection.Range, NumRows:=3, _
        NumColumns:=3)
    myTable.Cell(2, 1).SetWidth _
        ColumnWidth:=InchesToPoints(1.5), _
        RulerStyle:=wdAdjustNone

EDITED CODE
Set newDoc = Documents.Add
        Set myTable = _
    newDoc.Tables.Add(Range:=Selection.Range, NumRows:=3, _
    NumColumns:=3)
'***** Word constant wdPreferredWidthPercent = 2
myTable.PreferredWidthType = 2
myTable.PreferredWidth = 100
    myTable.Cell(2, 1).SetWidth _
        ColumnWidth:=InchesToPoints(1.5), _
        RulerStyle:=wdAdjustNone

A: Found through the magic of google:
Selection.Tables(1).PreferredWidthType = wdPreferredWidthPercent
Selection.Tables(1).PreferredWidth = 100

Says Word 2000, tried and works in Word 2010.
(In your case you probably have to add wdApp. before the Selection object, and make sure that Selection points to the place in the document where the table is.)
EDIT
My code sample updated to match your updated code:
'***** Word constant wdPreferredWidthPercent = 2
myTable.PreferredWidthType = 2
myTable.PreferredWidth = 100

Place it right after the Set myTable = line.
EDIT 2
The underscore in VBA means that the one code line extends over several lines, so you can't put code in between (if that is what's not working).
Code sample in context:
Set myTable = _
    newDoc.Tables.Add(Range:=Selection.Range, NumRows:=3, _
    NumColumns:=3)
'***** Word constant wdPreferredWidthPercent = 2
myTable.PreferredWidthType = 2
myTable.PreferredWidth = 100

EDIT 3
Set newDoc = wdApp.Documents.Add
Set myTable = _
    newDoc.Tables.Add(Range:=wdApp.Selection.Range, NumRows:=3, _
    NumColumns:=3)

'***** Word constant wdPreferredWidthPercent = 2
myTable.PreferredWidthType = 2
myTable.PreferredWidth = 100

myTable.Cell(2, 1).SetWidth _
    ColumnWidth:=wdApp.InchesToPoints(1.5), _
    RulerStyle:=0 '*****wdAdjustNone

A: Try this:
myTable.AutoFitBehavior wdAutoFitWindow

of if you are late binding:
myTable.AutoFitBehavior 2

This will autofit the table within the word document margins.
Is this what you're trying?


text:
Q: WPF binding to parent content in datatrigger I have a custom control with a style. The control is bound to a property in my viewmodel
<controls:PromoAlarmBox Content="{Binding Controller.IOGRP1W.Value}"/>

I want to create a datatrigger which changes the color of the control depending on the bound value and this works
<Style TargetType="{x:Type local:PromoAlarmBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    <Rectangle x:Name="PART_rectangle" VerticalAlignment="Stretch" Fill="Yellow" Stroke="Black" Height="20" Width="20"/>

                    <ControlTemplate.Triggers>
                            <DataTrigger Binding="{Binding Controller.IOGRP1W.Value, UpdateSourceTrigger=PropertyChanged}" Value="1">

                            <Setter Property="Fill" TargetName="PART_rectangle" Value="Red" />

                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

So far so good. I can make it work if I refer to the same property in the datatrigger as the control is bound to. My problem is that I have multiple instances of the same control bound to different values and I don't want to create a new style for each one of them so my question is how can I bind to the bound value of the control in the datatrigger.

A: Found It. Love WPF but it seems that you can spend weeks just studying different binding expressions
 <DataTrigger Binding="{Binding Path=Content, RelativeSource={RelativeSource Mode=Self}}" Value="1">

A: Maybe you could try this:
<ControlTemplate.Triggers>
    <Trigger Property="Content" Value="1">
        <Setter Property="Fill" TargetName="PART_rectangle" Value="Red" />
    </Trigger>
</ControlTemplate.Triggers>

This way the Trigger should bind to the Content property of the PromoAlarmBox.

A: You should use PriorityBinding to achieve the target behavior


text:
Q: How to uninstall Xampp-VM 7.2 completely in Mac? Actually when i tried to uninstall it , and reinstall it , it restore automatically all old files , without creating new ones .
I had the latest Xampp 7.2.10 , i removed it from my mac to reinstall new one  , the Xampp that i removed i had changed mistakenly it's etc folder files , however when i reinstalled it i got same old etc folder which are corrupted  , and i got same everything as the old Xampp which i already deleted.
This problem i tried to solved it the whole day but i got same problem over and over again .
The old way of deinstalling it doesn't seem to work with 7.2.

A: The XAMPP-VM virtual machine files and logs are stored within your home directory on the OS X host, in the ~/.bitnami/stackman/machines/xampp/vm (invisible folder).
Just delete the .bitnami folder and re-lunch XAMPP to have a clean installation of Lampp volume.


text:
Q: Projection with Automapper I need made a projection from database to model entity. Before get data in database and map to Entity with unity of word and reposy:
 public async Task<IEnumerable<Entity>> GetProjectsSponsorByYear(Guid idUser)
    {
        logger.Trace("Called GetProjectsSponsorByYear method in ProjectBusiness");
        var Entitys = await this.unitOfWork.Repository<Entity>().Queryable().Where(p => p.SponsorId == idUser && p.Draft == true).ToListAsync();

 return listProjectDataBaseAsModel;

, after that use automapper for create a map between Entity and model:
this.CreateMap<Entity, Model>()
            .ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.ID))
            .ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))

public async Task<IEnumerable<Model>> GetProjectHistoricList()
    {
        logger.Trace("Called GetProjectHistoricList method in ProjectService");

        var allProjects = await this.projectBusiness.GetAll();

        var allProjectsGrid = this.entityMapper.Map<IEnumerable<Entity>, IEnumerable<Model>>(allProjects);

        return allProjectsGrid;
    }

But now i need made a projection from database to model entity, the problem is when use createMap, for configuration automapper, i have property with method
 .ForMember(dest => dest.ImpactSupervisorDescription, opt => opt.MapFrom(src => src.ImpactSupervisor.GetDescription()))

when made the projection between repository and model with ProjectTo method a get Exection from Linq.
I know this exection is for Linq create a query and not implement this method into her.
Need to know if there is any way to achieve this, either before or after the projection.

A: Check out the AutoMapper.EF6 project, it uses another project, DelegateDecompiler, to build out projections based on the method and property contents. It examines the IL and builds an expression to match that IL to then pass to your queryable provider:
https://www.nuget.org/packages/AutoMapper.EF6/
Then you can project straight from the queryable to list:
var allProjectsGrid = await this.projectBusiness.GetAll()
                                .ProjectToListAsync<Model>();

And as a side note, you don't need those ForMember calls for ID and Title, that's the Auto part of AutoMapper :)


text:
Q: Oracle: What is the best way to use two tables in a mutually exclusive way? I have the following sample query
select a.name,c.company
from employee a, company c
where a.comp_id = c.comp_id
and a.active='Y'

Now I have two new tables
company_profile, (Profile values for each company. Each company may or may not have data in this table)
profile_defaults  (contains default profile values for each profile item  independent of company)
Now I need to refer to column "show_data" in company_profile for a specific company. If there is no row for that company then i need to take the value from the profile_defaults table. How do I integrate this logic in the first query which I mentioned above in the best possible way.
Table

Employee
|Name|Comp_id|active|
Company
|Comp_id|Name|
Company_Profile
|comp_profile_id|profile_id|comp_id|profile_name|profile_value|
Profile_Defaults
|profile_id|profile_name|profile_value|
There are many other tables used. But I shortened it for four tables alone for this case now.

A: Try using this query:
SELECT a.name, c.company, NVL(cp.profile_value, pd.profile_value)
FROM employee a INNER JOIN company c
ON a.comp_id = c.comp_id
LEFT JOIN company_profile cp
ON c.comp_id = cp.comp_id
LEFT JOIN profile_defaults pd
ON cp.profile_id = pd.profile_id

This solution assumes that you have columns comp_id in both the company_profile and default profile_defaults tables to which you can join a record for a given company.  As @PM77-1 mentioned, I use NVL() to first check the company_profile table, and default to profile_defaults if nothing is found in the former.


text:
Q: How to build Poisson autoregression model I have a SpatialPolygonsDataFrame object in R with about 3000 polygons and associated data. I have columns of expected and observed cases. For the moment, I don't have any covariates.
I'd like to perform spatial smoothing. I have used functions such as empbaysmooth(), lognormalEB(), EBlocal() from the DCluster package but have not been happy with the results.
Therefore I would like to do a conditional autoregression using spautolm() - I would like to model a Poisson model of observed versus expected with neighbour weighting.
I cannot figure out how to specify such a model. How do I specify merely a Poisson model for the spautolm command with no covariates?
Or am I barking up the wrong tree altogether?

A: All models have an implicit (constant) covariate whose name is "1", which may be mentioned explicitly, as in y ~ 1. An example appears near the bottom of p. 12 at http://cran.r-project.org/web/packages/spdep/vignettes/sids.pdf.


text:
Q: split 1200 page document into 500 pages and then the remaining I am new to the Unix world, and I have text files that contain 1200 pages identified by ^L.   Is there an effective way to break of that file to have 2 separate files of 500 pages each and then a 3rd with the remaining pages.
I'm thinking something like read the file to locate the first ^L then count the next 500 output to temporary file, continue reading to create the next temporary file or is there a more effective way?
My script is written in bash running MKS toolkit.

A: Assuming every page starts with ^L (a literal Ctrl+L):
awk '/^L/ { p++ } (p-1) % 500 == 0 { f = FILENAME "-page-" p ".txt" } { print > f }' file.txt

This would count the lines with ^L and if the count minus 1 is a factor of 500 (page 1, page 501, page 1001 etc.) it will set the variable f to a filename to output the following text into.
The ^L in the awk code is not the two characters ^ and L, but a literal Ctrl+L (you may type this with Ctrl+VCtrl+L). You may also use \014 in place of this.
For a small test document test.txt:
^L
page 1
^L
page 2
^L
page 3
^L
page 4

... and changing 500 to 2 for testing, this generates two files, test.txt-page-1.txt and test.txt-page-3.txt, each containing two lines (page marker and text) from the input file.
test.txt-page-1.txt:
^L
page 1
^L
page 2

test.txt-page-3.txt:
^L
page 3
^L
page 4

The files that are to be parsed apparently have a header before the first page marker. This header needs to be ignored.  The following variation on the above awk command does this:
awk '/^L/ { p++ } (p-1) % 500 == 0 { f = FILENAME "-page-" p ".txt" } p > 0 { print > f }' file.txt

By restricting the output to when p is greater than zero, we require that at least one page marker has been parsed before outputting anything.

A: Here's another option. This one anchors on the ^L character (I assume it's a single character, octal 014 rather than the two literals ^ and L). For your source data file called original.txt it will split each page into its own file. From there you can concatenate them into the required chunks:
# GNU csplit
csplit --prefix='page_' --digits=4 original.txt $'/\014/+1' '{*}'

# MKS csplit
csplit -f 'page_' -n 4 -k original.txt $'/\014/+1' '{9999}'

# Concatenate the required sets of pages together
cat page_{0000..0499} > part_1.txt
cat page_{0500..0999} > part_2.txt
cat page_{1000..9999} > part_3.txt

# Tidy up
rm page_????

A: If good old gnu split can be used:
split -t '^L' -l 500 bigFile part_

*

*-t '^L'  - unit separator is ^L

*separate in files with 500 units

*in bash, to introduce ^L we have to type ^V ^L. It is also possible to use the octal notation:split -t $'\014' ...

A: Is this a text file or a more complex (PDF, WORD etc)? Maybe you should give the builtin split command a try. it works something like this
split -l1000 textfile

This will split into your text file into multiple files with 1000 lines each.


text:
Q: How to serialze the correct fields that are stored on has a has_many through relation table I have a has_many through relationship. But I need to serialize a field stored on the relation table as workflow_state.
To do this I have to access the relation table directly.
Here is the current serializer I have:
class OrderSerializer < ActiveModel::Serializer

  attributes :id, :number, :slug, :quoted, :invoiced, :paid, :reciepted, :void, :refund, :workflow_state
  has_one :table
  has_one :user
  has_one :quote
  has_one :reciept
  has_many :items

  class RecieptSerializer < ActiveModel::Serializer
    attributes :id, :order_number, :number, :slug, :cost, :paid, :vat, :total, :change
  end

  class UserSerializer < ActiveModel::Serializer
    attributes :id, :name, :email
  end

  class QuoteSerializer < ActiveModel::Serializer
    attributes :id, :order_number, :number, :slug, :cost, :vat, :total
  end

  class TableSerializer < ActiveModel::Serializer
    attributes :id, :number, :position
  end

  def items
    customized_items = []

    object.items.each do |item|
      # Assign object attributes (returns a hash)
      # ===========================================================
      custom_item = item.attributes
      # has_one w/only specified attributes
      custom_item[:category] = item.category.slice(:id, :name, :icon)
      custom_item[:workflow_state] = item.order_items.find_by_item_id(item.id).workflow_state
      customized_items.push(custom_item)
    end

    return customized_items
  end
end

The issue is it gives the correct type of response however the field it shows is wrong says 'created' for all items. But when I check the database, the field is "preparing".
Response:
{
    "order": {
        "id": 7,
        "number": 7,
        "slug": "61b8a5ad-b3f9-4492-b7d7-2c61684c4988",
        "quoted": true,
        "invoiced": false,
        "paid": false,
        "reciepted": false,
        "void": false,
        "refund": false,
        "workflow_state": "preparing",
        "table": {
            "id": 9,
            "number": 9,
            "position": "Bar"
        },
        "user": {
            "id": 1,
            "name": "admin",
            "email": "admin@admin.com"
        },
        "quote": {
            "id": 7,
            "order_number": 7,
            "number": 7,
            "slug": "43f0ca98-84dc-4e6d-8062-f3f1ef1f2e5f",
            "cost": "22.0",
            "vat": "0.0",
            "total": "22.0"
        },
        "reciept": null,
        "items": [
            {
                "id": 1,
                "name": "Eggs bendict",
                "icon": "breakfast",
                "cost": "5.5",
                "price": "7.5",
                "description": "Eggs on toasted muffins with holindais sauce",
                "category_id": 1,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.603Z",
                "updated_at": "2020-06-26T07:45:44.603Z",
                "category": {
                    "id": 1,
                    "name": "Breakfast",
                    "icon": "breakfast"
                },
                "workflow_state": "created"
            },
            {
                "id": 1,
                "name": "Eggs bendict",
                "icon": "breakfast",
                "cost": "5.5",
                "price": "7.5",
                "description": "Eggs on toasted muffins with holindais sauce",
                "category_id": 1,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.603Z",
                "updated_at": "2020-06-26T07:45:44.603Z",
                "category": {
                    "id": 1,
                    "name": "Breakfast",
                    "icon": "breakfast"
                },
                "workflow_state": "created"
            },
            {
                "id": 1,
                "name": "Eggs bendict",
                "icon": "breakfast",
                "cost": "5.5",
                "price": "7.5",
                "description": "Eggs on toasted muffins with holindais sauce",
                "category_id": 1,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.603Z",
                "updated_at": "2020-06-26T07:45:44.603Z",
                "category": {
                    "id": 1,
                    "name": "Breakfast",
                    "icon": "breakfast"
                },
                "workflow_state": "created"
            },
            {
                "id": 13,
                "name": "Fries",
                "icon": "fries",
                "cost": "5.5",
                "price": "7.5",
                "description": "Fries",
                "category_id": 5,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.636Z",
                "updated_at": "2020-06-26T07:45:44.636Z",
                "category": {
                    "id": 5,
                    "name": "Sides",
                    "icon": "fries"
                },
                "workflow_state": "created"
            }
        ]
    }
}

What I'm thinking is this:
custom_item[:workflow_state] = item.order_items.find_by_item_id(item.id).workflow_state

Its probably serializing the first item that in order_items with item id as specified.
Is there a better way to serialise a field from the relation table for a given relation?

A: I refactored the whole app to not use a has_many :through relationship.


text:
Q: left-trunctable prime SCHEME I am trying to define a variable in SCHEME that has 1 integer argument, and evaluates to #t if the inputted argument is a left-truncatable prime number, and false otherwise.  An example of a left-truncatable prime number is 137, since 137, 37, and 7 are all prime.  Thanks!

A: you need to define a function IS-PRIME? that checks if a number is prime, and also a LEFT-TRUNCATE function that takes 137 to 37, 37 to 7 and 7 to 0.
With these two pieces you can build your function by checking if the input is prime then left truncating it and then checking that until you hit zero.


text:
Q: Stop and restart command in Spyder I am new to Python and Spyder.
On the top right of the IPython console you find a red square button in order to stop the current command.
I had to do this several times. Afterwards, I wanted to restart (the adapted code), but nothing happens - no message, nothing.
After restarting, again nothing happened. I have no idea if the command was running or not - my guess is not because no output was produced.
The only thing I could do was to close and restart Spyder.
Any suggestions how to stop and restart commands correctly?
How can I ensure that nothing is running in the background before restarting Spyder?

A: I don't know if this will help, but try this:
import sys
import os

def restart():
    os.execl(sys.executable, sys.executable, *sys.argv)

Then just add restart() at anytime in the script to restart it.


text:
Q: Stability and Bifurcation Diagram if $ \frac{dx}{dt}= x(a^2-x^2) $ find and classify the stability of the equilibrium points, and draw the bifurcation diagram.
I have found the stability of the function at $x =0,-a,a$ I believe $0$ is a unstable equilibrium while $-a,a$ are both stable equilibrium. I then drew the bifurication diagram, it looks like the absolute value graph but sideways, is this correct?
Thanks!


text:
Q: Power Form Docusign I am fetching the powerForm url to send contracts to clients. I would like to know if there is a way to get the envelopeId created once I fetch that url.
This is everything i got from the call enter image description here

A: PowerForms are for end-users, not for your integration.
If what you want is what you describe, you don't need a powerform, just a template and then you use the API to make an envelope from the template that you send to your recipients.
Follow code example in here:
https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-template-remote/


text:
Q: How to show multiple lines of text in Listbox in Winform? I have a listbox whose items contain only text. The listbox is having some fixed width. When I add a text which is having more width compare to the lisbox width, I am NOT able to see the remaining text.
Any solution will be helpful.

A: How about you remove the Width property?
that way the control will expand automatically - as wide as the maximum item
EDIT: Might not be a good idea, BUT:
You could nest the ListBox inside a Panel, and set the Panel's width to a constant value, while having Scrollbars enabled. that way - even if there's a line WIDER than the other lines - the user will be able to scroll.

A: If you're using WPF, add a text block and use it's text wrapping capabilities.
ListBox lb = new ListBox();
ListBoxItem li = new ListBoxItem();
TextBlock txtBlock = new TextBlock();
txtBlock.Width = 50;
txtBlock.TextWrapping = TextWrapping.Wrap;
...
li.Content = txtBlock;
lb.Items.Add(li);

If not, have a look at this answer for your question.


text:
Q: Coordinates of tilted circle. The original question is as follows:
Imagine a wire located at the intersection of $x^2+y^2+z^2=1$ and $x+y+z=0$, whose density depends on position according to $\rho({\bf x})=x^2$ per unit length. Show that the mass of the wire is $\frac{2}{3}\pi$.
I am thinking to parametrize the intersection first and do line integral over the curve. However, I can not properly write out the intersection.  Anybody has any thought on how to tackle this?

A: If you really want to do it the hard way, you could use the knowledge that the intersection is a circle and points on it are orthogonal to the unit vector $\hat{\eta} = (\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}})$.
To find a parametrization of the circle, you need a point on the circle as a starting point.
One way to do that is pick a random vector, not in the direction
of $\pm \vec{\eta}$, project it to its components orthogonal to $\hat{\eta}$ and then
normalize it to a unit vector.
If you do this to the unit vector $\hat{x} = (1,0,0)$ in the $x$-direction, you end up
with the point $\vec{p} = (\frac{2}{\sqrt{6}},-\frac{1}{\sqrt{6}}, -\frac{1}{\sqrt{6}} )$ lying on the circle.
To generate the whole circle, you rotate $\vec{p}$ for some angle $\theta \in [0,2\pi)$ along the axis corresponds to $\hat{\eta}$. Let $\vec{q} = \vec{\eta} \times \vec{p} = ( 0, \frac{1}{\sqrt{2}},-\frac{1}{\sqrt{2}} )$. The resulting locus has the
form:
$$\vec{r}(\theta)
= \vec{p} \cos\theta + \vec{q}\sin\theta =
\left(\frac{2\cos\theta}{\sqrt{6}},
-\frac{\cos\theta}{\sqrt{6}} + \frac{\sin\theta}{\sqrt{2}},
-\frac{\cos\theta}{\sqrt{6}} - \frac{\sin\theta}{\sqrt{2}} \right)$$
This is a parametrization of the circle you want. Using this, one can calculate the desired mass as
$$\int_0^{2\pi} ( \vec{r}(\theta) \cdot \hat{x} )^2 d\theta
= \int_0^{2\pi} \frac23\cos^2\theta d\theta
= \frac23\times\frac12\times 2\pi = \frac23\pi$$


text:
Q: Unified method to embed documents (html/pdf/swf/...) in html Do you know of any JS lib, or method, that unifies method of embedding external documents (PDF, HTML, SWF, and so on) into div?
Only universal method I'm aware of, is to simply use an iframe, but it's said to be bad idea. Is there any lib trying to unify this? Or iframe way is the way?

A: Try this library, it allows multiple file formats, HTML documents, or components:
multiBox - for MooTools 1.2


text:
Q: How to render a graph when Mysql data is updated in Vue? I organized like this,
Back-end: Nodejs - Insert a data to MYSQL periodically.
DB: MYSQL
Front-end: Vue.js - Draw and Re-render a Graph with Mysql Data when data is updated.
In this situation, do I have to check a MYSQL data per seconds whether it is latest or not? and then I have to render a graph again?
Or is there a way like when MYSQL data is updated, triggering a specific methods that is re-render a graph(automatically).
I prefer a second way though, I have no idea it is possible.
Someone can give an advises me plz? or example?

A: What you could do is using socket.io for this. The moment you update your database in Node.js you then also send a notification or the data over a socket, which tells your Vue.js application that it needs to load new data or gives it the data directly.
I used the following npm packages for my setup with Vue.js and Node.js:
 Vue: socket.io-client
 Node: socket.io

I followed these 2 sites when I faced a similar problem to get a hang of sockets:
https://socket.io/get-started/chat/#Introduction
https://medium.com/@jaouad_45834/basic-chat-web-app-using-express-js-vue-js-socket-io-429588e841f0


text:
Q: Dynamic compile time mixins I'm trying to come up with a way to define dynamic mixins at compile time. I currently have a very hacky solution that only partially does what I want, but I'm not sure how to improve it.
I'm aware of some more C++ like solutions using typelist's, but they require all of the types to be defined statically which I'm trying to avoid.
This is mostly just a thought exercise to learn C++ better, and I'm sure that my current implementation is not very good C++.  Any suggestions for improvements or different ideas to try would be welcome.
The main problems with my current implementation are:

*

*Each mixin class is only aware of itself and classes lower then itself in the hierarchy. I'd like each mixin class to be able to return a new mixin with a different underlying type.  In the example code below I'd like PrintOnce to be able to have a method which returns a PrintTwice<PrintOnce<Printer<int > > > object.

*Any usage of this idea would need to have an order of header inclusion.  All the boiler plate code in the beginning would need to be in one header, then all of the mixin classes would need to be defined, and finally the make_mixed function could be defined.  Currently any mixin defined after the make_mixed function is ignored.

*The macro's and general hackyness of the implementation.

I apologize for the length, but this is the most simplified example I could come up with.
Thanks for any help.
#include <string>
#include <vector>
#include <iostream>

using namespace std;

template<class Underlying>
struct Printer
{
    Printer(const Underlying &val) : val_(val) {}

    Underlying get_val() { return val_; }

  private:
    Underlying val_;
};

#define CURRENT_NUMBER_MIXED_IN_CLASSES() \
    MixinCount<0, __LINE__>::value

#define INCREMENT_MIXIN_CLASS_COUNTER() \
    template<int id>                                               \
    struct MixinClassCounter< CURRENT_NUMBER_MIXED_IN_CLASSES(), id>    \
    {                                                                   \
        static const bool is_defined = true;                            \
    }

template< bool b, typename i, typename j >
struct select_value;

template<class i, class j>
struct select_value<true, i, j>
{
    static const int value = i::value;
};

template<class i, class j>
struct select_value<false, i, j>
{
    static const int value = j::value;
};

template<int i>
struct IntToVal
{
    static const int value = i;
};

namespace
{
    template<int count, int id>
    struct MixinClassCounter
    {
        static const bool is_defined = false;
    };

    template<int count, int id>
    struct MixinCount
    {
        static const int value = select_value<MixinClassCounter<count, id>::is_defined,
                                              MixinCount<count + 1, id>,
                                              IntToVal<count> >::value;
    };

    template<class Underlying, int i>
    struct MixinBuilder {};

    template<class Underlying>
    struct MixinBuilder<Underlying, 0>
    {
        typedef Printer<Underlying> type;
    };
    INCREMENT_MIXIN_CLASS_COUNTER();
}

#define DECLARE_MIXIN_BEGIN(name) \
    template<class Base> \
    struct name : Base   \
    {                    \
        template<class Underlying>                  \
        name(const Underlying &val) : Base(val) {}

#define DECLARE_MIXIN_END(name)                 \
    };                                          \
    namespace                                   \
    {                                               \
        template<class Underlying>                                         \
        struct MixinBuilder<Underlying, CURRENT_NUMBER_MIXED_IN_CLASSES()> \
        {                                                                   \
            typedef name< typename MixinBuilder<Underlying, CURRENT_NUMBER_MIXED_IN_CLASSES() - 1>::type > type; \
        };                                                                  \
        INCREMENT_MIXIN_CLASS_COUNTER();                                    \
    }                                                                       \

DECLARE_MIXIN_BEGIN(PrintOnce)
void print_once()
{
    cout << Base::get_val() << endl;
}
DECLARE_MIXIN_END(PrintOnce)

DECLARE_MIXIN_BEGIN(PrintTwice)
void print_twice()
{
    cout << Base::get_val() << endl;
    cout << Base::get_val() << endl;
}
DECLARE_MIXIN_END(PrintTwice)

template<class T>
typename MixinBuilder<T, CURRENT_NUMBER_MIXED_IN_CLASSES() - 1>::type make_mixed(const T &val)
{
    return typename MixinBuilder<T, CURRENT_NUMBER_MIXED_IN_CLASSES() - 1>::type(val);
}

int main()
{
    string test("this is a test");
    auto printable_string = make_mixed(test);

    printable_string.print_once();
    printable_string.print_twice();
}

A: Here's a cleaner solution without macros:
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

template <typename T>
struct RefWrapper
{
    T *self;
    RefWrapper () : self (nullptr) {abort ();} // should never be called
    RefWrapper (T &self) : self (&self) {}
};

template <typename T>
struct PrintOnce : virtual RefWrapper<T>
{
    PrintOnce () {}             // workaround gcc 4.6 bug
    void print_once () {cout << *RefWrapper<T>::self << endl;}
};

template <typename T>
struct PrintTwice : virtual RefWrapper<T>
{
    PrintTwice () {}            // workaround gcc 4.6 bug
    void print_twice ()
    {
        cout << *RefWrapper<T>::self << endl;
        cout << *RefWrapper<T>::self << endl;
    }
};

template <typename T, typename... Args>
struct Mixed : Args...
{
    Mixed (T &self) :
        RefWrapper<T> (self),
        Args ()... {}

    Mixed (const Mixed &copy) :
        RefWrapper<T> (*copy.self),
        Args ()... {}
};

template <template <typename U> class Mixin, typename T>
Mixed<T, Mixin<T> > add_mixin (T &original)
{
    return Mixed<T, Mixin<T> > (original);
}

template <template <typename U> class Mixin, typename T,
          typename... OtherMixins>
Mixed<T, OtherMixins..., Mixin<T> >
add_mixin (Mixed<T, OtherMixins...> &original)
{
    return Mixed<T, OtherMixins..., Mixin<T> > (*original.self);
}

int main ()
{
    string foo = "test";

    auto p1 = add_mixin<PrintOnce> (foo);
    p1.print_once ();

    auto p2 = add_mixin<PrintTwice> (p1);
    p2.print_once ();
    p2.print_twice ();
}

Unfortunately, it still doesn't accomplish your requirement of having each mixin class being aware of all other mixin classes. I'm not sure if that's even possible at compile-time, though.


text:
Q: How to assign the javascript variable value to php variable
Possible Duplicate:
How to pass JavaScript variables to PHP?

I want to assign the javascript variable to php variable
$msg = "<script>document.write(message)</script>";
$f = new FacebookPost;
$f->message  = $msg;

But it is not working......

A: PHP is executed before javascript. You can't do that. PHP is server based, JavaScript is client based.
When PHP is finished executing, it outputs HTML. In the HTML there can be JavaScript code also. So PHP can 'control' JavaScript by outputting JavaScript code to the page, but not the other way around. You'd have to use Ajax-call for that.

A: Javascript works on the user's computer, PHP works on your server. In order to send variables from JS to PHP and vice versa, you need communication such as a page load.
Have a look here on what you can do: How to pass JavaScript variables to PHP? or more specifically the first answer (https://stackoverflow.com/a/1917626/1311593)

A: Javascript, is a client side script, Where as PHP is a server side script.
The only way you can send data to PHP is through redirection or ajax.

A: You cannot do that this way. You have to transmit values via $_GET, $_POST or $_COOKIE, after the script has been executed by client.


text:
Q: Passing of information by tabs Currently i have this inside my main class.
So i'm trying to create an object in order to pass information around, between the two tabs. for example after making a new order, i can go to the next tab to check the orders.
Book b = new Book();

So i tried to pass the object by.
I just started learning java a few weeks ago so please keep it simple. thanks alot.
And i'm trying doing it without a submit button, so when i click on the next tab, it will call the listener and store the infomation into the object. is it possible?

A: the main method, doesn't return any value, so you can't pass it's return value to another method like that.
I think you want something like
public class Order extends JPanel
{
    public Book b;
    public Order()
    {
        b = new Book();
    }
    ...
}

and then you can pass it as
AMethodThatUsesBook(myOrder.b)

or you might be trying to instantiate the object
Order myOrder = new Order();

and then you can pass that as a value
tp.addTab("New Order", myOrder);


text:
Q: League of Legends Login Issues I installed League of Legends through PlayOnLinux. The launcher opens and I'm able to get to the login page. However it stops there. Whenever I try to login it keeps saying that I have in invalid username and password combination although I'm pretty sure I'm using the right one since I can login in a friend's computer. Did i miss a step in installing and patching LoL?

A: I fixed this problem by changing my preferred server from EU West to NA.


text:
Q: Detecting text in image using MSER I'm trying to follow this tutorial http://www.mathworks.com/help/vision/examples/automatically-detect-and-recognize-text-in-natural-images.html to detect text in image using Matlab.
As a first step, the tutorial uses detectMSERFeatures to detect textual regions in the image. However, when I use this step on my image, the textual regions aren't detected.
Here is the snippet I'm using:
colorImage = imread('demo.png');
I = rgb2gray(colorImage);
% Detect MSER regions.
[mserRegions] = detectMSERFeatures(I, ...
    'RegionAreaRange',[200 8000],'ThresholdDelta',4);
figure
imshow(I)
hold on
plot(mserRegions, 'showPixelList', true,'showEllipses',false)
title('MSER regions')
hold off

And here is the original image
and here is the image after the first step
[![enter image description here][2]][2]
Update
I've played around with parameters but none seem to detect textual region perfectly. Is there a better way to accomplish this than tweaking numbers? Tweaking the parameters won't work for wide array of images I might have.
Some parameters I've tried and their results:
[mserRegions] = detectMSERFeatures(I, ...
    'RegionAreaRange',[30 100],'ThresholdDelta',12);

[mserRegions] = detectMSERFeatures(I, ...
    'RegionAreaRange',[30 600],'ThresholdDelta',12);

A: Disclaimer: completely untested.
Try reducing MaxAreaVariation, since your text & background have very little variation (reduce false positives). You should be able to crank this down pretty far since it looks like the text was digitally generated (wouldn't work as well if it was a picture of text).
Try reducing the minimum value for RegionAreaRange, since small characters may be smaller than 200 pixels (increase true positives). At 200, you're probably filtering out most of your text.
Try increasing ThresholdDelta, since you know there is stark contrast between the text and background (reduce false positives). This won't be quite as effective as MaxAreaVariation for filtering, but should help a bit.


text:
Q: log4net CSV File Appender Custom Parameters I am currently using log4net for an application I am working on. I have setup a CsvRollingFileAppender but am wonder how I can extend it to log passed parameters. An example would be something along the lines of the following:
log.Info(string.format("{0} - {1} - {2} - {3}", value1, value2, value3, value4));

The config for my Appender looks like this
<appender name="CsvRollingFileAppender" type="DataCalcuation.Classes.CsvHeaderOverride">
  <threshold value="INFO" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <file value="logs/" />
  <datePattern value="'DataCaclulation'.MM.dd.yyyy'.csv'" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="5MB" />
  <staticLogFileName value="false" />
  <layout type="log4net.Layout.PatternLayout">
    <header value="DateTime,Level,Location,Message
" />
    <conversionPattern value="%date{M/d/yyyy H:mm:ss.fff},%level,%location,%message%newline" />
  </layout>
</appender>

I would like to have it setup to have the headers of
 DateTime, Level, Location, PassedValue1, PassedValue2,  .....

I have stumbled across a few different articles like the following and wondered if that was the correct approach or if there was a more efficient way
Any insight would be greatly appreciated
I think I have to do something like this
 - Mapping message properties to CSV columns using log4net
Answer:
As promised here is the code I used to achieve what I was looking to do all credit goes to Steven Padfield whose post I used
I created a class called CsvLogEvent with the items I wanted to capture in the log
public class CsvLogEvent
{
     public int Value1 {get; set;}
     public string Value2 {get; set;}
     public string Value3 {get; set;}
     public int Value4 {get; set;}
}

I then used the following format to log the events
private readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

log.Info(new CsvLogEvent {
     Value1 = 1,
     Value2 = "Test",
     Value3 = "Log Event",
     Value4 = 0
});

To property format the CSV output I had to create a class to handle the new Pattern
public class CsvPattern : PatternLayout
{
     public override void Format(TextWriter writer, LoggingEvent loggingEvent)
     {
          if (loggingEvent.MessageObject != null)
          {
               PropertyInfo[] properties = loggingEvent.MessageObject.GetType().GetProperties();
               foreach(PropertyInfo prop in properties)
               {
                    object value = prop.GetValue(loggingEvent.MessageObject, null);
                    loggingEvent.Properties[prop.Name] = value;
               }
           }
           base.Format(writer, loggingEvent);
     }
}

Then finally setup the appender in your app.config file
<appender name="Test" type="DataCalcuation.Classes.CsvAppender">
  <threshold value="INFO" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <file value="logs/" />
  <datePattern value="'DataCaclulation'.MM.dd.yyyy'.csv'" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="5MB" />
  <staticLogFileName value="false" />
  <layout type="DataCalcuation.Classes.CsvPattern">
    <header value="DateTime,Level,Location,Value1, Value2, Value3, Value4
" />
    <conversionPattern value="%date{M/d/yyyy H:mm:ss.fff},%level,%location,%property{Value1},%property{Value2},%property{Value3},%property{Value4}%newline" />
  </layout>
</appender>

*

*Adding custom parameters to the log

*Log4Net Custom Appender


text:
Q: How to configure rails_admin to change integer input field into select field? I am using rails_admin with devise. I have a plain User model (having the typical devise attributes) as well as an additional integer type attribute called role_type. When I view http://0.0.0.0:5000/admin/user/1/edit in the browser, I see ten devise attributes, plus my Role type (though it is an type="number" input field) whereas I want it to be a select drop down menu. I have done some searching around, and have added a configuration to rails_admin.rb as well as a corresponding partial, and though I get the drop down I want, it's the only thing I get for the whole user edit view.
I want to configure the way rails_admin displays the :role_type field, while (obviously) also being able to edit the rest of the User fields.
db/migrate/20131119000715_add_role_type_to_user.rb
class AddRoleTypeToUser < ActiveRecord::Migration
  def change
    add_column :users, :role_type, :integer, null: false, default: 0
  end
end

app/models/user.rb
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ROLES = ['default', 'admin', 'moderator']
end

Gemfile
gem 'rails_admin', github: 'sferik/rails_admin'

config/initializers/rails_admin.rb
RailsAdmin.config do |config|
  config.model User do
    edit do
      field :role_type do
        partial 'form'
      end
    end
  end
end

app/views/rails_admin/main/_form.html.erb
<%= form.select :role_type, User::ROLES.each_with_index.map { |e, i| [e, i] } %>

A: You can create a role_type_enum method in your model that returns User::ROLES
https://github.com/sferik/rails_admin/wiki/Enumeration

A: I know this is a little late but I came accross this problem today, and found a solution!
If anyone stumbles on this: by changing field: you_column_name do to configure: your_column_name do in your rails_admin initializer, it should still show all your other fields and change only the one specified.
Thanks to the doc: https://github.com/sferik/rails_admin/wiki/Fields


text:
Q: Rspec Rails 3.1 Integration test. How to send post request headers for mobile, http basic authentication and JSON? I have an RSPEC integration test for a Rails 3.1 app that needs to test an api for a mobile client by issuing a POST request with JSON params and a mobile header that needs to use http_basic authentication
As the request object is not available in an integration test I'm kinda stuck
This is the code I have so far
    it "successfully posts scores" do
# request.env["HTTP_ACCEPT"] = "application/json" #This causes an error as request is nly available in controller tests

      post "scores", :score => {:mobile_user_id => @mobile_user.id, :points => 50, :time_taken => 7275}.to_json,
           :format => :json, :user_agent => 'Mobile', 'HTTP_AUTHORIZATION' =>  get_basic_auth
    end

The post request does not recognise that I am using http basic authentication but unsure if the format for json is correct. Any help appreciated
get_basic_auth is a helper me4thod that looks like this
  def get_basic_auth
    user = 'user'
    pw = 'secret'
    ActionController::HttpAuthentication::Basic.encode_credentials user, pw
  end

I use a before_filter in my controllers that checks for mobile and http_basic_authentication that looks like this
  def authorize
    logger.debug("@@@@ Authorizing request #{request.inspect}")
    if mobile_device?
        authenticate_or_request_with_http_basic do |username, password|
          username == Mobile::Application.config.mobile_login_name && Mobile::Application.config.mobile_password
        end
    else
      unless current_user
        redirect_to login_url, :notice => "Please log in"
      end
    end
  end

I get a redirect to login so obviously the mobile header is not being accepted so I have no idea really if any of the other headers are working
UPDATE
Figured it out
  post("scores", {:score => {:mobile_user_id => @mobile_user.id, :points => 50, :time_taken => 7275}}.to_json,
       {"HTTP_USER_AGENT" => "Mobile", 'HTTP_AUTHORIZATION' => get_basic_auth, 'HTTP_CONTENT_TYPE' => "application/json"})

Does the trick nicely

A: I figured out what I needed to do
post("scores", {:score => {:mobile_user_id => @mobile_user.id, :points => 50, :time_taken => 7275}}.to_json,
       {"HTTP_USER_AGENT" => "Mobile", 'HTTP_AUTHORIZATION' => get_basic_auth, 'HTTP_CONTENT_TYPE' => "application/json"}

Obviously the "mobile" user agent is not needed to test normal json requests.
Hope that helps someone


text:
Q: Get-EC2Instance Creds cannot find region I have been at this all day, we have an account that uses permissions to spin up ec2 instance, it is used heavily and worked without concerns. I have deleted the credentials.ini and config.ini files and reEntered aws configure with even a new password.
It says the creds are fine, however, if I run something simple like (Get-EC2Instance).instances I get in return the following error:
get-ec2instance : Name resolution failure attempting to reach service in region Region (as supplied to the -Region parameter or from configured shell default). The remote name could not be resolved: 'ec2.region.amazonaws.com'.
Note the url says region, even if I set a default in the config region to something like us-east-1
I tried a different person on the same box, and no problems. What can I do to purge the user and try again? The user is using a group permission and that should have not altered (just encase what instances would it need for create & delete ec2?)


text:
Q: How to add a few non open source jars to Artifactory so that they can be pulled by another Gradle/Maven project In my Gradle/Maven build script there are a few jars that are not available for download from maven repository because they are not open source. (These jars were developed by some projects in my organization anymore that are not being worked on anymore).
My requirement is to add these jars to an Artifactory with group id, artifact id and version number. In this way when I point my repository to Artifactory in my build script, these jars can be pulled out.
I am looking for mvn-install kind of command for Artifactory.
I also found below question while researching :
Deploying project JAR to artifactory programmatically but this does not specify group id, artifact id and version number that I need so that another project's Maven/Gradle build script can pull that jar from Artifactory.
The Artifactory is locally deployed in my system at the moment (later on it will be moved to a server).

A: You can deploy those JAR's via Artifactory WebUI and when doing the deploy use the "Deploy as Maven Artifact" That will deploy those artifacts with the correct group id, artifact id and version number.
See here


text: Q: How to bring footnotes closer to page number? As can be seen in the screenshot, my footnotes are abnormally far away from the page number. I use the normal \footnote command and have so far tried \usepackage[bottom]{footmisc} and had a few ideas with the fancyhdr package, none of which worked. Any suggestions?


text:
Q: Extract Number of Followers from Twitter using BeautifulSoup I am trying to automate the process of obtaining the number of followers different twitter accounts using the page source.
I have the following code for one account
from bs4 import BeautifulSoup
import requests
username='justinbieber'
url = 'https://www.twitter.com/'+username
r = requests.get(url)
soup = BeautifulSoup(r.content)
for tag in soup.findAll('a'):
    if tag.has_key('class'):
        if tag['class'] == 'ProfileNav-stat ProfileNav-stat--link u-borderUserColor u-textCenter js-tooltip js-nav u-textUserColor':
            if tag['href'] == '/justinbieber/followers':
                print tag.title
                break

I am not sure where did I went wrong. I understand that we can use Twitter API to obtain the number of followers. However, I wish to try to obtain it through this method as well to try it out. Any suggestions?
I've modified the code from here

A: If I were you, I'd be passing the class name as an argument to the find() function instead of find_all() and I'd first look for the <li> element that contains the anchor you're loooking for. It'd look something like this
from bs4 import BeautifulSoup
import requests
username='justinbieber'
url = 'https://www.twitter.com/'+username
r = requests.get(url)
soup = BeautifulSoup(r.content)

f = soup.find('li', class_="ProfileNav-item--followers")
title = f.find('a')['title']
print title
# 81,346,708 Followers

num_followers = int(title.split(' ')[0].replace(',',''))
print num_followers
# 81346708

PS findAll() was renamed to find_all() in bs4


text:
Q: Logitech K380 fn + opt + cmd + L puts my Mac to sleep I have used the keyboard combination control + option + command + L on a daily basis for years. I recently bought the Logitech K380 not noticing that it swaps the position of the Fn and Ctrl keys (when compared to a standard Mac keyboard).
Due to years of muscle memory, I regularly now press Fn + Opt + Cmd + L on the K380, which seems to instantly put my Mac to sleep. Is there any way for me to disable this so that my computer does not go to sleep when I accidentally press this combination?
Also, interestingly, the same combination (Fn + Opt + Cmd + L) on my Mac's built-in keyboard does NOT cause my computer to go to sleep.


text:
Q: Passing javascript variable to php with other html variable using post method I want to send variable rows to post2.php with other HTML form variable using POST or GET methods.
The below code gives an error:
Notice: Undefined index: row1 in C:\xampp\htdocs\PhpProject1\OtherUsableItems\post2.php on line 8

post1.php

  <form action="post2.php" method="post">

         1
         <INPUT name="n1[]"type="text" />
         <INPUT name="n2[]"type="text" />
        <SELECT name="country[]" type="select-one">
                <OPTION value="in">India</OPTION>
                <OPTION value="de">Germany</OPTION>
                <OPTION value="fr">France</OPTION>
                <OPTION value="us">United States</OPTION>
                <OPTION value="ch">Switzerland</OPTION>
            </SELECT>

 <INPUT type="button" value="Add Row" onclick="addRow('dataTable');"/>
 <button id="bt" onclick="count('dataTable');">Submit</button>
 </form>

post2.php
<?php
    $n1 = $_POST['n1'];
    $n2 = $_POST['n2'];
    $country = $_POST['country'];
    echo $n1[0];
    echo $n2[0];
    echo $country[0];
    $count = $_POST['row1'];
    echo $count;
?>

A: Try changing to 'row' instead of 'row1'
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
$country = $_POST['country'];
echo $n1[0];
echo $n2[0];
echo $country[0];
$count = $_POST['row'];
echo $count;

In the future, use print_r to see the value of $_POST.
In addition to the above instructions, I would remove the 2nd


text:
Q: C# Reading file as bytes, converting it to UTF-8, then back ruins the data When I read the file as Bytes, convert it to UTF8 (so I can edit contents later) but then convert it back to Bytes and save it, it messes up the file and adds random stuff to it. The size goes from 11,096 KB to 17,692 KB.
private void inj()
        {
            string appAsarPath = this.filePath + "app.asar";
            this.backupAsar = File.ReadAllBytes(appAsarPath);
            string asarContents = Encoding.UTF8.GetString(this.backupAsar);
            File.WriteAllBytes(appAsarPath, Encoding.UTF8.GetBytes(asarContents));
        }

Here are some of the contents of the file.


text:
Q: Multiple Subforms in Datasheet View in Access I have two subforms on my main Access Form, I am familiar with linking parent and child forms using the Link Master Fields, And Link Child Fields on each subform.
On my form, Subform1 is linked to an ID on the Main Form, and Subform2 is linked to an ID on Subform1.
I have previously got it working where if the user clicks on a record in subform 1, then Subform 2 gets dynamically updated to show specific data (this is when subform2 is set up as a Single Form View.
What I am trying to do, is get both subforms in datasheet view, and clicking on a record on subform1, should then requery subform2 for all related records of the item selected in subform2.
Is this possible with native Access functionality, Otherwise, is there a VBA solution?
thanks.

A: you won't be able to do it with native access functionality: Subform2 would need to be a child of subform1 for that.
However you should be able to do it with VBA, readily enough.
In the form displayed in the Subform1 control, create a Form_Current event. This will fire whenever the current record changes in Subform1. Then use that event to reset the recordsource of subform2, directly or indirectly.
For example, suppose the MainForm shows information from a table called Person, and Subform1 shows information about contact episodes between persons and our organisation, and Subform2 details information about communication within these contact episodes.
The data will be something like this:
Mainform: SELECT * FROM Person
Subform1:   SELECT * FROM PersonEpisode
Subform2:     SELECT * FROM EpisodeCommunication

The data in subform1 can be kept to that pertaining to just the person displayed on Mainform using LinkChild/Master as you know, or alternatively, Mainform's Form_Current event could be used to change the recordsource of subform1 like so:
private sub Form_Current()    'on mainform
    Subform1.Form.RecordSource = "SELECT * FROM PersonEpisode WHERE PersonID = " & me.ID
end sub

Likewise then, the form_Current in subform1 is then used to keep subform2 current to subform1:
private sub Form_Current()    'in Subform1
    Forms!Mainform!Subform2.Form.Recordsource = "SELECT * FROM EpisodeCommunication WHERE EpisodeID = " & me.EpisodeID
end sub

This should work fine. If you prefer you could instead:
private sub Form_Current()    'in Subform1
    Me.Parent!Subform2.Form.Recordsource = "SELECT * FROM EpisodeCommunication WHERE EpisodeID = " & me.EpisodeID
end sub

This is functionally identical to the previous definition, but removes the name "MainForm" from the call, thus meaning that if someone decides to change the name of MainForm, or to clone this functionality to another form at some point in the future, this code will not have to be rewritten or modified.